1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> 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 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word"; 139 140 // FIXME: Remove this once the bug has been fixed! 141 extern cl::opt<bool> ANDIGlueBug; 142 143 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 144 const PPCSubtarget &STI) 145 : TargetLowering(TM), Subtarget(STI) { 146 // Initialize map that relates the PPC addressing modes to the computed flags 147 // of a load/store instruction. The map is used to determine the optimal 148 // addressing mode when selecting load and stores. 149 initializeAddrModeMap(); 150 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 151 // arguments are at least 4/8 bytes aligned. 152 bool isPPC64 = Subtarget.isPPC64(); 153 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 154 155 // Set up the register classes. 156 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 157 if (!useSoftFloat()) { 158 if (hasSPE()) { 159 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 160 // EFPU2 APU only supports f32 161 if (!Subtarget.hasEFPU2()) 162 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 163 } else { 164 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 165 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 166 } 167 } 168 169 // Match BITREVERSE to customized fast code sequence in the td file. 170 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 171 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 172 173 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 174 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 175 176 // Custom lower inline assembly to check for special registers. 177 setOperationAction(ISD::INLINEASM, MVT::Other, Custom); 178 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom); 179 180 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 181 for (MVT VT : MVT::integer_valuetypes()) { 182 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 183 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 184 } 185 186 if (Subtarget.isISA3_0()) { 187 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 188 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 189 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 190 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 191 } else { 192 // No extending loads from f16 or HW conversions back and forth. 193 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 194 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 195 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 196 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 197 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 198 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 199 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 200 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 201 } 202 203 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 204 205 // PowerPC has pre-inc load and store's. 206 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 207 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 208 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 209 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 210 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 211 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 212 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 213 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 214 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 215 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 216 if (!Subtarget.hasSPE()) { 217 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 218 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 219 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 220 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 221 } 222 223 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 224 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 225 for (MVT VT : ScalarIntVTs) { 226 setOperationAction(ISD::ADDC, VT, Legal); 227 setOperationAction(ISD::ADDE, VT, Legal); 228 setOperationAction(ISD::SUBC, VT, Legal); 229 setOperationAction(ISD::SUBE, VT, Legal); 230 } 231 232 if (Subtarget.useCRBits()) { 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 234 235 if (isPPC64 || Subtarget.hasFPCVT()) { 236 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 237 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 238 isPPC64 ? MVT::i64 : MVT::i32); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 240 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 241 isPPC64 ? MVT::i64 : MVT::i32); 242 243 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 244 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 245 isPPC64 ? MVT::i64 : MVT::i32); 246 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 247 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 248 isPPC64 ? MVT::i64 : MVT::i32); 249 250 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 251 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 252 isPPC64 ? MVT::i64 : MVT::i32); 253 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 254 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 255 isPPC64 ? MVT::i64 : MVT::i32); 256 257 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 258 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 259 isPPC64 ? MVT::i64 : MVT::i32); 260 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 261 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 262 isPPC64 ? MVT::i64 : MVT::i32); 263 } else { 264 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 265 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 266 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 267 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 268 } 269 270 // PowerPC does not support direct load/store of condition registers. 271 setOperationAction(ISD::LOAD, MVT::i1, Custom); 272 setOperationAction(ISD::STORE, MVT::i1, Custom); 273 274 // FIXME: Remove this once the ANDI glue bug is fixed: 275 if (ANDIGlueBug) 276 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 277 278 for (MVT VT : MVT::integer_valuetypes()) { 279 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 280 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 281 setTruncStoreAction(VT, MVT::i1, Expand); 282 } 283 284 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 285 } 286 287 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 288 // PPC (the libcall is not available). 289 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 290 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 291 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 292 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 293 294 // We do not currently implement these libm ops for PowerPC. 295 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 296 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 297 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 298 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 299 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 300 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 301 302 // PowerPC has no SREM/UREM instructions unless we are on P9 303 // On P9 we may use a hardware instruction to compute the remainder. 304 // When the result of both the remainder and the division is required it is 305 // more efficient to compute the remainder from the result of the division 306 // rather than use the remainder instruction. The instructions are legalized 307 // directly because the DivRemPairsPass performs the transformation at the IR 308 // level. 309 if (Subtarget.isISA3_0()) { 310 setOperationAction(ISD::SREM, MVT::i32, Legal); 311 setOperationAction(ISD::UREM, MVT::i32, Legal); 312 setOperationAction(ISD::SREM, MVT::i64, Legal); 313 setOperationAction(ISD::UREM, MVT::i64, Legal); 314 } else { 315 setOperationAction(ISD::SREM, MVT::i32, Expand); 316 setOperationAction(ISD::UREM, MVT::i32, Expand); 317 setOperationAction(ISD::SREM, MVT::i64, Expand); 318 setOperationAction(ISD::UREM, MVT::i64, Expand); 319 } 320 321 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 322 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 323 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 324 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 325 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 326 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 327 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 328 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 329 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 330 331 // Handle constrained floating-point operations of scalar. 332 // TODO: Handle SPE specific operation. 333 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 334 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 335 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 336 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 337 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 338 339 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 340 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 341 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 342 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 343 344 if (!Subtarget.hasSPE()) { 345 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 346 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 347 } 348 349 if (Subtarget.hasVSX()) { 350 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 352 } 353 354 if (Subtarget.hasFSQRT()) { 355 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 356 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 357 } 358 359 if (Subtarget.hasFPRND()) { 360 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 361 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 363 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 364 365 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 366 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 367 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 368 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 369 } 370 371 // We don't support sin/cos/sqrt/fmod/pow 372 setOperationAction(ISD::FSIN , MVT::f64, Expand); 373 setOperationAction(ISD::FCOS , MVT::f64, Expand); 374 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 375 setOperationAction(ISD::FREM , MVT::f64, Expand); 376 setOperationAction(ISD::FPOW , MVT::f64, Expand); 377 setOperationAction(ISD::FSIN , MVT::f32, Expand); 378 setOperationAction(ISD::FCOS , MVT::f32, Expand); 379 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 380 setOperationAction(ISD::FREM , MVT::f32, Expand); 381 setOperationAction(ISD::FPOW , MVT::f32, Expand); 382 383 // MASS transformation for LLVM intrinsics with replicating fast-math flag 384 // to be consistent to PPCGenScalarMASSEntries pass 385 if (TM.getOptLevel() == CodeGenOpt::Aggressive && 386 TM.Options.PPCGenScalarMASSEntries) { 387 setOperationAction(ISD::FSIN , MVT::f64, Custom); 388 setOperationAction(ISD::FCOS , MVT::f64, Custom); 389 setOperationAction(ISD::FPOW , MVT::f64, Custom); 390 setOperationAction(ISD::FLOG, MVT::f64, Custom); 391 setOperationAction(ISD::FLOG10, MVT::f64, Custom); 392 setOperationAction(ISD::FEXP, MVT::f64, Custom); 393 setOperationAction(ISD::FSIN , MVT::f32, Custom); 394 setOperationAction(ISD::FCOS , MVT::f32, Custom); 395 setOperationAction(ISD::FPOW , MVT::f32, Custom); 396 setOperationAction(ISD::FLOG, MVT::f32, Custom); 397 setOperationAction(ISD::FLOG10, MVT::f32, Custom); 398 setOperationAction(ISD::FEXP, MVT::f32, Custom); 399 } 400 401 if (Subtarget.hasSPE()) { 402 setOperationAction(ISD::FMA , MVT::f64, Expand); 403 setOperationAction(ISD::FMA , MVT::f32, Expand); 404 } else { 405 setOperationAction(ISD::FMA , MVT::f64, Legal); 406 setOperationAction(ISD::FMA , MVT::f32, Legal); 407 } 408 409 if (Subtarget.hasSPE()) 410 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 411 412 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 413 414 // If we're enabling GP optimizations, use hardware square root 415 if (!Subtarget.hasFSQRT() && 416 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 417 Subtarget.hasFRE())) 418 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 419 420 if (!Subtarget.hasFSQRT() && 421 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 422 Subtarget.hasFRES())) 423 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 424 425 if (Subtarget.hasFCPSGN()) { 426 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 427 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 428 } else { 429 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 430 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 431 } 432 433 if (Subtarget.hasFPRND()) { 434 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 435 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 436 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 437 setOperationAction(ISD::FROUND, MVT::f64, Legal); 438 439 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 440 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 441 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 442 setOperationAction(ISD::FROUND, MVT::f32, Legal); 443 } 444 445 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 446 // to speed up scalar BSWAP64. 447 // CTPOP or CTTZ were introduced in P8/P9 respectively 448 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 449 if (Subtarget.hasP9Vector() && Subtarget.isPPC64()) 450 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 451 else 452 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 453 if (Subtarget.isISA3_0()) { 454 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 455 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 456 } else { 457 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 458 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 459 } 460 461 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 462 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 463 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 464 } else { 465 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 466 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 467 } 468 469 // PowerPC does not have ROTR 470 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 471 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 472 473 if (!Subtarget.useCRBits()) { 474 // PowerPC does not have Select 475 setOperationAction(ISD::SELECT, MVT::i32, Expand); 476 setOperationAction(ISD::SELECT, MVT::i64, Expand); 477 setOperationAction(ISD::SELECT, MVT::f32, Expand); 478 setOperationAction(ISD::SELECT, MVT::f64, Expand); 479 } 480 481 // PowerPC wants to turn select_cc of FP into fsel when possible. 482 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 483 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 484 485 // PowerPC wants to optimize integer setcc a bit 486 if (!Subtarget.useCRBits()) 487 setOperationAction(ISD::SETCC, MVT::i32, Custom); 488 489 if (Subtarget.hasFPU()) { 490 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 491 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 492 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 493 494 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 495 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 496 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 497 } 498 499 // PowerPC does not have BRCOND which requires SetCC 500 if (!Subtarget.useCRBits()) 501 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 502 503 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 504 505 if (Subtarget.hasSPE()) { 506 // SPE has built-in conversions 507 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 508 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 509 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 510 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 511 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 512 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 513 514 // SPE supports signaling compare of f32/f64. 515 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 516 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 517 } else { 518 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 519 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 520 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 521 522 // PowerPC does not have [U|S]INT_TO_FP 523 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 524 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 525 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 526 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 527 } 528 529 if (Subtarget.hasDirectMove() && isPPC64) { 530 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 531 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 532 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 533 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 534 if (TM.Options.UnsafeFPMath) { 535 setOperationAction(ISD::LRINT, MVT::f64, Legal); 536 setOperationAction(ISD::LRINT, MVT::f32, Legal); 537 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 538 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 539 setOperationAction(ISD::LROUND, MVT::f64, Legal); 540 setOperationAction(ISD::LROUND, MVT::f32, Legal); 541 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 542 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 543 } 544 } else { 545 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 546 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 547 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 548 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 549 } 550 551 // We cannot sextinreg(i1). Expand to shifts. 552 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 553 554 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 555 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 556 // support continuation, user-level threading, and etc.. As a result, no 557 // other SjLj exception interfaces are implemented and please don't build 558 // your own exception handling based on them. 559 // LLVM/Clang supports zero-cost DWARF exception handling. 560 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 561 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 562 563 // We want to legalize GlobalAddress and ConstantPool nodes into the 564 // appropriate instructions to materialize the address. 565 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 566 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 567 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 568 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 569 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 570 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 571 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 572 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 573 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 574 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 575 576 // TRAP is legal. 577 setOperationAction(ISD::TRAP, MVT::Other, Legal); 578 579 // TRAMPOLINE is custom lowered. 580 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 581 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 582 583 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 584 setOperationAction(ISD::VASTART , MVT::Other, Custom); 585 586 if (Subtarget.is64BitELFABI()) { 587 // VAARG always uses double-word chunks, so promote anything smaller. 588 setOperationAction(ISD::VAARG, MVT::i1, Promote); 589 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 590 setOperationAction(ISD::VAARG, MVT::i8, Promote); 591 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 592 setOperationAction(ISD::VAARG, MVT::i16, Promote); 593 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 594 setOperationAction(ISD::VAARG, MVT::i32, Promote); 595 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 596 setOperationAction(ISD::VAARG, MVT::Other, Expand); 597 } else if (Subtarget.is32BitELFABI()) { 598 // VAARG is custom lowered with the 32-bit SVR4 ABI. 599 setOperationAction(ISD::VAARG, MVT::Other, Custom); 600 setOperationAction(ISD::VAARG, MVT::i64, Custom); 601 } else 602 setOperationAction(ISD::VAARG, MVT::Other, Expand); 603 604 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 605 if (Subtarget.is32BitELFABI()) 606 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 607 else 608 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 609 610 // Use the default implementation. 611 setOperationAction(ISD::VAEND , MVT::Other, Expand); 612 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 613 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 614 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 615 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 616 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 617 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 618 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 619 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 620 621 // We want to custom lower some of our intrinsics. 622 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 623 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom); 624 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom); 625 626 // To handle counter-based loop conditions. 627 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 628 629 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 630 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 631 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 632 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 633 634 // Comparisons that require checking two conditions. 635 if (Subtarget.hasSPE()) { 636 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 637 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 638 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 639 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 640 } 641 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 642 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 643 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 644 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 645 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 646 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 647 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 648 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 649 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 650 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 651 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 652 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 653 654 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 655 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 656 657 if (Subtarget.has64BitSupport()) { 658 // They also have instructions for converting between i64 and fp. 659 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 660 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 661 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 662 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 663 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 664 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 665 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 666 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 667 // This is just the low 32 bits of a (signed) fp->i64 conversion. 668 // We cannot do this with Promote because i64 is not a legal type. 669 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 670 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 671 672 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 673 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 674 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 675 } 676 } else { 677 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 678 if (Subtarget.hasSPE()) { 679 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 680 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 681 } else { 682 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 683 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 684 } 685 } 686 687 // With the instructions enabled under FPCVT, we can do everything. 688 if (Subtarget.hasFPCVT()) { 689 if (Subtarget.has64BitSupport()) { 690 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 691 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 692 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 693 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 694 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 695 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 696 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 697 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 698 } 699 700 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 701 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 702 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 703 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 704 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 705 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 706 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 707 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 708 } 709 710 if (Subtarget.use64BitRegs()) { 711 // 64-bit PowerPC implementations can support i64 types directly 712 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 713 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 714 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 715 // 64-bit PowerPC wants to expand i128 shifts itself. 716 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 717 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 718 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 719 } else { 720 // 32-bit PowerPC wants to expand i64 shifts itself. 721 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 722 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 723 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 724 } 725 726 // PowerPC has better expansions for funnel shifts than the generic 727 // TargetLowering::expandFunnelShift. 728 if (Subtarget.has64BitSupport()) { 729 setOperationAction(ISD::FSHL, MVT::i64, Custom); 730 setOperationAction(ISD::FSHR, MVT::i64, Custom); 731 } 732 setOperationAction(ISD::FSHL, MVT::i32, Custom); 733 setOperationAction(ISD::FSHR, MVT::i32, Custom); 734 735 if (Subtarget.hasVSX()) { 736 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 737 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 738 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 739 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 740 } 741 742 if (Subtarget.hasAltivec()) { 743 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 744 setOperationAction(ISD::SADDSAT, VT, Legal); 745 setOperationAction(ISD::SSUBSAT, VT, Legal); 746 setOperationAction(ISD::UADDSAT, VT, Legal); 747 setOperationAction(ISD::USUBSAT, VT, Legal); 748 } 749 // First set operation action for all vector types to expand. Then we 750 // will selectively turn on ones that can be effectively codegen'd. 751 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 752 // add/sub are legal for all supported vector VT's. 753 setOperationAction(ISD::ADD, VT, Legal); 754 setOperationAction(ISD::SUB, VT, Legal); 755 756 // For v2i64, these are only valid with P8Vector. This is corrected after 757 // the loop. 758 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 759 setOperationAction(ISD::SMAX, VT, Legal); 760 setOperationAction(ISD::SMIN, VT, Legal); 761 setOperationAction(ISD::UMAX, VT, Legal); 762 setOperationAction(ISD::UMIN, VT, Legal); 763 } 764 else { 765 setOperationAction(ISD::SMAX, VT, Expand); 766 setOperationAction(ISD::SMIN, VT, Expand); 767 setOperationAction(ISD::UMAX, VT, Expand); 768 setOperationAction(ISD::UMIN, VT, Expand); 769 } 770 771 if (Subtarget.hasVSX()) { 772 setOperationAction(ISD::FMAXNUM, VT, Legal); 773 setOperationAction(ISD::FMINNUM, VT, Legal); 774 } 775 776 // Vector instructions introduced in P8 777 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 778 setOperationAction(ISD::CTPOP, VT, Legal); 779 setOperationAction(ISD::CTLZ, VT, Legal); 780 } 781 else { 782 setOperationAction(ISD::CTPOP, VT, Expand); 783 setOperationAction(ISD::CTLZ, VT, Expand); 784 } 785 786 // Vector instructions introduced in P9 787 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 788 setOperationAction(ISD::CTTZ, VT, Legal); 789 else 790 setOperationAction(ISD::CTTZ, VT, Expand); 791 792 // We promote all shuffles to v16i8. 793 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 794 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 795 796 // We promote all non-typed operations to v4i32. 797 setOperationAction(ISD::AND , VT, Promote); 798 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 799 setOperationAction(ISD::OR , VT, Promote); 800 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 801 setOperationAction(ISD::XOR , VT, Promote); 802 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 803 setOperationAction(ISD::LOAD , VT, Promote); 804 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 805 setOperationAction(ISD::SELECT, VT, Promote); 806 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 807 setOperationAction(ISD::VSELECT, VT, Legal); 808 setOperationAction(ISD::SELECT_CC, VT, Promote); 809 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 810 setOperationAction(ISD::STORE, VT, Promote); 811 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 812 813 // No other operations are legal. 814 setOperationAction(ISD::MUL , VT, Expand); 815 setOperationAction(ISD::SDIV, VT, Expand); 816 setOperationAction(ISD::SREM, VT, Expand); 817 setOperationAction(ISD::UDIV, VT, Expand); 818 setOperationAction(ISD::UREM, VT, Expand); 819 setOperationAction(ISD::FDIV, VT, Expand); 820 setOperationAction(ISD::FREM, VT, Expand); 821 setOperationAction(ISD::FNEG, VT, Expand); 822 setOperationAction(ISD::FSQRT, VT, Expand); 823 setOperationAction(ISD::FLOG, VT, Expand); 824 setOperationAction(ISD::FLOG10, VT, Expand); 825 setOperationAction(ISD::FLOG2, VT, Expand); 826 setOperationAction(ISD::FEXP, VT, Expand); 827 setOperationAction(ISD::FEXP2, VT, Expand); 828 setOperationAction(ISD::FSIN, VT, Expand); 829 setOperationAction(ISD::FCOS, VT, Expand); 830 setOperationAction(ISD::FABS, VT, Expand); 831 setOperationAction(ISD::FFLOOR, VT, Expand); 832 setOperationAction(ISD::FCEIL, VT, Expand); 833 setOperationAction(ISD::FTRUNC, VT, Expand); 834 setOperationAction(ISD::FRINT, VT, Expand); 835 setOperationAction(ISD::FNEARBYINT, VT, Expand); 836 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 837 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 838 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 839 setOperationAction(ISD::MULHU, VT, Expand); 840 setOperationAction(ISD::MULHS, VT, Expand); 841 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 842 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 843 setOperationAction(ISD::UDIVREM, VT, Expand); 844 setOperationAction(ISD::SDIVREM, VT, Expand); 845 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 846 setOperationAction(ISD::FPOW, VT, Expand); 847 setOperationAction(ISD::BSWAP, VT, Expand); 848 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 849 setOperationAction(ISD::ROTL, VT, Expand); 850 setOperationAction(ISD::ROTR, VT, Expand); 851 852 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 853 setTruncStoreAction(VT, InnerVT, Expand); 854 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 855 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 856 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 857 } 858 } 859 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 860 if (!Subtarget.hasP8Vector()) { 861 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 862 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 863 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 864 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 865 } 866 867 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 868 // with merges, splats, etc. 869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 870 871 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 872 // are cheap, so handle them before they get expanded to scalar. 873 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 874 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 875 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 876 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 877 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 878 879 setOperationAction(ISD::AND , MVT::v4i32, Legal); 880 setOperationAction(ISD::OR , MVT::v4i32, Legal); 881 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 882 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 883 setOperationAction(ISD::SELECT, MVT::v4i32, 884 Subtarget.useCRBits() ? Legal : Expand); 885 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 886 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 887 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 888 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 889 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 890 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 891 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 892 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 893 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 894 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 895 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 896 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 897 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 898 899 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 900 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 901 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 902 if (Subtarget.hasAltivec()) 903 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 904 setOperationAction(ISD::ROTL, VT, Legal); 905 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 906 if (Subtarget.hasP8Altivec()) 907 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 908 909 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 910 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 911 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 912 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 913 914 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 915 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 916 917 if (Subtarget.hasVSX()) { 918 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 919 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 920 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 921 } 922 923 if (Subtarget.hasP8Altivec()) 924 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 925 else 926 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 927 928 if (Subtarget.isISA3_1()) { 929 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 930 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 931 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 932 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 933 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 934 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 935 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 936 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 937 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 938 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 939 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 940 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 941 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 942 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 943 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 944 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 945 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 946 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 947 } 948 949 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 950 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 951 952 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 953 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 954 955 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 956 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 957 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 958 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 959 960 // Altivec does not contain unordered floating-point compare instructions 961 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 962 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 963 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 964 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 965 966 if (Subtarget.hasVSX()) { 967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 968 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 969 if (Subtarget.hasP8Vector()) { 970 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 972 } 973 if (Subtarget.hasDirectMove() && isPPC64) { 974 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 975 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 976 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 977 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 979 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 982 } 983 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 984 985 // The nearbyint variants are not allowed to raise the inexact exception 986 // so we can only code-gen them with unsafe math. 987 if (TM.Options.UnsafeFPMath) { 988 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 989 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 990 } 991 992 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 993 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 994 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 995 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 996 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 997 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 998 setOperationAction(ISD::FROUND, MVT::f64, Legal); 999 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1000 1001 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1002 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1003 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1004 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1005 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1006 1007 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 1008 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1009 1010 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 1011 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 1012 1013 // Share the Altivec comparison restrictions. 1014 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 1015 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 1016 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 1017 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 1018 1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1020 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 1021 1022 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 1023 1024 if (Subtarget.hasP8Vector()) 1025 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1026 1027 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1028 1029 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1030 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1031 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1032 1033 if (Subtarget.hasP8Altivec()) { 1034 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1035 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1036 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1037 1038 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1039 // SRL, but not for SRA because of the instructions available: 1040 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1041 // doing 1042 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1043 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1044 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1045 1046 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1047 } 1048 else { 1049 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1050 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1051 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1052 1053 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1054 1055 // VSX v2i64 only supports non-arithmetic operations. 1056 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1057 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1058 } 1059 1060 if (Subtarget.isISA3_1()) 1061 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1062 else 1063 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1064 1065 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1066 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1067 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1068 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1069 1070 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1071 1072 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1073 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1074 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1075 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1076 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1077 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1078 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1079 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1080 1081 // Custom handling for partial vectors of integers converted to 1082 // floating point. We already have optimal handling for v2i32 through 1083 // the DAG combine, so those aren't necessary. 1084 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1085 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1086 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1087 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1088 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1089 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1090 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1091 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1092 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1093 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1094 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1095 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1096 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1097 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1098 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1099 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1100 1101 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1102 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1103 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1104 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1105 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1106 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1107 1108 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1109 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1110 1111 // Handle constrained floating-point operations of vector. 1112 // The predictor is `hasVSX` because altivec instruction has 1113 // no exception but VSX vector instruction has. 1114 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1115 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1116 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1117 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1118 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1119 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1120 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1121 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1122 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1123 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1124 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1125 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1126 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1127 1128 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1129 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1130 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1131 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1132 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1133 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1134 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1135 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1136 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1137 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1138 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1139 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1140 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1141 1142 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1143 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1144 1145 for (MVT FPT : MVT::fp_valuetypes()) 1146 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1147 1148 // Expand the SELECT to SELECT_CC 1149 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1150 1151 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1152 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1153 1154 // No implementation for these ops for PowerPC. 1155 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1156 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1157 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1158 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1159 setOperationAction(ISD::FREM, MVT::f128, Expand); 1160 } 1161 1162 if (Subtarget.hasP8Altivec()) { 1163 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1164 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1165 } 1166 1167 if (Subtarget.hasP9Vector()) { 1168 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1169 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1170 1171 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1172 // SRL, but not for SRA because of the instructions available: 1173 // VS{RL} and VS{RL}O. 1174 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1175 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1176 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1177 1178 setOperationAction(ISD::FADD, MVT::f128, Legal); 1179 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1180 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1181 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1182 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1183 1184 setOperationAction(ISD::FMA, MVT::f128, Legal); 1185 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1186 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1187 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1188 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1189 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1190 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1191 1192 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1193 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1194 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1195 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1196 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1197 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1198 1199 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1200 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1201 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1202 1203 // Handle constrained floating-point operations of fp128 1204 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1205 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1206 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1207 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1208 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1209 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1210 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1211 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1212 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1213 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1214 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1215 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1216 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1217 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1218 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1219 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1220 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1221 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1222 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1223 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1224 } else if (Subtarget.hasVSX()) { 1225 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1226 setOperationAction(ISD::STORE, MVT::f128, Promote); 1227 1228 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1229 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1230 1231 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1232 // fp_to_uint and int_to_fp. 1233 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1234 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1235 1236 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1237 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1238 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1239 setOperationAction(ISD::FABS, MVT::f128, Expand); 1240 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1241 setOperationAction(ISD::FMA, MVT::f128, Expand); 1242 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1243 1244 // Expand the fp_extend if the target type is fp128. 1245 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1246 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1247 1248 // Expand the fp_round if the source type is fp128. 1249 for (MVT VT : {MVT::f32, MVT::f64}) { 1250 setOperationAction(ISD::FP_ROUND, VT, Custom); 1251 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1252 } 1253 1254 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1255 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1256 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1257 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1258 1259 // Lower following f128 select_cc pattern: 1260 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1261 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1262 1263 // We need to handle f128 SELECT_CC with integer result type. 1264 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1265 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1266 } 1267 1268 if (Subtarget.hasP9Altivec()) { 1269 if (Subtarget.isISA3_1()) { 1270 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 1271 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal); 1272 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal); 1273 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal); 1274 } else { 1275 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1276 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1277 } 1278 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1279 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1280 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1281 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1282 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1283 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1284 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1285 } 1286 1287 if (Subtarget.hasP10Vector()) { 1288 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1289 } 1290 } 1291 1292 if (Subtarget.pairedVectorMemops()) { 1293 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1294 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1295 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1296 } 1297 if (Subtarget.hasMMA()) { 1298 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1299 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1300 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1301 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1302 } 1303 1304 if (Subtarget.has64BitSupport()) 1305 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1306 1307 if (Subtarget.isISA3_1()) 1308 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1309 1310 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1311 1312 if (!isPPC64) { 1313 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1314 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1315 } 1316 1317 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) { 1318 setMaxAtomicSizeInBitsSupported(128); 1319 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 1320 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 1321 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom); 1322 } 1323 1324 setBooleanContents(ZeroOrOneBooleanContent); 1325 1326 if (Subtarget.hasAltivec()) { 1327 // Altivec instructions set fields to all zeros or all ones. 1328 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1329 } 1330 1331 if (!isPPC64) { 1332 // These libcalls are not available in 32-bit. 1333 setLibcallName(RTLIB::SHL_I128, nullptr); 1334 setLibcallName(RTLIB::SRL_I128, nullptr); 1335 setLibcallName(RTLIB::SRA_I128, nullptr); 1336 setLibcallName(RTLIB::MULO_I64, nullptr); 1337 } 1338 1339 if (!isPPC64) 1340 setMaxAtomicSizeInBitsSupported(32); 1341 1342 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1343 1344 // We have target-specific dag combine patterns for the following nodes: 1345 setTargetDAGCombine(ISD::ADD); 1346 setTargetDAGCombine(ISD::SHL); 1347 setTargetDAGCombine(ISD::SRA); 1348 setTargetDAGCombine(ISD::SRL); 1349 setTargetDAGCombine(ISD::MUL); 1350 setTargetDAGCombine(ISD::FMA); 1351 setTargetDAGCombine(ISD::SINT_TO_FP); 1352 setTargetDAGCombine(ISD::BUILD_VECTOR); 1353 if (Subtarget.hasFPCVT()) 1354 setTargetDAGCombine(ISD::UINT_TO_FP); 1355 setTargetDAGCombine(ISD::LOAD); 1356 setTargetDAGCombine(ISD::STORE); 1357 setTargetDAGCombine(ISD::BR_CC); 1358 if (Subtarget.useCRBits()) 1359 setTargetDAGCombine(ISD::BRCOND); 1360 setTargetDAGCombine(ISD::BSWAP); 1361 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1362 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1363 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1364 1365 setTargetDAGCombine(ISD::SIGN_EXTEND); 1366 setTargetDAGCombine(ISD::ZERO_EXTEND); 1367 setTargetDAGCombine(ISD::ANY_EXTEND); 1368 1369 setTargetDAGCombine(ISD::TRUNCATE); 1370 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1371 1372 1373 if (Subtarget.useCRBits()) { 1374 setTargetDAGCombine(ISD::TRUNCATE); 1375 setTargetDAGCombine(ISD::SETCC); 1376 setTargetDAGCombine(ISD::SELECT_CC); 1377 } 1378 1379 if (Subtarget.hasP9Altivec()) { 1380 setTargetDAGCombine(ISD::ABS); 1381 setTargetDAGCombine(ISD::VSELECT); 1382 } 1383 1384 setLibcallName(RTLIB::LOG_F128, "logf128"); 1385 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1386 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1387 setLibcallName(RTLIB::EXP_F128, "expf128"); 1388 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1389 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1390 setLibcallName(RTLIB::COS_F128, "cosf128"); 1391 setLibcallName(RTLIB::POW_F128, "powf128"); 1392 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1393 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1394 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1395 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1396 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1397 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1398 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1399 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1400 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1401 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1402 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1403 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1404 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1405 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1406 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1407 1408 // With 32 condition bits, we don't need to sink (and duplicate) compares 1409 // aggressively in CodeGenPrep. 1410 if (Subtarget.useCRBits()) { 1411 setHasMultipleConditionRegisters(); 1412 setJumpIsExpensive(); 1413 } 1414 1415 setMinFunctionAlignment(Align(4)); 1416 1417 switch (Subtarget.getCPUDirective()) { 1418 default: break; 1419 case PPC::DIR_970: 1420 case PPC::DIR_A2: 1421 case PPC::DIR_E500: 1422 case PPC::DIR_E500mc: 1423 case PPC::DIR_E5500: 1424 case PPC::DIR_PWR4: 1425 case PPC::DIR_PWR5: 1426 case PPC::DIR_PWR5X: 1427 case PPC::DIR_PWR6: 1428 case PPC::DIR_PWR6X: 1429 case PPC::DIR_PWR7: 1430 case PPC::DIR_PWR8: 1431 case PPC::DIR_PWR9: 1432 case PPC::DIR_PWR10: 1433 case PPC::DIR_PWR_FUTURE: 1434 setPrefLoopAlignment(Align(16)); 1435 setPrefFunctionAlignment(Align(16)); 1436 break; 1437 } 1438 1439 if (Subtarget.enableMachineScheduler()) 1440 setSchedulingPreference(Sched::Source); 1441 else 1442 setSchedulingPreference(Sched::Hybrid); 1443 1444 computeRegisterProperties(STI.getRegisterInfo()); 1445 1446 // The Freescale cores do better with aggressive inlining of memcpy and 1447 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1448 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1449 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1450 MaxStoresPerMemset = 32; 1451 MaxStoresPerMemsetOptSize = 16; 1452 MaxStoresPerMemcpy = 32; 1453 MaxStoresPerMemcpyOptSize = 8; 1454 MaxStoresPerMemmove = 32; 1455 MaxStoresPerMemmoveOptSize = 8; 1456 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1457 // The A2 also benefits from (very) aggressive inlining of memcpy and 1458 // friends. The overhead of a the function call, even when warm, can be 1459 // over one hundred cycles. 1460 MaxStoresPerMemset = 128; 1461 MaxStoresPerMemcpy = 128; 1462 MaxStoresPerMemmove = 128; 1463 MaxLoadsPerMemcmp = 128; 1464 } else { 1465 MaxLoadsPerMemcmp = 8; 1466 MaxLoadsPerMemcmpOptSize = 4; 1467 } 1468 1469 IsStrictFPEnabled = true; 1470 1471 // Let the subtarget (CPU) decide if a predictable select is more expensive 1472 // than the corresponding branch. This information is used in CGP to decide 1473 // when to convert selects into branches. 1474 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1475 } 1476 1477 // *********************************** NOTE ************************************ 1478 // For selecting load and store instructions, the addressing modes are defined 1479 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD 1480 // patterns to match the load the store instructions. 1481 // 1482 // The TD definitions for the addressing modes correspond to their respective 1483 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely 1484 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the 1485 // address mode flags of a particular node. Afterwards, the computed address 1486 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal 1487 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement 1488 // accordingly, based on the preferred addressing mode. 1489 // 1490 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode. 1491 // MemOpFlags contains all the possible flags that can be used to compute the 1492 // optimal addressing mode for load and store instructions. 1493 // AddrMode contains all the possible load and store addressing modes available 1494 // on Power (such as DForm, DSForm, DQForm, XForm, etc.) 1495 // 1496 // When adding new load and store instructions, it is possible that new address 1497 // flags may need to be added into MemOpFlags, and a new addressing mode will 1498 // need to be added to AddrMode. An entry of the new addressing mode (consisting 1499 // of the minimal and main distinguishing address flags for the new load/store 1500 // instructions) will need to be added into initializeAddrModeMap() below. 1501 // Finally, when adding new addressing modes, the getAddrModeForFlags() will 1502 // need to be updated to account for selecting the optimal addressing mode. 1503 // ***************************************************************************** 1504 /// Initialize the map that relates the different addressing modes of the load 1505 /// and store instructions to a set of flags. This ensures the load/store 1506 /// instruction is correctly matched during instruction selection. 1507 void PPCTargetLowering::initializeAddrModeMap() { 1508 AddrModesMap[PPC::AM_DForm] = { 1509 // LWZ, STW 1510 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt, 1511 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt, 1512 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1513 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1514 // LBZ, LHZ, STB, STH 1515 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1516 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1517 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1518 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1519 // LHA 1520 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1521 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1522 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1523 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1524 // LFS, LFD, STFS, STFD 1525 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1526 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1527 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1528 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1529 }; 1530 AddrModesMap[PPC::AM_DSForm] = { 1531 // LWA 1532 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt, 1533 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1534 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1535 // LD, STD 1536 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt, 1537 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt, 1538 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt, 1539 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64 1540 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1541 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1542 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1543 }; 1544 AddrModesMap[PPC::AM_DQForm] = { 1545 // LXV, STXV 1546 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1547 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1548 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1549 }; 1550 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 | 1551 PPC::MOF_SubtargetP10}; 1552 // TODO: Add mapping for quadword load/store. 1553 } 1554 1555 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1556 /// the desired ByVal argument alignment. 1557 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1558 if (MaxAlign == MaxMaxAlign) 1559 return; 1560 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1561 if (MaxMaxAlign >= 32 && 1562 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1563 MaxAlign = Align(32); 1564 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1565 MaxAlign < 16) 1566 MaxAlign = Align(16); 1567 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1568 Align EltAlign; 1569 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1570 if (EltAlign > MaxAlign) 1571 MaxAlign = EltAlign; 1572 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1573 for (auto *EltTy : STy->elements()) { 1574 Align EltAlign; 1575 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1576 if (EltAlign > MaxAlign) 1577 MaxAlign = EltAlign; 1578 if (MaxAlign == MaxMaxAlign) 1579 break; 1580 } 1581 } 1582 } 1583 1584 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1585 /// function arguments in the caller parameter area. 1586 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1587 const DataLayout &DL) const { 1588 // 16byte and wider vectors are passed on 16byte boundary. 1589 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1590 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1591 if (Subtarget.hasAltivec()) 1592 getMaxByValAlign(Ty, Alignment, Align(16)); 1593 return Alignment.value(); 1594 } 1595 1596 bool PPCTargetLowering::useSoftFloat() const { 1597 return Subtarget.useSoftFloat(); 1598 } 1599 1600 bool PPCTargetLowering::hasSPE() const { 1601 return Subtarget.hasSPE(); 1602 } 1603 1604 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1605 return VT.isScalarInteger(); 1606 } 1607 1608 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1609 switch ((PPCISD::NodeType)Opcode) { 1610 case PPCISD::FIRST_NUMBER: break; 1611 case PPCISD::FSEL: return "PPCISD::FSEL"; 1612 case PPCISD::XSMAXC: return "PPCISD::XSMAXC"; 1613 case PPCISD::XSMINC: return "PPCISD::XSMINC"; 1614 case PPCISD::FCFID: return "PPCISD::FCFID"; 1615 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1616 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1617 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1618 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1619 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1620 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1621 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1622 case PPCISD::FP_TO_UINT_IN_VSR: 1623 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1624 case PPCISD::FP_TO_SINT_IN_VSR: 1625 return "PPCISD::FP_TO_SINT_IN_VSR"; 1626 case PPCISD::FRE: return "PPCISD::FRE"; 1627 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1628 case PPCISD::FTSQRT: 1629 return "PPCISD::FTSQRT"; 1630 case PPCISD::FSQRT: 1631 return "PPCISD::FSQRT"; 1632 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1633 case PPCISD::VPERM: return "PPCISD::VPERM"; 1634 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1635 case PPCISD::XXSPLTI_SP_TO_DP: 1636 return "PPCISD::XXSPLTI_SP_TO_DP"; 1637 case PPCISD::XXSPLTI32DX: 1638 return "PPCISD::XXSPLTI32DX"; 1639 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1640 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1641 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1642 case PPCISD::CMPB: return "PPCISD::CMPB"; 1643 case PPCISD::Hi: return "PPCISD::Hi"; 1644 case PPCISD::Lo: return "PPCISD::Lo"; 1645 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1646 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1647 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1648 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1649 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1650 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1651 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1652 case PPCISD::SRL: return "PPCISD::SRL"; 1653 case PPCISD::SRA: return "PPCISD::SRA"; 1654 case PPCISD::SHL: return "PPCISD::SHL"; 1655 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1656 case PPCISD::CALL: return "PPCISD::CALL"; 1657 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1658 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1659 case PPCISD::CALL_RM: 1660 return "PPCISD::CALL_RM"; 1661 case PPCISD::CALL_NOP_RM: 1662 return "PPCISD::CALL_NOP_RM"; 1663 case PPCISD::CALL_NOTOC_RM: 1664 return "PPCISD::CALL_NOTOC_RM"; 1665 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1666 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1667 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1668 case PPCISD::BCTRL_RM: 1669 return "PPCISD::BCTRL_RM"; 1670 case PPCISD::BCTRL_LOAD_TOC_RM: 1671 return "PPCISD::BCTRL_LOAD_TOC_RM"; 1672 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1673 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1674 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1675 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1676 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1677 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1678 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1679 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1680 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1681 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1682 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1683 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1684 case PPCISD::ANDI_rec_1_EQ_BIT: 1685 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1686 case PPCISD::ANDI_rec_1_GT_BIT: 1687 return "PPCISD::ANDI_rec_1_GT_BIT"; 1688 case PPCISD::VCMP: return "PPCISD::VCMP"; 1689 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1690 case PPCISD::LBRX: return "PPCISD::LBRX"; 1691 case PPCISD::STBRX: return "PPCISD::STBRX"; 1692 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1693 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1694 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1695 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1696 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1697 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1698 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1699 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1700 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1701 case PPCISD::ST_VSR_SCAL_INT: 1702 return "PPCISD::ST_VSR_SCAL_INT"; 1703 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1704 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1705 case PPCISD::BDZ: return "PPCISD::BDZ"; 1706 case PPCISD::MFFS: return "PPCISD::MFFS"; 1707 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1708 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1709 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1710 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1711 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1712 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1713 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1714 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1715 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1716 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1717 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1718 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1719 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1720 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1721 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1722 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1723 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1724 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1725 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1726 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1727 case PPCISD::PADDI_DTPREL: 1728 return "PPCISD::PADDI_DTPREL"; 1729 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1730 case PPCISD::SC: return "PPCISD::SC"; 1731 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1732 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1733 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1734 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1735 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1736 case PPCISD::VABSD: return "PPCISD::VABSD"; 1737 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1738 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1739 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1740 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1741 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1742 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1743 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1744 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1745 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1746 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1747 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1748 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1749 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1750 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1751 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1752 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1753 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT"; 1754 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT"; 1755 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1756 case PPCISD::STRICT_FADDRTZ: 1757 return "PPCISD::STRICT_FADDRTZ"; 1758 case PPCISD::STRICT_FCTIDZ: 1759 return "PPCISD::STRICT_FCTIDZ"; 1760 case PPCISD::STRICT_FCTIWZ: 1761 return "PPCISD::STRICT_FCTIWZ"; 1762 case PPCISD::STRICT_FCTIDUZ: 1763 return "PPCISD::STRICT_FCTIDUZ"; 1764 case PPCISD::STRICT_FCTIWUZ: 1765 return "PPCISD::STRICT_FCTIWUZ"; 1766 case PPCISD::STRICT_FCFID: 1767 return "PPCISD::STRICT_FCFID"; 1768 case PPCISD::STRICT_FCFIDU: 1769 return "PPCISD::STRICT_FCFIDU"; 1770 case PPCISD::STRICT_FCFIDS: 1771 return "PPCISD::STRICT_FCFIDS"; 1772 case PPCISD::STRICT_FCFIDUS: 1773 return "PPCISD::STRICT_FCFIDUS"; 1774 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1775 } 1776 return nullptr; 1777 } 1778 1779 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1780 EVT VT) const { 1781 if (!VT.isVector()) 1782 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1783 1784 return VT.changeVectorElementTypeToInteger(); 1785 } 1786 1787 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1788 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1789 return true; 1790 } 1791 1792 //===----------------------------------------------------------------------===// 1793 // Node matching predicates, for use by the tblgen matching code. 1794 //===----------------------------------------------------------------------===// 1795 1796 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1797 static bool isFloatingPointZero(SDValue Op) { 1798 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1799 return CFP->getValueAPF().isZero(); 1800 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1801 // Maybe this has already been legalized into the constant pool? 1802 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1803 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1804 return CFP->getValueAPF().isZero(); 1805 } 1806 return false; 1807 } 1808 1809 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1810 /// true if Op is undef or if it matches the specified value. 1811 static bool isConstantOrUndef(int Op, int Val) { 1812 return Op < 0 || Op == Val; 1813 } 1814 1815 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1816 /// VPKUHUM instruction. 1817 /// The ShuffleKind distinguishes between big-endian operations with 1818 /// two different inputs (0), either-endian operations with two identical 1819 /// inputs (1), and little-endian operations with two different inputs (2). 1820 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1821 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1822 SelectionDAG &DAG) { 1823 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1824 if (ShuffleKind == 0) { 1825 if (IsLE) 1826 return false; 1827 for (unsigned i = 0; i != 16; ++i) 1828 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1829 return false; 1830 } else if (ShuffleKind == 2) { 1831 if (!IsLE) 1832 return false; 1833 for (unsigned i = 0; i != 16; ++i) 1834 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1835 return false; 1836 } else if (ShuffleKind == 1) { 1837 unsigned j = IsLE ? 0 : 1; 1838 for (unsigned i = 0; i != 8; ++i) 1839 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1840 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1841 return false; 1842 } 1843 return true; 1844 } 1845 1846 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1847 /// VPKUWUM instruction. 1848 /// The ShuffleKind distinguishes between big-endian operations with 1849 /// two different inputs (0), either-endian operations with two identical 1850 /// inputs (1), and little-endian operations with two different inputs (2). 1851 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1852 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1853 SelectionDAG &DAG) { 1854 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1855 if (ShuffleKind == 0) { 1856 if (IsLE) 1857 return false; 1858 for (unsigned i = 0; i != 16; i += 2) 1859 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1860 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1861 return false; 1862 } else if (ShuffleKind == 2) { 1863 if (!IsLE) 1864 return false; 1865 for (unsigned i = 0; i != 16; i += 2) 1866 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1867 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1868 return false; 1869 } else if (ShuffleKind == 1) { 1870 unsigned j = IsLE ? 0 : 2; 1871 for (unsigned i = 0; i != 8; i += 2) 1872 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1873 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1874 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1875 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1876 return false; 1877 } 1878 return true; 1879 } 1880 1881 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1882 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1883 /// current subtarget. 1884 /// 1885 /// The ShuffleKind distinguishes between big-endian operations with 1886 /// two different inputs (0), either-endian operations with two identical 1887 /// inputs (1), and little-endian operations with two different inputs (2). 1888 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1889 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1890 SelectionDAG &DAG) { 1891 const PPCSubtarget& Subtarget = 1892 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1893 if (!Subtarget.hasP8Vector()) 1894 return false; 1895 1896 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1897 if (ShuffleKind == 0) { 1898 if (IsLE) 1899 return false; 1900 for (unsigned i = 0; i != 16; i += 4) 1901 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1902 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1903 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1904 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1905 return false; 1906 } else if (ShuffleKind == 2) { 1907 if (!IsLE) 1908 return false; 1909 for (unsigned i = 0; i != 16; i += 4) 1910 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1911 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1912 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1913 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1914 return false; 1915 } else if (ShuffleKind == 1) { 1916 unsigned j = IsLE ? 0 : 4; 1917 for (unsigned i = 0; i != 8; i += 4) 1918 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1919 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1920 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1921 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1922 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1923 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1924 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1925 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1926 return false; 1927 } 1928 return true; 1929 } 1930 1931 /// isVMerge - Common function, used to match vmrg* shuffles. 1932 /// 1933 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1934 unsigned LHSStart, unsigned RHSStart) { 1935 if (N->getValueType(0) != MVT::v16i8) 1936 return false; 1937 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1938 "Unsupported merge size!"); 1939 1940 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1941 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1942 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1943 LHSStart+j+i*UnitSize) || 1944 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1945 RHSStart+j+i*UnitSize)) 1946 return false; 1947 } 1948 return true; 1949 } 1950 1951 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1952 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1953 /// The ShuffleKind distinguishes between big-endian merges with two 1954 /// different inputs (0), either-endian merges with two identical inputs (1), 1955 /// and little-endian merges with two different inputs (2). For the latter, 1956 /// the input operands are swapped (see PPCInstrAltivec.td). 1957 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1958 unsigned ShuffleKind, SelectionDAG &DAG) { 1959 if (DAG.getDataLayout().isLittleEndian()) { 1960 if (ShuffleKind == 1) // unary 1961 return isVMerge(N, UnitSize, 0, 0); 1962 else if (ShuffleKind == 2) // swapped 1963 return isVMerge(N, UnitSize, 0, 16); 1964 else 1965 return false; 1966 } else { 1967 if (ShuffleKind == 1) // unary 1968 return isVMerge(N, UnitSize, 8, 8); 1969 else if (ShuffleKind == 0) // normal 1970 return isVMerge(N, UnitSize, 8, 24); 1971 else 1972 return false; 1973 } 1974 } 1975 1976 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1977 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1978 /// The ShuffleKind distinguishes between big-endian merges with two 1979 /// different inputs (0), either-endian merges with two identical inputs (1), 1980 /// and little-endian merges with two different inputs (2). For the latter, 1981 /// the input operands are swapped (see PPCInstrAltivec.td). 1982 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1983 unsigned ShuffleKind, SelectionDAG &DAG) { 1984 if (DAG.getDataLayout().isLittleEndian()) { 1985 if (ShuffleKind == 1) // unary 1986 return isVMerge(N, UnitSize, 8, 8); 1987 else if (ShuffleKind == 2) // swapped 1988 return isVMerge(N, UnitSize, 8, 24); 1989 else 1990 return false; 1991 } else { 1992 if (ShuffleKind == 1) // unary 1993 return isVMerge(N, UnitSize, 0, 0); 1994 else if (ShuffleKind == 0) // normal 1995 return isVMerge(N, UnitSize, 0, 16); 1996 else 1997 return false; 1998 } 1999 } 2000 2001 /** 2002 * Common function used to match vmrgew and vmrgow shuffles 2003 * 2004 * The indexOffset determines whether to look for even or odd words in 2005 * the shuffle mask. This is based on the of the endianness of the target 2006 * machine. 2007 * - Little Endian: 2008 * - Use offset of 0 to check for odd elements 2009 * - Use offset of 4 to check for even elements 2010 * - Big Endian: 2011 * - Use offset of 0 to check for even elements 2012 * - Use offset of 4 to check for odd elements 2013 * A detailed description of the vector element ordering for little endian and 2014 * big endian can be found at 2015 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 2016 * Targeting your applications - what little endian and big endian IBM XL C/C++ 2017 * compiler differences mean to you 2018 * 2019 * The mask to the shuffle vector instruction specifies the indices of the 2020 * elements from the two input vectors to place in the result. The elements are 2021 * numbered in array-access order, starting with the first vector. These vectors 2022 * are always of type v16i8, thus each vector will contain 16 elements of size 2023 * 8. More info on the shuffle vector can be found in the 2024 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 2025 * Language Reference. 2026 * 2027 * The RHSStartValue indicates whether the same input vectors are used (unary) 2028 * or two different input vectors are used, based on the following: 2029 * - If the instruction uses the same vector for both inputs, the range of the 2030 * indices will be 0 to 15. In this case, the RHSStart value passed should 2031 * be 0. 2032 * - If the instruction has two different vectors then the range of the 2033 * indices will be 0 to 31. In this case, the RHSStart value passed should 2034 * be 16 (indices 0-15 specify elements in the first vector while indices 16 2035 * to 31 specify elements in the second vector). 2036 * 2037 * \param[in] N The shuffle vector SD Node to analyze 2038 * \param[in] IndexOffset Specifies whether to look for even or odd elements 2039 * \param[in] RHSStartValue Specifies the starting index for the righthand input 2040 * vector to the shuffle_vector instruction 2041 * \return true iff this shuffle vector represents an even or odd word merge 2042 */ 2043 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 2044 unsigned RHSStartValue) { 2045 if (N->getValueType(0) != MVT::v16i8) 2046 return false; 2047 2048 for (unsigned i = 0; i < 2; ++i) 2049 for (unsigned j = 0; j < 4; ++j) 2050 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 2051 i*RHSStartValue+j+IndexOffset) || 2052 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2053 i*RHSStartValue+j+IndexOffset+8)) 2054 return false; 2055 return true; 2056 } 2057 2058 /** 2059 * Determine if the specified shuffle mask is suitable for the vmrgew or 2060 * vmrgow instructions. 2061 * 2062 * \param[in] N The shuffle vector SD Node to analyze 2063 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2064 * \param[in] ShuffleKind Identify the type of merge: 2065 * - 0 = big-endian merge with two different inputs; 2066 * - 1 = either-endian merge with two identical inputs; 2067 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2068 * little-endian merges). 2069 * \param[in] DAG The current SelectionDAG 2070 * \return true iff this shuffle mask 2071 */ 2072 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2073 unsigned ShuffleKind, SelectionDAG &DAG) { 2074 if (DAG.getDataLayout().isLittleEndian()) { 2075 unsigned indexOffset = CheckEven ? 4 : 0; 2076 if (ShuffleKind == 1) // Unary 2077 return isVMerge(N, indexOffset, 0); 2078 else if (ShuffleKind == 2) // swapped 2079 return isVMerge(N, indexOffset, 16); 2080 else 2081 return false; 2082 } 2083 else { 2084 unsigned indexOffset = CheckEven ? 0 : 4; 2085 if (ShuffleKind == 1) // Unary 2086 return isVMerge(N, indexOffset, 0); 2087 else if (ShuffleKind == 0) // Normal 2088 return isVMerge(N, indexOffset, 16); 2089 else 2090 return false; 2091 } 2092 return false; 2093 } 2094 2095 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2096 /// amount, otherwise return -1. 2097 /// The ShuffleKind distinguishes between big-endian operations with two 2098 /// different inputs (0), either-endian operations with two identical inputs 2099 /// (1), and little-endian operations with two different inputs (2). For the 2100 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2101 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2102 SelectionDAG &DAG) { 2103 if (N->getValueType(0) != MVT::v16i8) 2104 return -1; 2105 2106 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2107 2108 // Find the first non-undef value in the shuffle mask. 2109 unsigned i; 2110 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2111 /*search*/; 2112 2113 if (i == 16) return -1; // all undef. 2114 2115 // Otherwise, check to see if the rest of the elements are consecutively 2116 // numbered from this value. 2117 unsigned ShiftAmt = SVOp->getMaskElt(i); 2118 if (ShiftAmt < i) return -1; 2119 2120 ShiftAmt -= i; 2121 bool isLE = DAG.getDataLayout().isLittleEndian(); 2122 2123 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2124 // Check the rest of the elements to see if they are consecutive. 2125 for (++i; i != 16; ++i) 2126 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2127 return -1; 2128 } else if (ShuffleKind == 1) { 2129 // Check the rest of the elements to see if they are consecutive. 2130 for (++i; i != 16; ++i) 2131 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2132 return -1; 2133 } else 2134 return -1; 2135 2136 if (isLE) 2137 ShiftAmt = 16 - ShiftAmt; 2138 2139 return ShiftAmt; 2140 } 2141 2142 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2143 /// specifies a splat of a single element that is suitable for input to 2144 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2145 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2146 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 2147 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2148 2149 // The consecutive indices need to specify an element, not part of two 2150 // different elements. So abandon ship early if this isn't the case. 2151 if (N->getMaskElt(0) % EltSize != 0) 2152 return false; 2153 2154 // This is a splat operation if each element of the permute is the same, and 2155 // if the value doesn't reference the second vector. 2156 unsigned ElementBase = N->getMaskElt(0); 2157 2158 // FIXME: Handle UNDEF elements too! 2159 if (ElementBase >= 16) 2160 return false; 2161 2162 // Check that the indices are consecutive, in the case of a multi-byte element 2163 // splatted with a v16i8 mask. 2164 for (unsigned i = 1; i != EltSize; ++i) 2165 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2166 return false; 2167 2168 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2169 if (N->getMaskElt(i) < 0) continue; 2170 for (unsigned j = 0; j != EltSize; ++j) 2171 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2172 return false; 2173 } 2174 return true; 2175 } 2176 2177 /// Check that the mask is shuffling N byte elements. Within each N byte 2178 /// element of the mask, the indices could be either in increasing or 2179 /// decreasing order as long as they are consecutive. 2180 /// \param[in] N the shuffle vector SD Node to analyze 2181 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2182 /// Word/DoubleWord/QuadWord). 2183 /// \param[in] StepLen the delta indices number among the N byte element, if 2184 /// the mask is in increasing/decreasing order then it is 1/-1. 2185 /// \return true iff the mask is shuffling N byte elements. 2186 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2187 int StepLen) { 2188 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2189 "Unexpected element width."); 2190 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2191 2192 unsigned NumOfElem = 16 / Width; 2193 unsigned MaskVal[16]; // Width is never greater than 16 2194 for (unsigned i = 0; i < NumOfElem; ++i) { 2195 MaskVal[0] = N->getMaskElt(i * Width); 2196 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2197 return false; 2198 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2199 return false; 2200 } 2201 2202 for (unsigned int j = 1; j < Width; ++j) { 2203 MaskVal[j] = N->getMaskElt(i * Width + j); 2204 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2205 return false; 2206 } 2207 } 2208 } 2209 2210 return true; 2211 } 2212 2213 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2214 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2215 if (!isNByteElemShuffleMask(N, 4, 1)) 2216 return false; 2217 2218 // Now we look at mask elements 0,4,8,12 2219 unsigned M0 = N->getMaskElt(0) / 4; 2220 unsigned M1 = N->getMaskElt(4) / 4; 2221 unsigned M2 = N->getMaskElt(8) / 4; 2222 unsigned M3 = N->getMaskElt(12) / 4; 2223 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2224 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2225 2226 // Below, let H and L be arbitrary elements of the shuffle mask 2227 // where H is in the range [4,7] and L is in the range [0,3]. 2228 // H, 1, 2, 3 or L, 5, 6, 7 2229 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2230 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2231 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2232 InsertAtByte = IsLE ? 12 : 0; 2233 Swap = M0 < 4; 2234 return true; 2235 } 2236 // 0, H, 2, 3 or 4, L, 6, 7 2237 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2238 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2239 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2240 InsertAtByte = IsLE ? 8 : 4; 2241 Swap = M1 < 4; 2242 return true; 2243 } 2244 // 0, 1, H, 3 or 4, 5, L, 7 2245 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2246 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2247 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2248 InsertAtByte = IsLE ? 4 : 8; 2249 Swap = M2 < 4; 2250 return true; 2251 } 2252 // 0, 1, 2, H or 4, 5, 6, L 2253 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2254 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2255 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2256 InsertAtByte = IsLE ? 0 : 12; 2257 Swap = M3 < 4; 2258 return true; 2259 } 2260 2261 // If both vector operands for the shuffle are the same vector, the mask will 2262 // contain only elements from the first one and the second one will be undef. 2263 if (N->getOperand(1).isUndef()) { 2264 ShiftElts = 0; 2265 Swap = true; 2266 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2267 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2268 InsertAtByte = IsLE ? 12 : 0; 2269 return true; 2270 } 2271 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2272 InsertAtByte = IsLE ? 8 : 4; 2273 return true; 2274 } 2275 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2276 InsertAtByte = IsLE ? 4 : 8; 2277 return true; 2278 } 2279 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2280 InsertAtByte = IsLE ? 0 : 12; 2281 return true; 2282 } 2283 } 2284 2285 return false; 2286 } 2287 2288 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2289 bool &Swap, bool IsLE) { 2290 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2291 // Ensure each byte index of the word is consecutive. 2292 if (!isNByteElemShuffleMask(N, 4, 1)) 2293 return false; 2294 2295 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2296 unsigned M0 = N->getMaskElt(0) / 4; 2297 unsigned M1 = N->getMaskElt(4) / 4; 2298 unsigned M2 = N->getMaskElt(8) / 4; 2299 unsigned M3 = N->getMaskElt(12) / 4; 2300 2301 // If both vector operands for the shuffle are the same vector, the mask will 2302 // contain only elements from the first one and the second one will be undef. 2303 if (N->getOperand(1).isUndef()) { 2304 assert(M0 < 4 && "Indexing into an undef vector?"); 2305 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2306 return false; 2307 2308 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2309 Swap = false; 2310 return true; 2311 } 2312 2313 // Ensure each word index of the ShuffleVector Mask is consecutive. 2314 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2315 return false; 2316 2317 if (IsLE) { 2318 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2319 // Input vectors don't need to be swapped if the leading element 2320 // of the result is one of the 3 left elements of the second vector 2321 // (or if there is no shift to be done at all). 2322 Swap = false; 2323 ShiftElts = (8 - M0) % 8; 2324 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2325 // Input vectors need to be swapped if the leading element 2326 // of the result is one of the 3 left elements of the first vector 2327 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2328 Swap = true; 2329 ShiftElts = (4 - M0) % 4; 2330 } 2331 2332 return true; 2333 } else { // BE 2334 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2335 // Input vectors don't need to be swapped if the leading element 2336 // of the result is one of the 4 elements of the first vector. 2337 Swap = false; 2338 ShiftElts = M0; 2339 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2340 // Input vectors need to be swapped if the leading element 2341 // of the result is one of the 4 elements of the right vector. 2342 Swap = true; 2343 ShiftElts = M0 - 4; 2344 } 2345 2346 return true; 2347 } 2348 } 2349 2350 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2351 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2352 2353 if (!isNByteElemShuffleMask(N, Width, -1)) 2354 return false; 2355 2356 for (int i = 0; i < 16; i += Width) 2357 if (N->getMaskElt(i) != i + Width - 1) 2358 return false; 2359 2360 return true; 2361 } 2362 2363 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2364 return isXXBRShuffleMaskHelper(N, 2); 2365 } 2366 2367 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2368 return isXXBRShuffleMaskHelper(N, 4); 2369 } 2370 2371 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2372 return isXXBRShuffleMaskHelper(N, 8); 2373 } 2374 2375 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2376 return isXXBRShuffleMaskHelper(N, 16); 2377 } 2378 2379 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2380 /// if the inputs to the instruction should be swapped and set \p DM to the 2381 /// value for the immediate. 2382 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2383 /// AND element 0 of the result comes from the first input (LE) or second input 2384 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2385 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2386 /// mask. 2387 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2388 bool &Swap, bool IsLE) { 2389 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2390 2391 // Ensure each byte index of the double word is consecutive. 2392 if (!isNByteElemShuffleMask(N, 8, 1)) 2393 return false; 2394 2395 unsigned M0 = N->getMaskElt(0) / 8; 2396 unsigned M1 = N->getMaskElt(8) / 8; 2397 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2398 2399 // If both vector operands for the shuffle are the same vector, the mask will 2400 // contain only elements from the first one and the second one will be undef. 2401 if (N->getOperand(1).isUndef()) { 2402 if ((M0 | M1) < 2) { 2403 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2404 Swap = false; 2405 return true; 2406 } else 2407 return false; 2408 } 2409 2410 if (IsLE) { 2411 if (M0 > 1 && M1 < 2) { 2412 Swap = false; 2413 } else if (M0 < 2 && M1 > 1) { 2414 M0 = (M0 + 2) % 4; 2415 M1 = (M1 + 2) % 4; 2416 Swap = true; 2417 } else 2418 return false; 2419 2420 // Note: if control flow comes here that means Swap is already set above 2421 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2422 return true; 2423 } else { // BE 2424 if (M0 < 2 && M1 > 1) { 2425 Swap = false; 2426 } else if (M0 > 1 && M1 < 2) { 2427 M0 = (M0 + 2) % 4; 2428 M1 = (M1 + 2) % 4; 2429 Swap = true; 2430 } else 2431 return false; 2432 2433 // Note: if control flow comes here that means Swap is already set above 2434 DM = (M0 << 1) + (M1 & 1); 2435 return true; 2436 } 2437 } 2438 2439 2440 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2441 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2442 /// elements are counted from the left of the vector register). 2443 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2444 SelectionDAG &DAG) { 2445 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2446 assert(isSplatShuffleMask(SVOp, EltSize)); 2447 if (DAG.getDataLayout().isLittleEndian()) 2448 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2449 else 2450 return SVOp->getMaskElt(0) / EltSize; 2451 } 2452 2453 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2454 /// by using a vspltis[bhw] instruction of the specified element size, return 2455 /// the constant being splatted. The ByteSize field indicates the number of 2456 /// bytes of each element [124] -> [bhw]. 2457 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2458 SDValue OpVal; 2459 2460 // If ByteSize of the splat is bigger than the element size of the 2461 // build_vector, then we have a case where we are checking for a splat where 2462 // multiple elements of the buildvector are folded together into a single 2463 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2464 unsigned EltSize = 16/N->getNumOperands(); 2465 if (EltSize < ByteSize) { 2466 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2467 SDValue UniquedVals[4]; 2468 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2469 2470 // See if all of the elements in the buildvector agree across. 2471 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2472 if (N->getOperand(i).isUndef()) continue; 2473 // If the element isn't a constant, bail fully out. 2474 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2475 2476 if (!UniquedVals[i&(Multiple-1)].getNode()) 2477 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2478 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2479 return SDValue(); // no match. 2480 } 2481 2482 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2483 // either constant or undef values that are identical for each chunk. See 2484 // if these chunks can form into a larger vspltis*. 2485 2486 // Check to see if all of the leading entries are either 0 or -1. If 2487 // neither, then this won't fit into the immediate field. 2488 bool LeadingZero = true; 2489 bool LeadingOnes = true; 2490 for (unsigned i = 0; i != Multiple-1; ++i) { 2491 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2492 2493 LeadingZero &= isNullConstant(UniquedVals[i]); 2494 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2495 } 2496 // Finally, check the least significant entry. 2497 if (LeadingZero) { 2498 if (!UniquedVals[Multiple-1].getNode()) 2499 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2500 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2501 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2502 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2503 } 2504 if (LeadingOnes) { 2505 if (!UniquedVals[Multiple-1].getNode()) 2506 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2507 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2508 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2509 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2510 } 2511 2512 return SDValue(); 2513 } 2514 2515 // Check to see if this buildvec has a single non-undef value in its elements. 2516 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2517 if (N->getOperand(i).isUndef()) continue; 2518 if (!OpVal.getNode()) 2519 OpVal = N->getOperand(i); 2520 else if (OpVal != N->getOperand(i)) 2521 return SDValue(); 2522 } 2523 2524 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2525 2526 unsigned ValSizeInBytes = EltSize; 2527 uint64_t Value = 0; 2528 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2529 Value = CN->getZExtValue(); 2530 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2531 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2532 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2533 } 2534 2535 // If the splat value is larger than the element value, then we can never do 2536 // this splat. The only case that we could fit the replicated bits into our 2537 // immediate field for would be zero, and we prefer to use vxor for it. 2538 if (ValSizeInBytes < ByteSize) return SDValue(); 2539 2540 // If the element value is larger than the splat value, check if it consists 2541 // of a repeated bit pattern of size ByteSize. 2542 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2543 return SDValue(); 2544 2545 // Properly sign extend the value. 2546 int MaskVal = SignExtend32(Value, ByteSize * 8); 2547 2548 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2549 if (MaskVal == 0) return SDValue(); 2550 2551 // Finally, if this value fits in a 5 bit sext field, return it 2552 if (SignExtend32<5>(MaskVal) == MaskVal) 2553 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2554 return SDValue(); 2555 } 2556 2557 //===----------------------------------------------------------------------===// 2558 // Addressing Mode Selection 2559 //===----------------------------------------------------------------------===// 2560 2561 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2562 /// or 64-bit immediate, and if the value can be accurately represented as a 2563 /// sign extension from a 16-bit value. If so, this returns true and the 2564 /// immediate. 2565 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2566 if (!isa<ConstantSDNode>(N)) 2567 return false; 2568 2569 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2570 if (N->getValueType(0) == MVT::i32) 2571 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2572 else 2573 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2574 } 2575 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2576 return isIntS16Immediate(Op.getNode(), Imm); 2577 } 2578 2579 /// Used when computing address flags for selecting loads and stores. 2580 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2581 /// An OR of two provably disjoint values is equivalent to an ADD. 2582 /// Most PPC load/store instructions compute the effective address as a sum, 2583 /// so doing this conversion is useful. 2584 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2585 if (N.getOpcode() != ISD::OR) 2586 return false; 2587 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2588 if (!LHSKnown.Zero.getBoolValue()) 2589 return false; 2590 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2591 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2592 } 2593 2594 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2595 /// be represented as an indexed [r+r] operation. 2596 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2597 SDValue &Index, 2598 SelectionDAG &DAG) const { 2599 for (SDNode *U : N->uses()) { 2600 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) { 2601 if (Memop->getMemoryVT() == MVT::f64) { 2602 Base = N.getOperand(0); 2603 Index = N.getOperand(1); 2604 return true; 2605 } 2606 } 2607 } 2608 return false; 2609 } 2610 2611 /// isIntS34Immediate - This method tests if value of node given can be 2612 /// accurately represented as a sign extension from a 34-bit value. If so, 2613 /// this returns true and the immediate. 2614 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2615 if (!isa<ConstantSDNode>(N)) 2616 return false; 2617 2618 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2619 return isInt<34>(Imm); 2620 } 2621 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2622 return isIntS34Immediate(Op.getNode(), Imm); 2623 } 2624 2625 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2626 /// can be represented as an indexed [r+r] operation. Returns false if it 2627 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2628 /// non-zero and N can be represented by a base register plus a signed 16-bit 2629 /// displacement, make a more precise judgement by checking (displacement % \p 2630 /// EncodingAlignment). 2631 bool PPCTargetLowering::SelectAddressRegReg( 2632 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2633 MaybeAlign EncodingAlignment) const { 2634 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2635 // a [pc+imm]. 2636 if (SelectAddressPCRel(N, Base)) 2637 return false; 2638 2639 int16_t Imm = 0; 2640 if (N.getOpcode() == ISD::ADD) { 2641 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2642 // SPE load/store can only handle 8-bit offsets. 2643 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2644 return true; 2645 if (isIntS16Immediate(N.getOperand(1), Imm) && 2646 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2647 return false; // r+i 2648 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2649 return false; // r+i 2650 2651 Base = N.getOperand(0); 2652 Index = N.getOperand(1); 2653 return true; 2654 } else if (N.getOpcode() == ISD::OR) { 2655 if (isIntS16Immediate(N.getOperand(1), Imm) && 2656 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2657 return false; // r+i can fold it if we can. 2658 2659 // If this is an or of disjoint bitfields, we can codegen this as an add 2660 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2661 // disjoint. 2662 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2663 2664 if (LHSKnown.Zero.getBoolValue()) { 2665 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2666 // If all of the bits are known zero on the LHS or RHS, the add won't 2667 // carry. 2668 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2669 Base = N.getOperand(0); 2670 Index = N.getOperand(1); 2671 return true; 2672 } 2673 } 2674 } 2675 2676 return false; 2677 } 2678 2679 // If we happen to be doing an i64 load or store into a stack slot that has 2680 // less than a 4-byte alignment, then the frame-index elimination may need to 2681 // use an indexed load or store instruction (because the offset may not be a 2682 // multiple of 4). The extra register needed to hold the offset comes from the 2683 // register scavenger, and it is possible that the scavenger will need to use 2684 // an emergency spill slot. As a result, we need to make sure that a spill slot 2685 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2686 // stack slot. 2687 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2688 // FIXME: This does not handle the LWA case. 2689 if (VT != MVT::i64) 2690 return; 2691 2692 // NOTE: We'll exclude negative FIs here, which come from argument 2693 // lowering, because there are no known test cases triggering this problem 2694 // using packed structures (or similar). We can remove this exclusion if 2695 // we find such a test case. The reason why this is so test-case driven is 2696 // because this entire 'fixup' is only to prevent crashes (from the 2697 // register scavenger) on not-really-valid inputs. For example, if we have: 2698 // %a = alloca i1 2699 // %b = bitcast i1* %a to i64* 2700 // store i64* a, i64 b 2701 // then the store should really be marked as 'align 1', but is not. If it 2702 // were marked as 'align 1' then the indexed form would have been 2703 // instruction-selected initially, and the problem this 'fixup' is preventing 2704 // won't happen regardless. 2705 if (FrameIdx < 0) 2706 return; 2707 2708 MachineFunction &MF = DAG.getMachineFunction(); 2709 MachineFrameInfo &MFI = MF.getFrameInfo(); 2710 2711 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2712 return; 2713 2714 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2715 FuncInfo->setHasNonRISpills(); 2716 } 2717 2718 /// Returns true if the address N can be represented by a base register plus 2719 /// a signed 16-bit displacement [r+imm], and if it is not better 2720 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2721 /// displacements that are multiples of that value. 2722 bool PPCTargetLowering::SelectAddressRegImm( 2723 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2724 MaybeAlign EncodingAlignment) const { 2725 // FIXME dl should come from parent load or store, not from address 2726 SDLoc dl(N); 2727 2728 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2729 // a [pc+imm]. 2730 if (SelectAddressPCRel(N, Base)) 2731 return false; 2732 2733 // If this can be more profitably realized as r+r, fail. 2734 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2735 return false; 2736 2737 if (N.getOpcode() == ISD::ADD) { 2738 int16_t imm = 0; 2739 if (isIntS16Immediate(N.getOperand(1), imm) && 2740 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2741 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2742 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2743 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2744 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2745 } else { 2746 Base = N.getOperand(0); 2747 } 2748 return true; // [r+i] 2749 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2750 // Match LOAD (ADD (X, Lo(G))). 2751 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2752 && "Cannot handle constant offsets yet!"); 2753 Disp = N.getOperand(1).getOperand(0); // The global address. 2754 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2755 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2756 Disp.getOpcode() == ISD::TargetConstantPool || 2757 Disp.getOpcode() == ISD::TargetJumpTable); 2758 Base = N.getOperand(0); 2759 return true; // [&g+r] 2760 } 2761 } else if (N.getOpcode() == ISD::OR) { 2762 int16_t imm = 0; 2763 if (isIntS16Immediate(N.getOperand(1), imm) && 2764 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2765 // If this is an or of disjoint bitfields, we can codegen this as an add 2766 // (for better address arithmetic) if the LHS and RHS of the OR are 2767 // provably disjoint. 2768 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2769 2770 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2771 // If all of the bits are known zero on the LHS or RHS, the add won't 2772 // carry. 2773 if (FrameIndexSDNode *FI = 2774 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2775 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2776 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2777 } else { 2778 Base = N.getOperand(0); 2779 } 2780 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2781 return true; 2782 } 2783 } 2784 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2785 // Loading from a constant address. 2786 2787 // If this address fits entirely in a 16-bit sext immediate field, codegen 2788 // this as "d, 0" 2789 int16_t Imm; 2790 if (isIntS16Immediate(CN, Imm) && 2791 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2792 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2793 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2794 CN->getValueType(0)); 2795 return true; 2796 } 2797 2798 // Handle 32-bit sext immediates with LIS + addr mode. 2799 if ((CN->getValueType(0) == MVT::i32 || 2800 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2801 (!EncodingAlignment || 2802 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2803 int Addr = (int)CN->getZExtValue(); 2804 2805 // Otherwise, break this down into an LIS + disp. 2806 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2807 2808 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2809 MVT::i32); 2810 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2811 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2812 return true; 2813 } 2814 } 2815 2816 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2817 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2818 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2819 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2820 } else 2821 Base = N; 2822 return true; // [r+0] 2823 } 2824 2825 /// Similar to the 16-bit case but for instructions that take a 34-bit 2826 /// displacement field (prefixed loads/stores). 2827 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2828 SDValue &Base, 2829 SelectionDAG &DAG) const { 2830 // Only on 64-bit targets. 2831 if (N.getValueType() != MVT::i64) 2832 return false; 2833 2834 SDLoc dl(N); 2835 int64_t Imm = 0; 2836 2837 if (N.getOpcode() == ISD::ADD) { 2838 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2839 return false; 2840 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2841 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2842 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2843 else 2844 Base = N.getOperand(0); 2845 return true; 2846 } 2847 2848 if (N.getOpcode() == ISD::OR) { 2849 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2850 return false; 2851 // If this is an or of disjoint bitfields, we can codegen this as an add 2852 // (for better address arithmetic) if the LHS and RHS of the OR are 2853 // provably disjoint. 2854 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2855 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2856 return false; 2857 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2858 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2859 else 2860 Base = N.getOperand(0); 2861 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2862 return true; 2863 } 2864 2865 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2866 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2867 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2868 return true; 2869 } 2870 2871 return false; 2872 } 2873 2874 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2875 /// represented as an indexed [r+r] operation. 2876 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2877 SDValue &Index, 2878 SelectionDAG &DAG) const { 2879 // Check to see if we can easily represent this as an [r+r] address. This 2880 // will fail if it thinks that the address is more profitably represented as 2881 // reg+imm, e.g. where imm = 0. 2882 if (SelectAddressRegReg(N, Base, Index, DAG)) 2883 return true; 2884 2885 // If the address is the result of an add, we will utilize the fact that the 2886 // address calculation includes an implicit add. However, we can reduce 2887 // register pressure if we do not materialize a constant just for use as the 2888 // index register. We only get rid of the add if it is not an add of a 2889 // value and a 16-bit signed constant and both have a single use. 2890 int16_t imm = 0; 2891 if (N.getOpcode() == ISD::ADD && 2892 (!isIntS16Immediate(N.getOperand(1), imm) || 2893 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2894 Base = N.getOperand(0); 2895 Index = N.getOperand(1); 2896 return true; 2897 } 2898 2899 // Otherwise, do it the hard way, using R0 as the base register. 2900 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2901 N.getValueType()); 2902 Index = N; 2903 return true; 2904 } 2905 2906 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2907 Ty *PCRelCand = dyn_cast<Ty>(N); 2908 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2909 } 2910 2911 /// Returns true if this address is a PC Relative address. 2912 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2913 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2914 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2915 // This is a materialize PC Relative node. Always select this as PC Relative. 2916 Base = N; 2917 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2918 return true; 2919 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2920 isValidPCRelNode<GlobalAddressSDNode>(N) || 2921 isValidPCRelNode<JumpTableSDNode>(N) || 2922 isValidPCRelNode<BlockAddressSDNode>(N)) 2923 return true; 2924 return false; 2925 } 2926 2927 /// Returns true if we should use a direct load into vector instruction 2928 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2929 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2930 2931 // If there are any other uses other than scalar to vector, then we should 2932 // keep it as a scalar load -> direct move pattern to prevent multiple 2933 // loads. 2934 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2935 if (!LD) 2936 return false; 2937 2938 EVT MemVT = LD->getMemoryVT(); 2939 if (!MemVT.isSimple()) 2940 return false; 2941 switch(MemVT.getSimpleVT().SimpleTy) { 2942 case MVT::i64: 2943 break; 2944 case MVT::i32: 2945 if (!ST.hasP8Vector()) 2946 return false; 2947 break; 2948 case MVT::i16: 2949 case MVT::i8: 2950 if (!ST.hasP9Vector()) 2951 return false; 2952 break; 2953 default: 2954 return false; 2955 } 2956 2957 SDValue LoadedVal(N, 0); 2958 if (!LoadedVal.hasOneUse()) 2959 return false; 2960 2961 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2962 UI != UE; ++UI) 2963 if (UI.getUse().get().getResNo() == 0 && 2964 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2965 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2966 return false; 2967 2968 return true; 2969 } 2970 2971 /// getPreIndexedAddressParts - returns true by value, base pointer and 2972 /// offset pointer and addressing mode by reference if the node's address 2973 /// can be legally represented as pre-indexed load / store address. 2974 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2975 SDValue &Offset, 2976 ISD::MemIndexedMode &AM, 2977 SelectionDAG &DAG) const { 2978 if (DisablePPCPreinc) return false; 2979 2980 bool isLoad = true; 2981 SDValue Ptr; 2982 EVT VT; 2983 unsigned Alignment; 2984 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2985 Ptr = LD->getBasePtr(); 2986 VT = LD->getMemoryVT(); 2987 Alignment = LD->getAlignment(); 2988 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2989 Ptr = ST->getBasePtr(); 2990 VT = ST->getMemoryVT(); 2991 Alignment = ST->getAlignment(); 2992 isLoad = false; 2993 } else 2994 return false; 2995 2996 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2997 // instructions because we can fold these into a more efficient instruction 2998 // instead, (such as LXSD). 2999 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 3000 return false; 3001 } 3002 3003 // PowerPC doesn't have preinc load/store instructions for vectors 3004 if (VT.isVector()) 3005 return false; 3006 3007 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 3008 // Common code will reject creating a pre-inc form if the base pointer 3009 // is a frame index, or if N is a store and the base pointer is either 3010 // the same as or a predecessor of the value being stored. Check for 3011 // those situations here, and try with swapped Base/Offset instead. 3012 bool Swap = false; 3013 3014 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 3015 Swap = true; 3016 else if (!isLoad) { 3017 SDValue Val = cast<StoreSDNode>(N)->getValue(); 3018 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 3019 Swap = true; 3020 } 3021 3022 if (Swap) 3023 std::swap(Base, Offset); 3024 3025 AM = ISD::PRE_INC; 3026 return true; 3027 } 3028 3029 // LDU/STU can only handle immediates that are a multiple of 4. 3030 if (VT != MVT::i64) { 3031 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 3032 return false; 3033 } else { 3034 // LDU/STU need an address with at least 4-byte alignment. 3035 if (Alignment < 4) 3036 return false; 3037 3038 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 3039 return false; 3040 } 3041 3042 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3043 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 3044 // sext i32 to i64 when addr mode is r+i. 3045 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 3046 LD->getExtensionType() == ISD::SEXTLOAD && 3047 isa<ConstantSDNode>(Offset)) 3048 return false; 3049 } 3050 3051 AM = ISD::PRE_INC; 3052 return true; 3053 } 3054 3055 //===----------------------------------------------------------------------===// 3056 // LowerOperation implementation 3057 //===----------------------------------------------------------------------===// 3058 3059 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3060 /// and LoOpFlags to the target MO flags. 3061 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3062 unsigned &HiOpFlags, unsigned &LoOpFlags, 3063 const GlobalValue *GV = nullptr) { 3064 HiOpFlags = PPCII::MO_HA; 3065 LoOpFlags = PPCII::MO_LO; 3066 3067 // Don't use the pic base if not in PIC relocation model. 3068 if (IsPIC) { 3069 HiOpFlags |= PPCII::MO_PIC_FLAG; 3070 LoOpFlags |= PPCII::MO_PIC_FLAG; 3071 } 3072 } 3073 3074 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3075 SelectionDAG &DAG) { 3076 SDLoc DL(HiPart); 3077 EVT PtrVT = HiPart.getValueType(); 3078 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3079 3080 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3081 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3082 3083 // With PIC, the first instruction is actually "GR+hi(&G)". 3084 if (isPIC) 3085 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3086 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3087 3088 // Generate non-pic code that has direct accesses to the constant pool. 3089 // The address of the global is just (hi(&g)+lo(&g)). 3090 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3091 } 3092 3093 static void setUsesTOCBasePtr(MachineFunction &MF) { 3094 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3095 FuncInfo->setUsesTOCBasePtr(); 3096 } 3097 3098 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3099 setUsesTOCBasePtr(DAG.getMachineFunction()); 3100 } 3101 3102 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3103 SDValue GA) const { 3104 const bool Is64Bit = Subtarget.isPPC64(); 3105 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3106 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3107 : Subtarget.isAIXABI() 3108 ? DAG.getRegister(PPC::R2, VT) 3109 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3110 SDValue Ops[] = { GA, Reg }; 3111 return DAG.getMemIntrinsicNode( 3112 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3113 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 3114 MachineMemOperand::MOLoad); 3115 } 3116 3117 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3118 SelectionDAG &DAG) const { 3119 EVT PtrVT = Op.getValueType(); 3120 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3121 const Constant *C = CP->getConstVal(); 3122 3123 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3124 // The actual address of the GlobalValue is stored in the TOC. 3125 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3126 if (Subtarget.isUsingPCRelativeCalls()) { 3127 SDLoc DL(CP); 3128 EVT Ty = getPointerTy(DAG.getDataLayout()); 3129 SDValue ConstPool = DAG.getTargetConstantPool( 3130 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3131 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3132 } 3133 setUsesTOCBasePtr(DAG); 3134 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3135 return getTOCEntry(DAG, SDLoc(CP), GA); 3136 } 3137 3138 unsigned MOHiFlag, MOLoFlag; 3139 bool IsPIC = isPositionIndependent(); 3140 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3141 3142 if (IsPIC && Subtarget.isSVR4ABI()) { 3143 SDValue GA = 3144 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3145 return getTOCEntry(DAG, SDLoc(CP), GA); 3146 } 3147 3148 SDValue CPIHi = 3149 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3150 SDValue CPILo = 3151 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3152 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3153 } 3154 3155 // For 64-bit PowerPC, prefer the more compact relative encodings. 3156 // This trades 32 bits per jump table entry for one or two instructions 3157 // on the jump site. 3158 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3159 if (isJumpTableRelative()) 3160 return MachineJumpTableInfo::EK_LabelDifference32; 3161 3162 return TargetLowering::getJumpTableEncoding(); 3163 } 3164 3165 bool PPCTargetLowering::isJumpTableRelative() const { 3166 if (UseAbsoluteJumpTables) 3167 return false; 3168 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3169 return true; 3170 return TargetLowering::isJumpTableRelative(); 3171 } 3172 3173 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3174 SelectionDAG &DAG) const { 3175 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3176 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3177 3178 switch (getTargetMachine().getCodeModel()) { 3179 case CodeModel::Small: 3180 case CodeModel::Medium: 3181 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3182 default: 3183 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3184 getPointerTy(DAG.getDataLayout())); 3185 } 3186 } 3187 3188 const MCExpr * 3189 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3190 unsigned JTI, 3191 MCContext &Ctx) const { 3192 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3193 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3194 3195 switch (getTargetMachine().getCodeModel()) { 3196 case CodeModel::Small: 3197 case CodeModel::Medium: 3198 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3199 default: 3200 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3201 } 3202 } 3203 3204 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3205 EVT PtrVT = Op.getValueType(); 3206 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3207 3208 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3209 if (Subtarget.isUsingPCRelativeCalls()) { 3210 SDLoc DL(JT); 3211 EVT Ty = getPointerTy(DAG.getDataLayout()); 3212 SDValue GA = 3213 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3214 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3215 return MatAddr; 3216 } 3217 3218 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3219 // The actual address of the GlobalValue is stored in the TOC. 3220 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3221 setUsesTOCBasePtr(DAG); 3222 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3223 return getTOCEntry(DAG, SDLoc(JT), GA); 3224 } 3225 3226 unsigned MOHiFlag, MOLoFlag; 3227 bool IsPIC = isPositionIndependent(); 3228 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3229 3230 if (IsPIC && Subtarget.isSVR4ABI()) { 3231 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3232 PPCII::MO_PIC_FLAG); 3233 return getTOCEntry(DAG, SDLoc(GA), GA); 3234 } 3235 3236 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3237 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3238 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3239 } 3240 3241 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3242 SelectionDAG &DAG) const { 3243 EVT PtrVT = Op.getValueType(); 3244 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3245 const BlockAddress *BA = BASDN->getBlockAddress(); 3246 3247 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3248 if (Subtarget.isUsingPCRelativeCalls()) { 3249 SDLoc DL(BASDN); 3250 EVT Ty = getPointerTy(DAG.getDataLayout()); 3251 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3252 PPCII::MO_PCREL_FLAG); 3253 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3254 return MatAddr; 3255 } 3256 3257 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3258 // The actual BlockAddress is stored in the TOC. 3259 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3260 setUsesTOCBasePtr(DAG); 3261 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3262 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3263 } 3264 3265 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3266 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3267 return getTOCEntry( 3268 DAG, SDLoc(BASDN), 3269 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3270 3271 unsigned MOHiFlag, MOLoFlag; 3272 bool IsPIC = isPositionIndependent(); 3273 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3274 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3275 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3276 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3277 } 3278 3279 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3280 SelectionDAG &DAG) const { 3281 if (Subtarget.isAIXABI()) 3282 return LowerGlobalTLSAddressAIX(Op, DAG); 3283 3284 return LowerGlobalTLSAddressLinux(Op, DAG); 3285 } 3286 3287 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3288 SelectionDAG &DAG) const { 3289 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3290 3291 if (DAG.getTarget().useEmulatedTLS()) 3292 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3293 3294 SDLoc dl(GA); 3295 const GlobalValue *GV = GA->getGlobal(); 3296 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3297 3298 // The general-dynamic model is the only access model supported for now, so 3299 // all the GlobalTLSAddress nodes are lowered with this model. 3300 // We need to generate two TOC entries, one for the variable offset, one for 3301 // the region handle. The global address for the TOC entry of the region 3302 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3303 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3304 SDValue VariableOffsetTGA = 3305 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3306 SDValue RegionHandleTGA = 3307 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3308 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3309 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3310 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3311 RegionHandle); 3312 } 3313 3314 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3315 SelectionDAG &DAG) const { 3316 // FIXME: TLS addresses currently use medium model code sequences, 3317 // which is the most useful form. Eventually support for small and 3318 // large models could be added if users need it, at the cost of 3319 // additional complexity. 3320 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3321 if (DAG.getTarget().useEmulatedTLS()) 3322 return LowerToTLSEmulatedModel(GA, DAG); 3323 3324 SDLoc dl(GA); 3325 const GlobalValue *GV = GA->getGlobal(); 3326 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3327 bool is64bit = Subtarget.isPPC64(); 3328 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3329 PICLevel::Level picLevel = M->getPICLevel(); 3330 3331 const TargetMachine &TM = getTargetMachine(); 3332 TLSModel::Model Model = TM.getTLSModel(GV); 3333 3334 if (Model == TLSModel::LocalExec) { 3335 if (Subtarget.isUsingPCRelativeCalls()) { 3336 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3337 SDValue TGA = DAG.getTargetGlobalAddress( 3338 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3339 SDValue MatAddr = 3340 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3341 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3342 } 3343 3344 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3345 PPCII::MO_TPREL_HA); 3346 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3347 PPCII::MO_TPREL_LO); 3348 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3349 : DAG.getRegister(PPC::R2, MVT::i32); 3350 3351 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3352 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3353 } 3354 3355 if (Model == TLSModel::InitialExec) { 3356 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3357 SDValue TGA = DAG.getTargetGlobalAddress( 3358 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3359 SDValue TGATLS = DAG.getTargetGlobalAddress( 3360 GV, dl, PtrVT, 0, 3361 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3362 SDValue TPOffset; 3363 if (IsPCRel) { 3364 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3365 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3366 MachinePointerInfo()); 3367 } else { 3368 SDValue GOTPtr; 3369 if (is64bit) { 3370 setUsesTOCBasePtr(DAG); 3371 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3372 GOTPtr = 3373 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3374 } else { 3375 if (!TM.isPositionIndependent()) 3376 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3377 else if (picLevel == PICLevel::SmallPIC) 3378 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3379 else 3380 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3381 } 3382 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3383 } 3384 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3385 } 3386 3387 if (Model == TLSModel::GeneralDynamic) { 3388 if (Subtarget.isUsingPCRelativeCalls()) { 3389 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3390 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3391 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3392 } 3393 3394 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3395 SDValue GOTPtr; 3396 if (is64bit) { 3397 setUsesTOCBasePtr(DAG); 3398 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3399 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3400 GOTReg, TGA); 3401 } else { 3402 if (picLevel == PICLevel::SmallPIC) 3403 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3404 else 3405 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3406 } 3407 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3408 GOTPtr, TGA, TGA); 3409 } 3410 3411 if (Model == TLSModel::LocalDynamic) { 3412 if (Subtarget.isUsingPCRelativeCalls()) { 3413 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3414 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3415 SDValue MatPCRel = 3416 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3417 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3418 } 3419 3420 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3421 SDValue GOTPtr; 3422 if (is64bit) { 3423 setUsesTOCBasePtr(DAG); 3424 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3425 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3426 GOTReg, TGA); 3427 } else { 3428 if (picLevel == PICLevel::SmallPIC) 3429 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3430 else 3431 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3432 } 3433 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3434 PtrVT, GOTPtr, TGA, TGA); 3435 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3436 PtrVT, TLSAddr, TGA); 3437 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3438 } 3439 3440 llvm_unreachable("Unknown TLS model!"); 3441 } 3442 3443 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3444 SelectionDAG &DAG) const { 3445 EVT PtrVT = Op.getValueType(); 3446 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3447 SDLoc DL(GSDN); 3448 const GlobalValue *GV = GSDN->getGlobal(); 3449 3450 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3451 // The actual address of the GlobalValue is stored in the TOC. 3452 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3453 if (Subtarget.isUsingPCRelativeCalls()) { 3454 EVT Ty = getPointerTy(DAG.getDataLayout()); 3455 if (isAccessedAsGotIndirect(Op)) { 3456 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3457 PPCII::MO_PCREL_FLAG | 3458 PPCII::MO_GOT_FLAG); 3459 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3460 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3461 MachinePointerInfo()); 3462 return Load; 3463 } else { 3464 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3465 PPCII::MO_PCREL_FLAG); 3466 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3467 } 3468 } 3469 setUsesTOCBasePtr(DAG); 3470 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3471 return getTOCEntry(DAG, DL, GA); 3472 } 3473 3474 unsigned MOHiFlag, MOLoFlag; 3475 bool IsPIC = isPositionIndependent(); 3476 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3477 3478 if (IsPIC && Subtarget.isSVR4ABI()) { 3479 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3480 GSDN->getOffset(), 3481 PPCII::MO_PIC_FLAG); 3482 return getTOCEntry(DAG, DL, GA); 3483 } 3484 3485 SDValue GAHi = 3486 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3487 SDValue GALo = 3488 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3489 3490 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3491 } 3492 3493 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3494 bool IsStrict = Op->isStrictFPOpcode(); 3495 ISD::CondCode CC = 3496 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3497 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3498 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3499 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3500 EVT LHSVT = LHS.getValueType(); 3501 SDLoc dl(Op); 3502 3503 // Soften the setcc with libcall if it is fp128. 3504 if (LHSVT == MVT::f128) { 3505 assert(!Subtarget.hasP9Vector() && 3506 "SETCC for f128 is already legal under Power9!"); 3507 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3508 Op->getOpcode() == ISD::STRICT_FSETCCS); 3509 if (RHS.getNode()) 3510 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3511 DAG.getCondCode(CC)); 3512 if (IsStrict) 3513 return DAG.getMergeValues({LHS, Chain}, dl); 3514 return LHS; 3515 } 3516 3517 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3518 3519 if (Op.getValueType() == MVT::v2i64) { 3520 // When the operands themselves are v2i64 values, we need to do something 3521 // special because VSX has no underlying comparison operations for these. 3522 if (LHS.getValueType() == MVT::v2i64) { 3523 // Equality can be handled by casting to the legal type for Altivec 3524 // comparisons, everything else needs to be expanded. 3525 if (CC != ISD::SETEQ && CC != ISD::SETNE) 3526 return SDValue(); 3527 SDValue SetCC32 = DAG.getSetCC( 3528 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3529 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC); 3530 int ShuffV[] = {1, 0, 3, 2}; 3531 SDValue Shuff = 3532 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV); 3533 return DAG.getBitcast(MVT::v2i64, 3534 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR, 3535 dl, MVT::v4i32, Shuff, SetCC32)); 3536 } 3537 3538 // We handle most of these in the usual way. 3539 return Op; 3540 } 3541 3542 // If we're comparing for equality to zero, expose the fact that this is 3543 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3544 // fold the new nodes. 3545 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3546 return V; 3547 3548 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3549 // Leave comparisons against 0 and -1 alone for now, since they're usually 3550 // optimized. FIXME: revisit this when we can custom lower all setcc 3551 // optimizations. 3552 if (C->isAllOnes() || C->isZero()) 3553 return SDValue(); 3554 } 3555 3556 // If we have an integer seteq/setne, turn it into a compare against zero 3557 // by xor'ing the rhs with the lhs, which is faster than setting a 3558 // condition register, reading it back out, and masking the correct bit. The 3559 // normal approach here uses sub to do this instead of xor. Using xor exposes 3560 // the result to other bit-twiddling opportunities. 3561 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3562 EVT VT = Op.getValueType(); 3563 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3564 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3565 } 3566 return SDValue(); 3567 } 3568 3569 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3570 SDNode *Node = Op.getNode(); 3571 EVT VT = Node->getValueType(0); 3572 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3573 SDValue InChain = Node->getOperand(0); 3574 SDValue VAListPtr = Node->getOperand(1); 3575 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3576 SDLoc dl(Node); 3577 3578 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3579 3580 // gpr_index 3581 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3582 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3583 InChain = GprIndex.getValue(1); 3584 3585 if (VT == MVT::i64) { 3586 // Check if GprIndex is even 3587 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3588 DAG.getConstant(1, dl, MVT::i32)); 3589 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3590 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3591 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3592 DAG.getConstant(1, dl, MVT::i32)); 3593 // Align GprIndex to be even if it isn't 3594 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3595 GprIndex); 3596 } 3597 3598 // fpr index is 1 byte after gpr 3599 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3600 DAG.getConstant(1, dl, MVT::i32)); 3601 3602 // fpr 3603 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3604 FprPtr, MachinePointerInfo(SV), MVT::i8); 3605 InChain = FprIndex.getValue(1); 3606 3607 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3608 DAG.getConstant(8, dl, MVT::i32)); 3609 3610 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3611 DAG.getConstant(4, dl, MVT::i32)); 3612 3613 // areas 3614 SDValue OverflowArea = 3615 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3616 InChain = OverflowArea.getValue(1); 3617 3618 SDValue RegSaveArea = 3619 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3620 InChain = RegSaveArea.getValue(1); 3621 3622 // select overflow_area if index > 8 3623 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3624 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3625 3626 // adjustment constant gpr_index * 4/8 3627 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3628 VT.isInteger() ? GprIndex : FprIndex, 3629 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3630 MVT::i32)); 3631 3632 // OurReg = RegSaveArea + RegConstant 3633 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3634 RegConstant); 3635 3636 // Floating types are 32 bytes into RegSaveArea 3637 if (VT.isFloatingPoint()) 3638 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3639 DAG.getConstant(32, dl, MVT::i32)); 3640 3641 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3642 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3643 VT.isInteger() ? GprIndex : FprIndex, 3644 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3645 MVT::i32)); 3646 3647 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3648 VT.isInteger() ? VAListPtr : FprPtr, 3649 MachinePointerInfo(SV), MVT::i8); 3650 3651 // determine if we should load from reg_save_area or overflow_area 3652 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3653 3654 // increase overflow_area by 4/8 if gpr/fpr > 8 3655 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3656 DAG.getConstant(VT.isInteger() ? 4 : 8, 3657 dl, MVT::i32)); 3658 3659 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3660 OverflowAreaPlusN); 3661 3662 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3663 MachinePointerInfo(), MVT::i32); 3664 3665 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3666 } 3667 3668 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3669 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3670 3671 // We have to copy the entire va_list struct: 3672 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3673 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3674 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3675 false, true, false, MachinePointerInfo(), 3676 MachinePointerInfo()); 3677 } 3678 3679 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3680 SelectionDAG &DAG) const { 3681 if (Subtarget.isAIXABI()) 3682 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3683 3684 return Op.getOperand(0); 3685 } 3686 3687 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3688 MachineFunction &MF = DAG.getMachineFunction(); 3689 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3690 3691 assert((Op.getOpcode() == ISD::INLINEASM || 3692 Op.getOpcode() == ISD::INLINEASM_BR) && 3693 "Expecting Inline ASM node."); 3694 3695 // If an LR store is already known to be required then there is not point in 3696 // checking this ASM as well. 3697 if (MFI.isLRStoreRequired()) 3698 return Op; 3699 3700 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3701 // type MVT::Glue. We want to ignore this last operand if that is the case. 3702 unsigned NumOps = Op.getNumOperands(); 3703 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3704 --NumOps; 3705 3706 // Check all operands that may contain the LR. 3707 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3708 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3709 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3710 ++i; // Skip the ID value. 3711 3712 switch (InlineAsm::getKind(Flags)) { 3713 default: 3714 llvm_unreachable("Bad flags!"); 3715 case InlineAsm::Kind_RegUse: 3716 case InlineAsm::Kind_Imm: 3717 case InlineAsm::Kind_Mem: 3718 i += NumVals; 3719 break; 3720 case InlineAsm::Kind_Clobber: 3721 case InlineAsm::Kind_RegDef: 3722 case InlineAsm::Kind_RegDefEarlyClobber: { 3723 for (; NumVals; --NumVals, ++i) { 3724 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3725 if (Reg != PPC::LR && Reg != PPC::LR8) 3726 continue; 3727 MFI.setLRStoreRequired(); 3728 return Op; 3729 } 3730 break; 3731 } 3732 } 3733 } 3734 3735 return Op; 3736 } 3737 3738 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3739 SelectionDAG &DAG) const { 3740 if (Subtarget.isAIXABI()) 3741 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3742 3743 SDValue Chain = Op.getOperand(0); 3744 SDValue Trmp = Op.getOperand(1); // trampoline 3745 SDValue FPtr = Op.getOperand(2); // nested function 3746 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3747 SDLoc dl(Op); 3748 3749 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3750 bool isPPC64 = (PtrVT == MVT::i64); 3751 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3752 3753 TargetLowering::ArgListTy Args; 3754 TargetLowering::ArgListEntry Entry; 3755 3756 Entry.Ty = IntPtrTy; 3757 Entry.Node = Trmp; Args.push_back(Entry); 3758 3759 // TrampSize == (isPPC64 ? 48 : 40); 3760 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3761 isPPC64 ? MVT::i64 : MVT::i32); 3762 Args.push_back(Entry); 3763 3764 Entry.Node = FPtr; Args.push_back(Entry); 3765 Entry.Node = Nest; Args.push_back(Entry); 3766 3767 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3768 TargetLowering::CallLoweringInfo CLI(DAG); 3769 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3770 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3771 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3772 3773 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3774 return CallResult.second; 3775 } 3776 3777 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3778 MachineFunction &MF = DAG.getMachineFunction(); 3779 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3780 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3781 3782 SDLoc dl(Op); 3783 3784 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3785 // vastart just stores the address of the VarArgsFrameIndex slot into the 3786 // memory location argument. 3787 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3788 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3789 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3790 MachinePointerInfo(SV)); 3791 } 3792 3793 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3794 // We suppose the given va_list is already allocated. 3795 // 3796 // typedef struct { 3797 // char gpr; /* index into the array of 8 GPRs 3798 // * stored in the register save area 3799 // * gpr=0 corresponds to r3, 3800 // * gpr=1 to r4, etc. 3801 // */ 3802 // char fpr; /* index into the array of 8 FPRs 3803 // * stored in the register save area 3804 // * fpr=0 corresponds to f1, 3805 // * fpr=1 to f2, etc. 3806 // */ 3807 // char *overflow_arg_area; 3808 // /* location on stack that holds 3809 // * the next overflow argument 3810 // */ 3811 // char *reg_save_area; 3812 // /* where r3:r10 and f1:f8 (if saved) 3813 // * are stored 3814 // */ 3815 // } va_list[1]; 3816 3817 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3818 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3819 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3820 PtrVT); 3821 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3822 PtrVT); 3823 3824 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3825 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3826 3827 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3828 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3829 3830 uint64_t FPROffset = 1; 3831 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3832 3833 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3834 3835 // Store first byte : number of int regs 3836 SDValue firstStore = 3837 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3838 MachinePointerInfo(SV), MVT::i8); 3839 uint64_t nextOffset = FPROffset; 3840 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3841 ConstFPROffset); 3842 3843 // Store second byte : number of float regs 3844 SDValue secondStore = 3845 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3846 MachinePointerInfo(SV, nextOffset), MVT::i8); 3847 nextOffset += StackOffset; 3848 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3849 3850 // Store second word : arguments given on stack 3851 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3852 MachinePointerInfo(SV, nextOffset)); 3853 nextOffset += FrameOffset; 3854 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3855 3856 // Store third word : arguments given in registers 3857 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3858 MachinePointerInfo(SV, nextOffset)); 3859 } 3860 3861 /// FPR - The set of FP registers that should be allocated for arguments 3862 /// on Darwin and AIX. 3863 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3864 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3865 PPC::F11, PPC::F12, PPC::F13}; 3866 3867 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3868 /// the stack. 3869 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3870 unsigned PtrByteSize) { 3871 unsigned ArgSize = ArgVT.getStoreSize(); 3872 if (Flags.isByVal()) 3873 ArgSize = Flags.getByValSize(); 3874 3875 // Round up to multiples of the pointer size, except for array members, 3876 // which are always packed. 3877 if (!Flags.isInConsecutiveRegs()) 3878 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3879 3880 return ArgSize; 3881 } 3882 3883 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3884 /// on the stack. 3885 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3886 ISD::ArgFlagsTy Flags, 3887 unsigned PtrByteSize) { 3888 Align Alignment(PtrByteSize); 3889 3890 // Altivec parameters are padded to a 16 byte boundary. 3891 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3892 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3893 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3894 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3895 Alignment = Align(16); 3896 3897 // ByVal parameters are aligned as requested. 3898 if (Flags.isByVal()) { 3899 auto BVAlign = Flags.getNonZeroByValAlign(); 3900 if (BVAlign > PtrByteSize) { 3901 if (BVAlign.value() % PtrByteSize != 0) 3902 llvm_unreachable( 3903 "ByVal alignment is not a multiple of the pointer size"); 3904 3905 Alignment = BVAlign; 3906 } 3907 } 3908 3909 // Array members are always packed to their original alignment. 3910 if (Flags.isInConsecutiveRegs()) { 3911 // If the array member was split into multiple registers, the first 3912 // needs to be aligned to the size of the full type. (Except for 3913 // ppcf128, which is only aligned as its f64 components.) 3914 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3915 Alignment = Align(OrigVT.getStoreSize()); 3916 else 3917 Alignment = Align(ArgVT.getStoreSize()); 3918 } 3919 3920 return Alignment; 3921 } 3922 3923 /// CalculateStackSlotUsed - Return whether this argument will use its 3924 /// stack slot (instead of being passed in registers). ArgOffset, 3925 /// AvailableFPRs, and AvailableVRs must hold the current argument 3926 /// position, and will be updated to account for this argument. 3927 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3928 unsigned PtrByteSize, unsigned LinkageSize, 3929 unsigned ParamAreaSize, unsigned &ArgOffset, 3930 unsigned &AvailableFPRs, 3931 unsigned &AvailableVRs) { 3932 bool UseMemory = false; 3933 3934 // Respect alignment of argument on the stack. 3935 Align Alignment = 3936 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3937 ArgOffset = alignTo(ArgOffset, Alignment); 3938 // If there's no space left in the argument save area, we must 3939 // use memory (this check also catches zero-sized arguments). 3940 if (ArgOffset >= LinkageSize + ParamAreaSize) 3941 UseMemory = true; 3942 3943 // Allocate argument on the stack. 3944 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3945 if (Flags.isInConsecutiveRegsLast()) 3946 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3947 // If we overran the argument save area, we must use memory 3948 // (this check catches arguments passed partially in memory) 3949 if (ArgOffset > LinkageSize + ParamAreaSize) 3950 UseMemory = true; 3951 3952 // However, if the argument is actually passed in an FPR or a VR, 3953 // we don't use memory after all. 3954 if (!Flags.isByVal()) { 3955 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3956 if (AvailableFPRs > 0) { 3957 --AvailableFPRs; 3958 return false; 3959 } 3960 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3961 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3962 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3963 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3964 if (AvailableVRs > 0) { 3965 --AvailableVRs; 3966 return false; 3967 } 3968 } 3969 3970 return UseMemory; 3971 } 3972 3973 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3974 /// ensure minimum alignment required for target. 3975 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3976 unsigned NumBytes) { 3977 return alignTo(NumBytes, Lowering->getStackAlign()); 3978 } 3979 3980 SDValue PPCTargetLowering::LowerFormalArguments( 3981 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3982 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3983 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3984 if (Subtarget.isAIXABI()) 3985 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3986 InVals); 3987 if (Subtarget.is64BitELFABI()) 3988 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3989 InVals); 3990 assert(Subtarget.is32BitELFABI()); 3991 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3992 InVals); 3993 } 3994 3995 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3996 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3997 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3998 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3999 4000 // 32-bit SVR4 ABI Stack Frame Layout: 4001 // +-----------------------------------+ 4002 // +--> | Back chain | 4003 // | +-----------------------------------+ 4004 // | | Floating-point register save area | 4005 // | +-----------------------------------+ 4006 // | | General register save area | 4007 // | +-----------------------------------+ 4008 // | | CR save word | 4009 // | +-----------------------------------+ 4010 // | | VRSAVE save word | 4011 // | +-----------------------------------+ 4012 // | | Alignment padding | 4013 // | +-----------------------------------+ 4014 // | | Vector register save area | 4015 // | +-----------------------------------+ 4016 // | | Local variable space | 4017 // | +-----------------------------------+ 4018 // | | Parameter list area | 4019 // | +-----------------------------------+ 4020 // | | LR save word | 4021 // | +-----------------------------------+ 4022 // SP--> +--- | Back chain | 4023 // +-----------------------------------+ 4024 // 4025 // Specifications: 4026 // System V Application Binary Interface PowerPC Processor Supplement 4027 // AltiVec Technology Programming Interface Manual 4028 4029 MachineFunction &MF = DAG.getMachineFunction(); 4030 MachineFrameInfo &MFI = MF.getFrameInfo(); 4031 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4032 4033 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4034 // Potential tail calls could cause overwriting of argument stack slots. 4035 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4036 (CallConv == CallingConv::Fast)); 4037 const Align PtrAlign(4); 4038 4039 // Assign locations to all of the incoming arguments. 4040 SmallVector<CCValAssign, 16> ArgLocs; 4041 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4042 *DAG.getContext()); 4043 4044 // Reserve space for the linkage area on the stack. 4045 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4046 CCInfo.AllocateStack(LinkageSize, PtrAlign); 4047 if (useSoftFloat()) 4048 CCInfo.PreAnalyzeFormalArguments(Ins); 4049 4050 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 4051 CCInfo.clearWasPPCF128(); 4052 4053 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4054 CCValAssign &VA = ArgLocs[i]; 4055 4056 // Arguments stored in registers. 4057 if (VA.isRegLoc()) { 4058 const TargetRegisterClass *RC; 4059 EVT ValVT = VA.getValVT(); 4060 4061 switch (ValVT.getSimpleVT().SimpleTy) { 4062 default: 4063 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4064 case MVT::i1: 4065 case MVT::i32: 4066 RC = &PPC::GPRCRegClass; 4067 break; 4068 case MVT::f32: 4069 if (Subtarget.hasP8Vector()) 4070 RC = &PPC::VSSRCRegClass; 4071 else if (Subtarget.hasSPE()) 4072 RC = &PPC::GPRCRegClass; 4073 else 4074 RC = &PPC::F4RCRegClass; 4075 break; 4076 case MVT::f64: 4077 if (Subtarget.hasVSX()) 4078 RC = &PPC::VSFRCRegClass; 4079 else if (Subtarget.hasSPE()) 4080 // SPE passes doubles in GPR pairs. 4081 RC = &PPC::GPRCRegClass; 4082 else 4083 RC = &PPC::F8RCRegClass; 4084 break; 4085 case MVT::v16i8: 4086 case MVT::v8i16: 4087 case MVT::v4i32: 4088 RC = &PPC::VRRCRegClass; 4089 break; 4090 case MVT::v4f32: 4091 RC = &PPC::VRRCRegClass; 4092 break; 4093 case MVT::v2f64: 4094 case MVT::v2i64: 4095 RC = &PPC::VRRCRegClass; 4096 break; 4097 } 4098 4099 SDValue ArgValue; 4100 // Transform the arguments stored in physical registers into 4101 // virtual ones. 4102 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4103 assert(i + 1 < e && "No second half of double precision argument"); 4104 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4105 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4106 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4107 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4108 if (!Subtarget.isLittleEndian()) 4109 std::swap (ArgValueLo, ArgValueHi); 4110 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4111 ArgValueHi); 4112 } else { 4113 Register Reg = MF.addLiveIn(VA.getLocReg(), RC); 4114 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4115 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4116 if (ValVT == MVT::i1) 4117 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4118 } 4119 4120 InVals.push_back(ArgValue); 4121 } else { 4122 // Argument stored in memory. 4123 assert(VA.isMemLoc()); 4124 4125 // Get the extended size of the argument type in stack 4126 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4127 // Get the actual size of the argument type 4128 unsigned ObjSize = VA.getValVT().getStoreSize(); 4129 unsigned ArgOffset = VA.getLocMemOffset(); 4130 // Stack objects in PPC32 are right justified. 4131 ArgOffset += ArgSize - ObjSize; 4132 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4133 4134 // Create load nodes to retrieve arguments from the stack. 4135 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4136 InVals.push_back( 4137 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4138 } 4139 } 4140 4141 // Assign locations to all of the incoming aggregate by value arguments. 4142 // Aggregates passed by value are stored in the local variable space of the 4143 // caller's stack frame, right above the parameter list area. 4144 SmallVector<CCValAssign, 16> ByValArgLocs; 4145 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4146 ByValArgLocs, *DAG.getContext()); 4147 4148 // Reserve stack space for the allocations in CCInfo. 4149 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4150 4151 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4152 4153 // Area that is at least reserved in the caller of this function. 4154 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4155 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4156 4157 // Set the size that is at least reserved in caller of this function. Tail 4158 // call optimized function's reserved stack space needs to be aligned so that 4159 // taking the difference between two stack areas will result in an aligned 4160 // stack. 4161 MinReservedArea = 4162 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4163 FuncInfo->setMinReservedArea(MinReservedArea); 4164 4165 SmallVector<SDValue, 8> MemOps; 4166 4167 // If the function takes variable number of arguments, make a frame index for 4168 // the start of the first vararg value... for expansion of llvm.va_start. 4169 if (isVarArg) { 4170 static const MCPhysReg GPArgRegs[] = { 4171 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4172 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4173 }; 4174 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 4175 4176 static const MCPhysReg FPArgRegs[] = { 4177 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4178 PPC::F8 4179 }; 4180 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 4181 4182 if (useSoftFloat() || hasSPE()) 4183 NumFPArgRegs = 0; 4184 4185 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4186 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4187 4188 // Make room for NumGPArgRegs and NumFPArgRegs. 4189 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4190 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4191 4192 FuncInfo->setVarArgsStackOffset( 4193 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4194 CCInfo.getNextStackOffset(), true)); 4195 4196 FuncInfo->setVarArgsFrameIndex( 4197 MFI.CreateStackObject(Depth, Align(8), false)); 4198 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4199 4200 // The fixed integer arguments of a variadic function are stored to the 4201 // VarArgsFrameIndex on the stack so that they may be loaded by 4202 // dereferencing the result of va_next. 4203 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4204 // Get an existing live-in vreg, or add a new one. 4205 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4206 if (!VReg) 4207 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4208 4209 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4210 SDValue Store = 4211 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4212 MemOps.push_back(Store); 4213 // Increment the address by four for the next argument to store 4214 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4215 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4216 } 4217 4218 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4219 // is set. 4220 // The double arguments are stored to the VarArgsFrameIndex 4221 // on the stack. 4222 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4223 // Get an existing live-in vreg, or add a new one. 4224 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4225 if (!VReg) 4226 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4227 4228 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4229 SDValue Store = 4230 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4231 MemOps.push_back(Store); 4232 // Increment the address by eight for the next argument to store 4233 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4234 PtrVT); 4235 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4236 } 4237 } 4238 4239 if (!MemOps.empty()) 4240 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4241 4242 return Chain; 4243 } 4244 4245 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4246 // value to MVT::i64 and then truncate to the correct register size. 4247 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4248 EVT ObjectVT, SelectionDAG &DAG, 4249 SDValue ArgVal, 4250 const SDLoc &dl) const { 4251 if (Flags.isSExt()) 4252 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4253 DAG.getValueType(ObjectVT)); 4254 else if (Flags.isZExt()) 4255 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4256 DAG.getValueType(ObjectVT)); 4257 4258 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4259 } 4260 4261 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4262 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4263 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4264 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4265 // TODO: add description of PPC stack frame format, or at least some docs. 4266 // 4267 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4268 bool isLittleEndian = Subtarget.isLittleEndian(); 4269 MachineFunction &MF = DAG.getMachineFunction(); 4270 MachineFrameInfo &MFI = MF.getFrameInfo(); 4271 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4272 4273 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4274 "fastcc not supported on varargs functions"); 4275 4276 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4277 // Potential tail calls could cause overwriting of argument stack slots. 4278 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4279 (CallConv == CallingConv::Fast)); 4280 unsigned PtrByteSize = 8; 4281 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4282 4283 static const MCPhysReg GPR[] = { 4284 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4285 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4286 }; 4287 static const MCPhysReg VR[] = { 4288 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4289 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4290 }; 4291 4292 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4293 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4294 const unsigned Num_VR_Regs = array_lengthof(VR); 4295 4296 // Do a first pass over the arguments to determine whether the ABI 4297 // guarantees that our caller has allocated the parameter save area 4298 // on its stack frame. In the ELFv1 ABI, this is always the case; 4299 // in the ELFv2 ABI, it is true if this is a vararg function or if 4300 // any parameter is located in a stack slot. 4301 4302 bool HasParameterArea = !isELFv2ABI || isVarArg; 4303 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4304 unsigned NumBytes = LinkageSize; 4305 unsigned AvailableFPRs = Num_FPR_Regs; 4306 unsigned AvailableVRs = Num_VR_Regs; 4307 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4308 if (Ins[i].Flags.isNest()) 4309 continue; 4310 4311 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4312 PtrByteSize, LinkageSize, ParamAreaSize, 4313 NumBytes, AvailableFPRs, AvailableVRs)) 4314 HasParameterArea = true; 4315 } 4316 4317 // Add DAG nodes to load the arguments or copy them out of registers. On 4318 // entry to a function on PPC, the arguments start after the linkage area, 4319 // although the first ones are often in registers. 4320 4321 unsigned ArgOffset = LinkageSize; 4322 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4323 SmallVector<SDValue, 8> MemOps; 4324 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4325 unsigned CurArgIdx = 0; 4326 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4327 SDValue ArgVal; 4328 bool needsLoad = false; 4329 EVT ObjectVT = Ins[ArgNo].VT; 4330 EVT OrigVT = Ins[ArgNo].ArgVT; 4331 unsigned ObjSize = ObjectVT.getStoreSize(); 4332 unsigned ArgSize = ObjSize; 4333 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4334 if (Ins[ArgNo].isOrigArg()) { 4335 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4336 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4337 } 4338 // We re-align the argument offset for each argument, except when using the 4339 // fast calling convention, when we need to make sure we do that only when 4340 // we'll actually use a stack slot. 4341 unsigned CurArgOffset; 4342 Align Alignment; 4343 auto ComputeArgOffset = [&]() { 4344 /* Respect alignment of argument on the stack. */ 4345 Alignment = 4346 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4347 ArgOffset = alignTo(ArgOffset, Alignment); 4348 CurArgOffset = ArgOffset; 4349 }; 4350 4351 if (CallConv != CallingConv::Fast) { 4352 ComputeArgOffset(); 4353 4354 /* Compute GPR index associated with argument offset. */ 4355 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4356 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4357 } 4358 4359 // FIXME the codegen can be much improved in some cases. 4360 // We do not have to keep everything in memory. 4361 if (Flags.isByVal()) { 4362 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4363 4364 if (CallConv == CallingConv::Fast) 4365 ComputeArgOffset(); 4366 4367 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4368 ObjSize = Flags.getByValSize(); 4369 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4370 // Empty aggregate parameters do not take up registers. Examples: 4371 // struct { } a; 4372 // union { } b; 4373 // int c[0]; 4374 // etc. However, we have to provide a place-holder in InVals, so 4375 // pretend we have an 8-byte item at the current address for that 4376 // purpose. 4377 if (!ObjSize) { 4378 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4379 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4380 InVals.push_back(FIN); 4381 continue; 4382 } 4383 4384 // Create a stack object covering all stack doublewords occupied 4385 // by the argument. If the argument is (fully or partially) on 4386 // the stack, or if the argument is fully in registers but the 4387 // caller has allocated the parameter save anyway, we can refer 4388 // directly to the caller's stack frame. Otherwise, create a 4389 // local copy in our own frame. 4390 int FI; 4391 if (HasParameterArea || 4392 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4393 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4394 else 4395 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4396 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4397 4398 // Handle aggregates smaller than 8 bytes. 4399 if (ObjSize < PtrByteSize) { 4400 // The value of the object is its address, which differs from the 4401 // address of the enclosing doubleword on big-endian systems. 4402 SDValue Arg = FIN; 4403 if (!isLittleEndian) { 4404 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4405 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4406 } 4407 InVals.push_back(Arg); 4408 4409 if (GPR_idx != Num_GPR_Regs) { 4410 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4411 FuncInfo->addLiveInAttr(VReg, Flags); 4412 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4413 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8); 4414 SDValue Store = 4415 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4416 MachinePointerInfo(&*FuncArg), ObjType); 4417 MemOps.push_back(Store); 4418 } 4419 // Whether we copied from a register or not, advance the offset 4420 // into the parameter save area by a full doubleword. 4421 ArgOffset += PtrByteSize; 4422 continue; 4423 } 4424 4425 // The value of the object is its address, which is the address of 4426 // its first stack doubleword. 4427 InVals.push_back(FIN); 4428 4429 // Store whatever pieces of the object are in registers to memory. 4430 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4431 if (GPR_idx == Num_GPR_Regs) 4432 break; 4433 4434 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4435 FuncInfo->addLiveInAttr(VReg, Flags); 4436 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4437 SDValue Addr = FIN; 4438 if (j) { 4439 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4440 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4441 } 4442 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4443 MachinePointerInfo(&*FuncArg, j)); 4444 MemOps.push_back(Store); 4445 ++GPR_idx; 4446 } 4447 ArgOffset += ArgSize; 4448 continue; 4449 } 4450 4451 switch (ObjectVT.getSimpleVT().SimpleTy) { 4452 default: llvm_unreachable("Unhandled argument type!"); 4453 case MVT::i1: 4454 case MVT::i32: 4455 case MVT::i64: 4456 if (Flags.isNest()) { 4457 // The 'nest' parameter, if any, is passed in R11. 4458 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4459 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4460 4461 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4462 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4463 4464 break; 4465 } 4466 4467 // These can be scalar arguments or elements of an integer array type 4468 // passed directly. Clang may use those instead of "byval" aggregate 4469 // types to avoid forcing arguments to memory unnecessarily. 4470 if (GPR_idx != Num_GPR_Regs) { 4471 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4472 FuncInfo->addLiveInAttr(VReg, Flags); 4473 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4474 4475 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4476 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4477 // value to MVT::i64 and then truncate to the correct register size. 4478 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4479 } else { 4480 if (CallConv == CallingConv::Fast) 4481 ComputeArgOffset(); 4482 4483 needsLoad = true; 4484 ArgSize = PtrByteSize; 4485 } 4486 if (CallConv != CallingConv::Fast || needsLoad) 4487 ArgOffset += 8; 4488 break; 4489 4490 case MVT::f32: 4491 case MVT::f64: 4492 // These can be scalar arguments or elements of a float array type 4493 // passed directly. The latter are used to implement ELFv2 homogenous 4494 // float aggregates. 4495 if (FPR_idx != Num_FPR_Regs) { 4496 unsigned VReg; 4497 4498 if (ObjectVT == MVT::f32) 4499 VReg = MF.addLiveIn(FPR[FPR_idx], 4500 Subtarget.hasP8Vector() 4501 ? &PPC::VSSRCRegClass 4502 : &PPC::F4RCRegClass); 4503 else 4504 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4505 ? &PPC::VSFRCRegClass 4506 : &PPC::F8RCRegClass); 4507 4508 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4509 ++FPR_idx; 4510 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4511 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4512 // once we support fp <-> gpr moves. 4513 4514 // This can only ever happen in the presence of f32 array types, 4515 // since otherwise we never run out of FPRs before running out 4516 // of GPRs. 4517 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4518 FuncInfo->addLiveInAttr(VReg, Flags); 4519 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4520 4521 if (ObjectVT == MVT::f32) { 4522 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4523 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4524 DAG.getConstant(32, dl, MVT::i32)); 4525 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4526 } 4527 4528 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4529 } else { 4530 if (CallConv == CallingConv::Fast) 4531 ComputeArgOffset(); 4532 4533 needsLoad = true; 4534 } 4535 4536 // When passing an array of floats, the array occupies consecutive 4537 // space in the argument area; only round up to the next doubleword 4538 // at the end of the array. Otherwise, each float takes 8 bytes. 4539 if (CallConv != CallingConv::Fast || needsLoad) { 4540 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4541 ArgOffset += ArgSize; 4542 if (Flags.isInConsecutiveRegsLast()) 4543 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4544 } 4545 break; 4546 case MVT::v4f32: 4547 case MVT::v4i32: 4548 case MVT::v8i16: 4549 case MVT::v16i8: 4550 case MVT::v2f64: 4551 case MVT::v2i64: 4552 case MVT::v1i128: 4553 case MVT::f128: 4554 // These can be scalar arguments or elements of a vector array type 4555 // passed directly. The latter are used to implement ELFv2 homogenous 4556 // vector aggregates. 4557 if (VR_idx != Num_VR_Regs) { 4558 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4559 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4560 ++VR_idx; 4561 } else { 4562 if (CallConv == CallingConv::Fast) 4563 ComputeArgOffset(); 4564 needsLoad = true; 4565 } 4566 if (CallConv != CallingConv::Fast || needsLoad) 4567 ArgOffset += 16; 4568 break; 4569 } 4570 4571 // We need to load the argument to a virtual register if we determined 4572 // above that we ran out of physical registers of the appropriate type. 4573 if (needsLoad) { 4574 if (ObjSize < ArgSize && !isLittleEndian) 4575 CurArgOffset += ArgSize - ObjSize; 4576 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4577 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4578 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4579 } 4580 4581 InVals.push_back(ArgVal); 4582 } 4583 4584 // Area that is at least reserved in the caller of this function. 4585 unsigned MinReservedArea; 4586 if (HasParameterArea) 4587 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4588 else 4589 MinReservedArea = LinkageSize; 4590 4591 // Set the size that is at least reserved in caller of this function. Tail 4592 // call optimized functions' reserved stack space needs to be aligned so that 4593 // taking the difference between two stack areas will result in an aligned 4594 // stack. 4595 MinReservedArea = 4596 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4597 FuncInfo->setMinReservedArea(MinReservedArea); 4598 4599 // If the function takes variable number of arguments, make a frame index for 4600 // the start of the first vararg value... for expansion of llvm.va_start. 4601 // On ELFv2ABI spec, it writes: 4602 // C programs that are intended to be *portable* across different compilers 4603 // and architectures must use the header file <stdarg.h> to deal with variable 4604 // argument lists. 4605 if (isVarArg && MFI.hasVAStart()) { 4606 int Depth = ArgOffset; 4607 4608 FuncInfo->setVarArgsFrameIndex( 4609 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4610 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4611 4612 // If this function is vararg, store any remaining integer argument regs 4613 // to their spots on the stack so that they may be loaded by dereferencing 4614 // the result of va_next. 4615 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4616 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4617 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4618 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4619 SDValue Store = 4620 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4621 MemOps.push_back(Store); 4622 // Increment the address by four for the next argument to store 4623 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4624 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4625 } 4626 } 4627 4628 if (!MemOps.empty()) 4629 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4630 4631 return Chain; 4632 } 4633 4634 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4635 /// adjusted to accommodate the arguments for the tailcall. 4636 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4637 unsigned ParamSize) { 4638 4639 if (!isTailCall) return 0; 4640 4641 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4642 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4643 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4644 // Remember only if the new adjustment is bigger. 4645 if (SPDiff < FI->getTailCallSPDelta()) 4646 FI->setTailCallSPDelta(SPDiff); 4647 4648 return SPDiff; 4649 } 4650 4651 static bool isFunctionGlobalAddress(SDValue Callee); 4652 4653 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4654 const TargetMachine &TM) { 4655 // It does not make sense to call callsShareTOCBase() with a caller that 4656 // is PC Relative since PC Relative callers do not have a TOC. 4657 #ifndef NDEBUG 4658 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4659 assert(!STICaller->isUsingPCRelativeCalls() && 4660 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4661 #endif 4662 4663 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4664 // don't have enough information to determine if the caller and callee share 4665 // the same TOC base, so we have to pessimistically assume they don't for 4666 // correctness. 4667 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4668 if (!G) 4669 return false; 4670 4671 const GlobalValue *GV = G->getGlobal(); 4672 4673 // If the callee is preemptable, then the static linker will use a plt-stub 4674 // which saves the toc to the stack, and needs a nop after the call 4675 // instruction to convert to a toc-restore. 4676 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4677 return false; 4678 4679 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4680 // We may need a TOC restore in the situation where the caller requires a 4681 // valid TOC but the callee is PC Relative and does not. 4682 const Function *F = dyn_cast<Function>(GV); 4683 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4684 4685 // If we have an Alias we can try to get the function from there. 4686 if (Alias) { 4687 const GlobalObject *GlobalObj = Alias->getAliaseeObject(); 4688 F = dyn_cast<Function>(GlobalObj); 4689 } 4690 4691 // If we still have no valid function pointer we do not have enough 4692 // information to determine if the callee uses PC Relative calls so we must 4693 // assume that it does. 4694 if (!F) 4695 return false; 4696 4697 // If the callee uses PC Relative we cannot guarantee that the callee won't 4698 // clobber the TOC of the caller and so we must assume that the two 4699 // functions do not share a TOC base. 4700 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4701 if (STICallee->isUsingPCRelativeCalls()) 4702 return false; 4703 4704 // If the GV is not a strong definition then we need to assume it can be 4705 // replaced by another function at link time. The function that replaces 4706 // it may not share the same TOC as the caller since the callee may be 4707 // replaced by a PC Relative version of the same function. 4708 if (!GV->isStrongDefinitionForLinker()) 4709 return false; 4710 4711 // The medium and large code models are expected to provide a sufficiently 4712 // large TOC to provide all data addressing needs of a module with a 4713 // single TOC. 4714 if (CodeModel::Medium == TM.getCodeModel() || 4715 CodeModel::Large == TM.getCodeModel()) 4716 return true; 4717 4718 // Any explicitly-specified sections and section prefixes must also match. 4719 // Also, if we're using -ffunction-sections, then each function is always in 4720 // a different section (the same is true for COMDAT functions). 4721 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4722 GV->getSection() != Caller->getSection()) 4723 return false; 4724 if (const auto *F = dyn_cast<Function>(GV)) { 4725 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4726 return false; 4727 } 4728 4729 return true; 4730 } 4731 4732 static bool 4733 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4734 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4735 assert(Subtarget.is64BitELFABI()); 4736 4737 const unsigned PtrByteSize = 8; 4738 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4739 4740 static const MCPhysReg GPR[] = { 4741 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4742 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4743 }; 4744 static const MCPhysReg VR[] = { 4745 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4746 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4747 }; 4748 4749 const unsigned NumGPRs = array_lengthof(GPR); 4750 const unsigned NumFPRs = 13; 4751 const unsigned NumVRs = array_lengthof(VR); 4752 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4753 4754 unsigned NumBytes = LinkageSize; 4755 unsigned AvailableFPRs = NumFPRs; 4756 unsigned AvailableVRs = NumVRs; 4757 4758 for (const ISD::OutputArg& Param : Outs) { 4759 if (Param.Flags.isNest()) continue; 4760 4761 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4762 LinkageSize, ParamAreaSize, NumBytes, 4763 AvailableFPRs, AvailableVRs)) 4764 return true; 4765 } 4766 return false; 4767 } 4768 4769 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4770 if (CB.arg_size() != CallerFn->arg_size()) 4771 return false; 4772 4773 auto CalleeArgIter = CB.arg_begin(); 4774 auto CalleeArgEnd = CB.arg_end(); 4775 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4776 4777 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4778 const Value* CalleeArg = *CalleeArgIter; 4779 const Value* CallerArg = &(*CallerArgIter); 4780 if (CalleeArg == CallerArg) 4781 continue; 4782 4783 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4784 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4785 // } 4786 // 1st argument of callee is undef and has the same type as caller. 4787 if (CalleeArg->getType() == CallerArg->getType() && 4788 isa<UndefValue>(CalleeArg)) 4789 continue; 4790 4791 return false; 4792 } 4793 4794 return true; 4795 } 4796 4797 // Returns true if TCO is possible between the callers and callees 4798 // calling conventions. 4799 static bool 4800 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4801 CallingConv::ID CalleeCC) { 4802 // Tail calls are possible with fastcc and ccc. 4803 auto isTailCallableCC = [] (CallingConv::ID CC){ 4804 return CC == CallingConv::C || CC == CallingConv::Fast; 4805 }; 4806 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4807 return false; 4808 4809 // We can safely tail call both fastcc and ccc callees from a c calling 4810 // convention caller. If the caller is fastcc, we may have less stack space 4811 // than a non-fastcc caller with the same signature so disable tail-calls in 4812 // that case. 4813 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4814 } 4815 4816 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4817 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4818 const SmallVectorImpl<ISD::OutputArg> &Outs, 4819 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4820 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4821 4822 if (DisableSCO && !TailCallOpt) return false; 4823 4824 // Variadic argument functions are not supported. 4825 if (isVarArg) return false; 4826 4827 auto &Caller = DAG.getMachineFunction().getFunction(); 4828 // Check that the calling conventions are compatible for tco. 4829 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4830 return false; 4831 4832 // Caller contains any byval parameter is not supported. 4833 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4834 return false; 4835 4836 // Callee contains any byval parameter is not supported, too. 4837 // Note: This is a quick work around, because in some cases, e.g. 4838 // caller's stack size > callee's stack size, we are still able to apply 4839 // sibling call optimization. For example, gcc is able to do SCO for caller1 4840 // in the following example, but not for caller2. 4841 // struct test { 4842 // long int a; 4843 // char ary[56]; 4844 // } gTest; 4845 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4846 // b->a = v.a; 4847 // return 0; 4848 // } 4849 // void caller1(struct test a, struct test c, struct test *b) { 4850 // callee(gTest, b); } 4851 // void caller2(struct test *b) { callee(gTest, b); } 4852 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4853 return false; 4854 4855 // If callee and caller use different calling conventions, we cannot pass 4856 // parameters on stack since offsets for the parameter area may be different. 4857 if (Caller.getCallingConv() != CalleeCC && 4858 needStackSlotPassParameters(Subtarget, Outs)) 4859 return false; 4860 4861 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4862 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4863 // callee potentially have different TOC bases then we cannot tail call since 4864 // we need to restore the TOC pointer after the call. 4865 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4866 // We cannot guarantee this for indirect calls or calls to external functions. 4867 // When PC-Relative addressing is used, the concept of the TOC is no longer 4868 // applicable so this check is not required. 4869 // Check first for indirect calls. 4870 if (!Subtarget.isUsingPCRelativeCalls() && 4871 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4872 return false; 4873 4874 // Check if we share the TOC base. 4875 if (!Subtarget.isUsingPCRelativeCalls() && 4876 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4877 return false; 4878 4879 // TCO allows altering callee ABI, so we don't have to check further. 4880 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4881 return true; 4882 4883 if (DisableSCO) return false; 4884 4885 // If callee use the same argument list that caller is using, then we can 4886 // apply SCO on this case. If it is not, then we need to check if callee needs 4887 // stack for passing arguments. 4888 // PC Relative tail calls may not have a CallBase. 4889 // If there is no CallBase we cannot verify if we have the same argument 4890 // list so assume that we don't have the same argument list. 4891 if (CB && !hasSameArgumentList(&Caller, *CB) && 4892 needStackSlotPassParameters(Subtarget, Outs)) 4893 return false; 4894 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4895 return false; 4896 4897 return true; 4898 } 4899 4900 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4901 /// for tail call optimization. Targets which want to do tail call 4902 /// optimization should implement this function. 4903 bool 4904 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4905 CallingConv::ID CalleeCC, 4906 bool isVarArg, 4907 const SmallVectorImpl<ISD::InputArg> &Ins, 4908 SelectionDAG& DAG) const { 4909 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4910 return false; 4911 4912 // Variable argument functions are not supported. 4913 if (isVarArg) 4914 return false; 4915 4916 MachineFunction &MF = DAG.getMachineFunction(); 4917 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4918 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4919 // Functions containing by val parameters are not supported. 4920 for (unsigned i = 0; i != Ins.size(); i++) { 4921 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4922 if (Flags.isByVal()) return false; 4923 } 4924 4925 // Non-PIC/GOT tail calls are supported. 4926 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4927 return true; 4928 4929 // At the moment we can only do local tail calls (in same module, hidden 4930 // or protected) if we are generating PIC. 4931 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4932 return G->getGlobal()->hasHiddenVisibility() 4933 || G->getGlobal()->hasProtectedVisibility(); 4934 } 4935 4936 return false; 4937 } 4938 4939 /// isCallCompatibleAddress - Return the immediate to use if the specified 4940 /// 32-bit value is representable in the immediate field of a BxA instruction. 4941 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4942 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4943 if (!C) return nullptr; 4944 4945 int Addr = C->getZExtValue(); 4946 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4947 SignExtend32<26>(Addr) != Addr) 4948 return nullptr; // Top 6 bits have to be sext of immediate. 4949 4950 return DAG 4951 .getConstant( 4952 (int)C->getZExtValue() >> 2, SDLoc(Op), 4953 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4954 .getNode(); 4955 } 4956 4957 namespace { 4958 4959 struct TailCallArgumentInfo { 4960 SDValue Arg; 4961 SDValue FrameIdxOp; 4962 int FrameIdx = 0; 4963 4964 TailCallArgumentInfo() = default; 4965 }; 4966 4967 } // end anonymous namespace 4968 4969 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4970 static void StoreTailCallArgumentsToStackSlot( 4971 SelectionDAG &DAG, SDValue Chain, 4972 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4973 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4974 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4975 SDValue Arg = TailCallArgs[i].Arg; 4976 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4977 int FI = TailCallArgs[i].FrameIdx; 4978 // Store relative to framepointer. 4979 MemOpChains.push_back(DAG.getStore( 4980 Chain, dl, Arg, FIN, 4981 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4982 } 4983 } 4984 4985 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4986 /// the appropriate stack slot for the tail call optimized function call. 4987 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4988 SDValue OldRetAddr, SDValue OldFP, 4989 int SPDiff, const SDLoc &dl) { 4990 if (SPDiff) { 4991 // Calculate the new stack slot for the return address. 4992 MachineFunction &MF = DAG.getMachineFunction(); 4993 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4994 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4995 bool isPPC64 = Subtarget.isPPC64(); 4996 int SlotSize = isPPC64 ? 8 : 4; 4997 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4998 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4999 NewRetAddrLoc, true); 5000 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5001 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5002 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5003 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5004 } 5005 return Chain; 5006 } 5007 5008 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5009 /// the position of the argument. 5010 static void 5011 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5012 SDValue Arg, int SPDiff, unsigned ArgOffset, 5013 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5014 int Offset = ArgOffset + SPDiff; 5015 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5016 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5017 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5018 SDValue FIN = DAG.getFrameIndex(FI, VT); 5019 TailCallArgumentInfo Info; 5020 Info.Arg = Arg; 5021 Info.FrameIdxOp = FIN; 5022 Info.FrameIdx = FI; 5023 TailCallArguments.push_back(Info); 5024 } 5025 5026 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5027 /// stack slot. Returns the chain as result and the loaded frame pointers in 5028 /// LROpOut/FPOpout. Used when tail calling. 5029 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5030 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5031 SDValue &FPOpOut, const SDLoc &dl) const { 5032 if (SPDiff) { 5033 // Load the LR and FP stack slot for later adjusting. 5034 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5035 LROpOut = getReturnAddrFrameIndex(DAG); 5036 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5037 Chain = SDValue(LROpOut.getNode(), 1); 5038 } 5039 return Chain; 5040 } 5041 5042 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5043 /// by "Src" to address "Dst" of size "Size". Alignment information is 5044 /// specified by the specific parameter attribute. The copy will be passed as 5045 /// a byval function parameter. 5046 /// Sometimes what we are copying is the end of a larger object, the part that 5047 /// does not fit in registers. 5048 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5049 SDValue Chain, ISD::ArgFlagsTy Flags, 5050 SelectionDAG &DAG, const SDLoc &dl) { 5051 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5052 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5053 Flags.getNonZeroByValAlign(), false, false, false, 5054 MachinePointerInfo(), MachinePointerInfo()); 5055 } 5056 5057 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5058 /// tail calls. 5059 static void LowerMemOpCallTo( 5060 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5061 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5062 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5063 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5064 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5065 if (!isTailCall) { 5066 if (isVector) { 5067 SDValue StackPtr; 5068 if (isPPC64) 5069 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5070 else 5071 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5072 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5073 DAG.getConstant(ArgOffset, dl, PtrVT)); 5074 } 5075 MemOpChains.push_back( 5076 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5077 // Calculate and remember argument location. 5078 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5079 TailCallArguments); 5080 } 5081 5082 static void 5083 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5084 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5085 SDValue FPOp, 5086 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5087 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5088 // might overwrite each other in case of tail call optimization. 5089 SmallVector<SDValue, 8> MemOpChains2; 5090 // Do not flag preceding copytoreg stuff together with the following stuff. 5091 InFlag = SDValue(); 5092 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5093 MemOpChains2, dl); 5094 if (!MemOpChains2.empty()) 5095 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5096 5097 // Store the return address to the appropriate stack slot. 5098 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5099 5100 // Emit callseq_end just before tailcall node. 5101 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5102 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5103 InFlag = Chain.getValue(1); 5104 } 5105 5106 // Is this global address that of a function that can be called by name? (as 5107 // opposed to something that must hold a descriptor for an indirect call). 5108 static bool isFunctionGlobalAddress(SDValue Callee) { 5109 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5110 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5111 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5112 return false; 5113 5114 return G->getGlobal()->getValueType()->isFunctionTy(); 5115 } 5116 5117 return false; 5118 } 5119 5120 SDValue PPCTargetLowering::LowerCallResult( 5121 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5122 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5123 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5124 SmallVector<CCValAssign, 16> RVLocs; 5125 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5126 *DAG.getContext()); 5127 5128 CCRetInfo.AnalyzeCallResult( 5129 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5130 ? RetCC_PPC_Cold 5131 : RetCC_PPC); 5132 5133 // Copy all of the result registers out of their specified physreg. 5134 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5135 CCValAssign &VA = RVLocs[i]; 5136 assert(VA.isRegLoc() && "Can only return in registers!"); 5137 5138 SDValue Val; 5139 5140 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5141 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5142 InFlag); 5143 Chain = Lo.getValue(1); 5144 InFlag = Lo.getValue(2); 5145 VA = RVLocs[++i]; // skip ahead to next loc 5146 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5147 InFlag); 5148 Chain = Hi.getValue(1); 5149 InFlag = Hi.getValue(2); 5150 if (!Subtarget.isLittleEndian()) 5151 std::swap (Lo, Hi); 5152 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5153 } else { 5154 Val = DAG.getCopyFromReg(Chain, dl, 5155 VA.getLocReg(), VA.getLocVT(), InFlag); 5156 Chain = Val.getValue(1); 5157 InFlag = Val.getValue(2); 5158 } 5159 5160 switch (VA.getLocInfo()) { 5161 default: llvm_unreachable("Unknown loc info!"); 5162 case CCValAssign::Full: break; 5163 case CCValAssign::AExt: 5164 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5165 break; 5166 case CCValAssign::ZExt: 5167 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5168 DAG.getValueType(VA.getValVT())); 5169 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5170 break; 5171 case CCValAssign::SExt: 5172 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5173 DAG.getValueType(VA.getValVT())); 5174 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5175 break; 5176 } 5177 5178 InVals.push_back(Val); 5179 } 5180 5181 return Chain; 5182 } 5183 5184 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5185 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5186 // PatchPoint calls are not indirect. 5187 if (isPatchPoint) 5188 return false; 5189 5190 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5191 return false; 5192 5193 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5194 // becuase the immediate function pointer points to a descriptor instead of 5195 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5196 // pointer immediate points to the global entry point, while the BLA would 5197 // need to jump to the local entry point (see rL211174). 5198 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5199 isBLACompatibleAddress(Callee, DAG)) 5200 return false; 5201 5202 return true; 5203 } 5204 5205 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5206 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5207 return Subtarget.isAIXABI() || 5208 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5209 } 5210 5211 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5212 const Function &Caller, const SDValue &Callee, 5213 const PPCSubtarget &Subtarget, 5214 const TargetMachine &TM, 5215 bool IsStrictFPCall = false) { 5216 if (CFlags.IsTailCall) 5217 return PPCISD::TC_RETURN; 5218 5219 unsigned RetOpc = 0; 5220 // This is a call through a function pointer. 5221 if (CFlags.IsIndirect) { 5222 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5223 // indirect calls. The save of the caller's TOC pointer to the stack will be 5224 // inserted into the DAG as part of call lowering. The restore of the TOC 5225 // pointer is modeled by using a pseudo instruction for the call opcode that 5226 // represents the 2 instruction sequence of an indirect branch and link, 5227 // immediately followed by a load of the TOC pointer from the the stack save 5228 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5229 // as it is not saved or used. 5230 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5231 : PPCISD::BCTRL; 5232 } else if (Subtarget.isUsingPCRelativeCalls()) { 5233 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5234 RetOpc = PPCISD::CALL_NOTOC; 5235 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5236 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5237 // immediately following the call instruction if the caller and callee may 5238 // have different TOC bases. At link time if the linker determines the calls 5239 // may not share a TOC base, the call is redirected to a trampoline inserted 5240 // by the linker. The trampoline will (among other things) save the callers 5241 // TOC pointer at an ABI designated offset in the linkage area and the 5242 // linker will rewrite the nop to be a load of the TOC pointer from the 5243 // linkage area into gpr2. 5244 RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5245 : PPCISD::CALL_NOP; 5246 else 5247 RetOpc = PPCISD::CALL; 5248 if (IsStrictFPCall) { 5249 switch (RetOpc) { 5250 default: 5251 llvm_unreachable("Unknown call opcode"); 5252 case PPCISD::BCTRL_LOAD_TOC: 5253 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM; 5254 break; 5255 case PPCISD::BCTRL: 5256 RetOpc = PPCISD::BCTRL_RM; 5257 break; 5258 case PPCISD::CALL_NOTOC: 5259 RetOpc = PPCISD::CALL_NOTOC_RM; 5260 break; 5261 case PPCISD::CALL: 5262 RetOpc = PPCISD::CALL_RM; 5263 break; 5264 case PPCISD::CALL_NOP: 5265 RetOpc = PPCISD::CALL_NOP_RM; 5266 break; 5267 } 5268 } 5269 return RetOpc; 5270 } 5271 5272 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5273 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5274 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5275 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5276 return SDValue(Dest, 0); 5277 5278 // Returns true if the callee is local, and false otherwise. 5279 auto isLocalCallee = [&]() { 5280 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5281 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5282 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5283 5284 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5285 !isa_and_nonnull<GlobalIFunc>(GV); 5286 }; 5287 5288 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5289 // a static relocation model causes some versions of GNU LD (2.17.50, at 5290 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5291 // built with secure-PLT. 5292 bool UsePlt = 5293 Subtarget.is32BitELFABI() && !isLocalCallee() && 5294 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5295 5296 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5297 const TargetMachine &TM = Subtarget.getTargetMachine(); 5298 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5299 MCSymbolXCOFF *S = 5300 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5301 5302 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5303 return DAG.getMCSymbol(S, PtrVT); 5304 }; 5305 5306 if (isFunctionGlobalAddress(Callee)) { 5307 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5308 5309 if (Subtarget.isAIXABI()) { 5310 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5311 return getAIXFuncEntryPointSymbolSDNode(GV); 5312 } 5313 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5314 UsePlt ? PPCII::MO_PLT : 0); 5315 } 5316 5317 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5318 const char *SymName = S->getSymbol(); 5319 if (Subtarget.isAIXABI()) { 5320 // If there exists a user-declared function whose name is the same as the 5321 // ExternalSymbol's, then we pick up the user-declared version. 5322 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5323 if (const Function *F = 5324 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5325 return getAIXFuncEntryPointSymbolSDNode(F); 5326 5327 // On AIX, direct function calls reference the symbol for the function's 5328 // entry point, which is named by prepending a "." before the function's 5329 // C-linkage name. A Qualname is returned here because an external 5330 // function entry point is a csect with XTY_ER property. 5331 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5332 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5333 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5334 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5335 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5336 return Sec->getQualNameSymbol(); 5337 }; 5338 5339 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5340 } 5341 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5342 UsePlt ? PPCII::MO_PLT : 0); 5343 } 5344 5345 // No transformation needed. 5346 assert(Callee.getNode() && "What no callee?"); 5347 return Callee; 5348 } 5349 5350 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5351 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5352 "Expected a CALLSEQ_STARTSDNode."); 5353 5354 // The last operand is the chain, except when the node has glue. If the node 5355 // has glue, then the last operand is the glue, and the chain is the second 5356 // last operand. 5357 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5358 if (LastValue.getValueType() != MVT::Glue) 5359 return LastValue; 5360 5361 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5362 } 5363 5364 // Creates the node that moves a functions address into the count register 5365 // to prepare for an indirect call instruction. 5366 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5367 SDValue &Glue, SDValue &Chain, 5368 const SDLoc &dl) { 5369 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5370 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5371 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5372 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5373 // The glue is the second value produced. 5374 Glue = Chain.getValue(1); 5375 } 5376 5377 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5378 SDValue &Glue, SDValue &Chain, 5379 SDValue CallSeqStart, 5380 const CallBase *CB, const SDLoc &dl, 5381 bool hasNest, 5382 const PPCSubtarget &Subtarget) { 5383 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5384 // entry point, but to the function descriptor (the function entry point 5385 // address is part of the function descriptor though). 5386 // The function descriptor is a three doubleword structure with the 5387 // following fields: function entry point, TOC base address and 5388 // environment pointer. 5389 // Thus for a call through a function pointer, the following actions need 5390 // to be performed: 5391 // 1. Save the TOC of the caller in the TOC save area of its stack 5392 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5393 // 2. Load the address of the function entry point from the function 5394 // descriptor. 5395 // 3. Load the TOC of the callee from the function descriptor into r2. 5396 // 4. Load the environment pointer from the function descriptor into 5397 // r11. 5398 // 5. Branch to the function entry point address. 5399 // 6. On return of the callee, the TOC of the caller needs to be 5400 // restored (this is done in FinishCall()). 5401 // 5402 // The loads are scheduled at the beginning of the call sequence, and the 5403 // register copies are flagged together to ensure that no other 5404 // operations can be scheduled in between. E.g. without flagging the 5405 // copies together, a TOC access in the caller could be scheduled between 5406 // the assignment of the callee TOC and the branch to the callee, which leads 5407 // to incorrect code. 5408 5409 // Start by loading the function address from the descriptor. 5410 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5411 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5412 ? (MachineMemOperand::MODereferenceable | 5413 MachineMemOperand::MOInvariant) 5414 : MachineMemOperand::MONone; 5415 5416 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5417 5418 // Registers used in building the DAG. 5419 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5420 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5421 5422 // Offsets of descriptor members. 5423 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5424 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5425 5426 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5427 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5428 5429 // One load for the functions entry point address. 5430 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5431 Alignment, MMOFlags); 5432 5433 // One for loading the TOC anchor for the module that contains the called 5434 // function. 5435 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5436 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5437 SDValue TOCPtr = 5438 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5439 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5440 5441 // One for loading the environment pointer. 5442 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5443 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5444 SDValue LoadEnvPtr = 5445 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5446 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5447 5448 5449 // Then copy the newly loaded TOC anchor to the TOC pointer. 5450 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5451 Chain = TOCVal.getValue(0); 5452 Glue = TOCVal.getValue(1); 5453 5454 // If the function call has an explicit 'nest' parameter, it takes the 5455 // place of the environment pointer. 5456 assert((!hasNest || !Subtarget.isAIXABI()) && 5457 "Nest parameter is not supported on AIX."); 5458 if (!hasNest) { 5459 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5460 Chain = EnvVal.getValue(0); 5461 Glue = EnvVal.getValue(1); 5462 } 5463 5464 // The rest of the indirect call sequence is the same as the non-descriptor 5465 // DAG. 5466 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5467 } 5468 5469 static void 5470 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5471 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5472 SelectionDAG &DAG, 5473 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5474 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5475 const PPCSubtarget &Subtarget) { 5476 const bool IsPPC64 = Subtarget.isPPC64(); 5477 // MVT for a general purpose register. 5478 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5479 5480 // First operand is always the chain. 5481 Ops.push_back(Chain); 5482 5483 // If it's a direct call pass the callee as the second operand. 5484 if (!CFlags.IsIndirect) 5485 Ops.push_back(Callee); 5486 else { 5487 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5488 5489 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5490 // on the stack (this would have been done in `LowerCall_64SVR4` or 5491 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5492 // represents both the indirect branch and a load that restores the TOC 5493 // pointer from the linkage area. The operand for the TOC restore is an add 5494 // of the TOC save offset to the stack pointer. This must be the second 5495 // operand: after the chain input but before any other variadic arguments. 5496 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5497 // saved or used. 5498 if (isTOCSaveRestoreRequired(Subtarget)) { 5499 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5500 5501 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5502 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5503 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5504 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5505 Ops.push_back(AddTOC); 5506 } 5507 5508 // Add the register used for the environment pointer. 5509 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5510 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5511 RegVT)); 5512 5513 5514 // Add CTR register as callee so a bctr can be emitted later. 5515 if (CFlags.IsTailCall) 5516 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5517 } 5518 5519 // If this is a tail call add stack pointer delta. 5520 if (CFlags.IsTailCall) 5521 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5522 5523 // Add argument registers to the end of the list so that they are known live 5524 // into the call. 5525 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5526 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5527 RegsToPass[i].second.getValueType())); 5528 5529 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5530 // no way to mark dependencies as implicit here. 5531 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5532 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5533 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5534 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5535 5536 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5537 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5538 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5539 5540 // Add a register mask operand representing the call-preserved registers. 5541 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5542 const uint32_t *Mask = 5543 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5544 assert(Mask && "Missing call preserved mask for calling convention"); 5545 Ops.push_back(DAG.getRegisterMask(Mask)); 5546 5547 // If the glue is valid, it is the last operand. 5548 if (Glue.getNode()) 5549 Ops.push_back(Glue); 5550 } 5551 5552 SDValue PPCTargetLowering::FinishCall( 5553 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5554 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5555 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5556 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5557 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5558 5559 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5560 Subtarget.isAIXABI()) 5561 setUsesTOCBasePtr(DAG); 5562 5563 unsigned CallOpc = 5564 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5565 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false); 5566 5567 if (!CFlags.IsIndirect) 5568 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5569 else if (Subtarget.usesFunctionDescriptors()) 5570 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5571 dl, CFlags.HasNest, Subtarget); 5572 else 5573 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5574 5575 // Build the operand list for the call instruction. 5576 SmallVector<SDValue, 8> Ops; 5577 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5578 SPDiff, Subtarget); 5579 5580 // Emit tail call. 5581 if (CFlags.IsTailCall) { 5582 // Indirect tail call when using PC Relative calls do not have the same 5583 // constraints. 5584 assert(((Callee.getOpcode() == ISD::Register && 5585 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5586 Callee.getOpcode() == ISD::TargetExternalSymbol || 5587 Callee.getOpcode() == ISD::TargetGlobalAddress || 5588 isa<ConstantSDNode>(Callee) || 5589 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5590 "Expecting a global address, external symbol, absolute value, " 5591 "register or an indirect tail call when PC Relative calls are " 5592 "used."); 5593 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5594 assert(CallOpc == PPCISD::TC_RETURN && 5595 "Unexpected call opcode for a tail call."); 5596 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5597 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5598 } 5599 5600 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5601 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5602 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5603 Glue = Chain.getValue(1); 5604 5605 // When performing tail call optimization the callee pops its arguments off 5606 // the stack. Account for this here so these bytes can be pushed back on in 5607 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5608 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5609 getTargetMachine().Options.GuaranteedTailCallOpt) 5610 ? NumBytes 5611 : 0; 5612 5613 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5614 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5615 Glue, dl); 5616 Glue = Chain.getValue(1); 5617 5618 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5619 DAG, InVals); 5620 } 5621 5622 SDValue 5623 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5624 SmallVectorImpl<SDValue> &InVals) const { 5625 SelectionDAG &DAG = CLI.DAG; 5626 SDLoc &dl = CLI.DL; 5627 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5628 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5629 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5630 SDValue Chain = CLI.Chain; 5631 SDValue Callee = CLI.Callee; 5632 bool &isTailCall = CLI.IsTailCall; 5633 CallingConv::ID CallConv = CLI.CallConv; 5634 bool isVarArg = CLI.IsVarArg; 5635 bool isPatchPoint = CLI.IsPatchPoint; 5636 const CallBase *CB = CLI.CB; 5637 5638 if (isTailCall) { 5639 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5640 isTailCall = false; 5641 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5642 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5643 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5644 else 5645 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5646 Ins, DAG); 5647 if (isTailCall) { 5648 ++NumTailCalls; 5649 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5650 ++NumSiblingCalls; 5651 5652 // PC Relative calls no longer guarantee that the callee is a Global 5653 // Address Node. The callee could be an indirect tail call in which 5654 // case the SDValue for the callee could be a load (to load the address 5655 // of a function pointer) or it may be a register copy (to move the 5656 // address of the callee from a function parameter into a virtual 5657 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5658 assert((Subtarget.isUsingPCRelativeCalls() || 5659 isa<GlobalAddressSDNode>(Callee)) && 5660 "Callee should be an llvm::Function object."); 5661 5662 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5663 << "\nTCO callee: "); 5664 LLVM_DEBUG(Callee.dump()); 5665 } 5666 } 5667 5668 if (!isTailCall && CB && CB->isMustTailCall()) 5669 report_fatal_error("failed to perform tail call elimination on a call " 5670 "site marked musttail"); 5671 5672 // When long calls (i.e. indirect calls) are always used, calls are always 5673 // made via function pointer. If we have a function name, first translate it 5674 // into a pointer. 5675 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5676 !isTailCall) 5677 Callee = LowerGlobalAddress(Callee, DAG); 5678 5679 CallFlags CFlags( 5680 CallConv, isTailCall, isVarArg, isPatchPoint, 5681 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5682 // hasNest 5683 Subtarget.is64BitELFABI() && 5684 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5685 CLI.NoMerge); 5686 5687 if (Subtarget.isAIXABI()) 5688 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5689 InVals, CB); 5690 5691 assert(Subtarget.isSVR4ABI()); 5692 if (Subtarget.isPPC64()) 5693 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5694 InVals, CB); 5695 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5696 InVals, CB); 5697 } 5698 5699 SDValue PPCTargetLowering::LowerCall_32SVR4( 5700 SDValue Chain, SDValue Callee, CallFlags CFlags, 5701 const SmallVectorImpl<ISD::OutputArg> &Outs, 5702 const SmallVectorImpl<SDValue> &OutVals, 5703 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5704 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5705 const CallBase *CB) const { 5706 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5707 // of the 32-bit SVR4 ABI stack frame layout. 5708 5709 const CallingConv::ID CallConv = CFlags.CallConv; 5710 const bool IsVarArg = CFlags.IsVarArg; 5711 const bool IsTailCall = CFlags.IsTailCall; 5712 5713 assert((CallConv == CallingConv::C || 5714 CallConv == CallingConv::Cold || 5715 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5716 5717 const Align PtrAlign(4); 5718 5719 MachineFunction &MF = DAG.getMachineFunction(); 5720 5721 // Mark this function as potentially containing a function that contains a 5722 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5723 // and restoring the callers stack pointer in this functions epilog. This is 5724 // done because by tail calling the called function might overwrite the value 5725 // in this function's (MF) stack pointer stack slot 0(SP). 5726 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5727 CallConv == CallingConv::Fast) 5728 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5729 5730 // Count how many bytes are to be pushed on the stack, including the linkage 5731 // area, parameter list area and the part of the local variable space which 5732 // contains copies of aggregates which are passed by value. 5733 5734 // Assign locations to all of the outgoing arguments. 5735 SmallVector<CCValAssign, 16> ArgLocs; 5736 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5737 5738 // Reserve space for the linkage area on the stack. 5739 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5740 PtrAlign); 5741 if (useSoftFloat()) 5742 CCInfo.PreAnalyzeCallOperands(Outs); 5743 5744 if (IsVarArg) { 5745 // Handle fixed and variable vector arguments differently. 5746 // Fixed vector arguments go into registers as long as registers are 5747 // available. Variable vector arguments always go into memory. 5748 unsigned NumArgs = Outs.size(); 5749 5750 for (unsigned i = 0; i != NumArgs; ++i) { 5751 MVT ArgVT = Outs[i].VT; 5752 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5753 bool Result; 5754 5755 if (Outs[i].IsFixed) { 5756 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5757 CCInfo); 5758 } else { 5759 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5760 ArgFlags, CCInfo); 5761 } 5762 5763 if (Result) { 5764 #ifndef NDEBUG 5765 errs() << "Call operand #" << i << " has unhandled type " 5766 << EVT(ArgVT).getEVTString() << "\n"; 5767 #endif 5768 llvm_unreachable(nullptr); 5769 } 5770 } 5771 } else { 5772 // All arguments are treated the same. 5773 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5774 } 5775 CCInfo.clearWasPPCF128(); 5776 5777 // Assign locations to all of the outgoing aggregate by value arguments. 5778 SmallVector<CCValAssign, 16> ByValArgLocs; 5779 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5780 5781 // Reserve stack space for the allocations in CCInfo. 5782 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5783 5784 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5785 5786 // Size of the linkage area, parameter list area and the part of the local 5787 // space variable where copies of aggregates which are passed by value are 5788 // stored. 5789 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5790 5791 // Calculate by how many bytes the stack has to be adjusted in case of tail 5792 // call optimization. 5793 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5794 5795 // Adjust the stack pointer for the new arguments... 5796 // These operations are automatically eliminated by the prolog/epilog pass 5797 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5798 SDValue CallSeqStart = Chain; 5799 5800 // Load the return address and frame pointer so it can be moved somewhere else 5801 // later. 5802 SDValue LROp, FPOp; 5803 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5804 5805 // Set up a copy of the stack pointer for use loading and storing any 5806 // arguments that may not fit in the registers available for argument 5807 // passing. 5808 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5809 5810 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5811 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5812 SmallVector<SDValue, 8> MemOpChains; 5813 5814 bool seenFloatArg = false; 5815 // Walk the register/memloc assignments, inserting copies/loads. 5816 // i - Tracks the index into the list of registers allocated for the call 5817 // RealArgIdx - Tracks the index into the list of actual function arguments 5818 // j - Tracks the index into the list of byval arguments 5819 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5820 i != e; 5821 ++i, ++RealArgIdx) { 5822 CCValAssign &VA = ArgLocs[i]; 5823 SDValue Arg = OutVals[RealArgIdx]; 5824 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5825 5826 if (Flags.isByVal()) { 5827 // Argument is an aggregate which is passed by value, thus we need to 5828 // create a copy of it in the local variable space of the current stack 5829 // frame (which is the stack frame of the caller) and pass the address of 5830 // this copy to the callee. 5831 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5832 CCValAssign &ByValVA = ByValArgLocs[j++]; 5833 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5834 5835 // Memory reserved in the local variable space of the callers stack frame. 5836 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5837 5838 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5839 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5840 StackPtr, PtrOff); 5841 5842 // Create a copy of the argument in the local area of the current 5843 // stack frame. 5844 SDValue MemcpyCall = 5845 CreateCopyOfByValArgument(Arg, PtrOff, 5846 CallSeqStart.getNode()->getOperand(0), 5847 Flags, DAG, dl); 5848 5849 // This must go outside the CALLSEQ_START..END. 5850 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5851 SDLoc(MemcpyCall)); 5852 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5853 NewCallSeqStart.getNode()); 5854 Chain = CallSeqStart = NewCallSeqStart; 5855 5856 // Pass the address of the aggregate copy on the stack either in a 5857 // physical register or in the parameter list area of the current stack 5858 // frame to the callee. 5859 Arg = PtrOff; 5860 } 5861 5862 // When useCRBits() is true, there can be i1 arguments. 5863 // It is because getRegisterType(MVT::i1) => MVT::i1, 5864 // and for other integer types getRegisterType() => MVT::i32. 5865 // Extend i1 and ensure callee will get i32. 5866 if (Arg.getValueType() == MVT::i1) 5867 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5868 dl, MVT::i32, Arg); 5869 5870 if (VA.isRegLoc()) { 5871 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5872 // Put argument in a physical register. 5873 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5874 bool IsLE = Subtarget.isLittleEndian(); 5875 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5876 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5877 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5878 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5879 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5880 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5881 SVal.getValue(0))); 5882 } else 5883 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5884 } else { 5885 // Put argument in the parameter list area of the current stack frame. 5886 assert(VA.isMemLoc()); 5887 unsigned LocMemOffset = VA.getLocMemOffset(); 5888 5889 if (!IsTailCall) { 5890 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5891 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5892 StackPtr, PtrOff); 5893 5894 MemOpChains.push_back( 5895 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5896 } else { 5897 // Calculate and remember argument location. 5898 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5899 TailCallArguments); 5900 } 5901 } 5902 } 5903 5904 if (!MemOpChains.empty()) 5905 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5906 5907 // Build a sequence of copy-to-reg nodes chained together with token chain 5908 // and flag operands which copy the outgoing args into the appropriate regs. 5909 SDValue InFlag; 5910 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5911 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5912 RegsToPass[i].second, InFlag); 5913 InFlag = Chain.getValue(1); 5914 } 5915 5916 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5917 // registers. 5918 if (IsVarArg) { 5919 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5920 SDValue Ops[] = { Chain, InFlag }; 5921 5922 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5923 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5924 5925 InFlag = Chain.getValue(1); 5926 } 5927 5928 if (IsTailCall) 5929 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5930 TailCallArguments); 5931 5932 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5933 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5934 } 5935 5936 // Copy an argument into memory, being careful to do this outside the 5937 // call sequence for the call to which the argument belongs. 5938 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5939 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5940 SelectionDAG &DAG, const SDLoc &dl) const { 5941 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5942 CallSeqStart.getNode()->getOperand(0), 5943 Flags, DAG, dl); 5944 // The MEMCPY must go outside the CALLSEQ_START..END. 5945 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5946 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5947 SDLoc(MemcpyCall)); 5948 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5949 NewCallSeqStart.getNode()); 5950 return NewCallSeqStart; 5951 } 5952 5953 SDValue PPCTargetLowering::LowerCall_64SVR4( 5954 SDValue Chain, SDValue Callee, CallFlags CFlags, 5955 const SmallVectorImpl<ISD::OutputArg> &Outs, 5956 const SmallVectorImpl<SDValue> &OutVals, 5957 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5958 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5959 const CallBase *CB) const { 5960 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5961 bool isLittleEndian = Subtarget.isLittleEndian(); 5962 unsigned NumOps = Outs.size(); 5963 bool IsSibCall = false; 5964 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5965 5966 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5967 unsigned PtrByteSize = 8; 5968 5969 MachineFunction &MF = DAG.getMachineFunction(); 5970 5971 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5972 IsSibCall = true; 5973 5974 // Mark this function as potentially containing a function that contains a 5975 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5976 // and restoring the callers stack pointer in this functions epilog. This is 5977 // done because by tail calling the called function might overwrite the value 5978 // in this function's (MF) stack pointer stack slot 0(SP). 5979 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5980 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5981 5982 assert(!(IsFastCall && CFlags.IsVarArg) && 5983 "fastcc not supported on varargs functions"); 5984 5985 // Count how many bytes are to be pushed on the stack, including the linkage 5986 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5987 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5988 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5989 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5990 unsigned NumBytes = LinkageSize; 5991 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5992 5993 static const MCPhysReg GPR[] = { 5994 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5995 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5996 }; 5997 static const MCPhysReg VR[] = { 5998 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5999 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6000 }; 6001 6002 const unsigned NumGPRs = array_lengthof(GPR); 6003 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6004 const unsigned NumVRs = array_lengthof(VR); 6005 6006 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6007 // can be passed to the callee in registers. 6008 // For the fast calling convention, there is another check below. 6009 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6010 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6011 if (!HasParameterArea) { 6012 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6013 unsigned AvailableFPRs = NumFPRs; 6014 unsigned AvailableVRs = NumVRs; 6015 unsigned NumBytesTmp = NumBytes; 6016 for (unsigned i = 0; i != NumOps; ++i) { 6017 if (Outs[i].Flags.isNest()) continue; 6018 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6019 PtrByteSize, LinkageSize, ParamAreaSize, 6020 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6021 HasParameterArea = true; 6022 } 6023 } 6024 6025 // When using the fast calling convention, we don't provide backing for 6026 // arguments that will be in registers. 6027 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6028 6029 // Avoid allocating parameter area for fastcc functions if all the arguments 6030 // can be passed in the registers. 6031 if (IsFastCall) 6032 HasParameterArea = false; 6033 6034 // Add up all the space actually used. 6035 for (unsigned i = 0; i != NumOps; ++i) { 6036 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6037 EVT ArgVT = Outs[i].VT; 6038 EVT OrigVT = Outs[i].ArgVT; 6039 6040 if (Flags.isNest()) 6041 continue; 6042 6043 if (IsFastCall) { 6044 if (Flags.isByVal()) { 6045 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6046 if (NumGPRsUsed > NumGPRs) 6047 HasParameterArea = true; 6048 } else { 6049 switch (ArgVT.getSimpleVT().SimpleTy) { 6050 default: llvm_unreachable("Unexpected ValueType for argument!"); 6051 case MVT::i1: 6052 case MVT::i32: 6053 case MVT::i64: 6054 if (++NumGPRsUsed <= NumGPRs) 6055 continue; 6056 break; 6057 case MVT::v4i32: 6058 case MVT::v8i16: 6059 case MVT::v16i8: 6060 case MVT::v2f64: 6061 case MVT::v2i64: 6062 case MVT::v1i128: 6063 case MVT::f128: 6064 if (++NumVRsUsed <= NumVRs) 6065 continue; 6066 break; 6067 case MVT::v4f32: 6068 if (++NumVRsUsed <= NumVRs) 6069 continue; 6070 break; 6071 case MVT::f32: 6072 case MVT::f64: 6073 if (++NumFPRsUsed <= NumFPRs) 6074 continue; 6075 break; 6076 } 6077 HasParameterArea = true; 6078 } 6079 } 6080 6081 /* Respect alignment of argument on the stack. */ 6082 auto Alignement = 6083 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6084 NumBytes = alignTo(NumBytes, Alignement); 6085 6086 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6087 if (Flags.isInConsecutiveRegsLast()) 6088 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6089 } 6090 6091 unsigned NumBytesActuallyUsed = NumBytes; 6092 6093 // In the old ELFv1 ABI, 6094 // the prolog code of the callee may store up to 8 GPR argument registers to 6095 // the stack, allowing va_start to index over them in memory if its varargs. 6096 // Because we cannot tell if this is needed on the caller side, we have to 6097 // conservatively assume that it is needed. As such, make sure we have at 6098 // least enough stack space for the caller to store the 8 GPRs. 6099 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6100 // really requires memory operands, e.g. a vararg function. 6101 if (HasParameterArea) 6102 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6103 else 6104 NumBytes = LinkageSize; 6105 6106 // Tail call needs the stack to be aligned. 6107 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6108 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6109 6110 int SPDiff = 0; 6111 6112 // Calculate by how many bytes the stack has to be adjusted in case of tail 6113 // call optimization. 6114 if (!IsSibCall) 6115 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6116 6117 // To protect arguments on the stack from being clobbered in a tail call, 6118 // force all the loads to happen before doing any other lowering. 6119 if (CFlags.IsTailCall) 6120 Chain = DAG.getStackArgumentTokenFactor(Chain); 6121 6122 // Adjust the stack pointer for the new arguments... 6123 // These operations are automatically eliminated by the prolog/epilog pass 6124 if (!IsSibCall) 6125 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6126 SDValue CallSeqStart = Chain; 6127 6128 // Load the return address and frame pointer so it can be move somewhere else 6129 // later. 6130 SDValue LROp, FPOp; 6131 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6132 6133 // Set up a copy of the stack pointer for use loading and storing any 6134 // arguments that may not fit in the registers available for argument 6135 // passing. 6136 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6137 6138 // Figure out which arguments are going to go in registers, and which in 6139 // memory. Also, if this is a vararg function, floating point operations 6140 // must be stored to our stack, and loaded into integer regs as well, if 6141 // any integer regs are available for argument passing. 6142 unsigned ArgOffset = LinkageSize; 6143 6144 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6145 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6146 6147 SmallVector<SDValue, 8> MemOpChains; 6148 for (unsigned i = 0; i != NumOps; ++i) { 6149 SDValue Arg = OutVals[i]; 6150 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6151 EVT ArgVT = Outs[i].VT; 6152 EVT OrigVT = Outs[i].ArgVT; 6153 6154 // PtrOff will be used to store the current argument to the stack if a 6155 // register cannot be found for it. 6156 SDValue PtrOff; 6157 6158 // We re-align the argument offset for each argument, except when using the 6159 // fast calling convention, when we need to make sure we do that only when 6160 // we'll actually use a stack slot. 6161 auto ComputePtrOff = [&]() { 6162 /* Respect alignment of argument on the stack. */ 6163 auto Alignment = 6164 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6165 ArgOffset = alignTo(ArgOffset, Alignment); 6166 6167 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6168 6169 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6170 }; 6171 6172 if (!IsFastCall) { 6173 ComputePtrOff(); 6174 6175 /* Compute GPR index associated with argument offset. */ 6176 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6177 GPR_idx = std::min(GPR_idx, NumGPRs); 6178 } 6179 6180 // Promote integers to 64-bit values. 6181 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6182 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6183 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6184 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6185 } 6186 6187 // FIXME memcpy is used way more than necessary. Correctness first. 6188 // Note: "by value" is code for passing a structure by value, not 6189 // basic types. 6190 if (Flags.isByVal()) { 6191 // Note: Size includes alignment padding, so 6192 // struct x { short a; char b; } 6193 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6194 // These are the proper values we need for right-justifying the 6195 // aggregate in a parameter register. 6196 unsigned Size = Flags.getByValSize(); 6197 6198 // An empty aggregate parameter takes up no storage and no 6199 // registers. 6200 if (Size == 0) 6201 continue; 6202 6203 if (IsFastCall) 6204 ComputePtrOff(); 6205 6206 // All aggregates smaller than 8 bytes must be passed right-justified. 6207 if (Size==1 || Size==2 || Size==4) { 6208 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6209 if (GPR_idx != NumGPRs) { 6210 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6211 MachinePointerInfo(), VT); 6212 MemOpChains.push_back(Load.getValue(1)); 6213 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6214 6215 ArgOffset += PtrByteSize; 6216 continue; 6217 } 6218 } 6219 6220 if (GPR_idx == NumGPRs && Size < 8) { 6221 SDValue AddPtr = PtrOff; 6222 if (!isLittleEndian) { 6223 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6224 PtrOff.getValueType()); 6225 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6226 } 6227 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6228 CallSeqStart, 6229 Flags, DAG, dl); 6230 ArgOffset += PtrByteSize; 6231 continue; 6232 } 6233 // Copy the object to parameter save area if it can not be entirely passed 6234 // by registers. 6235 // FIXME: we only need to copy the parts which need to be passed in 6236 // parameter save area. For the parts passed by registers, we don't need 6237 // to copy them to the stack although we need to allocate space for them 6238 // in parameter save area. 6239 if ((NumGPRs - GPR_idx) * PtrByteSize < Size) 6240 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6241 CallSeqStart, 6242 Flags, DAG, dl); 6243 6244 // When a register is available, pass a small aggregate right-justified. 6245 if (Size < 8 && GPR_idx != NumGPRs) { 6246 // The easiest way to get this right-justified in a register 6247 // is to copy the structure into the rightmost portion of a 6248 // local variable slot, then load the whole slot into the 6249 // register. 6250 // FIXME: The memcpy seems to produce pretty awful code for 6251 // small aggregates, particularly for packed ones. 6252 // FIXME: It would be preferable to use the slot in the 6253 // parameter save area instead of a new local variable. 6254 SDValue AddPtr = PtrOff; 6255 if (!isLittleEndian) { 6256 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6257 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6258 } 6259 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6260 CallSeqStart, 6261 Flags, DAG, dl); 6262 6263 // Load the slot into the register. 6264 SDValue Load = 6265 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6266 MemOpChains.push_back(Load.getValue(1)); 6267 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6268 6269 // Done with this argument. 6270 ArgOffset += PtrByteSize; 6271 continue; 6272 } 6273 6274 // For aggregates larger than PtrByteSize, copy the pieces of the 6275 // object that fit into registers from the parameter save area. 6276 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6277 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6278 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6279 if (GPR_idx != NumGPRs) { 6280 SDValue Load = 6281 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6282 MemOpChains.push_back(Load.getValue(1)); 6283 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6284 ArgOffset += PtrByteSize; 6285 } else { 6286 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6287 break; 6288 } 6289 } 6290 continue; 6291 } 6292 6293 switch (Arg.getSimpleValueType().SimpleTy) { 6294 default: llvm_unreachable("Unexpected ValueType for argument!"); 6295 case MVT::i1: 6296 case MVT::i32: 6297 case MVT::i64: 6298 if (Flags.isNest()) { 6299 // The 'nest' parameter, if any, is passed in R11. 6300 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6301 break; 6302 } 6303 6304 // These can be scalar arguments or elements of an integer array type 6305 // passed directly. Clang may use those instead of "byval" aggregate 6306 // types to avoid forcing arguments to memory unnecessarily. 6307 if (GPR_idx != NumGPRs) { 6308 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6309 } else { 6310 if (IsFastCall) 6311 ComputePtrOff(); 6312 6313 assert(HasParameterArea && 6314 "Parameter area must exist to pass an argument in memory."); 6315 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6316 true, CFlags.IsTailCall, false, MemOpChains, 6317 TailCallArguments, dl); 6318 if (IsFastCall) 6319 ArgOffset += PtrByteSize; 6320 } 6321 if (!IsFastCall) 6322 ArgOffset += PtrByteSize; 6323 break; 6324 case MVT::f32: 6325 case MVT::f64: { 6326 // These can be scalar arguments or elements of a float array type 6327 // passed directly. The latter are used to implement ELFv2 homogenous 6328 // float aggregates. 6329 6330 // Named arguments go into FPRs first, and once they overflow, the 6331 // remaining arguments go into GPRs and then the parameter save area. 6332 // Unnamed arguments for vararg functions always go to GPRs and 6333 // then the parameter save area. For now, put all arguments to vararg 6334 // routines always in both locations (FPR *and* GPR or stack slot). 6335 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6336 bool NeededLoad = false; 6337 6338 // First load the argument into the next available FPR. 6339 if (FPR_idx != NumFPRs) 6340 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6341 6342 // Next, load the argument into GPR or stack slot if needed. 6343 if (!NeedGPROrStack) 6344 ; 6345 else if (GPR_idx != NumGPRs && !IsFastCall) { 6346 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6347 // once we support fp <-> gpr moves. 6348 6349 // In the non-vararg case, this can only ever happen in the 6350 // presence of f32 array types, since otherwise we never run 6351 // out of FPRs before running out of GPRs. 6352 SDValue ArgVal; 6353 6354 // Double values are always passed in a single GPR. 6355 if (Arg.getValueType() != MVT::f32) { 6356 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6357 6358 // Non-array float values are extended and passed in a GPR. 6359 } else if (!Flags.isInConsecutiveRegs()) { 6360 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6361 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6362 6363 // If we have an array of floats, we collect every odd element 6364 // together with its predecessor into one GPR. 6365 } else if (ArgOffset % PtrByteSize != 0) { 6366 SDValue Lo, Hi; 6367 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6368 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6369 if (!isLittleEndian) 6370 std::swap(Lo, Hi); 6371 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6372 6373 // The final element, if even, goes into the first half of a GPR. 6374 } else if (Flags.isInConsecutiveRegsLast()) { 6375 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6376 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6377 if (!isLittleEndian) 6378 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6379 DAG.getConstant(32, dl, MVT::i32)); 6380 6381 // Non-final even elements are skipped; they will be handled 6382 // together the with subsequent argument on the next go-around. 6383 } else 6384 ArgVal = SDValue(); 6385 6386 if (ArgVal.getNode()) 6387 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6388 } else { 6389 if (IsFastCall) 6390 ComputePtrOff(); 6391 6392 // Single-precision floating-point values are mapped to the 6393 // second (rightmost) word of the stack doubleword. 6394 if (Arg.getValueType() == MVT::f32 && 6395 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6396 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6397 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6398 } 6399 6400 assert(HasParameterArea && 6401 "Parameter area must exist to pass an argument in memory."); 6402 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6403 true, CFlags.IsTailCall, false, MemOpChains, 6404 TailCallArguments, dl); 6405 6406 NeededLoad = true; 6407 } 6408 // When passing an array of floats, the array occupies consecutive 6409 // space in the argument area; only round up to the next doubleword 6410 // at the end of the array. Otherwise, each float takes 8 bytes. 6411 if (!IsFastCall || NeededLoad) { 6412 ArgOffset += (Arg.getValueType() == MVT::f32 && 6413 Flags.isInConsecutiveRegs()) ? 4 : 8; 6414 if (Flags.isInConsecutiveRegsLast()) 6415 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6416 } 6417 break; 6418 } 6419 case MVT::v4f32: 6420 case MVT::v4i32: 6421 case MVT::v8i16: 6422 case MVT::v16i8: 6423 case MVT::v2f64: 6424 case MVT::v2i64: 6425 case MVT::v1i128: 6426 case MVT::f128: 6427 // These can be scalar arguments or elements of a vector array type 6428 // passed directly. The latter are used to implement ELFv2 homogenous 6429 // vector aggregates. 6430 6431 // For a varargs call, named arguments go into VRs or on the stack as 6432 // usual; unnamed arguments always go to the stack or the corresponding 6433 // GPRs when within range. For now, we always put the value in both 6434 // locations (or even all three). 6435 if (CFlags.IsVarArg) { 6436 assert(HasParameterArea && 6437 "Parameter area must exist if we have a varargs call."); 6438 // We could elide this store in the case where the object fits 6439 // entirely in R registers. Maybe later. 6440 SDValue Store = 6441 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6442 MemOpChains.push_back(Store); 6443 if (VR_idx != NumVRs) { 6444 SDValue Load = 6445 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6446 MemOpChains.push_back(Load.getValue(1)); 6447 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6448 } 6449 ArgOffset += 16; 6450 for (unsigned i=0; i<16; i+=PtrByteSize) { 6451 if (GPR_idx == NumGPRs) 6452 break; 6453 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6454 DAG.getConstant(i, dl, PtrVT)); 6455 SDValue Load = 6456 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6457 MemOpChains.push_back(Load.getValue(1)); 6458 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6459 } 6460 break; 6461 } 6462 6463 // Non-varargs Altivec params go into VRs or on the stack. 6464 if (VR_idx != NumVRs) { 6465 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6466 } else { 6467 if (IsFastCall) 6468 ComputePtrOff(); 6469 6470 assert(HasParameterArea && 6471 "Parameter area must exist to pass an argument in memory."); 6472 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6473 true, CFlags.IsTailCall, true, MemOpChains, 6474 TailCallArguments, dl); 6475 if (IsFastCall) 6476 ArgOffset += 16; 6477 } 6478 6479 if (!IsFastCall) 6480 ArgOffset += 16; 6481 break; 6482 } 6483 } 6484 6485 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6486 "mismatch in size of parameter area"); 6487 (void)NumBytesActuallyUsed; 6488 6489 if (!MemOpChains.empty()) 6490 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6491 6492 // Check if this is an indirect call (MTCTR/BCTRL). 6493 // See prepareDescriptorIndirectCall and buildCallOperands for more 6494 // information about calls through function pointers in the 64-bit SVR4 ABI. 6495 if (CFlags.IsIndirect) { 6496 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6497 // caller in the TOC save area. 6498 if (isTOCSaveRestoreRequired(Subtarget)) { 6499 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6500 // Load r2 into a virtual register and store it to the TOC save area. 6501 setUsesTOCBasePtr(DAG); 6502 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6503 // TOC save area offset. 6504 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6505 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6506 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6507 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6508 MachinePointerInfo::getStack( 6509 DAG.getMachineFunction(), TOCSaveOffset)); 6510 } 6511 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6512 // This does not mean the MTCTR instruction must use R12; it's easier 6513 // to model this as an extra parameter, so do that. 6514 if (isELFv2ABI && !CFlags.IsPatchPoint) 6515 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6516 } 6517 6518 // Build a sequence of copy-to-reg nodes chained together with token chain 6519 // and flag operands which copy the outgoing args into the appropriate regs. 6520 SDValue InFlag; 6521 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6522 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6523 RegsToPass[i].second, InFlag); 6524 InFlag = Chain.getValue(1); 6525 } 6526 6527 if (CFlags.IsTailCall && !IsSibCall) 6528 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6529 TailCallArguments); 6530 6531 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6532 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6533 } 6534 6535 // Returns true when the shadow of a general purpose argument register 6536 // in the parameter save area is aligned to at least 'RequiredAlign'. 6537 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6538 assert(RequiredAlign.value() <= 16 && 6539 "Required alignment greater than stack alignment."); 6540 switch (Reg) { 6541 default: 6542 report_fatal_error("called on invalid register."); 6543 case PPC::R5: 6544 case PPC::R9: 6545 case PPC::X3: 6546 case PPC::X5: 6547 case PPC::X7: 6548 case PPC::X9: 6549 // These registers are 16 byte aligned which is the most strict aligment 6550 // we can support. 6551 return true; 6552 case PPC::R3: 6553 case PPC::R7: 6554 case PPC::X4: 6555 case PPC::X6: 6556 case PPC::X8: 6557 case PPC::X10: 6558 // The shadow of these registers in the PSA is 8 byte aligned. 6559 return RequiredAlign <= 8; 6560 case PPC::R4: 6561 case PPC::R6: 6562 case PPC::R8: 6563 case PPC::R10: 6564 return RequiredAlign <= 4; 6565 } 6566 } 6567 6568 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6569 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6570 CCState &S) { 6571 AIXCCState &State = static_cast<AIXCCState &>(S); 6572 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6573 State.getMachineFunction().getSubtarget()); 6574 const bool IsPPC64 = Subtarget.isPPC64(); 6575 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6576 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6577 6578 if (ValVT == MVT::f128) 6579 report_fatal_error("f128 is unimplemented on AIX."); 6580 6581 if (ArgFlags.isNest()) 6582 report_fatal_error("Nest arguments are unimplemented."); 6583 6584 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6585 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6586 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6587 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6588 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6589 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6590 6591 static const MCPhysReg VR[] = {// Vector registers. 6592 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6593 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6594 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6595 6596 if (ArgFlags.isByVal()) { 6597 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6598 report_fatal_error("Pass-by-value arguments with alignment greater than " 6599 "register width are not supported."); 6600 6601 const unsigned ByValSize = ArgFlags.getByValSize(); 6602 6603 // An empty aggregate parameter takes up no storage and no registers, 6604 // but needs a MemLoc for a stack slot for the formal arguments side. 6605 if (ByValSize == 0) { 6606 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6607 State.getNextStackOffset(), RegVT, 6608 LocInfo)); 6609 return false; 6610 } 6611 6612 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6613 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6614 for (const unsigned E = Offset + StackSize; Offset < E; 6615 Offset += PtrAlign.value()) { 6616 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6617 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6618 else { 6619 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6620 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6621 LocInfo)); 6622 break; 6623 } 6624 } 6625 return false; 6626 } 6627 6628 // Arguments always reserve parameter save area. 6629 switch (ValVT.SimpleTy) { 6630 default: 6631 report_fatal_error("Unhandled value type for argument."); 6632 case MVT::i64: 6633 // i64 arguments should have been split to i32 for PPC32. 6634 assert(IsPPC64 && "PPC32 should have split i64 values."); 6635 LLVM_FALLTHROUGH; 6636 case MVT::i1: 6637 case MVT::i32: { 6638 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6639 // AIX integer arguments are always passed in register width. 6640 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6641 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6642 : CCValAssign::LocInfo::ZExt; 6643 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6644 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6645 else 6646 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6647 6648 return false; 6649 } 6650 case MVT::f32: 6651 case MVT::f64: { 6652 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6653 const unsigned StoreSize = LocVT.getStoreSize(); 6654 // Floats are always 4-byte aligned in the PSA on AIX. 6655 // This includes f64 in 64-bit mode for ABI compatibility. 6656 const unsigned Offset = 6657 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6658 unsigned FReg = State.AllocateReg(FPR); 6659 if (FReg) 6660 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6661 6662 // Reserve and initialize GPRs or initialize the PSA as required. 6663 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6664 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6665 assert(FReg && "An FPR should be available when a GPR is reserved."); 6666 if (State.isVarArg()) { 6667 // Successfully reserved GPRs are only initialized for vararg calls. 6668 // Custom handling is required for: 6669 // f64 in PPC32 needs to be split into 2 GPRs. 6670 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6671 State.addLoc( 6672 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6673 } 6674 } else { 6675 // If there are insufficient GPRs, the PSA needs to be initialized. 6676 // Initialization occurs even if an FPR was initialized for 6677 // compatibility with the AIX XL compiler. The full memory for the 6678 // argument will be initialized even if a prior word is saved in GPR. 6679 // A custom memLoc is used when the argument also passes in FPR so 6680 // that the callee handling can skip over it easily. 6681 State.addLoc( 6682 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6683 LocInfo) 6684 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6685 break; 6686 } 6687 } 6688 6689 return false; 6690 } 6691 case MVT::v4f32: 6692 case MVT::v4i32: 6693 case MVT::v8i16: 6694 case MVT::v16i8: 6695 case MVT::v2i64: 6696 case MVT::v2f64: 6697 case MVT::v1i128: { 6698 const unsigned VecSize = 16; 6699 const Align VecAlign(VecSize); 6700 6701 if (!State.isVarArg()) { 6702 // If there are vector registers remaining we don't consume any stack 6703 // space. 6704 if (unsigned VReg = State.AllocateReg(VR)) { 6705 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6706 return false; 6707 } 6708 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6709 // might be allocated in the portion of the PSA that is shadowed by the 6710 // GPRs. 6711 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6712 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6713 return false; 6714 } 6715 6716 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6717 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6718 6719 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6720 // Burn any underaligned registers and their shadowed stack space until 6721 // we reach the required alignment. 6722 while (NextRegIndex != GPRs.size() && 6723 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6724 // Shadow allocate register and its stack shadow. 6725 unsigned Reg = State.AllocateReg(GPRs); 6726 State.AllocateStack(PtrSize, PtrAlign); 6727 assert(Reg && "Allocating register unexpectedly failed."); 6728 (void)Reg; 6729 NextRegIndex = State.getFirstUnallocated(GPRs); 6730 } 6731 6732 // Vectors that are passed as fixed arguments are handled differently. 6733 // They are passed in VRs if any are available (unlike arguments passed 6734 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6735 // functions) 6736 if (State.isFixed(ValNo)) { 6737 if (unsigned VReg = State.AllocateReg(VR)) { 6738 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6739 // Shadow allocate GPRs and stack space even though we pass in a VR. 6740 for (unsigned I = 0; I != VecSize; I += PtrSize) 6741 State.AllocateReg(GPRs); 6742 State.AllocateStack(VecSize, VecAlign); 6743 return false; 6744 } 6745 // No vector registers remain so pass on the stack. 6746 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6747 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6748 return false; 6749 } 6750 6751 // If all GPRS are consumed then we pass the argument fully on the stack. 6752 if (NextRegIndex == GPRs.size()) { 6753 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6754 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6755 return false; 6756 } 6757 6758 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6759 // half of the argument, and then need to pass the remaining half on the 6760 // stack. 6761 if (GPRs[NextRegIndex] == PPC::R9) { 6762 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6763 State.addLoc( 6764 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6765 6766 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6767 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6768 assert(FirstReg && SecondReg && 6769 "Allocating R9 or R10 unexpectedly failed."); 6770 State.addLoc( 6771 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6772 State.addLoc( 6773 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6774 return false; 6775 } 6776 6777 // We have enough GPRs to fully pass the vector argument, and we have 6778 // already consumed any underaligned registers. Start with the custom 6779 // MemLoc and then the custom RegLocs. 6780 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6781 State.addLoc( 6782 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6783 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6784 const unsigned Reg = State.AllocateReg(GPRs); 6785 assert(Reg && "Failed to allocated register for vararg vector argument"); 6786 State.addLoc( 6787 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6788 } 6789 return false; 6790 } 6791 } 6792 return true; 6793 } 6794 6795 // So far, this function is only used by LowerFormalArguments_AIX() 6796 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6797 bool IsPPC64, 6798 bool HasP8Vector, 6799 bool HasVSX) { 6800 assert((IsPPC64 || SVT != MVT::i64) && 6801 "i64 should have been split for 32-bit codegen."); 6802 6803 switch (SVT) { 6804 default: 6805 report_fatal_error("Unexpected value type for formal argument"); 6806 case MVT::i1: 6807 case MVT::i32: 6808 case MVT::i64: 6809 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6810 case MVT::f32: 6811 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass; 6812 case MVT::f64: 6813 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass; 6814 case MVT::v4f32: 6815 case MVT::v4i32: 6816 case MVT::v8i16: 6817 case MVT::v16i8: 6818 case MVT::v2i64: 6819 case MVT::v2f64: 6820 case MVT::v1i128: 6821 return &PPC::VRRCRegClass; 6822 } 6823 } 6824 6825 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6826 SelectionDAG &DAG, SDValue ArgValue, 6827 MVT LocVT, const SDLoc &dl) { 6828 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6829 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6830 6831 if (Flags.isSExt()) 6832 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6833 DAG.getValueType(ValVT)); 6834 else if (Flags.isZExt()) 6835 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6836 DAG.getValueType(ValVT)); 6837 6838 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6839 } 6840 6841 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6842 const unsigned LASize = FL->getLinkageSize(); 6843 6844 if (PPC::GPRCRegClass.contains(Reg)) { 6845 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6846 "Reg must be a valid argument register!"); 6847 return LASize + 4 * (Reg - PPC::R3); 6848 } 6849 6850 if (PPC::G8RCRegClass.contains(Reg)) { 6851 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6852 "Reg must be a valid argument register!"); 6853 return LASize + 8 * (Reg - PPC::X3); 6854 } 6855 6856 llvm_unreachable("Only general purpose registers expected."); 6857 } 6858 6859 // AIX ABI Stack Frame Layout: 6860 // 6861 // Low Memory +--------------------------------------------+ 6862 // SP +---> | Back chain | ---+ 6863 // | +--------------------------------------------+ | 6864 // | | Saved Condition Register | | 6865 // | +--------------------------------------------+ | 6866 // | | Saved Linkage Register | | 6867 // | +--------------------------------------------+ | Linkage Area 6868 // | | Reserved for compilers | | 6869 // | +--------------------------------------------+ | 6870 // | | Reserved for binders | | 6871 // | +--------------------------------------------+ | 6872 // | | Saved TOC pointer | ---+ 6873 // | +--------------------------------------------+ 6874 // | | Parameter save area | 6875 // | +--------------------------------------------+ 6876 // | | Alloca space | 6877 // | +--------------------------------------------+ 6878 // | | Local variable space | 6879 // | +--------------------------------------------+ 6880 // | | Float/int conversion temporary | 6881 // | +--------------------------------------------+ 6882 // | | Save area for AltiVec registers | 6883 // | +--------------------------------------------+ 6884 // | | AltiVec alignment padding | 6885 // | +--------------------------------------------+ 6886 // | | Save area for VRSAVE register | 6887 // | +--------------------------------------------+ 6888 // | | Save area for General Purpose registers | 6889 // | +--------------------------------------------+ 6890 // | | Save area for Floating Point registers | 6891 // | +--------------------------------------------+ 6892 // +---- | Back chain | 6893 // High Memory +--------------------------------------------+ 6894 // 6895 // Specifications: 6896 // AIX 7.2 Assembler Language Reference 6897 // Subroutine linkage convention 6898 6899 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6900 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6901 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6902 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6903 6904 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6905 CallConv == CallingConv::Fast) && 6906 "Unexpected calling convention!"); 6907 6908 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6909 report_fatal_error("Tail call support is unimplemented on AIX."); 6910 6911 if (useSoftFloat()) 6912 report_fatal_error("Soft float support is unimplemented on AIX."); 6913 6914 const PPCSubtarget &Subtarget = 6915 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6916 6917 const bool IsPPC64 = Subtarget.isPPC64(); 6918 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6919 6920 // Assign locations to all of the incoming arguments. 6921 SmallVector<CCValAssign, 16> ArgLocs; 6922 MachineFunction &MF = DAG.getMachineFunction(); 6923 MachineFrameInfo &MFI = MF.getFrameInfo(); 6924 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6925 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6926 6927 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6928 // Reserve space for the linkage area on the stack. 6929 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6930 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6931 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6932 6933 SmallVector<SDValue, 8> MemOps; 6934 6935 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6936 CCValAssign &VA = ArgLocs[I++]; 6937 MVT LocVT = VA.getLocVT(); 6938 MVT ValVT = VA.getValVT(); 6939 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6940 // For compatibility with the AIX XL compiler, the float args in the 6941 // parameter save area are initialized even if the argument is available 6942 // in register. The caller is required to initialize both the register 6943 // and memory, however, the callee can choose to expect it in either. 6944 // The memloc is dismissed here because the argument is retrieved from 6945 // the register. 6946 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6947 continue; 6948 6949 auto HandleMemLoc = [&]() { 6950 const unsigned LocSize = LocVT.getStoreSize(); 6951 const unsigned ValSize = ValVT.getStoreSize(); 6952 assert((ValSize <= LocSize) && 6953 "Object size is larger than size of MemLoc"); 6954 int CurArgOffset = VA.getLocMemOffset(); 6955 // Objects are right-justified because AIX is big-endian. 6956 if (LocSize > ValSize) 6957 CurArgOffset += LocSize - ValSize; 6958 // Potential tail calls could cause overwriting of argument stack slots. 6959 const bool IsImmutable = 6960 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6961 (CallConv == CallingConv::Fast)); 6962 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6963 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6964 SDValue ArgValue = 6965 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6966 InVals.push_back(ArgValue); 6967 }; 6968 6969 // Vector arguments to VaArg functions are passed both on the stack, and 6970 // in any available GPRs. Load the value from the stack and add the GPRs 6971 // as live ins. 6972 if (VA.isMemLoc() && VA.needsCustom()) { 6973 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6974 assert(isVarArg && "Only use custom memloc for vararg."); 6975 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6976 // matching custom RegLocs. 6977 const unsigned OriginalValNo = VA.getValNo(); 6978 (void)OriginalValNo; 6979 6980 auto HandleCustomVecRegLoc = [&]() { 6981 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6982 "Missing custom RegLoc."); 6983 VA = ArgLocs[I++]; 6984 assert(VA.getValVT().isVector() && 6985 "Unexpected Val type for custom RegLoc."); 6986 assert(VA.getValNo() == OriginalValNo && 6987 "ValNo mismatch between custom MemLoc and RegLoc."); 6988 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6989 MF.addLiveIn(VA.getLocReg(), 6990 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 6991 Subtarget.hasVSX())); 6992 }; 6993 6994 HandleMemLoc(); 6995 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6996 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6997 // R10. 6998 HandleCustomVecRegLoc(); 6999 HandleCustomVecRegLoc(); 7000 7001 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 7002 // we passed the vector in R5, R6, R7 and R8. 7003 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 7004 assert(!IsPPC64 && 7005 "Only 2 custom RegLocs expected for 64-bit codegen."); 7006 HandleCustomVecRegLoc(); 7007 HandleCustomVecRegLoc(); 7008 } 7009 7010 continue; 7011 } 7012 7013 if (VA.isRegLoc()) { 7014 if (VA.getValVT().isScalarInteger()) 7015 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7016 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 7017 switch (VA.getValVT().SimpleTy) { 7018 default: 7019 report_fatal_error("Unhandled value type for argument."); 7020 case MVT::f32: 7021 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 7022 break; 7023 case MVT::f64: 7024 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 7025 break; 7026 } 7027 } else if (VA.getValVT().isVector()) { 7028 switch (VA.getValVT().SimpleTy) { 7029 default: 7030 report_fatal_error("Unhandled value type for argument."); 7031 case MVT::v16i8: 7032 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 7033 break; 7034 case MVT::v8i16: 7035 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 7036 break; 7037 case MVT::v4i32: 7038 case MVT::v2i64: 7039 case MVT::v1i128: 7040 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 7041 break; 7042 case MVT::v4f32: 7043 case MVT::v2f64: 7044 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 7045 break; 7046 } 7047 } 7048 } 7049 7050 if (Flags.isByVal() && VA.isMemLoc()) { 7051 const unsigned Size = 7052 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7053 PtrByteSize); 7054 const int FI = MF.getFrameInfo().CreateFixedObject( 7055 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7056 /* IsAliased */ true); 7057 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7058 InVals.push_back(FIN); 7059 7060 continue; 7061 } 7062 7063 if (Flags.isByVal()) { 7064 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7065 7066 const MCPhysReg ArgReg = VA.getLocReg(); 7067 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7068 7069 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7070 report_fatal_error("Over aligned byvals not supported yet."); 7071 7072 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7073 const int FI = MF.getFrameInfo().CreateFixedObject( 7074 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7075 /* IsAliased */ true); 7076 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7077 InVals.push_back(FIN); 7078 7079 // Add live ins for all the RegLocs for the same ByVal. 7080 const TargetRegisterClass *RegClass = 7081 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7082 7083 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7084 unsigned Offset) { 7085 const Register VReg = MF.addLiveIn(PhysReg, RegClass); 7086 // Since the callers side has left justified the aggregate in the 7087 // register, we can simply store the entire register into the stack 7088 // slot. 7089 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7090 // The store to the fixedstack object is needed becuase accessing a 7091 // field of the ByVal will use a gep and load. Ideally we will optimize 7092 // to extracting the value from the register directly, and elide the 7093 // stores when the arguments address is not taken, but that will need to 7094 // be future work. 7095 SDValue Store = DAG.getStore( 7096 CopyFrom.getValue(1), dl, CopyFrom, 7097 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7098 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7099 7100 MemOps.push_back(Store); 7101 }; 7102 7103 unsigned Offset = 0; 7104 HandleRegLoc(VA.getLocReg(), Offset); 7105 Offset += PtrByteSize; 7106 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7107 Offset += PtrByteSize) { 7108 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7109 "RegLocs should be for ByVal argument."); 7110 7111 const CCValAssign RL = ArgLocs[I++]; 7112 HandleRegLoc(RL.getLocReg(), Offset); 7113 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7114 } 7115 7116 if (Offset != StackSize) { 7117 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7118 "Expected MemLoc for remaining bytes."); 7119 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7120 // Consume the MemLoc.The InVal has already been emitted, so nothing 7121 // more needs to be done. 7122 ++I; 7123 } 7124 7125 continue; 7126 } 7127 7128 if (VA.isRegLoc() && !VA.needsCustom()) { 7129 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7130 Register VReg = 7131 MF.addLiveIn(VA.getLocReg(), 7132 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7133 Subtarget.hasVSX())); 7134 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7135 if (ValVT.isScalarInteger() && 7136 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7137 ArgValue = 7138 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7139 } 7140 InVals.push_back(ArgValue); 7141 continue; 7142 } 7143 if (VA.isMemLoc()) { 7144 HandleMemLoc(); 7145 continue; 7146 } 7147 } 7148 7149 // On AIX a minimum of 8 words is saved to the parameter save area. 7150 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7151 // Area that is at least reserved in the caller of this function. 7152 unsigned CallerReservedArea = 7153 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7154 7155 // Set the size that is at least reserved in caller of this function. Tail 7156 // call optimized function's reserved stack space needs to be aligned so 7157 // that taking the difference between two stack areas will result in an 7158 // aligned stack. 7159 CallerReservedArea = 7160 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7161 FuncInfo->setMinReservedArea(CallerReservedArea); 7162 7163 if (isVarArg) { 7164 FuncInfo->setVarArgsFrameIndex( 7165 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7166 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7167 7168 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7169 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7170 7171 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7172 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7173 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7174 7175 // The fixed integer arguments of a variadic function are stored to the 7176 // VarArgsFrameIndex on the stack so that they may be loaded by 7177 // dereferencing the result of va_next. 7178 for (unsigned GPRIndex = 7179 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7180 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7181 7182 const Register VReg = 7183 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7184 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7185 7186 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7187 SDValue Store = 7188 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7189 MemOps.push_back(Store); 7190 // Increment the address for the next argument to store. 7191 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7192 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7193 } 7194 } 7195 7196 if (!MemOps.empty()) 7197 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7198 7199 return Chain; 7200 } 7201 7202 SDValue PPCTargetLowering::LowerCall_AIX( 7203 SDValue Chain, SDValue Callee, CallFlags CFlags, 7204 const SmallVectorImpl<ISD::OutputArg> &Outs, 7205 const SmallVectorImpl<SDValue> &OutVals, 7206 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7207 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7208 const CallBase *CB) const { 7209 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7210 // AIX ABI stack frame layout. 7211 7212 assert((CFlags.CallConv == CallingConv::C || 7213 CFlags.CallConv == CallingConv::Cold || 7214 CFlags.CallConv == CallingConv::Fast) && 7215 "Unexpected calling convention!"); 7216 7217 if (CFlags.IsPatchPoint) 7218 report_fatal_error("This call type is unimplemented on AIX."); 7219 7220 const PPCSubtarget& Subtarget = 7221 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7222 7223 MachineFunction &MF = DAG.getMachineFunction(); 7224 SmallVector<CCValAssign, 16> ArgLocs; 7225 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7226 *DAG.getContext()); 7227 7228 // Reserve space for the linkage save area (LSA) on the stack. 7229 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7230 // [SP][CR][LR][2 x reserved][TOC]. 7231 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7232 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7233 const bool IsPPC64 = Subtarget.isPPC64(); 7234 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7235 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7236 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7237 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7238 7239 // The prolog code of the callee may store up to 8 GPR argument registers to 7240 // the stack, allowing va_start to index over them in memory if the callee 7241 // is variadic. 7242 // Because we cannot tell if this is needed on the caller side, we have to 7243 // conservatively assume that it is needed. As such, make sure we have at 7244 // least enough stack space for the caller to store the 8 GPRs. 7245 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7246 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7247 CCInfo.getNextStackOffset()); 7248 7249 // Adjust the stack pointer for the new arguments... 7250 // These operations are automatically eliminated by the prolog/epilog pass. 7251 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7252 SDValue CallSeqStart = Chain; 7253 7254 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7255 SmallVector<SDValue, 8> MemOpChains; 7256 7257 // Set up a copy of the stack pointer for loading and storing any 7258 // arguments that may not fit in the registers available for argument 7259 // passing. 7260 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7261 : DAG.getRegister(PPC::R1, MVT::i32); 7262 7263 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7264 const unsigned ValNo = ArgLocs[I].getValNo(); 7265 SDValue Arg = OutVals[ValNo]; 7266 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7267 7268 if (Flags.isByVal()) { 7269 const unsigned ByValSize = Flags.getByValSize(); 7270 7271 // Nothing to do for zero-sized ByVals on the caller side. 7272 if (!ByValSize) { 7273 ++I; 7274 continue; 7275 } 7276 7277 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7278 return DAG.getExtLoad( 7279 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7280 (LoadOffset != 0) 7281 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7282 : Arg, 7283 MachinePointerInfo(), VT); 7284 }; 7285 7286 unsigned LoadOffset = 0; 7287 7288 // Initialize registers, which are fully occupied by the by-val argument. 7289 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7290 SDValue Load = GetLoad(PtrVT, LoadOffset); 7291 MemOpChains.push_back(Load.getValue(1)); 7292 LoadOffset += PtrByteSize; 7293 const CCValAssign &ByValVA = ArgLocs[I++]; 7294 assert(ByValVA.getValNo() == ValNo && 7295 "Unexpected location for pass-by-value argument."); 7296 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7297 } 7298 7299 if (LoadOffset == ByValSize) 7300 continue; 7301 7302 // There must be one more loc to handle the remainder. 7303 assert(ArgLocs[I].getValNo() == ValNo && 7304 "Expected additional location for by-value argument."); 7305 7306 if (ArgLocs[I].isMemLoc()) { 7307 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7308 const CCValAssign &ByValVA = ArgLocs[I++]; 7309 ISD::ArgFlagsTy MemcpyFlags = Flags; 7310 // Only memcpy the bytes that don't pass in register. 7311 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7312 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7313 (LoadOffset != 0) 7314 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7315 : Arg, 7316 DAG.getObjectPtrOffset(dl, StackPtr, 7317 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7318 CallSeqStart, MemcpyFlags, DAG, dl); 7319 continue; 7320 } 7321 7322 // Initialize the final register residue. 7323 // Any residue that occupies the final by-val arg register must be 7324 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7325 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7326 // 2 and 1 byte loads. 7327 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7328 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7329 "Unexpected register residue for by-value argument."); 7330 SDValue ResidueVal; 7331 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7332 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7333 const MVT VT = 7334 N == 1 ? MVT::i8 7335 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7336 SDValue Load = GetLoad(VT, LoadOffset); 7337 MemOpChains.push_back(Load.getValue(1)); 7338 LoadOffset += N; 7339 Bytes += N; 7340 7341 // By-val arguments are passed left-justfied in register. 7342 // Every load here needs to be shifted, otherwise a full register load 7343 // should have been used. 7344 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7345 "Unexpected load emitted during handling of pass-by-value " 7346 "argument."); 7347 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7348 EVT ShiftAmountTy = 7349 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7350 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7351 SDValue ShiftedLoad = 7352 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7353 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7354 ShiftedLoad) 7355 : ShiftedLoad; 7356 } 7357 7358 const CCValAssign &ByValVA = ArgLocs[I++]; 7359 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7360 continue; 7361 } 7362 7363 CCValAssign &VA = ArgLocs[I++]; 7364 const MVT LocVT = VA.getLocVT(); 7365 const MVT ValVT = VA.getValVT(); 7366 7367 switch (VA.getLocInfo()) { 7368 default: 7369 report_fatal_error("Unexpected argument extension type."); 7370 case CCValAssign::Full: 7371 break; 7372 case CCValAssign::ZExt: 7373 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7374 break; 7375 case CCValAssign::SExt: 7376 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7377 break; 7378 } 7379 7380 if (VA.isRegLoc() && !VA.needsCustom()) { 7381 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7382 continue; 7383 } 7384 7385 // Vector arguments passed to VarArg functions need custom handling when 7386 // they are passed (at least partially) in GPRs. 7387 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7388 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7389 // Store value to its stack slot. 7390 SDValue PtrOff = 7391 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7392 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7393 SDValue Store = 7394 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7395 MemOpChains.push_back(Store); 7396 const unsigned OriginalValNo = VA.getValNo(); 7397 // Then load the GPRs from the stack 7398 unsigned LoadOffset = 0; 7399 auto HandleCustomVecRegLoc = [&]() { 7400 assert(I != E && "Unexpected end of CCvalAssigns."); 7401 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7402 "Expected custom RegLoc."); 7403 CCValAssign RegVA = ArgLocs[I++]; 7404 assert(RegVA.getValNo() == OriginalValNo && 7405 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7406 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7407 DAG.getConstant(LoadOffset, dl, PtrVT)); 7408 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7409 MemOpChains.push_back(Load.getValue(1)); 7410 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7411 LoadOffset += PtrByteSize; 7412 }; 7413 7414 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7415 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7416 // R10. 7417 HandleCustomVecRegLoc(); 7418 HandleCustomVecRegLoc(); 7419 7420 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7421 ArgLocs[I].getValNo() == OriginalValNo) { 7422 assert(!IsPPC64 && 7423 "Only 2 custom RegLocs expected for 64-bit codegen."); 7424 HandleCustomVecRegLoc(); 7425 HandleCustomVecRegLoc(); 7426 } 7427 7428 continue; 7429 } 7430 7431 if (VA.isMemLoc()) { 7432 SDValue PtrOff = 7433 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7434 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7435 MemOpChains.push_back( 7436 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7437 7438 continue; 7439 } 7440 7441 if (!ValVT.isFloatingPoint()) 7442 report_fatal_error( 7443 "Unexpected register handling for calling convention."); 7444 7445 // Custom handling is used for GPR initializations for vararg float 7446 // arguments. 7447 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7448 LocVT.isInteger() && 7449 "Custom register handling only expected for VarArg."); 7450 7451 SDValue ArgAsInt = 7452 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7453 7454 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7455 // f32 in 32-bit GPR 7456 // f64 in 64-bit GPR 7457 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7458 else if (Arg.getValueType().getFixedSizeInBits() < 7459 LocVT.getFixedSizeInBits()) 7460 // f32 in 64-bit GPR. 7461 RegsToPass.push_back(std::make_pair( 7462 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7463 else { 7464 // f64 in two 32-bit GPRs 7465 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7466 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7467 "Unexpected custom register for argument!"); 7468 CCValAssign &GPR1 = VA; 7469 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7470 DAG.getConstant(32, dl, MVT::i8)); 7471 RegsToPass.push_back(std::make_pair( 7472 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7473 7474 if (I != E) { 7475 // If only 1 GPR was available, there will only be one custom GPR and 7476 // the argument will also pass in memory. 7477 CCValAssign &PeekArg = ArgLocs[I]; 7478 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7479 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7480 CCValAssign &GPR2 = ArgLocs[I++]; 7481 RegsToPass.push_back(std::make_pair( 7482 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7483 } 7484 } 7485 } 7486 } 7487 7488 if (!MemOpChains.empty()) 7489 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7490 7491 // For indirect calls, we need to save the TOC base to the stack for 7492 // restoration after the call. 7493 if (CFlags.IsIndirect) { 7494 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7495 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7496 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7497 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7498 const unsigned TOCSaveOffset = 7499 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7500 7501 setUsesTOCBasePtr(DAG); 7502 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7503 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7504 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7505 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7506 Chain = DAG.getStore( 7507 Val.getValue(1), dl, Val, AddPtr, 7508 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7509 } 7510 7511 // Build a sequence of copy-to-reg nodes chained together with token chain 7512 // and flag operands which copy the outgoing args into the appropriate regs. 7513 SDValue InFlag; 7514 for (auto Reg : RegsToPass) { 7515 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7516 InFlag = Chain.getValue(1); 7517 } 7518 7519 const int SPDiff = 0; 7520 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7521 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7522 } 7523 7524 bool 7525 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7526 MachineFunction &MF, bool isVarArg, 7527 const SmallVectorImpl<ISD::OutputArg> &Outs, 7528 LLVMContext &Context) const { 7529 SmallVector<CCValAssign, 16> RVLocs; 7530 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7531 return CCInfo.CheckReturn( 7532 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7533 ? RetCC_PPC_Cold 7534 : RetCC_PPC); 7535 } 7536 7537 SDValue 7538 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7539 bool isVarArg, 7540 const SmallVectorImpl<ISD::OutputArg> &Outs, 7541 const SmallVectorImpl<SDValue> &OutVals, 7542 const SDLoc &dl, SelectionDAG &DAG) const { 7543 SmallVector<CCValAssign, 16> RVLocs; 7544 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7545 *DAG.getContext()); 7546 CCInfo.AnalyzeReturn(Outs, 7547 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7548 ? RetCC_PPC_Cold 7549 : RetCC_PPC); 7550 7551 SDValue Flag; 7552 SmallVector<SDValue, 4> RetOps(1, Chain); 7553 7554 // Copy the result values into the output registers. 7555 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7556 CCValAssign &VA = RVLocs[i]; 7557 assert(VA.isRegLoc() && "Can only return in registers!"); 7558 7559 SDValue Arg = OutVals[RealResIdx]; 7560 7561 switch (VA.getLocInfo()) { 7562 default: llvm_unreachable("Unknown loc info!"); 7563 case CCValAssign::Full: break; 7564 case CCValAssign::AExt: 7565 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7566 break; 7567 case CCValAssign::ZExt: 7568 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7569 break; 7570 case CCValAssign::SExt: 7571 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7572 break; 7573 } 7574 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7575 bool isLittleEndian = Subtarget.isLittleEndian(); 7576 // Legalize ret f64 -> ret 2 x i32. 7577 SDValue SVal = 7578 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7579 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7580 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7581 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7582 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7583 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7584 Flag = Chain.getValue(1); 7585 VA = RVLocs[++i]; // skip ahead to next loc 7586 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7587 } else 7588 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7589 Flag = Chain.getValue(1); 7590 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7591 } 7592 7593 RetOps[0] = Chain; // Update chain. 7594 7595 // Add the flag if we have it. 7596 if (Flag.getNode()) 7597 RetOps.push_back(Flag); 7598 7599 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7600 } 7601 7602 SDValue 7603 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7604 SelectionDAG &DAG) const { 7605 SDLoc dl(Op); 7606 7607 // Get the correct type for integers. 7608 EVT IntVT = Op.getValueType(); 7609 7610 // Get the inputs. 7611 SDValue Chain = Op.getOperand(0); 7612 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7613 // Build a DYNAREAOFFSET node. 7614 SDValue Ops[2] = {Chain, FPSIdx}; 7615 SDVTList VTs = DAG.getVTList(IntVT); 7616 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7617 } 7618 7619 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7620 SelectionDAG &DAG) const { 7621 // When we pop the dynamic allocation we need to restore the SP link. 7622 SDLoc dl(Op); 7623 7624 // Get the correct type for pointers. 7625 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7626 7627 // Construct the stack pointer operand. 7628 bool isPPC64 = Subtarget.isPPC64(); 7629 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7630 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7631 7632 // Get the operands for the STACKRESTORE. 7633 SDValue Chain = Op.getOperand(0); 7634 SDValue SaveSP = Op.getOperand(1); 7635 7636 // Load the old link SP. 7637 SDValue LoadLinkSP = 7638 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7639 7640 // Restore the stack pointer. 7641 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7642 7643 // Store the old link SP. 7644 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7645 } 7646 7647 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7648 MachineFunction &MF = DAG.getMachineFunction(); 7649 bool isPPC64 = Subtarget.isPPC64(); 7650 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7651 7652 // Get current frame pointer save index. The users of this index will be 7653 // primarily DYNALLOC instructions. 7654 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7655 int RASI = FI->getReturnAddrSaveIndex(); 7656 7657 // If the frame pointer save index hasn't been defined yet. 7658 if (!RASI) { 7659 // Find out what the fix offset of the frame pointer save area. 7660 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7661 // Allocate the frame index for frame pointer save area. 7662 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7663 // Save the result. 7664 FI->setReturnAddrSaveIndex(RASI); 7665 } 7666 return DAG.getFrameIndex(RASI, PtrVT); 7667 } 7668 7669 SDValue 7670 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7671 MachineFunction &MF = DAG.getMachineFunction(); 7672 bool isPPC64 = Subtarget.isPPC64(); 7673 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7674 7675 // Get current frame pointer save index. The users of this index will be 7676 // primarily DYNALLOC instructions. 7677 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7678 int FPSI = FI->getFramePointerSaveIndex(); 7679 7680 // If the frame pointer save index hasn't been defined yet. 7681 if (!FPSI) { 7682 // Find out what the fix offset of the frame pointer save area. 7683 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7684 // Allocate the frame index for frame pointer save area. 7685 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7686 // Save the result. 7687 FI->setFramePointerSaveIndex(FPSI); 7688 } 7689 return DAG.getFrameIndex(FPSI, PtrVT); 7690 } 7691 7692 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7693 SelectionDAG &DAG) const { 7694 MachineFunction &MF = DAG.getMachineFunction(); 7695 // Get the inputs. 7696 SDValue Chain = Op.getOperand(0); 7697 SDValue Size = Op.getOperand(1); 7698 SDLoc dl(Op); 7699 7700 // Get the correct type for pointers. 7701 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7702 // Negate the size. 7703 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7704 DAG.getConstant(0, dl, PtrVT), Size); 7705 // Construct a node for the frame pointer save index. 7706 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7707 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7708 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7709 if (hasInlineStackProbe(MF)) 7710 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7711 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7712 } 7713 7714 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7715 SelectionDAG &DAG) const { 7716 MachineFunction &MF = DAG.getMachineFunction(); 7717 7718 bool isPPC64 = Subtarget.isPPC64(); 7719 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7720 7721 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7722 return DAG.getFrameIndex(FI, PtrVT); 7723 } 7724 7725 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7726 SelectionDAG &DAG) const { 7727 SDLoc DL(Op); 7728 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7729 DAG.getVTList(MVT::i32, MVT::Other), 7730 Op.getOperand(0), Op.getOperand(1)); 7731 } 7732 7733 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7734 SelectionDAG &DAG) const { 7735 SDLoc DL(Op); 7736 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7737 Op.getOperand(0), Op.getOperand(1)); 7738 } 7739 7740 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7741 if (Op.getValueType().isVector()) 7742 return LowerVectorLoad(Op, DAG); 7743 7744 assert(Op.getValueType() == MVT::i1 && 7745 "Custom lowering only for i1 loads"); 7746 7747 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7748 7749 SDLoc dl(Op); 7750 LoadSDNode *LD = cast<LoadSDNode>(Op); 7751 7752 SDValue Chain = LD->getChain(); 7753 SDValue BasePtr = LD->getBasePtr(); 7754 MachineMemOperand *MMO = LD->getMemOperand(); 7755 7756 SDValue NewLD = 7757 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7758 BasePtr, MVT::i8, MMO); 7759 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7760 7761 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7762 return DAG.getMergeValues(Ops, dl); 7763 } 7764 7765 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7766 if (Op.getOperand(1).getValueType().isVector()) 7767 return LowerVectorStore(Op, DAG); 7768 7769 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7770 "Custom lowering only for i1 stores"); 7771 7772 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7773 7774 SDLoc dl(Op); 7775 StoreSDNode *ST = cast<StoreSDNode>(Op); 7776 7777 SDValue Chain = ST->getChain(); 7778 SDValue BasePtr = ST->getBasePtr(); 7779 SDValue Value = ST->getValue(); 7780 MachineMemOperand *MMO = ST->getMemOperand(); 7781 7782 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7783 Value); 7784 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7785 } 7786 7787 // FIXME: Remove this once the ANDI glue bug is fixed: 7788 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7789 assert(Op.getValueType() == MVT::i1 && 7790 "Custom lowering only for i1 results"); 7791 7792 SDLoc DL(Op); 7793 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7794 } 7795 7796 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7797 SelectionDAG &DAG) const { 7798 7799 // Implements a vector truncate that fits in a vector register as a shuffle. 7800 // We want to legalize vector truncates down to where the source fits in 7801 // a vector register (and target is therefore smaller than vector register 7802 // size). At that point legalization will try to custom lower the sub-legal 7803 // result and get here - where we can contain the truncate as a single target 7804 // operation. 7805 7806 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7807 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7808 // 7809 // We will implement it for big-endian ordering as this (where x denotes 7810 // undefined): 7811 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7812 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7813 // 7814 // The same operation in little-endian ordering will be: 7815 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7816 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7817 7818 EVT TrgVT = Op.getValueType(); 7819 assert(TrgVT.isVector() && "Vector type expected."); 7820 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7821 EVT EltVT = TrgVT.getVectorElementType(); 7822 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7823 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7824 !isPowerOf2_32(EltVT.getSizeInBits())) 7825 return SDValue(); 7826 7827 SDValue N1 = Op.getOperand(0); 7828 EVT SrcVT = N1.getValueType(); 7829 unsigned SrcSize = SrcVT.getSizeInBits(); 7830 if (SrcSize > 256 || 7831 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7832 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7833 return SDValue(); 7834 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7835 return SDValue(); 7836 7837 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7838 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7839 7840 SDLoc DL(Op); 7841 SDValue Op1, Op2; 7842 if (SrcSize == 256) { 7843 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7844 EVT SplitVT = 7845 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7846 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7847 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7848 DAG.getConstant(0, DL, VecIdxTy)); 7849 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7850 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7851 } 7852 else { 7853 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7854 Op2 = DAG.getUNDEF(WideVT); 7855 } 7856 7857 // First list the elements we want to keep. 7858 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7859 SmallVector<int, 16> ShuffV; 7860 if (Subtarget.isLittleEndian()) 7861 for (unsigned i = 0; i < TrgNumElts; ++i) 7862 ShuffV.push_back(i * SizeMult); 7863 else 7864 for (unsigned i = 1; i <= TrgNumElts; ++i) 7865 ShuffV.push_back(i * SizeMult - 1); 7866 7867 // Populate the remaining elements with undefs. 7868 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7869 // ShuffV.push_back(i + WideNumElts); 7870 ShuffV.push_back(WideNumElts + 1); 7871 7872 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7873 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7874 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7875 } 7876 7877 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7878 /// possible. 7879 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7880 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7881 EVT ResVT = Op.getValueType(); 7882 EVT CmpVT = Op.getOperand(0).getValueType(); 7883 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7884 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7885 SDLoc dl(Op); 7886 7887 // Without power9-vector, we don't have native instruction for f128 comparison. 7888 // Following transformation to libcall is needed for setcc: 7889 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7890 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7891 SDValue Z = DAG.getSetCC( 7892 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7893 LHS, RHS, CC); 7894 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7895 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7896 } 7897 7898 // Not FP, or using SPE? Not a fsel. 7899 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7900 Subtarget.hasSPE()) 7901 return Op; 7902 7903 SDNodeFlags Flags = Op.getNode()->getFlags(); 7904 7905 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the 7906 // presence of infinities. 7907 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7908 switch (CC) { 7909 default: 7910 break; 7911 case ISD::SETOGT: 7912 case ISD::SETGT: 7913 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS); 7914 case ISD::SETOLT: 7915 case ISD::SETLT: 7916 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS); 7917 } 7918 } 7919 7920 // We might be able to do better than this under some circumstances, but in 7921 // general, fsel-based lowering of select is a finite-math-only optimization. 7922 // For more information, see section F.3 of the 2.06 ISA specification. 7923 // With ISA 3.0 7924 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7925 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7926 return Op; 7927 7928 // If the RHS of the comparison is a 0.0, we don't need to do the 7929 // subtraction at all. 7930 SDValue Sel1; 7931 if (isFloatingPointZero(RHS)) 7932 switch (CC) { 7933 default: break; // SETUO etc aren't handled by fsel. 7934 case ISD::SETNE: 7935 std::swap(TV, FV); 7936 LLVM_FALLTHROUGH; 7937 case ISD::SETEQ: 7938 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7939 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7940 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7941 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7942 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7943 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7944 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7945 case ISD::SETULT: 7946 case ISD::SETLT: 7947 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7948 LLVM_FALLTHROUGH; 7949 case ISD::SETOGE: 7950 case ISD::SETGE: 7951 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7952 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7953 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7954 case ISD::SETUGT: 7955 case ISD::SETGT: 7956 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7957 LLVM_FALLTHROUGH; 7958 case ISD::SETOLE: 7959 case ISD::SETLE: 7960 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7961 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7962 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7963 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7964 } 7965 7966 SDValue Cmp; 7967 switch (CC) { 7968 default: break; // SETUO etc aren't handled by fsel. 7969 case ISD::SETNE: 7970 std::swap(TV, FV); 7971 LLVM_FALLTHROUGH; 7972 case ISD::SETEQ: 7973 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7974 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7975 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7976 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7977 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7978 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7979 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7980 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7981 case ISD::SETULT: 7982 case ISD::SETLT: 7983 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7984 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7985 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7986 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7987 case ISD::SETOGE: 7988 case ISD::SETGE: 7989 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7990 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7991 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7992 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7993 case ISD::SETUGT: 7994 case ISD::SETGT: 7995 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7996 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7997 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7998 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7999 case ISD::SETOLE: 8000 case ISD::SETLE: 8001 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8002 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8003 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8004 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8005 } 8006 return Op; 8007 } 8008 8009 static unsigned getPPCStrictOpcode(unsigned Opc) { 8010 switch (Opc) { 8011 default: 8012 llvm_unreachable("No strict version of this opcode!"); 8013 case PPCISD::FCTIDZ: 8014 return PPCISD::STRICT_FCTIDZ; 8015 case PPCISD::FCTIWZ: 8016 return PPCISD::STRICT_FCTIWZ; 8017 case PPCISD::FCTIDUZ: 8018 return PPCISD::STRICT_FCTIDUZ; 8019 case PPCISD::FCTIWUZ: 8020 return PPCISD::STRICT_FCTIWUZ; 8021 case PPCISD::FCFID: 8022 return PPCISD::STRICT_FCFID; 8023 case PPCISD::FCFIDU: 8024 return PPCISD::STRICT_FCFIDU; 8025 case PPCISD::FCFIDS: 8026 return PPCISD::STRICT_FCFIDS; 8027 case PPCISD::FCFIDUS: 8028 return PPCISD::STRICT_FCFIDUS; 8029 } 8030 } 8031 8032 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8033 const PPCSubtarget &Subtarget) { 8034 SDLoc dl(Op); 8035 bool IsStrict = Op->isStrictFPOpcode(); 8036 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8037 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8038 8039 // TODO: Any other flags to propagate? 8040 SDNodeFlags Flags; 8041 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8042 8043 // For strict nodes, source is the second operand. 8044 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8045 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8046 assert(Src.getValueType().isFloatingPoint()); 8047 if (Src.getValueType() == MVT::f32) { 8048 if (IsStrict) { 8049 Src = 8050 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8051 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8052 Chain = Src.getValue(1); 8053 } else 8054 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8055 } 8056 SDValue Conv; 8057 unsigned Opc = ISD::DELETED_NODE; 8058 switch (Op.getSimpleValueType().SimpleTy) { 8059 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8060 case MVT::i32: 8061 Opc = IsSigned ? PPCISD::FCTIWZ 8062 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8063 break; 8064 case MVT::i64: 8065 assert((IsSigned || Subtarget.hasFPCVT()) && 8066 "i64 FP_TO_UINT is supported only with FPCVT"); 8067 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8068 } 8069 if (IsStrict) { 8070 Opc = getPPCStrictOpcode(Opc); 8071 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8072 {Chain, Src}, Flags); 8073 } else { 8074 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8075 } 8076 return Conv; 8077 } 8078 8079 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8080 SelectionDAG &DAG, 8081 const SDLoc &dl) const { 8082 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8083 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8084 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8085 bool IsStrict = Op->isStrictFPOpcode(); 8086 8087 // Convert the FP value to an int value through memory. 8088 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8089 (IsSigned || Subtarget.hasFPCVT()); 8090 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8091 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8092 MachinePointerInfo MPI = 8093 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8094 8095 // Emit a store to the stack slot. 8096 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8097 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8098 if (i32Stack) { 8099 MachineFunction &MF = DAG.getMachineFunction(); 8100 Alignment = Align(4); 8101 MachineMemOperand *MMO = 8102 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8103 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8104 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8105 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8106 } else 8107 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8108 8109 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8110 // add in a bias on big endian. 8111 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8112 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8113 DAG.getConstant(4, dl, FIPtr.getValueType())); 8114 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8115 } 8116 8117 RLI.Chain = Chain; 8118 RLI.Ptr = FIPtr; 8119 RLI.MPI = MPI; 8120 RLI.Alignment = Alignment; 8121 } 8122 8123 /// Custom lowers floating point to integer conversions to use 8124 /// the direct move instructions available in ISA 2.07 to avoid the 8125 /// need for load/store combinations. 8126 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8127 SelectionDAG &DAG, 8128 const SDLoc &dl) const { 8129 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8130 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8131 if (Op->isStrictFPOpcode()) 8132 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8133 else 8134 return Mov; 8135 } 8136 8137 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8138 const SDLoc &dl) const { 8139 bool IsStrict = Op->isStrictFPOpcode(); 8140 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8141 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8142 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8143 EVT SrcVT = Src.getValueType(); 8144 EVT DstVT = Op.getValueType(); 8145 8146 // FP to INT conversions are legal for f128. 8147 if (SrcVT == MVT::f128) 8148 return Subtarget.hasP9Vector() ? Op : SDValue(); 8149 8150 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8151 // PPC (the libcall is not available). 8152 if (SrcVT == MVT::ppcf128) { 8153 if (DstVT == MVT::i32) { 8154 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8155 // set other fast-math flags to FP operations in both strict and 8156 // non-strict cases. (FP_TO_SINT, FSUB) 8157 SDNodeFlags Flags; 8158 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8159 8160 if (IsSigned) { 8161 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8162 DAG.getIntPtrConstant(0, dl)); 8163 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8164 DAG.getIntPtrConstant(1, dl)); 8165 8166 // Add the two halves of the long double in round-to-zero mode, and use 8167 // a smaller FP_TO_SINT. 8168 if (IsStrict) { 8169 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8170 DAG.getVTList(MVT::f64, MVT::Other), 8171 {Op.getOperand(0), Lo, Hi}, Flags); 8172 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8173 DAG.getVTList(MVT::i32, MVT::Other), 8174 {Res.getValue(1), Res}, Flags); 8175 } else { 8176 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8177 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8178 } 8179 } else { 8180 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8181 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8182 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8183 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8184 if (IsStrict) { 8185 // Sel = Src < 0x80000000 8186 // FltOfs = select Sel, 0.0, 0x80000000 8187 // IntOfs = select Sel, 0, 0x80000000 8188 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8189 SDValue Chain = Op.getOperand(0); 8190 EVT SetCCVT = 8191 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8192 EVT DstSetCCVT = 8193 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8194 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8195 Chain, true); 8196 Chain = Sel.getValue(1); 8197 8198 SDValue FltOfs = DAG.getSelect( 8199 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8200 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8201 8202 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8203 DAG.getVTList(SrcVT, MVT::Other), 8204 {Chain, Src, FltOfs}, Flags); 8205 Chain = Val.getValue(1); 8206 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8207 DAG.getVTList(DstVT, MVT::Other), 8208 {Chain, Val}, Flags); 8209 Chain = SInt.getValue(1); 8210 SDValue IntOfs = DAG.getSelect( 8211 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8212 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8213 return DAG.getMergeValues({Result, Chain}, dl); 8214 } else { 8215 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8216 // FIXME: generated code sucks. 8217 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8218 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8219 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8220 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8221 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8222 } 8223 } 8224 } 8225 8226 return SDValue(); 8227 } 8228 8229 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8230 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8231 8232 ReuseLoadInfo RLI; 8233 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8234 8235 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8236 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8237 } 8238 8239 // We're trying to insert a regular store, S, and then a load, L. If the 8240 // incoming value, O, is a load, we might just be able to have our load use the 8241 // address used by O. However, we don't know if anything else will store to 8242 // that address before we can load from it. To prevent this situation, we need 8243 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8244 // the same chain operand as O, we create a token factor from the chain results 8245 // of O and L, and we replace all uses of O's chain result with that token 8246 // factor (see spliceIntoChain below for this last part). 8247 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8248 ReuseLoadInfo &RLI, 8249 SelectionDAG &DAG, 8250 ISD::LoadExtType ET) const { 8251 // Conservatively skip reusing for constrained FP nodes. 8252 if (Op->isStrictFPOpcode()) 8253 return false; 8254 8255 SDLoc dl(Op); 8256 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8257 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8258 if (ET == ISD::NON_EXTLOAD && 8259 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8260 isOperationLegalOrCustom(Op.getOpcode(), 8261 Op.getOperand(0).getValueType())) { 8262 8263 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8264 return true; 8265 } 8266 8267 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8268 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8269 LD->isNonTemporal()) 8270 return false; 8271 if (LD->getMemoryVT() != MemVT) 8272 return false; 8273 8274 // If the result of the load is an illegal type, then we can't build a 8275 // valid chain for reuse since the legalised loads and token factor node that 8276 // ties the legalised loads together uses a different output chain then the 8277 // illegal load. 8278 if (!isTypeLegal(LD->getValueType(0))) 8279 return false; 8280 8281 RLI.Ptr = LD->getBasePtr(); 8282 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8283 assert(LD->getAddressingMode() == ISD::PRE_INC && 8284 "Non-pre-inc AM on PPC?"); 8285 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8286 LD->getOffset()); 8287 } 8288 8289 RLI.Chain = LD->getChain(); 8290 RLI.MPI = LD->getPointerInfo(); 8291 RLI.IsDereferenceable = LD->isDereferenceable(); 8292 RLI.IsInvariant = LD->isInvariant(); 8293 RLI.Alignment = LD->getAlign(); 8294 RLI.AAInfo = LD->getAAInfo(); 8295 RLI.Ranges = LD->getRanges(); 8296 8297 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8298 return true; 8299 } 8300 8301 // Given the head of the old chain, ResChain, insert a token factor containing 8302 // it and NewResChain, and make users of ResChain now be users of that token 8303 // factor. 8304 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8305 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8306 SDValue NewResChain, 8307 SelectionDAG &DAG) const { 8308 if (!ResChain) 8309 return; 8310 8311 SDLoc dl(NewResChain); 8312 8313 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8314 NewResChain, DAG.getUNDEF(MVT::Other)); 8315 assert(TF.getNode() != NewResChain.getNode() && 8316 "A new TF really is required here"); 8317 8318 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8319 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8320 } 8321 8322 /// Analyze profitability of direct move 8323 /// prefer float load to int load plus direct move 8324 /// when there is no integer use of int load 8325 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8326 SDNode *Origin = Op.getOperand(0).getNode(); 8327 if (Origin->getOpcode() != ISD::LOAD) 8328 return true; 8329 8330 // If there is no LXSIBZX/LXSIHZX, like Power8, 8331 // prefer direct move if the memory size is 1 or 2 bytes. 8332 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8333 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8334 return true; 8335 8336 for (SDNode::use_iterator UI = Origin->use_begin(), 8337 UE = Origin->use_end(); 8338 UI != UE; ++UI) { 8339 8340 // Only look at the users of the loaded value. 8341 if (UI.getUse().get().getResNo() != 0) 8342 continue; 8343 8344 if (UI->getOpcode() != ISD::SINT_TO_FP && 8345 UI->getOpcode() != ISD::UINT_TO_FP && 8346 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8347 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8348 return true; 8349 } 8350 8351 return false; 8352 } 8353 8354 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8355 const PPCSubtarget &Subtarget, 8356 SDValue Chain = SDValue()) { 8357 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8358 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8359 SDLoc dl(Op); 8360 8361 // TODO: Any other flags to propagate? 8362 SDNodeFlags Flags; 8363 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8364 8365 // If we have FCFIDS, then use it when converting to single-precision. 8366 // Otherwise, convert to double-precision and then round. 8367 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8368 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8369 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8370 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8371 if (Op->isStrictFPOpcode()) { 8372 if (!Chain) 8373 Chain = Op.getOperand(0); 8374 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8375 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8376 } else 8377 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8378 } 8379 8380 /// Custom lowers integer to floating point conversions to use 8381 /// the direct move instructions available in ISA 2.07 to avoid the 8382 /// need for load/store combinations. 8383 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8384 SelectionDAG &DAG, 8385 const SDLoc &dl) const { 8386 assert((Op.getValueType() == MVT::f32 || 8387 Op.getValueType() == MVT::f64) && 8388 "Invalid floating point type as target of conversion"); 8389 assert(Subtarget.hasFPCVT() && 8390 "Int to FP conversions with direct moves require FPCVT"); 8391 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8392 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8393 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8394 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8395 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8396 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8397 return convertIntToFP(Op, Mov, DAG, Subtarget); 8398 } 8399 8400 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8401 8402 EVT VecVT = Vec.getValueType(); 8403 assert(VecVT.isVector() && "Expected a vector type."); 8404 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8405 8406 EVT EltVT = VecVT.getVectorElementType(); 8407 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8408 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8409 8410 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8411 SmallVector<SDValue, 16> Ops(NumConcat); 8412 Ops[0] = Vec; 8413 SDValue UndefVec = DAG.getUNDEF(VecVT); 8414 for (unsigned i = 1; i < NumConcat; ++i) 8415 Ops[i] = UndefVec; 8416 8417 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8418 } 8419 8420 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8421 const SDLoc &dl) const { 8422 bool IsStrict = Op->isStrictFPOpcode(); 8423 unsigned Opc = Op.getOpcode(); 8424 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8425 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8426 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8427 "Unexpected conversion type"); 8428 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8429 "Supports conversions to v2f64/v4f32 only."); 8430 8431 // TODO: Any other flags to propagate? 8432 SDNodeFlags Flags; 8433 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8434 8435 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8436 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8437 8438 SDValue Wide = widenVec(DAG, Src, dl); 8439 EVT WideVT = Wide.getValueType(); 8440 unsigned WideNumElts = WideVT.getVectorNumElements(); 8441 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8442 8443 SmallVector<int, 16> ShuffV; 8444 for (unsigned i = 0; i < WideNumElts; ++i) 8445 ShuffV.push_back(i + WideNumElts); 8446 8447 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8448 int SaveElts = FourEltRes ? 4 : 2; 8449 if (Subtarget.isLittleEndian()) 8450 for (int i = 0; i < SaveElts; i++) 8451 ShuffV[i * Stride] = i; 8452 else 8453 for (int i = 1; i <= SaveElts; i++) 8454 ShuffV[i * Stride - 1] = i - 1; 8455 8456 SDValue ShuffleSrc2 = 8457 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8458 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8459 8460 SDValue Extend; 8461 if (SignedConv) { 8462 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8463 EVT ExtVT = Src.getValueType(); 8464 if (Subtarget.hasP9Altivec()) 8465 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8466 IntermediateVT.getVectorNumElements()); 8467 8468 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8469 DAG.getValueType(ExtVT)); 8470 } else 8471 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8472 8473 if (IsStrict) 8474 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8475 {Op.getOperand(0), Extend}, Flags); 8476 8477 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8478 } 8479 8480 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8481 SelectionDAG &DAG) const { 8482 SDLoc dl(Op); 8483 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8484 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8485 bool IsStrict = Op->isStrictFPOpcode(); 8486 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8487 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8488 8489 // TODO: Any other flags to propagate? 8490 SDNodeFlags Flags; 8491 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8492 8493 EVT InVT = Src.getValueType(); 8494 EVT OutVT = Op.getValueType(); 8495 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8496 isOperationCustom(Op.getOpcode(), InVT)) 8497 return LowerINT_TO_FPVector(Op, DAG, dl); 8498 8499 // Conversions to f128 are legal. 8500 if (Op.getValueType() == MVT::f128) 8501 return Subtarget.hasP9Vector() ? Op : SDValue(); 8502 8503 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8504 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8505 return SDValue(); 8506 8507 if (Src.getValueType() == MVT::i1) { 8508 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8509 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8510 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8511 if (IsStrict) 8512 return DAG.getMergeValues({Sel, Chain}, dl); 8513 else 8514 return Sel; 8515 } 8516 8517 // If we have direct moves, we can do all the conversion, skip the store/load 8518 // however, without FPCVT we can't do most conversions. 8519 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8520 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8521 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8522 8523 assert((IsSigned || Subtarget.hasFPCVT()) && 8524 "UINT_TO_FP is supported only with FPCVT"); 8525 8526 if (Src.getValueType() == MVT::i64) { 8527 SDValue SINT = Src; 8528 // When converting to single-precision, we actually need to convert 8529 // to double-precision first and then round to single-precision. 8530 // To avoid double-rounding effects during that operation, we have 8531 // to prepare the input operand. Bits that might be truncated when 8532 // converting to double-precision are replaced by a bit that won't 8533 // be lost at this stage, but is below the single-precision rounding 8534 // position. 8535 // 8536 // However, if -enable-unsafe-fp-math is in effect, accept double 8537 // rounding to avoid the extra overhead. 8538 if (Op.getValueType() == MVT::f32 && 8539 !Subtarget.hasFPCVT() && 8540 !DAG.getTarget().Options.UnsafeFPMath) { 8541 8542 // Twiddle input to make sure the low 11 bits are zero. (If this 8543 // is the case, we are guaranteed the value will fit into the 53 bit 8544 // mantissa of an IEEE double-precision value without rounding.) 8545 // If any of those low 11 bits were not zero originally, make sure 8546 // bit 12 (value 2048) is set instead, so that the final rounding 8547 // to single-precision gets the correct result. 8548 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8549 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8550 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8551 Round, DAG.getConstant(2047, dl, MVT::i64)); 8552 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8553 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8554 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8555 8556 // However, we cannot use that value unconditionally: if the magnitude 8557 // of the input value is small, the bit-twiddling we did above might 8558 // end up visibly changing the output. Fortunately, in that case, we 8559 // don't need to twiddle bits since the original input will convert 8560 // exactly to double-precision floating-point already. Therefore, 8561 // construct a conditional to use the original value if the top 11 8562 // bits are all sign-bit copies, and use the rounded value computed 8563 // above otherwise. 8564 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8565 SINT, DAG.getConstant(53, dl, MVT::i32)); 8566 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8567 Cond, DAG.getConstant(1, dl, MVT::i64)); 8568 Cond = DAG.getSetCC( 8569 dl, 8570 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8571 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8572 8573 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8574 } 8575 8576 ReuseLoadInfo RLI; 8577 SDValue Bits; 8578 8579 MachineFunction &MF = DAG.getMachineFunction(); 8580 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8581 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8582 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8583 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8584 } else if (Subtarget.hasLFIWAX() && 8585 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8586 MachineMemOperand *MMO = 8587 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8588 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8589 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8590 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8591 DAG.getVTList(MVT::f64, MVT::Other), 8592 Ops, MVT::i32, MMO); 8593 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8594 } else if (Subtarget.hasFPCVT() && 8595 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8596 MachineMemOperand *MMO = 8597 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8598 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8599 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8600 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8601 DAG.getVTList(MVT::f64, MVT::Other), 8602 Ops, MVT::i32, MMO); 8603 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8604 } else if (((Subtarget.hasLFIWAX() && 8605 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8606 (Subtarget.hasFPCVT() && 8607 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8608 SINT.getOperand(0).getValueType() == MVT::i32) { 8609 MachineFrameInfo &MFI = MF.getFrameInfo(); 8610 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8611 8612 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8613 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8614 8615 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8616 MachinePointerInfo::getFixedStack( 8617 DAG.getMachineFunction(), FrameIdx)); 8618 Chain = Store; 8619 8620 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8621 "Expected an i32 store"); 8622 8623 RLI.Ptr = FIdx; 8624 RLI.Chain = Chain; 8625 RLI.MPI = 8626 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8627 RLI.Alignment = Align(4); 8628 8629 MachineMemOperand *MMO = 8630 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8631 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8632 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8633 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8634 PPCISD::LFIWZX : PPCISD::LFIWAX, 8635 dl, DAG.getVTList(MVT::f64, MVT::Other), 8636 Ops, MVT::i32, MMO); 8637 Chain = Bits.getValue(1); 8638 } else 8639 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8640 8641 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8642 if (IsStrict) 8643 Chain = FP.getValue(1); 8644 8645 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8646 if (IsStrict) 8647 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8648 DAG.getVTList(MVT::f32, MVT::Other), 8649 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8650 else 8651 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8652 DAG.getIntPtrConstant(0, dl)); 8653 } 8654 return FP; 8655 } 8656 8657 assert(Src.getValueType() == MVT::i32 && 8658 "Unhandled INT_TO_FP type in custom expander!"); 8659 // Since we only generate this in 64-bit mode, we can take advantage of 8660 // 64-bit registers. In particular, sign extend the input value into the 8661 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8662 // then lfd it and fcfid it. 8663 MachineFunction &MF = DAG.getMachineFunction(); 8664 MachineFrameInfo &MFI = MF.getFrameInfo(); 8665 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8666 8667 SDValue Ld; 8668 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8669 ReuseLoadInfo RLI; 8670 bool ReusingLoad; 8671 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8672 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8673 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8674 8675 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8676 MachinePointerInfo::getFixedStack( 8677 DAG.getMachineFunction(), FrameIdx)); 8678 Chain = Store; 8679 8680 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8681 "Expected an i32 store"); 8682 8683 RLI.Ptr = FIdx; 8684 RLI.Chain = Chain; 8685 RLI.MPI = 8686 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8687 RLI.Alignment = Align(4); 8688 } 8689 8690 MachineMemOperand *MMO = 8691 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8692 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8693 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8694 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8695 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8696 MVT::i32, MMO); 8697 Chain = Ld.getValue(1); 8698 if (ReusingLoad) 8699 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8700 } else { 8701 assert(Subtarget.isPPC64() && 8702 "i32->FP without LFIWAX supported only on PPC64"); 8703 8704 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8705 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8706 8707 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8708 8709 // STD the extended value into the stack slot. 8710 SDValue Store = DAG.getStore( 8711 Chain, dl, Ext64, FIdx, 8712 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8713 Chain = Store; 8714 8715 // Load the value as a double. 8716 Ld = DAG.getLoad( 8717 MVT::f64, dl, Chain, FIdx, 8718 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8719 Chain = Ld.getValue(1); 8720 } 8721 8722 // FCFID it and return it. 8723 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8724 if (IsStrict) 8725 Chain = FP.getValue(1); 8726 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8727 if (IsStrict) 8728 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8729 DAG.getVTList(MVT::f32, MVT::Other), 8730 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8731 else 8732 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8733 DAG.getIntPtrConstant(0, dl)); 8734 } 8735 return FP; 8736 } 8737 8738 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8739 SelectionDAG &DAG) const { 8740 SDLoc dl(Op); 8741 /* 8742 The rounding mode is in bits 30:31 of FPSR, and has the following 8743 settings: 8744 00 Round to nearest 8745 01 Round to 0 8746 10 Round to +inf 8747 11 Round to -inf 8748 8749 FLT_ROUNDS, on the other hand, expects the following: 8750 -1 Undefined 8751 0 Round to 0 8752 1 Round to nearest 8753 2 Round to +inf 8754 3 Round to -inf 8755 8756 To perform the conversion, we do: 8757 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8758 */ 8759 8760 MachineFunction &MF = DAG.getMachineFunction(); 8761 EVT VT = Op.getValueType(); 8762 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8763 8764 // Save FP Control Word to register 8765 SDValue Chain = Op.getOperand(0); 8766 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8767 Chain = MFFS.getValue(1); 8768 8769 SDValue CWD; 8770 if (isTypeLegal(MVT::i64)) { 8771 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8772 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8773 } else { 8774 // Save FP register to stack slot 8775 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8776 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8777 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8778 8779 // Load FP Control Word from low 32 bits of stack slot. 8780 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8781 "Stack slot adjustment is valid only on big endian subtargets!"); 8782 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8783 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8784 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8785 Chain = CWD.getValue(1); 8786 } 8787 8788 // Transform as necessary 8789 SDValue CWD1 = 8790 DAG.getNode(ISD::AND, dl, MVT::i32, 8791 CWD, DAG.getConstant(3, dl, MVT::i32)); 8792 SDValue CWD2 = 8793 DAG.getNode(ISD::SRL, dl, MVT::i32, 8794 DAG.getNode(ISD::AND, dl, MVT::i32, 8795 DAG.getNode(ISD::XOR, dl, MVT::i32, 8796 CWD, DAG.getConstant(3, dl, MVT::i32)), 8797 DAG.getConstant(3, dl, MVT::i32)), 8798 DAG.getConstant(1, dl, MVT::i32)); 8799 8800 SDValue RetVal = 8801 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8802 8803 RetVal = 8804 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8805 dl, VT, RetVal); 8806 8807 return DAG.getMergeValues({RetVal, Chain}, dl); 8808 } 8809 8810 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8811 EVT VT = Op.getValueType(); 8812 unsigned BitWidth = VT.getSizeInBits(); 8813 SDLoc dl(Op); 8814 assert(Op.getNumOperands() == 3 && 8815 VT == Op.getOperand(1).getValueType() && 8816 "Unexpected SHL!"); 8817 8818 // Expand into a bunch of logical ops. Note that these ops 8819 // depend on the PPC behavior for oversized shift amounts. 8820 SDValue Lo = Op.getOperand(0); 8821 SDValue Hi = Op.getOperand(1); 8822 SDValue Amt = Op.getOperand(2); 8823 EVT AmtVT = Amt.getValueType(); 8824 8825 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8826 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8827 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8828 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8829 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8830 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8831 DAG.getConstant(-BitWidth, dl, AmtVT)); 8832 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8833 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8834 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8835 SDValue OutOps[] = { OutLo, OutHi }; 8836 return DAG.getMergeValues(OutOps, dl); 8837 } 8838 8839 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8840 EVT VT = Op.getValueType(); 8841 SDLoc dl(Op); 8842 unsigned BitWidth = VT.getSizeInBits(); 8843 assert(Op.getNumOperands() == 3 && 8844 VT == Op.getOperand(1).getValueType() && 8845 "Unexpected SRL!"); 8846 8847 // Expand into a bunch of logical ops. Note that these ops 8848 // depend on the PPC behavior for oversized shift amounts. 8849 SDValue Lo = Op.getOperand(0); 8850 SDValue Hi = Op.getOperand(1); 8851 SDValue Amt = Op.getOperand(2); 8852 EVT AmtVT = Amt.getValueType(); 8853 8854 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8855 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8856 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8857 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8858 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8859 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8860 DAG.getConstant(-BitWidth, dl, AmtVT)); 8861 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8862 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8863 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8864 SDValue OutOps[] = { OutLo, OutHi }; 8865 return DAG.getMergeValues(OutOps, dl); 8866 } 8867 8868 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8869 SDLoc dl(Op); 8870 EVT VT = Op.getValueType(); 8871 unsigned BitWidth = VT.getSizeInBits(); 8872 assert(Op.getNumOperands() == 3 && 8873 VT == Op.getOperand(1).getValueType() && 8874 "Unexpected SRA!"); 8875 8876 // Expand into a bunch of logical ops, followed by a select_cc. 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::SRA, dl, VT, Hi, Tmp5); 8890 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8891 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8892 Tmp4, Tmp6, ISD::SETLE); 8893 SDValue OutOps[] = { OutLo, OutHi }; 8894 return DAG.getMergeValues(OutOps, dl); 8895 } 8896 8897 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8898 SelectionDAG &DAG) const { 8899 SDLoc dl(Op); 8900 EVT VT = Op.getValueType(); 8901 unsigned BitWidth = VT.getSizeInBits(); 8902 8903 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8904 SDValue X = Op.getOperand(0); 8905 SDValue Y = Op.getOperand(1); 8906 SDValue Z = Op.getOperand(2); 8907 EVT AmtVT = Z.getValueType(); 8908 8909 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8910 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8911 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8912 // on PowerPC shift by BW being well defined. 8913 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8914 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8915 SDValue SubZ = 8916 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8917 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8918 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8919 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8920 } 8921 8922 //===----------------------------------------------------------------------===// 8923 // Vector related lowering. 8924 // 8925 8926 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8927 /// element size of SplatSize. Cast the result to VT. 8928 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8929 SelectionDAG &DAG, const SDLoc &dl) { 8930 static const MVT VTys[] = { // canonical VT to use for each size. 8931 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8932 }; 8933 8934 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8935 8936 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8937 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8938 SplatSize = 1; 8939 Val = 0xFF; 8940 } 8941 8942 EVT CanonicalVT = VTys[SplatSize-1]; 8943 8944 // Build a canonical splat for this value. 8945 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8946 } 8947 8948 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8949 /// specified intrinsic ID. 8950 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8951 const SDLoc &dl, EVT DestVT = MVT::Other) { 8952 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8953 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8954 DAG.getConstant(IID, dl, MVT::i32), Op); 8955 } 8956 8957 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8958 /// specified intrinsic ID. 8959 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8960 SelectionDAG &DAG, const SDLoc &dl, 8961 EVT DestVT = MVT::Other) { 8962 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8963 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8964 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8965 } 8966 8967 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8968 /// specified intrinsic ID. 8969 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8970 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8971 EVT DestVT = MVT::Other) { 8972 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8973 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8974 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8975 } 8976 8977 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8978 /// amount. The result has the specified value type. 8979 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8980 SelectionDAG &DAG, const SDLoc &dl) { 8981 // Force LHS/RHS to be the right type. 8982 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8983 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8984 8985 int Ops[16]; 8986 for (unsigned i = 0; i != 16; ++i) 8987 Ops[i] = i + Amt; 8988 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8989 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8990 } 8991 8992 /// Do we have an efficient pattern in a .td file for this node? 8993 /// 8994 /// \param V - pointer to the BuildVectorSDNode being matched 8995 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8996 /// 8997 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8998 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8999 /// the opposite is true (expansion is beneficial) are: 9000 /// - The node builds a vector out of integers that are not 32 or 64-bits 9001 /// - The node builds a vector out of constants 9002 /// - The node is a "load-and-splat" 9003 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9004 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9005 bool HasDirectMove, 9006 bool HasP8Vector) { 9007 EVT VecVT = V->getValueType(0); 9008 bool RightType = VecVT == MVT::v2f64 || 9009 (HasP8Vector && VecVT == MVT::v4f32) || 9010 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9011 if (!RightType) 9012 return false; 9013 9014 bool IsSplat = true; 9015 bool IsLoad = false; 9016 SDValue Op0 = V->getOperand(0); 9017 9018 // This function is called in a block that confirms the node is not a constant 9019 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9020 // different constants. 9021 if (V->isConstant()) 9022 return false; 9023 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9024 if (V->getOperand(i).isUndef()) 9025 return false; 9026 // We want to expand nodes that represent load-and-splat even if the 9027 // loaded value is a floating point truncation or conversion to int. 9028 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9029 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9030 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9031 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9032 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9033 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9034 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9035 IsLoad = true; 9036 // If the operands are different or the input is not a load and has more 9037 // uses than just this BV node, then it isn't a splat. 9038 if (V->getOperand(i) != Op0 || 9039 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9040 IsSplat = false; 9041 } 9042 return !(IsSplat && IsLoad); 9043 } 9044 9045 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9046 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9047 9048 SDLoc dl(Op); 9049 SDValue Op0 = Op->getOperand(0); 9050 9051 if ((Op.getValueType() != MVT::f128) || 9052 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9053 (Op0.getOperand(0).getValueType() != MVT::i64) || 9054 (Op0.getOperand(1).getValueType() != MVT::i64)) 9055 return SDValue(); 9056 9057 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9058 Op0.getOperand(1)); 9059 } 9060 9061 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9062 const SDValue *InputLoad = &Op; 9063 if (InputLoad->getOpcode() == ISD::BITCAST) 9064 InputLoad = &InputLoad->getOperand(0); 9065 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9066 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9067 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9068 InputLoad = &InputLoad->getOperand(0); 9069 } 9070 if (InputLoad->getOpcode() != ISD::LOAD) 9071 return nullptr; 9072 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9073 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9074 } 9075 9076 // Convert the argument APFloat to a single precision APFloat if there is no 9077 // loss in information during the conversion to single precision APFloat and the 9078 // resulting number is not a denormal number. Return true if successful. 9079 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9080 APFloat APFloatToConvert = ArgAPFloat; 9081 bool LosesInfo = true; 9082 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9083 &LosesInfo); 9084 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9085 if (Success) 9086 ArgAPFloat = APFloatToConvert; 9087 return Success; 9088 } 9089 9090 // Bitcast the argument APInt to a double and convert it to a single precision 9091 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9092 // argument if there is no loss in information during the conversion from 9093 // double to single precision APFloat and the resulting number is not a denormal 9094 // number. Return true if successful. 9095 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9096 double DpValue = ArgAPInt.bitsToDouble(); 9097 APFloat APFloatDp(DpValue); 9098 bool Success = convertToNonDenormSingle(APFloatDp); 9099 if (Success) 9100 ArgAPInt = APFloatDp.bitcastToAPInt(); 9101 return Success; 9102 } 9103 9104 // Nondestructive check for convertTonNonDenormSingle. 9105 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9106 // Only convert if it loses info, since XXSPLTIDP should 9107 // handle the other case. 9108 APFloat APFloatToConvert = ArgAPFloat; 9109 bool LosesInfo = true; 9110 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9111 &LosesInfo); 9112 9113 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9114 } 9115 9116 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, 9117 unsigned &Opcode) { 9118 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0)); 9119 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode)) 9120 return false; 9121 9122 EVT Ty = Op->getValueType(0); 9123 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending 9124 // as we cannot handle extending loads for these types. 9125 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) && 9126 ISD::isNON_EXTLoad(InputNode)) 9127 return true; 9128 9129 EVT MemVT = InputNode->getMemoryVT(); 9130 // For v8i16 and v16i8 types, extending loads can be handled as long as the 9131 // memory VT is the same vector element VT type. 9132 // The loads feeding into the v8i16 and v16i8 types will be extending because 9133 // scalar i8/i16 are not legal types. 9134 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) && 9135 (MemVT == Ty.getVectorElementType())) 9136 return true; 9137 9138 if (Ty == MVT::v2i64) { 9139 // Check the extend type, when the input type is i32, and the output vector 9140 // type is v2i64. 9141 if (MemVT == MVT::i32) { 9142 if (ISD::isZEXTLoad(InputNode)) 9143 Opcode = PPCISD::ZEXT_LD_SPLAT; 9144 if (ISD::isSEXTLoad(InputNode)) 9145 Opcode = PPCISD::SEXT_LD_SPLAT; 9146 } 9147 return true; 9148 } 9149 return false; 9150 } 9151 9152 // If this is a case we can't handle, return null and let the default 9153 // expansion code take care of it. If we CAN select this case, and if it 9154 // selects to a single instruction, return Op. Otherwise, if we can codegen 9155 // this case more efficiently than a constant pool load, lower it to the 9156 // sequence of ops that should be used. 9157 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9158 SelectionDAG &DAG) const { 9159 SDLoc dl(Op); 9160 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9161 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9162 9163 // Check if this is a splat of a constant value. 9164 APInt APSplatBits, APSplatUndef; 9165 unsigned SplatBitSize; 9166 bool HasAnyUndefs; 9167 bool BVNIsConstantSplat = 9168 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9169 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9170 9171 // If it is a splat of a double, check if we can shrink it to a 32 bit 9172 // non-denormal float which when converted back to double gives us the same 9173 // double. This is to exploit the XXSPLTIDP instruction. 9174 // If we lose precision, we use XXSPLTI32DX. 9175 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9176 Subtarget.hasPrefixInstrs()) { 9177 // Check the type first to short-circuit so we don't modify APSplatBits if 9178 // this block isn't executed. 9179 if ((Op->getValueType(0) == MVT::v2f64) && 9180 convertToNonDenormSingle(APSplatBits)) { 9181 SDValue SplatNode = DAG.getNode( 9182 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9183 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9184 return DAG.getBitcast(Op.getValueType(), SplatNode); 9185 } else { 9186 // We may lose precision, so we have to use XXSPLTI32DX. 9187 9188 uint32_t Hi = 9189 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9190 uint32_t Lo = 9191 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9192 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9193 9194 if (!Hi || !Lo) 9195 // If either load is 0, then we should generate XXLXOR to set to 0. 9196 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9197 9198 if (Hi) 9199 SplatNode = DAG.getNode( 9200 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9201 DAG.getTargetConstant(0, dl, MVT::i32), 9202 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9203 9204 if (Lo) 9205 SplatNode = 9206 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9207 DAG.getTargetConstant(1, dl, MVT::i32), 9208 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9209 9210 return DAG.getBitcast(Op.getValueType(), SplatNode); 9211 } 9212 } 9213 9214 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9215 unsigned NewOpcode = PPCISD::LD_SPLAT; 9216 9217 // Handle load-and-splat patterns as we have instructions that will do this 9218 // in one go. 9219 if (DAG.isSplatValue(Op, true) && 9220 isValidSplatLoad(Subtarget, Op, NewOpcode)) { 9221 const SDValue *InputLoad = &Op.getOperand(0); 9222 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9223 9224 // If the input load is an extending load, it will be an i32 -> i64 9225 // extending load and isValidSplatLoad() will update NewOpcode. 9226 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits(); 9227 unsigned ElementSize = 9228 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2); 9229 9230 assert(((ElementSize == 2 * MemorySize) 9231 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || 9232 NewOpcode == PPCISD::SEXT_LD_SPLAT) 9233 : (NewOpcode == PPCISD::LD_SPLAT)) && 9234 "Unmatched element size and opcode!\n"); 9235 9236 // Checking for a single use of this load, we have to check for vector 9237 // width (128 bits) / ElementSize uses (since each operand of the 9238 // BUILD_VECTOR is a separate use of the value. 9239 unsigned NumUsesOfInputLD = 128 / ElementSize; 9240 for (SDValue BVInOp : Op->ops()) 9241 if (BVInOp.isUndef()) 9242 NumUsesOfInputLD--; 9243 9244 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector: 9245 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index 9246 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index 9247 // 15", but funciton IsValidSplatLoad() now will only return true when 9248 // the data at index 0 is not nullptr. So we will not get into trouble for 9249 // these cases. 9250 // 9251 // case 1 - lfiwzx/lfiwax 9252 // 1.1: load result is i32 and is sign/zero extend to i64; 9253 // 1.2: build a v2i64 vector type with above loaded value; 9254 // 1.3: the vector has only one value at index 0, others are all undef; 9255 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute. 9256 if (NumUsesOfInputLD == 1 && 9257 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT && 9258 !Subtarget.isLittleEndian() && Subtarget.hasVSX() && 9259 Subtarget.hasLFIWAX())) 9260 return SDValue(); 9261 9262 // case 2 - lxvr[hb]x 9263 // 2.1: load result is at most i16; 9264 // 2.2: build a vector with above loaded value; 9265 // 2.3: the vector has only one value at index 0, others are all undef; 9266 // 2.4: on LE target, so that lxvr[hb]x does not need any permute. 9267 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() && 9268 Subtarget.isISA3_1() && ElementSize <= 16) 9269 return SDValue(); 9270 9271 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9272 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9273 Subtarget.hasVSX()) { 9274 SDValue Ops[] = { 9275 LD->getChain(), // Chain 9276 LD->getBasePtr(), // Ptr 9277 DAG.getValueType(Op.getValueType()) // VT 9278 }; 9279 SDValue LdSplt = DAG.getMemIntrinsicNode( 9280 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops, 9281 LD->getMemoryVT(), LD->getMemOperand()); 9282 // Replace all uses of the output chain of the original load with the 9283 // output chain of the new load. 9284 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9285 LdSplt.getValue(1)); 9286 return LdSplt; 9287 } 9288 } 9289 9290 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9291 // 32-bits can be lowered to VSX instructions under certain conditions. 9292 // Without VSX, there is no pattern more efficient than expanding the node. 9293 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9294 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9295 Subtarget.hasP8Vector())) 9296 return Op; 9297 return SDValue(); 9298 } 9299 9300 uint64_t SplatBits = APSplatBits.getZExtValue(); 9301 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9302 unsigned SplatSize = SplatBitSize / 8; 9303 9304 // First, handle single instruction cases. 9305 9306 // All zeros? 9307 if (SplatBits == 0) { 9308 // Canonicalize all zero vectors to be v4i32. 9309 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9310 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9311 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9312 } 9313 return Op; 9314 } 9315 9316 // We have XXSPLTIW for constant splats four bytes wide. 9317 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9318 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9319 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9320 // turned into a 4-byte splat of 0xABABABAB. 9321 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9322 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9323 Op.getValueType(), DAG, dl); 9324 9325 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9326 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9327 dl); 9328 9329 // We have XXSPLTIB for constant splats one byte wide. 9330 if (Subtarget.hasP9Vector() && SplatSize == 1) 9331 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9332 dl); 9333 9334 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9335 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9336 (32-SplatBitSize)); 9337 if (SextVal >= -16 && SextVal <= 15) 9338 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9339 dl); 9340 9341 // Two instruction sequences. 9342 9343 // If this value is in the range [-32,30] and is even, use: 9344 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9345 // If this value is in the range [17,31] and is odd, use: 9346 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9347 // If this value is in the range [-31,-17] and is odd, use: 9348 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9349 // Note the last two are three-instruction sequences. 9350 if (SextVal >= -32 && SextVal <= 31) { 9351 // To avoid having these optimizations undone by constant folding, 9352 // we convert to a pseudo that will be expanded later into one of 9353 // the above forms. 9354 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9355 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9356 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9357 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9358 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9359 if (VT == Op.getValueType()) 9360 return RetVal; 9361 else 9362 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9363 } 9364 9365 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9366 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9367 // for fneg/fabs. 9368 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9369 // Make -1 and vspltisw -1: 9370 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9371 9372 // Make the VSLW intrinsic, computing 0x8000_0000. 9373 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9374 OnesV, DAG, dl); 9375 9376 // xor by OnesV to invert it. 9377 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9378 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9379 } 9380 9381 // Check to see if this is a wide variety of vsplti*, binop self cases. 9382 static const signed char SplatCsts[] = { 9383 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9384 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9385 }; 9386 9387 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9388 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9389 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9390 int i = SplatCsts[idx]; 9391 9392 // Figure out what shift amount will be used by altivec if shifted by i in 9393 // this splat size. 9394 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9395 9396 // vsplti + shl self. 9397 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9398 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9399 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9400 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9401 Intrinsic::ppc_altivec_vslw 9402 }; 9403 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9404 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9405 } 9406 9407 // vsplti + srl self. 9408 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9409 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9410 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9411 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9412 Intrinsic::ppc_altivec_vsrw 9413 }; 9414 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9415 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9416 } 9417 9418 // vsplti + rol self. 9419 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9420 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9421 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9422 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9423 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9424 Intrinsic::ppc_altivec_vrlw 9425 }; 9426 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9427 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9428 } 9429 9430 // t = vsplti c, result = vsldoi t, t, 1 9431 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9432 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9433 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9434 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9435 } 9436 // t = vsplti c, result = vsldoi t, t, 2 9437 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9438 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9439 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9440 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9441 } 9442 // t = vsplti c, result = vsldoi t, t, 3 9443 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9444 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9445 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9446 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9447 } 9448 } 9449 9450 return SDValue(); 9451 } 9452 9453 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9454 /// the specified operations to build the shuffle. 9455 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9456 SDValue RHS, SelectionDAG &DAG, 9457 const SDLoc &dl) { 9458 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9459 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9460 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9461 9462 enum { 9463 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9464 OP_VMRGHW, 9465 OP_VMRGLW, 9466 OP_VSPLTISW0, 9467 OP_VSPLTISW1, 9468 OP_VSPLTISW2, 9469 OP_VSPLTISW3, 9470 OP_VSLDOI4, 9471 OP_VSLDOI8, 9472 OP_VSLDOI12 9473 }; 9474 9475 if (OpNum == OP_COPY) { 9476 if (LHSID == (1*9+2)*9+3) return LHS; 9477 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9478 return RHS; 9479 } 9480 9481 SDValue OpLHS, OpRHS; 9482 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9483 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9484 9485 int ShufIdxs[16]; 9486 switch (OpNum) { 9487 default: llvm_unreachable("Unknown i32 permute!"); 9488 case OP_VMRGHW: 9489 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9490 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9491 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9492 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9493 break; 9494 case OP_VMRGLW: 9495 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9496 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9497 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9498 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9499 break; 9500 case OP_VSPLTISW0: 9501 for (unsigned i = 0; i != 16; ++i) 9502 ShufIdxs[i] = (i&3)+0; 9503 break; 9504 case OP_VSPLTISW1: 9505 for (unsigned i = 0; i != 16; ++i) 9506 ShufIdxs[i] = (i&3)+4; 9507 break; 9508 case OP_VSPLTISW2: 9509 for (unsigned i = 0; i != 16; ++i) 9510 ShufIdxs[i] = (i&3)+8; 9511 break; 9512 case OP_VSPLTISW3: 9513 for (unsigned i = 0; i != 16; ++i) 9514 ShufIdxs[i] = (i&3)+12; 9515 break; 9516 case OP_VSLDOI4: 9517 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9518 case OP_VSLDOI8: 9519 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9520 case OP_VSLDOI12: 9521 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9522 } 9523 EVT VT = OpLHS.getValueType(); 9524 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9525 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9526 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9527 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9528 } 9529 9530 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9531 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9532 /// SDValue. 9533 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9534 SelectionDAG &DAG) const { 9535 const unsigned BytesInVector = 16; 9536 bool IsLE = Subtarget.isLittleEndian(); 9537 SDLoc dl(N); 9538 SDValue V1 = N->getOperand(0); 9539 SDValue V2 = N->getOperand(1); 9540 unsigned ShiftElts = 0, InsertAtByte = 0; 9541 bool Swap = false; 9542 9543 // Shifts required to get the byte we want at element 7. 9544 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9545 0, 15, 14, 13, 12, 11, 10, 9}; 9546 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9547 1, 2, 3, 4, 5, 6, 7, 8}; 9548 9549 ArrayRef<int> Mask = N->getMask(); 9550 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9551 9552 // For each mask element, find out if we're just inserting something 9553 // from V2 into V1 or vice versa. 9554 // Possible permutations inserting an element from V2 into V1: 9555 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9556 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9557 // ... 9558 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9559 // Inserting from V1 into V2 will be similar, except mask range will be 9560 // [16,31]. 9561 9562 bool FoundCandidate = false; 9563 // If both vector operands for the shuffle are the same vector, the mask 9564 // will contain only elements from the first one and the second one will be 9565 // undef. 9566 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9567 // Go through the mask of half-words to find an element that's being moved 9568 // from one vector to the other. 9569 for (unsigned i = 0; i < BytesInVector; ++i) { 9570 unsigned CurrentElement = Mask[i]; 9571 // If 2nd operand is undefined, we should only look for element 7 in the 9572 // Mask. 9573 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9574 continue; 9575 9576 bool OtherElementsInOrder = true; 9577 // Examine the other elements in the Mask to see if they're in original 9578 // order. 9579 for (unsigned j = 0; j < BytesInVector; ++j) { 9580 if (j == i) 9581 continue; 9582 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9583 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9584 // in which we always assume we're always picking from the 1st operand. 9585 int MaskOffset = 9586 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9587 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9588 OtherElementsInOrder = false; 9589 break; 9590 } 9591 } 9592 // If other elements are in original order, we record the number of shifts 9593 // we need to get the element we want into element 7. Also record which byte 9594 // in the vector we should insert into. 9595 if (OtherElementsInOrder) { 9596 // If 2nd operand is undefined, we assume no shifts and no swapping. 9597 if (V2.isUndef()) { 9598 ShiftElts = 0; 9599 Swap = false; 9600 } else { 9601 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9602 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9603 : BigEndianShifts[CurrentElement & 0xF]; 9604 Swap = CurrentElement < BytesInVector; 9605 } 9606 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9607 FoundCandidate = true; 9608 break; 9609 } 9610 } 9611 9612 if (!FoundCandidate) 9613 return SDValue(); 9614 9615 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9616 // optionally with VECSHL if shift is required. 9617 if (Swap) 9618 std::swap(V1, V2); 9619 if (V2.isUndef()) 9620 V2 = V1; 9621 if (ShiftElts) { 9622 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9623 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9624 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9625 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9626 } 9627 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9628 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9629 } 9630 9631 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9632 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9633 /// SDValue. 9634 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9635 SelectionDAG &DAG) const { 9636 const unsigned NumHalfWords = 8; 9637 const unsigned BytesInVector = NumHalfWords * 2; 9638 // Check that the shuffle is on half-words. 9639 if (!isNByteElemShuffleMask(N, 2, 1)) 9640 return SDValue(); 9641 9642 bool IsLE = Subtarget.isLittleEndian(); 9643 SDLoc dl(N); 9644 SDValue V1 = N->getOperand(0); 9645 SDValue V2 = N->getOperand(1); 9646 unsigned ShiftElts = 0, InsertAtByte = 0; 9647 bool Swap = false; 9648 9649 // Shifts required to get the half-word we want at element 3. 9650 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9651 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9652 9653 uint32_t Mask = 0; 9654 uint32_t OriginalOrderLow = 0x1234567; 9655 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9656 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9657 // 32-bit space, only need 4-bit nibbles per element. 9658 for (unsigned i = 0; i < NumHalfWords; ++i) { 9659 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9660 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9661 } 9662 9663 // For each mask element, find out if we're just inserting something 9664 // from V2 into V1 or vice versa. Possible permutations inserting an element 9665 // from V2 into V1: 9666 // X, 1, 2, 3, 4, 5, 6, 7 9667 // 0, X, 2, 3, 4, 5, 6, 7 9668 // 0, 1, X, 3, 4, 5, 6, 7 9669 // 0, 1, 2, X, 4, 5, 6, 7 9670 // 0, 1, 2, 3, X, 5, 6, 7 9671 // 0, 1, 2, 3, 4, X, 6, 7 9672 // 0, 1, 2, 3, 4, 5, X, 7 9673 // 0, 1, 2, 3, 4, 5, 6, X 9674 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9675 9676 bool FoundCandidate = false; 9677 // Go through the mask of half-words to find an element that's being moved 9678 // from one vector to the other. 9679 for (unsigned i = 0; i < NumHalfWords; ++i) { 9680 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9681 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9682 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9683 uint32_t TargetOrder = 0x0; 9684 9685 // If both vector operands for the shuffle are the same vector, the mask 9686 // will contain only elements from the first one and the second one will be 9687 // undef. 9688 if (V2.isUndef()) { 9689 ShiftElts = 0; 9690 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9691 TargetOrder = OriginalOrderLow; 9692 Swap = false; 9693 // Skip if not the correct element or mask of other elements don't equal 9694 // to our expected order. 9695 if (MaskOneElt == VINSERTHSrcElem && 9696 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9697 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9698 FoundCandidate = true; 9699 break; 9700 } 9701 } else { // If both operands are defined. 9702 // Target order is [8,15] if the current mask is between [0,7]. 9703 TargetOrder = 9704 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9705 // Skip if mask of other elements don't equal our expected order. 9706 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9707 // We only need the last 3 bits for the number of shifts. 9708 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9709 : BigEndianShifts[MaskOneElt & 0x7]; 9710 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9711 Swap = MaskOneElt < NumHalfWords; 9712 FoundCandidate = true; 9713 break; 9714 } 9715 } 9716 } 9717 9718 if (!FoundCandidate) 9719 return SDValue(); 9720 9721 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9722 // optionally with VECSHL if shift is required. 9723 if (Swap) 9724 std::swap(V1, V2); 9725 if (V2.isUndef()) 9726 V2 = V1; 9727 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9728 if (ShiftElts) { 9729 // Double ShiftElts because we're left shifting on v16i8 type. 9730 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9731 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9732 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9733 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9734 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9735 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9736 } 9737 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9738 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9739 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9740 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9741 } 9742 9743 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9744 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9745 /// return the default SDValue. 9746 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9747 SelectionDAG &DAG) const { 9748 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9749 // to v16i8. Peek through the bitcasts to get the actual operands. 9750 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9751 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9752 9753 auto ShuffleMask = SVN->getMask(); 9754 SDValue VecShuffle(SVN, 0); 9755 SDLoc DL(SVN); 9756 9757 // Check that we have a four byte shuffle. 9758 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9759 return SDValue(); 9760 9761 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9762 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9763 std::swap(LHS, RHS); 9764 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9765 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9766 } 9767 9768 // Ensure that the RHS is a vector of constants. 9769 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9770 if (!BVN) 9771 return SDValue(); 9772 9773 // Check if RHS is a splat of 4-bytes (or smaller). 9774 APInt APSplatValue, APSplatUndef; 9775 unsigned SplatBitSize; 9776 bool HasAnyUndefs; 9777 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9778 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9779 SplatBitSize > 32) 9780 return SDValue(); 9781 9782 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9783 // The instruction splats a constant C into two words of the source vector 9784 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9785 // Thus we check that the shuffle mask is the equivalent of 9786 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9787 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9788 // within each word are consecutive, so we only need to check the first byte. 9789 SDValue Index; 9790 bool IsLE = Subtarget.isLittleEndian(); 9791 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9792 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9793 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9794 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9795 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9796 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9797 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9798 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9799 else 9800 return SDValue(); 9801 9802 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9803 // for XXSPLTI32DX. 9804 unsigned SplatVal = APSplatValue.getZExtValue(); 9805 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9806 SplatVal |= (SplatVal << SplatBitSize); 9807 9808 SDValue SplatNode = DAG.getNode( 9809 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9810 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9811 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9812 } 9813 9814 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9815 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9816 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9817 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9818 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9819 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9820 assert(Op.getValueType() == MVT::v1i128 && 9821 "Only set v1i128 as custom, other type shouldn't reach here!"); 9822 SDLoc dl(Op); 9823 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9824 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9825 unsigned SHLAmt = N1.getConstantOperandVal(0); 9826 if (SHLAmt % 8 == 0) { 9827 std::array<int, 16> Mask; 9828 std::iota(Mask.begin(), Mask.end(), 0); 9829 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9830 if (SDValue Shuffle = 9831 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9832 DAG.getUNDEF(MVT::v16i8), Mask)) 9833 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9834 } 9835 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9836 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9837 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9838 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9839 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9840 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9841 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9842 } 9843 9844 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9845 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9846 /// return the code it can be lowered into. Worst case, it can always be 9847 /// lowered into a vperm. 9848 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9849 SelectionDAG &DAG) const { 9850 SDLoc dl(Op); 9851 SDValue V1 = Op.getOperand(0); 9852 SDValue V2 = Op.getOperand(1); 9853 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9854 9855 // Any nodes that were combined in the target-independent combiner prior 9856 // to vector legalization will not be sent to the target combine. Try to 9857 // combine it here. 9858 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9859 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9860 return NewShuffle; 9861 Op = NewShuffle; 9862 SVOp = cast<ShuffleVectorSDNode>(Op); 9863 V1 = Op.getOperand(0); 9864 V2 = Op.getOperand(1); 9865 } 9866 EVT VT = Op.getValueType(); 9867 bool isLittleEndian = Subtarget.isLittleEndian(); 9868 9869 unsigned ShiftElts, InsertAtByte; 9870 bool Swap = false; 9871 9872 // If this is a load-and-splat, we can do that with a single instruction 9873 // in some cases. However if the load has multiple uses, we don't want to 9874 // combine it because that will just produce multiple loads. 9875 bool IsPermutedLoad = false; 9876 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9877 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9878 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9879 InputLoad->hasOneUse()) { 9880 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9881 int SplatIdx = 9882 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9883 9884 // The splat index for permuted loads will be in the left half of the vector 9885 // which is strictly wider than the loaded value by 8 bytes. So we need to 9886 // adjust the splat index to point to the correct address in memory. 9887 if (IsPermutedLoad) { 9888 assert((isLittleEndian || IsFourByte) && 9889 "Unexpected size for permuted load on big endian target"); 9890 SplatIdx += IsFourByte ? 2 : 1; 9891 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9892 "Splat of a value outside of the loaded memory"); 9893 } 9894 9895 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9896 // For 4-byte load-and-splat, we need Power9. 9897 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9898 uint64_t Offset = 0; 9899 if (IsFourByte) 9900 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9901 else 9902 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9903 9904 // If the width of the load is the same as the width of the splat, 9905 // loading with an offset would load the wrong memory. 9906 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9907 Offset = 0; 9908 9909 SDValue BasePtr = LD->getBasePtr(); 9910 if (Offset != 0) 9911 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9912 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9913 SDValue Ops[] = { 9914 LD->getChain(), // Chain 9915 BasePtr, // BasePtr 9916 DAG.getValueType(Op.getValueType()) // VT 9917 }; 9918 SDVTList VTL = 9919 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9920 SDValue LdSplt = 9921 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9922 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9923 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9924 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9925 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9926 return LdSplt; 9927 } 9928 } 9929 if (Subtarget.hasP9Vector() && 9930 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9931 isLittleEndian)) { 9932 if (Swap) 9933 std::swap(V1, V2); 9934 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9935 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9936 if (ShiftElts) { 9937 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9938 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9939 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9940 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9941 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9942 } 9943 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9944 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9945 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9946 } 9947 9948 if (Subtarget.hasPrefixInstrs()) { 9949 SDValue SplatInsertNode; 9950 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9951 return SplatInsertNode; 9952 } 9953 9954 if (Subtarget.hasP9Altivec()) { 9955 SDValue NewISDNode; 9956 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9957 return NewISDNode; 9958 9959 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9960 return NewISDNode; 9961 } 9962 9963 if (Subtarget.hasVSX() && 9964 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9965 if (Swap) 9966 std::swap(V1, V2); 9967 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9968 SDValue Conv2 = 9969 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9970 9971 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9972 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9973 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9974 } 9975 9976 if (Subtarget.hasVSX() && 9977 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9978 if (Swap) 9979 std::swap(V1, V2); 9980 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9981 SDValue Conv2 = 9982 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9983 9984 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9985 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9986 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9987 } 9988 9989 if (Subtarget.hasP9Vector()) { 9990 if (PPC::isXXBRHShuffleMask(SVOp)) { 9991 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9992 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9993 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9994 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9995 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9996 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9997 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9998 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9999 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10000 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 10001 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 10002 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 10003 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 10004 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 10005 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 10006 } 10007 } 10008 10009 if (Subtarget.hasVSX()) { 10010 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 10011 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 10012 10013 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10014 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 10015 DAG.getConstant(SplatIdx, dl, MVT::i32)); 10016 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 10017 } 10018 10019 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 10020 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 10021 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 10022 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 10023 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 10024 } 10025 } 10026 10027 // Cases that are handled by instructions that take permute immediates 10028 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10029 // selected by the instruction selector. 10030 if (V2.isUndef()) { 10031 if (PPC::isSplatShuffleMask(SVOp, 1) || 10032 PPC::isSplatShuffleMask(SVOp, 2) || 10033 PPC::isSplatShuffleMask(SVOp, 4) || 10034 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10035 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10036 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10037 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10038 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10039 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10040 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10041 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10042 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10043 (Subtarget.hasP8Altivec() && ( 10044 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10045 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10046 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10047 return Op; 10048 } 10049 } 10050 10051 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10052 // and produce a fixed permutation. If any of these match, do not lower to 10053 // VPERM. 10054 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10055 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10056 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10057 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10058 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10059 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10060 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10061 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10062 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10063 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10064 (Subtarget.hasP8Altivec() && ( 10065 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10066 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10067 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10068 return Op; 10069 10070 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10071 // perfect shuffle table to emit an optimal matching sequence. 10072 ArrayRef<int> PermMask = SVOp->getMask(); 10073 10074 unsigned PFIndexes[4]; 10075 bool isFourElementShuffle = true; 10076 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 10077 unsigned EltNo = 8; // Start out undef. 10078 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10079 if (PermMask[i*4+j] < 0) 10080 continue; // Undef, ignore it. 10081 10082 unsigned ByteSource = PermMask[i*4+j]; 10083 if ((ByteSource & 3) != j) { 10084 isFourElementShuffle = false; 10085 break; 10086 } 10087 10088 if (EltNo == 8) { 10089 EltNo = ByteSource/4; 10090 } else if (EltNo != ByteSource/4) { 10091 isFourElementShuffle = false; 10092 break; 10093 } 10094 } 10095 PFIndexes[i] = EltNo; 10096 } 10097 10098 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10099 // perfect shuffle vector to determine if it is cost effective to do this as 10100 // discrete instructions, or whether we should use a vperm. 10101 // For now, we skip this for little endian until such time as we have a 10102 // little-endian perfect shuffle table. 10103 if (isFourElementShuffle && !isLittleEndian) { 10104 // Compute the index in the perfect shuffle table. 10105 unsigned PFTableIndex = 10106 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10107 10108 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10109 unsigned Cost = (PFEntry >> 30); 10110 10111 // Determining when to avoid vperm is tricky. Many things affect the cost 10112 // of vperm, particularly how many times the perm mask needs to be computed. 10113 // For example, if the perm mask can be hoisted out of a loop or is already 10114 // used (perhaps because there are multiple permutes with the same shuffle 10115 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10116 // the loop requires an extra register. 10117 // 10118 // As a compromise, we only emit discrete instructions if the shuffle can be 10119 // generated in 3 or fewer operations. When we have loop information 10120 // available, if this block is within a loop, we should avoid using vperm 10121 // for 3-operation perms and use a constant pool load instead. 10122 if (Cost < 3) 10123 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10124 } 10125 10126 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10127 // vector that will get spilled to the constant pool. 10128 if (V2.isUndef()) V2 = V1; 10129 10130 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10131 // that it is in input element units, not in bytes. Convert now. 10132 10133 // For little endian, the order of the input vectors is reversed, and 10134 // the permutation mask is complemented with respect to 31. This is 10135 // necessary to produce proper semantics with the big-endian-biased vperm 10136 // instruction. 10137 EVT EltVT = V1.getValueType().getVectorElementType(); 10138 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10139 10140 SmallVector<SDValue, 16> ResultMask; 10141 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10142 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10143 10144 for (unsigned j = 0; j != BytesPerElement; ++j) 10145 if (isLittleEndian) 10146 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10147 dl, MVT::i32)); 10148 else 10149 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10150 MVT::i32)); 10151 } 10152 10153 ShufflesHandledWithVPERM++; 10154 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10155 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10156 LLVM_DEBUG(SVOp->dump()); 10157 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10158 LLVM_DEBUG(VPermMask.dump()); 10159 10160 if (isLittleEndian) 10161 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10162 V2, V1, VPermMask); 10163 else 10164 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10165 V1, V2, VPermMask); 10166 } 10167 10168 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10169 /// vector comparison. If it is, return true and fill in Opc/isDot with 10170 /// information about the intrinsic. 10171 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10172 bool &isDot, const PPCSubtarget &Subtarget) { 10173 unsigned IntrinsicID = 10174 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10175 CompareOpc = -1; 10176 isDot = false; 10177 switch (IntrinsicID) { 10178 default: 10179 return false; 10180 // Comparison predicates. 10181 case Intrinsic::ppc_altivec_vcmpbfp_p: 10182 CompareOpc = 966; 10183 isDot = true; 10184 break; 10185 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10186 CompareOpc = 198; 10187 isDot = true; 10188 break; 10189 case Intrinsic::ppc_altivec_vcmpequb_p: 10190 CompareOpc = 6; 10191 isDot = true; 10192 break; 10193 case Intrinsic::ppc_altivec_vcmpequh_p: 10194 CompareOpc = 70; 10195 isDot = true; 10196 break; 10197 case Intrinsic::ppc_altivec_vcmpequw_p: 10198 CompareOpc = 134; 10199 isDot = true; 10200 break; 10201 case Intrinsic::ppc_altivec_vcmpequd_p: 10202 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10203 CompareOpc = 199; 10204 isDot = true; 10205 } else 10206 return false; 10207 break; 10208 case Intrinsic::ppc_altivec_vcmpneb_p: 10209 case Intrinsic::ppc_altivec_vcmpneh_p: 10210 case Intrinsic::ppc_altivec_vcmpnew_p: 10211 case Intrinsic::ppc_altivec_vcmpnezb_p: 10212 case Intrinsic::ppc_altivec_vcmpnezh_p: 10213 case Intrinsic::ppc_altivec_vcmpnezw_p: 10214 if (Subtarget.hasP9Altivec()) { 10215 switch (IntrinsicID) { 10216 default: 10217 llvm_unreachable("Unknown comparison intrinsic."); 10218 case Intrinsic::ppc_altivec_vcmpneb_p: 10219 CompareOpc = 7; 10220 break; 10221 case Intrinsic::ppc_altivec_vcmpneh_p: 10222 CompareOpc = 71; 10223 break; 10224 case Intrinsic::ppc_altivec_vcmpnew_p: 10225 CompareOpc = 135; 10226 break; 10227 case Intrinsic::ppc_altivec_vcmpnezb_p: 10228 CompareOpc = 263; 10229 break; 10230 case Intrinsic::ppc_altivec_vcmpnezh_p: 10231 CompareOpc = 327; 10232 break; 10233 case Intrinsic::ppc_altivec_vcmpnezw_p: 10234 CompareOpc = 391; 10235 break; 10236 } 10237 isDot = true; 10238 } else 10239 return false; 10240 break; 10241 case Intrinsic::ppc_altivec_vcmpgefp_p: 10242 CompareOpc = 454; 10243 isDot = true; 10244 break; 10245 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10246 CompareOpc = 710; 10247 isDot = true; 10248 break; 10249 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10250 CompareOpc = 774; 10251 isDot = true; 10252 break; 10253 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10254 CompareOpc = 838; 10255 isDot = true; 10256 break; 10257 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10258 CompareOpc = 902; 10259 isDot = true; 10260 break; 10261 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10262 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10263 CompareOpc = 967; 10264 isDot = true; 10265 } else 10266 return false; 10267 break; 10268 case Intrinsic::ppc_altivec_vcmpgtub_p: 10269 CompareOpc = 518; 10270 isDot = true; 10271 break; 10272 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10273 CompareOpc = 582; 10274 isDot = true; 10275 break; 10276 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10277 CompareOpc = 646; 10278 isDot = true; 10279 break; 10280 case Intrinsic::ppc_altivec_vcmpgtud_p: 10281 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10282 CompareOpc = 711; 10283 isDot = true; 10284 } else 10285 return false; 10286 break; 10287 10288 case Intrinsic::ppc_altivec_vcmpequq: 10289 case Intrinsic::ppc_altivec_vcmpgtsq: 10290 case Intrinsic::ppc_altivec_vcmpgtuq: 10291 if (!Subtarget.isISA3_1()) 10292 return false; 10293 switch (IntrinsicID) { 10294 default: 10295 llvm_unreachable("Unknown comparison intrinsic."); 10296 case Intrinsic::ppc_altivec_vcmpequq: 10297 CompareOpc = 455; 10298 break; 10299 case Intrinsic::ppc_altivec_vcmpgtsq: 10300 CompareOpc = 903; 10301 break; 10302 case Intrinsic::ppc_altivec_vcmpgtuq: 10303 CompareOpc = 647; 10304 break; 10305 } 10306 break; 10307 10308 // VSX predicate comparisons use the same infrastructure 10309 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10310 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10311 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10312 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10313 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10314 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10315 if (Subtarget.hasVSX()) { 10316 switch (IntrinsicID) { 10317 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10318 CompareOpc = 99; 10319 break; 10320 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10321 CompareOpc = 115; 10322 break; 10323 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10324 CompareOpc = 107; 10325 break; 10326 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10327 CompareOpc = 67; 10328 break; 10329 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10330 CompareOpc = 83; 10331 break; 10332 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10333 CompareOpc = 75; 10334 break; 10335 } 10336 isDot = true; 10337 } else 10338 return false; 10339 break; 10340 10341 // Normal Comparisons. 10342 case Intrinsic::ppc_altivec_vcmpbfp: 10343 CompareOpc = 966; 10344 break; 10345 case Intrinsic::ppc_altivec_vcmpeqfp: 10346 CompareOpc = 198; 10347 break; 10348 case Intrinsic::ppc_altivec_vcmpequb: 10349 CompareOpc = 6; 10350 break; 10351 case Intrinsic::ppc_altivec_vcmpequh: 10352 CompareOpc = 70; 10353 break; 10354 case Intrinsic::ppc_altivec_vcmpequw: 10355 CompareOpc = 134; 10356 break; 10357 case Intrinsic::ppc_altivec_vcmpequd: 10358 if (Subtarget.hasP8Altivec()) 10359 CompareOpc = 199; 10360 else 10361 return false; 10362 break; 10363 case Intrinsic::ppc_altivec_vcmpneb: 10364 case Intrinsic::ppc_altivec_vcmpneh: 10365 case Intrinsic::ppc_altivec_vcmpnew: 10366 case Intrinsic::ppc_altivec_vcmpnezb: 10367 case Intrinsic::ppc_altivec_vcmpnezh: 10368 case Intrinsic::ppc_altivec_vcmpnezw: 10369 if (Subtarget.hasP9Altivec()) 10370 switch (IntrinsicID) { 10371 default: 10372 llvm_unreachable("Unknown comparison intrinsic."); 10373 case Intrinsic::ppc_altivec_vcmpneb: 10374 CompareOpc = 7; 10375 break; 10376 case Intrinsic::ppc_altivec_vcmpneh: 10377 CompareOpc = 71; 10378 break; 10379 case Intrinsic::ppc_altivec_vcmpnew: 10380 CompareOpc = 135; 10381 break; 10382 case Intrinsic::ppc_altivec_vcmpnezb: 10383 CompareOpc = 263; 10384 break; 10385 case Intrinsic::ppc_altivec_vcmpnezh: 10386 CompareOpc = 327; 10387 break; 10388 case Intrinsic::ppc_altivec_vcmpnezw: 10389 CompareOpc = 391; 10390 break; 10391 } 10392 else 10393 return false; 10394 break; 10395 case Intrinsic::ppc_altivec_vcmpgefp: 10396 CompareOpc = 454; 10397 break; 10398 case Intrinsic::ppc_altivec_vcmpgtfp: 10399 CompareOpc = 710; 10400 break; 10401 case Intrinsic::ppc_altivec_vcmpgtsb: 10402 CompareOpc = 774; 10403 break; 10404 case Intrinsic::ppc_altivec_vcmpgtsh: 10405 CompareOpc = 838; 10406 break; 10407 case Intrinsic::ppc_altivec_vcmpgtsw: 10408 CompareOpc = 902; 10409 break; 10410 case Intrinsic::ppc_altivec_vcmpgtsd: 10411 if (Subtarget.hasP8Altivec()) 10412 CompareOpc = 967; 10413 else 10414 return false; 10415 break; 10416 case Intrinsic::ppc_altivec_vcmpgtub: 10417 CompareOpc = 518; 10418 break; 10419 case Intrinsic::ppc_altivec_vcmpgtuh: 10420 CompareOpc = 582; 10421 break; 10422 case Intrinsic::ppc_altivec_vcmpgtuw: 10423 CompareOpc = 646; 10424 break; 10425 case Intrinsic::ppc_altivec_vcmpgtud: 10426 if (Subtarget.hasP8Altivec()) 10427 CompareOpc = 711; 10428 else 10429 return false; 10430 break; 10431 case Intrinsic::ppc_altivec_vcmpequq_p: 10432 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10433 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10434 if (!Subtarget.isISA3_1()) 10435 return false; 10436 switch (IntrinsicID) { 10437 default: 10438 llvm_unreachable("Unknown comparison intrinsic."); 10439 case Intrinsic::ppc_altivec_vcmpequq_p: 10440 CompareOpc = 455; 10441 break; 10442 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10443 CompareOpc = 903; 10444 break; 10445 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10446 CompareOpc = 647; 10447 break; 10448 } 10449 isDot = true; 10450 break; 10451 } 10452 return true; 10453 } 10454 10455 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10456 /// lower, do it, otherwise return null. 10457 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10458 SelectionDAG &DAG) const { 10459 unsigned IntrinsicID = 10460 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10461 10462 SDLoc dl(Op); 10463 10464 switch (IntrinsicID) { 10465 case Intrinsic::thread_pointer: 10466 // Reads the thread pointer register, used for __builtin_thread_pointer. 10467 if (Subtarget.isPPC64()) 10468 return DAG.getRegister(PPC::X13, MVT::i64); 10469 return DAG.getRegister(PPC::R2, MVT::i32); 10470 10471 case Intrinsic::ppc_mma_disassemble_acc: 10472 case Intrinsic::ppc_vsx_disassemble_pair: { 10473 int NumVecs = 2; 10474 SDValue WideVec = Op.getOperand(1); 10475 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10476 NumVecs = 4; 10477 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10478 } 10479 SmallVector<SDValue, 4> RetOps; 10480 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10481 SDValue Extract = DAG.getNode( 10482 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10483 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10484 : VecNo, 10485 dl, getPointerTy(DAG.getDataLayout()))); 10486 RetOps.push_back(Extract); 10487 } 10488 return DAG.getMergeValues(RetOps, dl); 10489 } 10490 10491 case Intrinsic::ppc_unpack_longdouble: { 10492 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10493 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && 10494 "Argument of long double unpack must be 0 or 1!"); 10495 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1), 10496 DAG.getConstant(!!(Idx->getSExtValue()), dl, 10497 Idx->getValueType(0))); 10498 } 10499 10500 case Intrinsic::ppc_compare_exp_lt: 10501 case Intrinsic::ppc_compare_exp_gt: 10502 case Intrinsic::ppc_compare_exp_eq: 10503 case Intrinsic::ppc_compare_exp_uo: { 10504 unsigned Pred; 10505 switch (IntrinsicID) { 10506 case Intrinsic::ppc_compare_exp_lt: 10507 Pred = PPC::PRED_LT; 10508 break; 10509 case Intrinsic::ppc_compare_exp_gt: 10510 Pred = PPC::PRED_GT; 10511 break; 10512 case Intrinsic::ppc_compare_exp_eq: 10513 Pred = PPC::PRED_EQ; 10514 break; 10515 case Intrinsic::ppc_compare_exp_uo: 10516 Pred = PPC::PRED_UN; 10517 break; 10518 } 10519 return SDValue( 10520 DAG.getMachineNode( 10521 PPC::SELECT_CC_I4, dl, MVT::i32, 10522 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32, 10523 Op.getOperand(1), Op.getOperand(2)), 10524 0), 10525 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10526 DAG.getTargetConstant(Pred, dl, MVT::i32)}), 10527 0); 10528 } 10529 case Intrinsic::ppc_test_data_class_d: 10530 case Intrinsic::ppc_test_data_class_f: { 10531 unsigned CmprOpc = PPC::XSTSTDCDP; 10532 if (IntrinsicID == Intrinsic::ppc_test_data_class_f) 10533 CmprOpc = PPC::XSTSTDCSP; 10534 return SDValue( 10535 DAG.getMachineNode( 10536 PPC::SELECT_CC_I4, dl, MVT::i32, 10537 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2), 10538 Op.getOperand(1)), 10539 0), 10540 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10541 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}), 10542 0); 10543 } 10544 case Intrinsic::ppc_convert_f128_to_ppcf128: 10545 case Intrinsic::ppc_convert_ppcf128_to_f128: { 10546 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128 10547 ? RTLIB::CONVERT_PPCF128_F128 10548 : RTLIB::CONVERT_F128_PPCF128; 10549 MakeLibCallOptions CallOptions; 10550 std::pair<SDValue, SDValue> Result = 10551 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions, 10552 dl, SDValue()); 10553 return Result.first; 10554 } 10555 } 10556 10557 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10558 // opcode number of the comparison. 10559 int CompareOpc; 10560 bool isDot; 10561 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10562 return SDValue(); // Don't custom lower most intrinsics. 10563 10564 // If this is a non-dot comparison, make the VCMP node and we are done. 10565 if (!isDot) { 10566 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10567 Op.getOperand(1), Op.getOperand(2), 10568 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10569 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10570 } 10571 10572 // Create the PPCISD altivec 'dot' comparison node. 10573 SDValue Ops[] = { 10574 Op.getOperand(2), // LHS 10575 Op.getOperand(3), // RHS 10576 DAG.getConstant(CompareOpc, dl, MVT::i32) 10577 }; 10578 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10579 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10580 10581 // Now that we have the comparison, emit a copy from the CR to a GPR. 10582 // This is flagged to the above dot comparison. 10583 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10584 DAG.getRegister(PPC::CR6, MVT::i32), 10585 CompNode.getValue(1)); 10586 10587 // Unpack the result based on how the target uses it. 10588 unsigned BitNo; // Bit # of CR6. 10589 bool InvertBit; // Invert result? 10590 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10591 default: // Can't happen, don't crash on invalid number though. 10592 case 0: // Return the value of the EQ bit of CR6. 10593 BitNo = 0; InvertBit = false; 10594 break; 10595 case 1: // Return the inverted value of the EQ bit of CR6. 10596 BitNo = 0; InvertBit = true; 10597 break; 10598 case 2: // Return the value of the LT bit of CR6. 10599 BitNo = 2; InvertBit = false; 10600 break; 10601 case 3: // Return the inverted value of the LT bit of CR6. 10602 BitNo = 2; InvertBit = true; 10603 break; 10604 } 10605 10606 // Shift the bit into the low position. 10607 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10608 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10609 // Isolate the bit. 10610 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10611 DAG.getConstant(1, dl, MVT::i32)); 10612 10613 // If we are supposed to, toggle the bit. 10614 if (InvertBit) 10615 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10616 DAG.getConstant(1, dl, MVT::i32)); 10617 return Flags; 10618 } 10619 10620 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10621 SelectionDAG &DAG) const { 10622 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10623 // the beginning of the argument list. 10624 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10625 SDLoc DL(Op); 10626 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10627 case Intrinsic::ppc_cfence: { 10628 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10629 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10630 SDValue Val = Op.getOperand(ArgStart + 1); 10631 EVT Ty = Val.getValueType(); 10632 if (Ty == MVT::i128) { 10633 // FIXME: Testing one of two paired registers is sufficient to guarantee 10634 // ordering? 10635 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val); 10636 } 10637 return SDValue( 10638 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10639 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val), 10640 Op.getOperand(0)), 10641 0); 10642 } 10643 default: 10644 break; 10645 } 10646 return SDValue(); 10647 } 10648 10649 // Lower scalar BSWAP64 to xxbrd. 10650 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10651 SDLoc dl(Op); 10652 if (!Subtarget.isPPC64()) 10653 return Op; 10654 // MTVSRDD 10655 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10656 Op.getOperand(0)); 10657 // XXBRD 10658 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10659 // MFVSRD 10660 int VectorIndex = 0; 10661 if (Subtarget.isLittleEndian()) 10662 VectorIndex = 1; 10663 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10664 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10665 return Op; 10666 } 10667 10668 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10669 // compared to a value that is atomically loaded (atomic loads zero-extend). 10670 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10671 SelectionDAG &DAG) const { 10672 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10673 "Expecting an atomic compare-and-swap here."); 10674 SDLoc dl(Op); 10675 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10676 EVT MemVT = AtomicNode->getMemoryVT(); 10677 if (MemVT.getSizeInBits() >= 32) 10678 return Op; 10679 10680 SDValue CmpOp = Op.getOperand(2); 10681 // If this is already correctly zero-extended, leave it alone. 10682 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10683 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10684 return Op; 10685 10686 // Clear the high bits of the compare operand. 10687 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10688 SDValue NewCmpOp = 10689 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10690 DAG.getConstant(MaskVal, dl, MVT::i32)); 10691 10692 // Replace the existing compare operand with the properly zero-extended one. 10693 SmallVector<SDValue, 4> Ops; 10694 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10695 Ops.push_back(AtomicNode->getOperand(i)); 10696 Ops[2] = NewCmpOp; 10697 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10698 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10699 auto NodeTy = 10700 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10701 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10702 } 10703 10704 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op, 10705 SelectionDAG &DAG) const { 10706 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode()); 10707 EVT MemVT = N->getMemoryVT(); 10708 assert(MemVT.getSimpleVT() == MVT::i128 && 10709 "Expect quadword atomic operations"); 10710 SDLoc dl(N); 10711 unsigned Opc = N->getOpcode(); 10712 switch (Opc) { 10713 case ISD::ATOMIC_LOAD: { 10714 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be 10715 // lowered to ppc instructions by pattern matching instruction selector. 10716 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other); 10717 SmallVector<SDValue, 4> Ops{ 10718 N->getOperand(0), 10719 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)}; 10720 for (int I = 1, E = N->getNumOperands(); I < E; ++I) 10721 Ops.push_back(N->getOperand(I)); 10722 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys, 10723 Ops, MemVT, N->getMemOperand()); 10724 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal); 10725 SDValue ValHi = 10726 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1)); 10727 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi, 10728 DAG.getConstant(64, dl, MVT::i32)); 10729 SDValue Val = 10730 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi}); 10731 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other}, 10732 {Val, LoadedVal.getValue(2)}); 10733 } 10734 case ISD::ATOMIC_STORE: { 10735 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be 10736 // lowered to ppc instructions by pattern matching instruction selector. 10737 SDVTList Tys = DAG.getVTList(MVT::Other); 10738 SmallVector<SDValue, 4> Ops{ 10739 N->getOperand(0), 10740 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)}; 10741 SDValue Val = N->getOperand(2); 10742 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val); 10743 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val, 10744 DAG.getConstant(64, dl, MVT::i32)); 10745 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi); 10746 Ops.push_back(ValLo); 10747 Ops.push_back(ValHi); 10748 Ops.push_back(N->getOperand(1)); 10749 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT, 10750 N->getMemOperand()); 10751 } 10752 default: 10753 llvm_unreachable("Unexpected atomic opcode"); 10754 } 10755 } 10756 10757 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10758 SelectionDAG &DAG) const { 10759 SDLoc dl(Op); 10760 // Create a stack slot that is 16-byte aligned. 10761 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10762 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10763 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10764 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10765 10766 // Store the input value into Value#0 of the stack slot. 10767 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10768 MachinePointerInfo()); 10769 // Load it out. 10770 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10771 } 10772 10773 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10774 SelectionDAG &DAG) const { 10775 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10776 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10777 10778 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10779 10780 EVT VT = Op.getValueType(); 10781 SDLoc dl(Op); 10782 SDValue V1 = Op.getOperand(0); 10783 SDValue V2 = Op.getOperand(1); 10784 10785 if (VT == MVT::v2f64 && C) 10786 return Op; 10787 10788 if (Subtarget.hasP9Vector()) { 10789 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way 10790 // because on P10, it allows this specific insert_vector_elt load pattern to 10791 // utilize the refactored load and store infrastructure in order to exploit 10792 // prefixed loads. 10793 // On targets with inexpensive direct moves (Power9 and up), a 10794 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer 10795 // load since a single precision load will involve conversion to double 10796 // precision on the load followed by another conversion to single precision. 10797 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) && 10798 (isa<LoadSDNode>(V2))) { 10799 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1); 10800 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2); 10801 SDValue InsVecElt = 10802 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector, 10803 BitcastLoad, Op.getOperand(2)); 10804 return DAG.getBitcast(MVT::v4f32, InsVecElt); 10805 } 10806 } 10807 10808 if (Subtarget.isISA3_1()) { 10809 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 10810 return SDValue(); 10811 // On P10, we have legal lowering for constant and variable indices for 10812 // all vectors. 10813 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10814 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64) 10815 return Op; 10816 } 10817 10818 // Before P10, we have legal lowering for constant indices but not for 10819 // variable ones. 10820 if (!C) 10821 return SDValue(); 10822 10823 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10824 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10825 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10826 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10827 unsigned InsertAtElement = C->getZExtValue(); 10828 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10829 if (Subtarget.isLittleEndian()) { 10830 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10831 } 10832 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10833 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10834 } 10835 return Op; 10836 } 10837 10838 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10839 SelectionDAG &DAG) const { 10840 SDLoc dl(Op); 10841 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10842 SDValue LoadChain = LN->getChain(); 10843 SDValue BasePtr = LN->getBasePtr(); 10844 EVT VT = Op.getValueType(); 10845 10846 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10847 return Op; 10848 10849 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10850 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10851 // 2 or 4 vsx registers. 10852 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10853 "Type unsupported without MMA"); 10854 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10855 "Type unsupported without paired vector support"); 10856 Align Alignment = LN->getAlign(); 10857 SmallVector<SDValue, 4> Loads; 10858 SmallVector<SDValue, 4> LoadChains; 10859 unsigned NumVecs = VT.getSizeInBits() / 128; 10860 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10861 SDValue Load = 10862 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10863 LN->getPointerInfo().getWithOffset(Idx * 16), 10864 commonAlignment(Alignment, Idx * 16), 10865 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10866 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10867 DAG.getConstant(16, dl, BasePtr.getValueType())); 10868 Loads.push_back(Load); 10869 LoadChains.push_back(Load.getValue(1)); 10870 } 10871 if (Subtarget.isLittleEndian()) { 10872 std::reverse(Loads.begin(), Loads.end()); 10873 std::reverse(LoadChains.begin(), LoadChains.end()); 10874 } 10875 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10876 SDValue Value = 10877 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10878 dl, VT, Loads); 10879 SDValue RetOps[] = {Value, TF}; 10880 return DAG.getMergeValues(RetOps, dl); 10881 } 10882 10883 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10884 SelectionDAG &DAG) const { 10885 SDLoc dl(Op); 10886 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10887 SDValue StoreChain = SN->getChain(); 10888 SDValue BasePtr = SN->getBasePtr(); 10889 SDValue Value = SN->getValue(); 10890 EVT StoreVT = Value.getValueType(); 10891 10892 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10893 return Op; 10894 10895 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10896 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10897 // underlying registers individually. 10898 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10899 "Type unsupported without MMA"); 10900 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10901 "Type unsupported without paired vector support"); 10902 Align Alignment = SN->getAlign(); 10903 SmallVector<SDValue, 4> Stores; 10904 unsigned NumVecs = 2; 10905 if (StoreVT == MVT::v512i1) { 10906 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10907 NumVecs = 4; 10908 } 10909 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10910 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10911 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10912 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10913 SDValue Store = 10914 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10915 SN->getPointerInfo().getWithOffset(Idx * 16), 10916 commonAlignment(Alignment, Idx * 16), 10917 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10918 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10919 DAG.getConstant(16, dl, BasePtr.getValueType())); 10920 Stores.push_back(Store); 10921 } 10922 SDValue TF = DAG.getTokenFactor(dl, Stores); 10923 return TF; 10924 } 10925 10926 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10927 SDLoc dl(Op); 10928 if (Op.getValueType() == MVT::v4i32) { 10929 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10930 10931 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10932 // +16 as shift amt. 10933 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10934 SDValue RHSSwap = // = vrlw RHS, 16 10935 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10936 10937 // Shrinkify inputs to v8i16. 10938 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10939 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10940 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10941 10942 // Low parts multiplied together, generating 32-bit results (we ignore the 10943 // top parts). 10944 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10945 LHS, RHS, DAG, dl, MVT::v4i32); 10946 10947 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10948 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10949 // Shift the high parts up 16 bits. 10950 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10951 Neg16, DAG, dl); 10952 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10953 } else if (Op.getValueType() == MVT::v16i8) { 10954 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10955 bool isLittleEndian = Subtarget.isLittleEndian(); 10956 10957 // Multiply the even 8-bit parts, producing 16-bit sums. 10958 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10959 LHS, RHS, DAG, dl, MVT::v8i16); 10960 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10961 10962 // Multiply the odd 8-bit parts, producing 16-bit sums. 10963 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10964 LHS, RHS, DAG, dl, MVT::v8i16); 10965 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10966 10967 // Merge the results together. Because vmuleub and vmuloub are 10968 // instructions with a big-endian bias, we must reverse the 10969 // element numbering and reverse the meaning of "odd" and "even" 10970 // when generating little endian code. 10971 int Ops[16]; 10972 for (unsigned i = 0; i != 8; ++i) { 10973 if (isLittleEndian) { 10974 Ops[i*2 ] = 2*i; 10975 Ops[i*2+1] = 2*i+16; 10976 } else { 10977 Ops[i*2 ] = 2*i+1; 10978 Ops[i*2+1] = 2*i+1+16; 10979 } 10980 } 10981 if (isLittleEndian) 10982 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10983 else 10984 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10985 } else { 10986 llvm_unreachable("Unknown mul to lower!"); 10987 } 10988 } 10989 10990 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10991 bool IsStrict = Op->isStrictFPOpcode(); 10992 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10993 !Subtarget.hasP9Vector()) 10994 return SDValue(); 10995 10996 return Op; 10997 } 10998 10999 // Custom lowering for fpext vf32 to v2f64 11000 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11001 11002 assert(Op.getOpcode() == ISD::FP_EXTEND && 11003 "Should only be called for ISD::FP_EXTEND"); 11004 11005 // FIXME: handle extends from half precision float vectors on P9. 11006 // We only want to custom lower an extend from v2f32 to v2f64. 11007 if (Op.getValueType() != MVT::v2f64 || 11008 Op.getOperand(0).getValueType() != MVT::v2f32) 11009 return SDValue(); 11010 11011 SDLoc dl(Op); 11012 SDValue Op0 = Op.getOperand(0); 11013 11014 switch (Op0.getOpcode()) { 11015 default: 11016 return SDValue(); 11017 case ISD::EXTRACT_SUBVECTOR: { 11018 assert(Op0.getNumOperands() == 2 && 11019 isa<ConstantSDNode>(Op0->getOperand(1)) && 11020 "Node should have 2 operands with second one being a constant!"); 11021 11022 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 11023 return SDValue(); 11024 11025 // Custom lower is only done for high or low doubleword. 11026 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 11027 if (Idx % 2 != 0) 11028 return SDValue(); 11029 11030 // Since input is v4f32, at this point Idx is either 0 or 2. 11031 // Shift to get the doubleword position we want. 11032 int DWord = Idx >> 1; 11033 11034 // High and low word positions are different on little endian. 11035 if (Subtarget.isLittleEndian()) 11036 DWord ^= 0x1; 11037 11038 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 11039 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 11040 } 11041 case ISD::FADD: 11042 case ISD::FMUL: 11043 case ISD::FSUB: { 11044 SDValue NewLoad[2]; 11045 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11046 // Ensure both input are loads. 11047 SDValue LdOp = Op0.getOperand(i); 11048 if (LdOp.getOpcode() != ISD::LOAD) 11049 return SDValue(); 11050 // Generate new load node. 11051 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11052 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11053 NewLoad[i] = DAG.getMemIntrinsicNode( 11054 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11055 LD->getMemoryVT(), LD->getMemOperand()); 11056 } 11057 SDValue NewOp = 11058 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11059 NewLoad[1], Op0.getNode()->getFlags()); 11060 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11061 DAG.getConstant(0, dl, MVT::i32)); 11062 } 11063 case ISD::LOAD: { 11064 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11065 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11066 SDValue NewLd = DAG.getMemIntrinsicNode( 11067 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11068 LD->getMemoryVT(), LD->getMemOperand()); 11069 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11070 DAG.getConstant(0, dl, MVT::i32)); 11071 } 11072 } 11073 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11074 } 11075 11076 /// LowerOperation - Provide custom lowering hooks for some operations. 11077 /// 11078 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11079 switch (Op.getOpcode()) { 11080 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11081 case ISD::FPOW: return lowerPow(Op, DAG); 11082 case ISD::FSIN: return lowerSin(Op, DAG); 11083 case ISD::FCOS: return lowerCos(Op, DAG); 11084 case ISD::FLOG: return lowerLog(Op, DAG); 11085 case ISD::FLOG10: return lowerLog10(Op, DAG); 11086 case ISD::FEXP: return lowerExp(Op, DAG); 11087 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11088 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11089 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11090 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11091 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11092 case ISD::STRICT_FSETCC: 11093 case ISD::STRICT_FSETCCS: 11094 case ISD::SETCC: return LowerSETCC(Op, DAG); 11095 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11096 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11097 11098 case ISD::INLINEASM: 11099 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 11100 // Variable argument lowering. 11101 case ISD::VASTART: return LowerVASTART(Op, DAG); 11102 case ISD::VAARG: return LowerVAARG(Op, DAG); 11103 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11104 11105 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11106 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11107 case ISD::GET_DYNAMIC_AREA_OFFSET: 11108 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11109 11110 // Exception handling lowering. 11111 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11112 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11113 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11114 11115 case ISD::LOAD: return LowerLOAD(Op, DAG); 11116 case ISD::STORE: return LowerSTORE(Op, DAG); 11117 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11118 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11119 case ISD::STRICT_FP_TO_UINT: 11120 case ISD::STRICT_FP_TO_SINT: 11121 case ISD::FP_TO_UINT: 11122 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11123 case ISD::STRICT_UINT_TO_FP: 11124 case ISD::STRICT_SINT_TO_FP: 11125 case ISD::UINT_TO_FP: 11126 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11127 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11128 11129 // Lower 64-bit shifts. 11130 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11131 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11132 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11133 11134 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11135 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11136 11137 // Vector-related lowering. 11138 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11139 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11140 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11141 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11142 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11143 case ISD::MUL: return LowerMUL(Op, DAG); 11144 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11145 case ISD::STRICT_FP_ROUND: 11146 case ISD::FP_ROUND: 11147 return LowerFP_ROUND(Op, DAG); 11148 case ISD::ROTL: return LowerROTL(Op, DAG); 11149 11150 // For counter-based loop handling. 11151 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11152 11153 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11154 11155 // Frame & Return address. 11156 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11157 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11158 11159 case ISD::INTRINSIC_VOID: 11160 return LowerINTRINSIC_VOID(Op, DAG); 11161 case ISD::BSWAP: 11162 return LowerBSWAP(Op, DAG); 11163 case ISD::ATOMIC_CMP_SWAP: 11164 return LowerATOMIC_CMP_SWAP(Op, DAG); 11165 case ISD::ATOMIC_STORE: 11166 return LowerATOMIC_LOAD_STORE(Op, DAG); 11167 } 11168 } 11169 11170 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11171 SmallVectorImpl<SDValue>&Results, 11172 SelectionDAG &DAG) const { 11173 SDLoc dl(N); 11174 switch (N->getOpcode()) { 11175 default: 11176 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11177 case ISD::ATOMIC_LOAD: { 11178 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG); 11179 Results.push_back(Res); 11180 Results.push_back(Res.getValue(1)); 11181 break; 11182 } 11183 case ISD::READCYCLECOUNTER: { 11184 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11185 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11186 11187 Results.push_back( 11188 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11189 Results.push_back(RTB.getValue(2)); 11190 break; 11191 } 11192 case ISD::INTRINSIC_W_CHAIN: { 11193 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11194 Intrinsic::loop_decrement) 11195 break; 11196 11197 assert(N->getValueType(0) == MVT::i1 && 11198 "Unexpected result type for CTR decrement intrinsic"); 11199 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11200 N->getValueType(0)); 11201 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11202 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11203 N->getOperand(1)); 11204 11205 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11206 Results.push_back(NewInt.getValue(1)); 11207 break; 11208 } 11209 case ISD::INTRINSIC_WO_CHAIN: { 11210 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) { 11211 case Intrinsic::ppc_pack_longdouble: 11212 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 11213 N->getOperand(2), N->getOperand(1))); 11214 break; 11215 case Intrinsic::ppc_convert_f128_to_ppcf128: 11216 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG)); 11217 break; 11218 } 11219 break; 11220 } 11221 case ISD::VAARG: { 11222 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11223 return; 11224 11225 EVT VT = N->getValueType(0); 11226 11227 if (VT == MVT::i64) { 11228 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11229 11230 Results.push_back(NewNode); 11231 Results.push_back(NewNode.getValue(1)); 11232 } 11233 return; 11234 } 11235 case ISD::STRICT_FP_TO_SINT: 11236 case ISD::STRICT_FP_TO_UINT: 11237 case ISD::FP_TO_SINT: 11238 case ISD::FP_TO_UINT: { 11239 // LowerFP_TO_INT() can only handle f32 and f64. 11240 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11241 MVT::ppcf128) 11242 return; 11243 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl); 11244 Results.push_back(LoweredValue); 11245 if (N->isStrictFPOpcode()) 11246 Results.push_back(LoweredValue.getValue(1)); 11247 return; 11248 } 11249 case ISD::TRUNCATE: { 11250 if (!N->getValueType(0).isVector()) 11251 return; 11252 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11253 if (Lowered) 11254 Results.push_back(Lowered); 11255 return; 11256 } 11257 case ISD::FSHL: 11258 case ISD::FSHR: 11259 // Don't handle funnel shifts here. 11260 return; 11261 case ISD::BITCAST: 11262 // Don't handle bitcast here. 11263 return; 11264 case ISD::FP_EXTEND: 11265 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11266 if (Lowered) 11267 Results.push_back(Lowered); 11268 return; 11269 } 11270 } 11271 11272 //===----------------------------------------------------------------------===// 11273 // Other Lowering Code 11274 //===----------------------------------------------------------------------===// 11275 11276 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 11277 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11278 Function *Func = Intrinsic::getDeclaration(M, Id); 11279 return Builder.CreateCall(Func, {}); 11280 } 11281 11282 // The mappings for emitLeading/TrailingFence is taken from 11283 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11284 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11285 Instruction *Inst, 11286 AtomicOrdering Ord) const { 11287 if (Ord == AtomicOrdering::SequentiallyConsistent) 11288 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11289 if (isReleaseOrStronger(Ord)) 11290 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11291 return nullptr; 11292 } 11293 11294 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11295 Instruction *Inst, 11296 AtomicOrdering Ord) const { 11297 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11298 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11299 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11300 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11301 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11302 return Builder.CreateCall( 11303 Intrinsic::getDeclaration( 11304 Builder.GetInsertBlock()->getParent()->getParent(), 11305 Intrinsic::ppc_cfence, {Inst->getType()}), 11306 {Inst}); 11307 // FIXME: Can use isync for rmw operation. 11308 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11309 } 11310 return nullptr; 11311 } 11312 11313 MachineBasicBlock * 11314 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11315 unsigned AtomicSize, 11316 unsigned BinOpcode, 11317 unsigned CmpOpcode, 11318 unsigned CmpPred) const { 11319 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11320 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11321 11322 auto LoadMnemonic = PPC::LDARX; 11323 auto StoreMnemonic = PPC::STDCX; 11324 switch (AtomicSize) { 11325 default: 11326 llvm_unreachable("Unexpected size of atomic entity"); 11327 case 1: 11328 LoadMnemonic = PPC::LBARX; 11329 StoreMnemonic = PPC::STBCX; 11330 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11331 break; 11332 case 2: 11333 LoadMnemonic = PPC::LHARX; 11334 StoreMnemonic = PPC::STHCX; 11335 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11336 break; 11337 case 4: 11338 LoadMnemonic = PPC::LWARX; 11339 StoreMnemonic = PPC::STWCX; 11340 break; 11341 case 8: 11342 LoadMnemonic = PPC::LDARX; 11343 StoreMnemonic = PPC::STDCX; 11344 break; 11345 } 11346 11347 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11348 MachineFunction *F = BB->getParent(); 11349 MachineFunction::iterator It = ++BB->getIterator(); 11350 11351 Register dest = MI.getOperand(0).getReg(); 11352 Register ptrA = MI.getOperand(1).getReg(); 11353 Register ptrB = MI.getOperand(2).getReg(); 11354 Register incr = MI.getOperand(3).getReg(); 11355 DebugLoc dl = MI.getDebugLoc(); 11356 11357 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11358 MachineBasicBlock *loop2MBB = 11359 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11360 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11361 F->insert(It, loopMBB); 11362 if (CmpOpcode) 11363 F->insert(It, loop2MBB); 11364 F->insert(It, exitMBB); 11365 exitMBB->splice(exitMBB->begin(), BB, 11366 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11367 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11368 11369 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11370 Register TmpReg = (!BinOpcode) ? incr : 11371 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11372 : &PPC::GPRCRegClass); 11373 11374 // thisMBB: 11375 // ... 11376 // fallthrough --> loopMBB 11377 BB->addSuccessor(loopMBB); 11378 11379 // loopMBB: 11380 // l[wd]arx dest, ptr 11381 // add r0, dest, incr 11382 // st[wd]cx. r0, ptr 11383 // bne- loopMBB 11384 // fallthrough --> exitMBB 11385 11386 // For max/min... 11387 // loopMBB: 11388 // l[wd]arx dest, ptr 11389 // cmpl?[wd] incr, dest 11390 // bgt exitMBB 11391 // loop2MBB: 11392 // st[wd]cx. dest, ptr 11393 // bne- loopMBB 11394 // fallthrough --> exitMBB 11395 11396 BB = loopMBB; 11397 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11398 .addReg(ptrA).addReg(ptrB); 11399 if (BinOpcode) 11400 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11401 if (CmpOpcode) { 11402 // Signed comparisons of byte or halfword values must be sign-extended. 11403 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11404 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11405 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11406 ExtReg).addReg(dest); 11407 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11408 .addReg(incr).addReg(ExtReg); 11409 } else 11410 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11411 .addReg(incr).addReg(dest); 11412 11413 BuildMI(BB, dl, TII->get(PPC::BCC)) 11414 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11415 BB->addSuccessor(loop2MBB); 11416 BB->addSuccessor(exitMBB); 11417 BB = loop2MBB; 11418 } 11419 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11420 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11421 BuildMI(BB, dl, TII->get(PPC::BCC)) 11422 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11423 BB->addSuccessor(loopMBB); 11424 BB->addSuccessor(exitMBB); 11425 11426 // exitMBB: 11427 // ... 11428 BB = exitMBB; 11429 return BB; 11430 } 11431 11432 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11433 switch(MI.getOpcode()) { 11434 default: 11435 return false; 11436 case PPC::COPY: 11437 return TII->isSignExtended(MI); 11438 case PPC::LHA: 11439 case PPC::LHA8: 11440 case PPC::LHAU: 11441 case PPC::LHAU8: 11442 case PPC::LHAUX: 11443 case PPC::LHAUX8: 11444 case PPC::LHAX: 11445 case PPC::LHAX8: 11446 case PPC::LWA: 11447 case PPC::LWAUX: 11448 case PPC::LWAX: 11449 case PPC::LWAX_32: 11450 case PPC::LWA_32: 11451 case PPC::PLHA: 11452 case PPC::PLHA8: 11453 case PPC::PLHA8pc: 11454 case PPC::PLHApc: 11455 case PPC::PLWA: 11456 case PPC::PLWA8: 11457 case PPC::PLWA8pc: 11458 case PPC::PLWApc: 11459 case PPC::EXTSB: 11460 case PPC::EXTSB8: 11461 case PPC::EXTSB8_32_64: 11462 case PPC::EXTSB8_rec: 11463 case PPC::EXTSB_rec: 11464 case PPC::EXTSH: 11465 case PPC::EXTSH8: 11466 case PPC::EXTSH8_32_64: 11467 case PPC::EXTSH8_rec: 11468 case PPC::EXTSH_rec: 11469 case PPC::EXTSW: 11470 case PPC::EXTSWSLI: 11471 case PPC::EXTSWSLI_32_64: 11472 case PPC::EXTSWSLI_32_64_rec: 11473 case PPC::EXTSWSLI_rec: 11474 case PPC::EXTSW_32: 11475 case PPC::EXTSW_32_64: 11476 case PPC::EXTSW_32_64_rec: 11477 case PPC::EXTSW_rec: 11478 case PPC::SRAW: 11479 case PPC::SRAWI: 11480 case PPC::SRAWI_rec: 11481 case PPC::SRAW_rec: 11482 return true; 11483 } 11484 return false; 11485 } 11486 11487 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11488 MachineInstr &MI, MachineBasicBlock *BB, 11489 bool is8bit, // operation 11490 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11491 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11492 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11493 11494 // If this is a signed comparison and the value being compared is not known 11495 // to be sign extended, sign extend it here. 11496 DebugLoc dl = MI.getDebugLoc(); 11497 MachineFunction *F = BB->getParent(); 11498 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11499 Register incr = MI.getOperand(3).getReg(); 11500 bool IsSignExtended = Register::isVirtualRegister(incr) && 11501 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11502 11503 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11504 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11505 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11506 .addReg(MI.getOperand(3).getReg()); 11507 MI.getOperand(3).setReg(ValueReg); 11508 } 11509 // If we support part-word atomic mnemonics, just use them 11510 if (Subtarget.hasPartwordAtomics()) 11511 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11512 CmpPred); 11513 11514 // In 64 bit mode we have to use 64 bits for addresses, even though the 11515 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11516 // registers without caring whether they're 32 or 64, but here we're 11517 // doing actual arithmetic on the addresses. 11518 bool is64bit = Subtarget.isPPC64(); 11519 bool isLittleEndian = Subtarget.isLittleEndian(); 11520 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11521 11522 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11523 MachineFunction::iterator It = ++BB->getIterator(); 11524 11525 Register dest = MI.getOperand(0).getReg(); 11526 Register ptrA = MI.getOperand(1).getReg(); 11527 Register ptrB = MI.getOperand(2).getReg(); 11528 11529 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11530 MachineBasicBlock *loop2MBB = 11531 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11532 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11533 F->insert(It, loopMBB); 11534 if (CmpOpcode) 11535 F->insert(It, loop2MBB); 11536 F->insert(It, exitMBB); 11537 exitMBB->splice(exitMBB->begin(), BB, 11538 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11539 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11540 11541 const TargetRegisterClass *RC = 11542 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11543 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11544 11545 Register PtrReg = RegInfo.createVirtualRegister(RC); 11546 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11547 Register ShiftReg = 11548 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11549 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11550 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11551 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11552 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11553 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11554 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11555 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11556 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11557 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11558 Register Ptr1Reg; 11559 Register TmpReg = 11560 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11561 11562 // thisMBB: 11563 // ... 11564 // fallthrough --> loopMBB 11565 BB->addSuccessor(loopMBB); 11566 11567 // The 4-byte load must be aligned, while a char or short may be 11568 // anywhere in the word. Hence all this nasty bookkeeping code. 11569 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11570 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11571 // xori shift, shift1, 24 [16] 11572 // rlwinm ptr, ptr1, 0, 0, 29 11573 // slw incr2, incr, shift 11574 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11575 // slw mask, mask2, shift 11576 // loopMBB: 11577 // lwarx tmpDest, ptr 11578 // add tmp, tmpDest, incr2 11579 // andc tmp2, tmpDest, mask 11580 // and tmp3, tmp, mask 11581 // or tmp4, tmp3, tmp2 11582 // stwcx. tmp4, ptr 11583 // bne- loopMBB 11584 // fallthrough --> exitMBB 11585 // srw SrwDest, tmpDest, shift 11586 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11587 if (ptrA != ZeroReg) { 11588 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11589 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11590 .addReg(ptrA) 11591 .addReg(ptrB); 11592 } else { 11593 Ptr1Reg = ptrB; 11594 } 11595 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11596 // mode. 11597 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11598 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11599 .addImm(3) 11600 .addImm(27) 11601 .addImm(is8bit ? 28 : 27); 11602 if (!isLittleEndian) 11603 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11604 .addReg(Shift1Reg) 11605 .addImm(is8bit ? 24 : 16); 11606 if (is64bit) 11607 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11608 .addReg(Ptr1Reg) 11609 .addImm(0) 11610 .addImm(61); 11611 else 11612 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11613 .addReg(Ptr1Reg) 11614 .addImm(0) 11615 .addImm(0) 11616 .addImm(29); 11617 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11618 if (is8bit) 11619 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11620 else { 11621 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11622 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11623 .addReg(Mask3Reg) 11624 .addImm(65535); 11625 } 11626 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11627 .addReg(Mask2Reg) 11628 .addReg(ShiftReg); 11629 11630 BB = loopMBB; 11631 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11632 .addReg(ZeroReg) 11633 .addReg(PtrReg); 11634 if (BinOpcode) 11635 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11636 .addReg(Incr2Reg) 11637 .addReg(TmpDestReg); 11638 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11639 .addReg(TmpDestReg) 11640 .addReg(MaskReg); 11641 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11642 if (CmpOpcode) { 11643 // For unsigned comparisons, we can directly compare the shifted values. 11644 // For signed comparisons we shift and sign extend. 11645 Register SReg = RegInfo.createVirtualRegister(GPRC); 11646 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11647 .addReg(TmpDestReg) 11648 .addReg(MaskReg); 11649 unsigned ValueReg = SReg; 11650 unsigned CmpReg = Incr2Reg; 11651 if (CmpOpcode == PPC::CMPW) { 11652 ValueReg = RegInfo.createVirtualRegister(GPRC); 11653 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11654 .addReg(SReg) 11655 .addReg(ShiftReg); 11656 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11657 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11658 .addReg(ValueReg); 11659 ValueReg = ValueSReg; 11660 CmpReg = incr; 11661 } 11662 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11663 .addReg(CmpReg) 11664 .addReg(ValueReg); 11665 BuildMI(BB, dl, TII->get(PPC::BCC)) 11666 .addImm(CmpPred) 11667 .addReg(PPC::CR0) 11668 .addMBB(exitMBB); 11669 BB->addSuccessor(loop2MBB); 11670 BB->addSuccessor(exitMBB); 11671 BB = loop2MBB; 11672 } 11673 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11674 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11675 .addReg(Tmp4Reg) 11676 .addReg(ZeroReg) 11677 .addReg(PtrReg); 11678 BuildMI(BB, dl, TII->get(PPC::BCC)) 11679 .addImm(PPC::PRED_NE) 11680 .addReg(PPC::CR0) 11681 .addMBB(loopMBB); 11682 BB->addSuccessor(loopMBB); 11683 BB->addSuccessor(exitMBB); 11684 11685 // exitMBB: 11686 // ... 11687 BB = exitMBB; 11688 // Since the shift amount is not a constant, we need to clear 11689 // the upper bits with a separate RLWINM. 11690 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11691 .addReg(SrwDestReg) 11692 .addImm(0) 11693 .addImm(is8bit ? 24 : 16) 11694 .addImm(31); 11695 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11696 .addReg(TmpDestReg) 11697 .addReg(ShiftReg); 11698 return BB; 11699 } 11700 11701 llvm::MachineBasicBlock * 11702 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11703 MachineBasicBlock *MBB) const { 11704 DebugLoc DL = MI.getDebugLoc(); 11705 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11706 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11707 11708 MachineFunction *MF = MBB->getParent(); 11709 MachineRegisterInfo &MRI = MF->getRegInfo(); 11710 11711 const BasicBlock *BB = MBB->getBasicBlock(); 11712 MachineFunction::iterator I = ++MBB->getIterator(); 11713 11714 Register DstReg = MI.getOperand(0).getReg(); 11715 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11716 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11717 Register mainDstReg = MRI.createVirtualRegister(RC); 11718 Register restoreDstReg = MRI.createVirtualRegister(RC); 11719 11720 MVT PVT = getPointerTy(MF->getDataLayout()); 11721 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11722 "Invalid Pointer Size!"); 11723 // For v = setjmp(buf), we generate 11724 // 11725 // thisMBB: 11726 // SjLjSetup mainMBB 11727 // bl mainMBB 11728 // v_restore = 1 11729 // b sinkMBB 11730 // 11731 // mainMBB: 11732 // buf[LabelOffset] = LR 11733 // v_main = 0 11734 // 11735 // sinkMBB: 11736 // v = phi(main, restore) 11737 // 11738 11739 MachineBasicBlock *thisMBB = MBB; 11740 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11741 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11742 MF->insert(I, mainMBB); 11743 MF->insert(I, sinkMBB); 11744 11745 MachineInstrBuilder MIB; 11746 11747 // Transfer the remainder of BB and its successor edges to sinkMBB. 11748 sinkMBB->splice(sinkMBB->begin(), MBB, 11749 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11750 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11751 11752 // Note that the structure of the jmp_buf used here is not compatible 11753 // with that used by libc, and is not designed to be. Specifically, it 11754 // stores only those 'reserved' registers that LLVM does not otherwise 11755 // understand how to spill. Also, by convention, by the time this 11756 // intrinsic is called, Clang has already stored the frame address in the 11757 // first slot of the buffer and stack address in the third. Following the 11758 // X86 target code, we'll store the jump address in the second slot. We also 11759 // need to save the TOC pointer (R2) to handle jumps between shared 11760 // libraries, and that will be stored in the fourth slot. The thread 11761 // identifier (R13) is not affected. 11762 11763 // thisMBB: 11764 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11765 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11766 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11767 11768 // Prepare IP either in reg. 11769 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11770 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11771 Register BufReg = MI.getOperand(1).getReg(); 11772 11773 if (Subtarget.is64BitELFABI()) { 11774 setUsesTOCBasePtr(*MBB->getParent()); 11775 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11776 .addReg(PPC::X2) 11777 .addImm(TOCOffset) 11778 .addReg(BufReg) 11779 .cloneMemRefs(MI); 11780 } 11781 11782 // Naked functions never have a base pointer, and so we use r1. For all 11783 // other functions, this decision must be delayed until during PEI. 11784 unsigned BaseReg; 11785 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11786 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11787 else 11788 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11789 11790 MIB = BuildMI(*thisMBB, MI, DL, 11791 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11792 .addReg(BaseReg) 11793 .addImm(BPOffset) 11794 .addReg(BufReg) 11795 .cloneMemRefs(MI); 11796 11797 // Setup 11798 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11799 MIB.addRegMask(TRI->getNoPreservedMask()); 11800 11801 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11802 11803 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11804 .addMBB(mainMBB); 11805 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11806 11807 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11808 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11809 11810 // mainMBB: 11811 // mainDstReg = 0 11812 MIB = 11813 BuildMI(mainMBB, DL, 11814 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11815 11816 // Store IP 11817 if (Subtarget.isPPC64()) { 11818 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11819 .addReg(LabelReg) 11820 .addImm(LabelOffset) 11821 .addReg(BufReg); 11822 } else { 11823 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11824 .addReg(LabelReg) 11825 .addImm(LabelOffset) 11826 .addReg(BufReg); 11827 } 11828 MIB.cloneMemRefs(MI); 11829 11830 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11831 mainMBB->addSuccessor(sinkMBB); 11832 11833 // sinkMBB: 11834 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11835 TII->get(PPC::PHI), DstReg) 11836 .addReg(mainDstReg).addMBB(mainMBB) 11837 .addReg(restoreDstReg).addMBB(thisMBB); 11838 11839 MI.eraseFromParent(); 11840 return sinkMBB; 11841 } 11842 11843 MachineBasicBlock * 11844 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11845 MachineBasicBlock *MBB) const { 11846 DebugLoc DL = MI.getDebugLoc(); 11847 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11848 11849 MachineFunction *MF = MBB->getParent(); 11850 MachineRegisterInfo &MRI = MF->getRegInfo(); 11851 11852 MVT PVT = getPointerTy(MF->getDataLayout()); 11853 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11854 "Invalid Pointer Size!"); 11855 11856 const TargetRegisterClass *RC = 11857 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11858 Register Tmp = MRI.createVirtualRegister(RC); 11859 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11860 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11861 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11862 unsigned BP = 11863 (PVT == MVT::i64) 11864 ? PPC::X30 11865 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11866 : PPC::R30); 11867 11868 MachineInstrBuilder MIB; 11869 11870 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11871 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11872 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11873 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11874 11875 Register BufReg = MI.getOperand(0).getReg(); 11876 11877 // Reload FP (the jumped-to function may not have had a 11878 // frame pointer, and if so, then its r31 will be restored 11879 // as necessary). 11880 if (PVT == MVT::i64) { 11881 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11882 .addImm(0) 11883 .addReg(BufReg); 11884 } else { 11885 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11886 .addImm(0) 11887 .addReg(BufReg); 11888 } 11889 MIB.cloneMemRefs(MI); 11890 11891 // Reload IP 11892 if (PVT == MVT::i64) { 11893 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11894 .addImm(LabelOffset) 11895 .addReg(BufReg); 11896 } else { 11897 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11898 .addImm(LabelOffset) 11899 .addReg(BufReg); 11900 } 11901 MIB.cloneMemRefs(MI); 11902 11903 // Reload SP 11904 if (PVT == MVT::i64) { 11905 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11906 .addImm(SPOffset) 11907 .addReg(BufReg); 11908 } else { 11909 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11910 .addImm(SPOffset) 11911 .addReg(BufReg); 11912 } 11913 MIB.cloneMemRefs(MI); 11914 11915 // Reload BP 11916 if (PVT == MVT::i64) { 11917 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11918 .addImm(BPOffset) 11919 .addReg(BufReg); 11920 } else { 11921 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11922 .addImm(BPOffset) 11923 .addReg(BufReg); 11924 } 11925 MIB.cloneMemRefs(MI); 11926 11927 // Reload TOC 11928 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11929 setUsesTOCBasePtr(*MBB->getParent()); 11930 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11931 .addImm(TOCOffset) 11932 .addReg(BufReg) 11933 .cloneMemRefs(MI); 11934 } 11935 11936 // Jump 11937 BuildMI(*MBB, MI, DL, 11938 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11939 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11940 11941 MI.eraseFromParent(); 11942 return MBB; 11943 } 11944 11945 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11946 // If the function specifically requests inline stack probes, emit them. 11947 if (MF.getFunction().hasFnAttribute("probe-stack")) 11948 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11949 "inline-asm"; 11950 return false; 11951 } 11952 11953 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11954 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11955 unsigned StackAlign = TFI->getStackAlignment(); 11956 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11957 "Unexpected stack alignment"); 11958 // The default stack probe size is 4096 if the function has no 11959 // stack-probe-size attribute. 11960 unsigned StackProbeSize = 4096; 11961 const Function &Fn = MF.getFunction(); 11962 if (Fn.hasFnAttribute("stack-probe-size")) 11963 Fn.getFnAttribute("stack-probe-size") 11964 .getValueAsString() 11965 .getAsInteger(0, StackProbeSize); 11966 // Round down to the stack alignment. 11967 StackProbeSize &= ~(StackAlign - 1); 11968 return StackProbeSize ? StackProbeSize : StackAlign; 11969 } 11970 11971 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11972 // into three phases. In the first phase, it uses pseudo instruction 11973 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11974 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11975 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11976 // MaxCallFrameSize so that it can calculate correct data area pointer. 11977 MachineBasicBlock * 11978 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11979 MachineBasicBlock *MBB) const { 11980 const bool isPPC64 = Subtarget.isPPC64(); 11981 MachineFunction *MF = MBB->getParent(); 11982 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11983 DebugLoc DL = MI.getDebugLoc(); 11984 const unsigned ProbeSize = getStackProbeSize(*MF); 11985 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11986 MachineRegisterInfo &MRI = MF->getRegInfo(); 11987 // The CFG of probing stack looks as 11988 // +-----+ 11989 // | MBB | 11990 // +--+--+ 11991 // | 11992 // +----v----+ 11993 // +--->+ TestMBB +---+ 11994 // | +----+----+ | 11995 // | | | 11996 // | +-----v----+ | 11997 // +---+ BlockMBB | | 11998 // +----------+ | 11999 // | 12000 // +---------+ | 12001 // | TailMBB +<--+ 12002 // +---------+ 12003 // In MBB, calculate previous frame pointer and final stack pointer. 12004 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 12005 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 12006 // TailMBB is spliced via \p MI. 12007 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 12008 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 12009 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 12010 12011 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 12012 MF->insert(MBBIter, TestMBB); 12013 MF->insert(MBBIter, BlockMBB); 12014 MF->insert(MBBIter, TailMBB); 12015 12016 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 12017 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12018 12019 Register DstReg = MI.getOperand(0).getReg(); 12020 Register NegSizeReg = MI.getOperand(1).getReg(); 12021 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 12022 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12023 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12024 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12025 12026 // Since value of NegSizeReg might be realigned in prologepilog, insert a 12027 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 12028 // NegSize. 12029 unsigned ProbeOpc; 12030 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 12031 ProbeOpc = 12032 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 12033 else 12034 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 12035 // and NegSizeReg will be allocated in the same phyreg to avoid 12036 // redundant copy when NegSizeReg has only one use which is current MI and 12037 // will be replaced by PREPARE_PROBED_ALLOCA then. 12038 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 12039 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 12040 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 12041 .addDef(ActualNegSizeReg) 12042 .addReg(NegSizeReg) 12043 .add(MI.getOperand(2)) 12044 .add(MI.getOperand(3)); 12045 12046 // Calculate final stack pointer, which equals to SP + ActualNegSize. 12047 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 12048 FinalStackPtr) 12049 .addReg(SPReg) 12050 .addReg(ActualNegSizeReg); 12051 12052 // Materialize a scratch register for update. 12053 int64_t NegProbeSize = -(int64_t)ProbeSize; 12054 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 12055 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12056 if (!isInt<16>(NegProbeSize)) { 12057 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12058 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 12059 .addImm(NegProbeSize >> 16); 12060 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 12061 ScratchReg) 12062 .addReg(TempReg) 12063 .addImm(NegProbeSize & 0xFFFF); 12064 } else 12065 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 12066 .addImm(NegProbeSize); 12067 12068 { 12069 // Probing leading residual part. 12070 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12071 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 12072 .addReg(ActualNegSizeReg) 12073 .addReg(ScratchReg); 12074 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12075 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 12076 .addReg(Div) 12077 .addReg(ScratchReg); 12078 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12079 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 12080 .addReg(Mul) 12081 .addReg(ActualNegSizeReg); 12082 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12083 .addReg(FramePointer) 12084 .addReg(SPReg) 12085 .addReg(NegMod); 12086 } 12087 12088 { 12089 // Remaining part should be multiple of ProbeSize. 12090 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 12091 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 12092 .addReg(SPReg) 12093 .addReg(FinalStackPtr); 12094 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 12095 .addImm(PPC::PRED_EQ) 12096 .addReg(CmpResult) 12097 .addMBB(TailMBB); 12098 TestMBB->addSuccessor(BlockMBB); 12099 TestMBB->addSuccessor(TailMBB); 12100 } 12101 12102 { 12103 // Touch the block. 12104 // |P...|P...|P... 12105 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12106 .addReg(FramePointer) 12107 .addReg(SPReg) 12108 .addReg(ScratchReg); 12109 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 12110 BlockMBB->addSuccessor(TestMBB); 12111 } 12112 12113 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 12114 // DYNAREAOFFSET pseudo instruction to get the future result. 12115 Register MaxCallFrameSizeReg = 12116 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12117 BuildMI(TailMBB, DL, 12118 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 12119 MaxCallFrameSizeReg) 12120 .add(MI.getOperand(2)) 12121 .add(MI.getOperand(3)); 12122 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 12123 .addReg(SPReg) 12124 .addReg(MaxCallFrameSizeReg); 12125 12126 // Splice instructions after MI to TailMBB. 12127 TailMBB->splice(TailMBB->end(), MBB, 12128 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12129 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 12130 MBB->addSuccessor(TestMBB); 12131 12132 // Delete the pseudo instruction. 12133 MI.eraseFromParent(); 12134 12135 ++NumDynamicAllocaProbed; 12136 return TailMBB; 12137 } 12138 12139 MachineBasicBlock * 12140 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12141 MachineBasicBlock *BB) const { 12142 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12143 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12144 if (Subtarget.is64BitELFABI() && 12145 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12146 !Subtarget.isUsingPCRelativeCalls()) { 12147 // Call lowering should have added an r2 operand to indicate a dependence 12148 // on the TOC base pointer value. It can't however, because there is no 12149 // way to mark the dependence as implicit there, and so the stackmap code 12150 // will confuse it with a regular operand. Instead, add the dependence 12151 // here. 12152 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12153 } 12154 12155 return emitPatchPoint(MI, BB); 12156 } 12157 12158 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12159 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12160 return emitEHSjLjSetJmp(MI, BB); 12161 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12162 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12163 return emitEHSjLjLongJmp(MI, BB); 12164 } 12165 12166 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12167 12168 // To "insert" these instructions we actually have to insert their 12169 // control-flow patterns. 12170 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12171 MachineFunction::iterator It = ++BB->getIterator(); 12172 12173 MachineFunction *F = BB->getParent(); 12174 MachineRegisterInfo &MRI = F->getRegInfo(); 12175 12176 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12177 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12178 MI.getOpcode() == PPC::SELECT_I8) { 12179 SmallVector<MachineOperand, 2> Cond; 12180 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12181 MI.getOpcode() == PPC::SELECT_CC_I8) 12182 Cond.push_back(MI.getOperand(4)); 12183 else 12184 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12185 Cond.push_back(MI.getOperand(1)); 12186 12187 DebugLoc dl = MI.getDebugLoc(); 12188 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12189 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12190 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12191 MI.getOpcode() == PPC::SELECT_CC_F8 || 12192 MI.getOpcode() == PPC::SELECT_CC_F16 || 12193 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12194 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12195 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12196 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12197 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12198 MI.getOpcode() == PPC::SELECT_CC_SPE || 12199 MI.getOpcode() == PPC::SELECT_F4 || 12200 MI.getOpcode() == PPC::SELECT_F8 || 12201 MI.getOpcode() == PPC::SELECT_F16 || 12202 MI.getOpcode() == PPC::SELECT_SPE || 12203 MI.getOpcode() == PPC::SELECT_SPE4 || 12204 MI.getOpcode() == PPC::SELECT_VRRC || 12205 MI.getOpcode() == PPC::SELECT_VSFRC || 12206 MI.getOpcode() == PPC::SELECT_VSSRC || 12207 MI.getOpcode() == PPC::SELECT_VSRC) { 12208 // The incoming instruction knows the destination vreg to set, the 12209 // condition code register to branch on, the true/false values to 12210 // select between, and a branch opcode to use. 12211 12212 // thisMBB: 12213 // ... 12214 // TrueVal = ... 12215 // cmpTY ccX, r1, r2 12216 // bCC copy1MBB 12217 // fallthrough --> copy0MBB 12218 MachineBasicBlock *thisMBB = BB; 12219 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12220 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12221 DebugLoc dl = MI.getDebugLoc(); 12222 F->insert(It, copy0MBB); 12223 F->insert(It, sinkMBB); 12224 12225 // Transfer the remainder of BB and its successor edges to sinkMBB. 12226 sinkMBB->splice(sinkMBB->begin(), BB, 12227 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12228 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12229 12230 // Next, add the true and fallthrough blocks as its successors. 12231 BB->addSuccessor(copy0MBB); 12232 BB->addSuccessor(sinkMBB); 12233 12234 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12235 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12236 MI.getOpcode() == PPC::SELECT_F16 || 12237 MI.getOpcode() == PPC::SELECT_SPE4 || 12238 MI.getOpcode() == PPC::SELECT_SPE || 12239 MI.getOpcode() == PPC::SELECT_VRRC || 12240 MI.getOpcode() == PPC::SELECT_VSFRC || 12241 MI.getOpcode() == PPC::SELECT_VSSRC || 12242 MI.getOpcode() == PPC::SELECT_VSRC) { 12243 BuildMI(BB, dl, TII->get(PPC::BC)) 12244 .addReg(MI.getOperand(1).getReg()) 12245 .addMBB(sinkMBB); 12246 } else { 12247 unsigned SelectPred = MI.getOperand(4).getImm(); 12248 BuildMI(BB, dl, TII->get(PPC::BCC)) 12249 .addImm(SelectPred) 12250 .addReg(MI.getOperand(1).getReg()) 12251 .addMBB(sinkMBB); 12252 } 12253 12254 // copy0MBB: 12255 // %FalseValue = ... 12256 // # fallthrough to sinkMBB 12257 BB = copy0MBB; 12258 12259 // Update machine-CFG edges 12260 BB->addSuccessor(sinkMBB); 12261 12262 // sinkMBB: 12263 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12264 // ... 12265 BB = sinkMBB; 12266 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12267 .addReg(MI.getOperand(3).getReg()) 12268 .addMBB(copy0MBB) 12269 .addReg(MI.getOperand(2).getReg()) 12270 .addMBB(thisMBB); 12271 } else if (MI.getOpcode() == PPC::ReadTB) { 12272 // To read the 64-bit time-base register on a 32-bit target, we read the 12273 // two halves. Should the counter have wrapped while it was being read, we 12274 // need to try again. 12275 // ... 12276 // readLoop: 12277 // mfspr Rx,TBU # load from TBU 12278 // mfspr Ry,TB # load from TB 12279 // mfspr Rz,TBU # load from TBU 12280 // cmpw crX,Rx,Rz # check if 'old'='new' 12281 // bne readLoop # branch if they're not equal 12282 // ... 12283 12284 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12285 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12286 DebugLoc dl = MI.getDebugLoc(); 12287 F->insert(It, readMBB); 12288 F->insert(It, sinkMBB); 12289 12290 // Transfer the remainder of BB and its successor edges to sinkMBB. 12291 sinkMBB->splice(sinkMBB->begin(), BB, 12292 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12293 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12294 12295 BB->addSuccessor(readMBB); 12296 BB = readMBB; 12297 12298 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12299 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12300 Register LoReg = MI.getOperand(0).getReg(); 12301 Register HiReg = MI.getOperand(1).getReg(); 12302 12303 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12304 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12305 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12306 12307 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12308 12309 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12310 .addReg(HiReg) 12311 .addReg(ReadAgainReg); 12312 BuildMI(BB, dl, TII->get(PPC::BCC)) 12313 .addImm(PPC::PRED_NE) 12314 .addReg(CmpReg) 12315 .addMBB(readMBB); 12316 12317 BB->addSuccessor(readMBB); 12318 BB->addSuccessor(sinkMBB); 12319 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12320 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12321 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12322 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12323 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12324 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12325 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12326 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12327 12328 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12329 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12330 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12331 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12332 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12333 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12334 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12335 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12336 12337 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12338 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12339 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12340 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12341 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12342 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12343 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12344 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12345 12346 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12347 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12348 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12349 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12350 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12351 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12352 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12353 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12354 12355 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12356 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12357 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12358 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12359 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12360 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12361 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12362 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12363 12364 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12365 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12366 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12367 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12368 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12369 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12370 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12371 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12372 12373 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12374 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12375 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12376 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12377 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12378 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12379 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12380 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12381 12382 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12383 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12384 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12385 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12386 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12387 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12388 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12389 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12390 12391 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12392 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12393 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12394 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12395 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12396 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12397 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12398 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12399 12400 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12401 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12402 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12403 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12404 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12405 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12406 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12407 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12408 12409 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12410 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12411 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12412 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12413 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12414 BB = EmitAtomicBinary(MI, BB, 4, 0); 12415 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12416 BB = EmitAtomicBinary(MI, BB, 8, 0); 12417 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12418 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12419 (Subtarget.hasPartwordAtomics() && 12420 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12421 (Subtarget.hasPartwordAtomics() && 12422 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12423 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12424 12425 auto LoadMnemonic = PPC::LDARX; 12426 auto StoreMnemonic = PPC::STDCX; 12427 switch (MI.getOpcode()) { 12428 default: 12429 llvm_unreachable("Compare and swap of unknown size"); 12430 case PPC::ATOMIC_CMP_SWAP_I8: 12431 LoadMnemonic = PPC::LBARX; 12432 StoreMnemonic = PPC::STBCX; 12433 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12434 break; 12435 case PPC::ATOMIC_CMP_SWAP_I16: 12436 LoadMnemonic = PPC::LHARX; 12437 StoreMnemonic = PPC::STHCX; 12438 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12439 break; 12440 case PPC::ATOMIC_CMP_SWAP_I32: 12441 LoadMnemonic = PPC::LWARX; 12442 StoreMnemonic = PPC::STWCX; 12443 break; 12444 case PPC::ATOMIC_CMP_SWAP_I64: 12445 LoadMnemonic = PPC::LDARX; 12446 StoreMnemonic = PPC::STDCX; 12447 break; 12448 } 12449 Register dest = MI.getOperand(0).getReg(); 12450 Register ptrA = MI.getOperand(1).getReg(); 12451 Register ptrB = MI.getOperand(2).getReg(); 12452 Register oldval = MI.getOperand(3).getReg(); 12453 Register newval = MI.getOperand(4).getReg(); 12454 DebugLoc dl = MI.getDebugLoc(); 12455 12456 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12457 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12458 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12459 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12460 F->insert(It, loop1MBB); 12461 F->insert(It, loop2MBB); 12462 F->insert(It, midMBB); 12463 F->insert(It, exitMBB); 12464 exitMBB->splice(exitMBB->begin(), BB, 12465 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12466 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12467 12468 // thisMBB: 12469 // ... 12470 // fallthrough --> loopMBB 12471 BB->addSuccessor(loop1MBB); 12472 12473 // loop1MBB: 12474 // l[bhwd]arx dest, ptr 12475 // cmp[wd] dest, oldval 12476 // bne- midMBB 12477 // loop2MBB: 12478 // st[bhwd]cx. newval, ptr 12479 // bne- loopMBB 12480 // b exitBB 12481 // midMBB: 12482 // st[bhwd]cx. dest, ptr 12483 // exitBB: 12484 BB = loop1MBB; 12485 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12486 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12487 .addReg(oldval) 12488 .addReg(dest); 12489 BuildMI(BB, dl, TII->get(PPC::BCC)) 12490 .addImm(PPC::PRED_NE) 12491 .addReg(PPC::CR0) 12492 .addMBB(midMBB); 12493 BB->addSuccessor(loop2MBB); 12494 BB->addSuccessor(midMBB); 12495 12496 BB = loop2MBB; 12497 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12498 .addReg(newval) 12499 .addReg(ptrA) 12500 .addReg(ptrB); 12501 BuildMI(BB, dl, TII->get(PPC::BCC)) 12502 .addImm(PPC::PRED_NE) 12503 .addReg(PPC::CR0) 12504 .addMBB(loop1MBB); 12505 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12506 BB->addSuccessor(loop1MBB); 12507 BB->addSuccessor(exitMBB); 12508 12509 BB = midMBB; 12510 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12511 .addReg(dest) 12512 .addReg(ptrA) 12513 .addReg(ptrB); 12514 BB->addSuccessor(exitMBB); 12515 12516 // exitMBB: 12517 // ... 12518 BB = exitMBB; 12519 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12520 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12521 // We must use 64-bit registers for addresses when targeting 64-bit, 12522 // since we're actually doing arithmetic on them. Other registers 12523 // can be 32-bit. 12524 bool is64bit = Subtarget.isPPC64(); 12525 bool isLittleEndian = Subtarget.isLittleEndian(); 12526 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12527 12528 Register dest = MI.getOperand(0).getReg(); 12529 Register ptrA = MI.getOperand(1).getReg(); 12530 Register ptrB = MI.getOperand(2).getReg(); 12531 Register oldval = MI.getOperand(3).getReg(); 12532 Register newval = MI.getOperand(4).getReg(); 12533 DebugLoc dl = MI.getDebugLoc(); 12534 12535 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12536 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12537 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12538 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12539 F->insert(It, loop1MBB); 12540 F->insert(It, loop2MBB); 12541 F->insert(It, midMBB); 12542 F->insert(It, exitMBB); 12543 exitMBB->splice(exitMBB->begin(), BB, 12544 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12545 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12546 12547 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12548 const TargetRegisterClass *RC = 12549 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12550 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12551 12552 Register PtrReg = RegInfo.createVirtualRegister(RC); 12553 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12554 Register ShiftReg = 12555 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12556 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12557 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12558 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12559 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12560 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12561 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12562 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12563 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12564 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12565 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12566 Register Ptr1Reg; 12567 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12568 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12569 // thisMBB: 12570 // ... 12571 // fallthrough --> loopMBB 12572 BB->addSuccessor(loop1MBB); 12573 12574 // The 4-byte load must be aligned, while a char or short may be 12575 // anywhere in the word. Hence all this nasty bookkeeping code. 12576 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12577 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12578 // xori shift, shift1, 24 [16] 12579 // rlwinm ptr, ptr1, 0, 0, 29 12580 // slw newval2, newval, shift 12581 // slw oldval2, oldval,shift 12582 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12583 // slw mask, mask2, shift 12584 // and newval3, newval2, mask 12585 // and oldval3, oldval2, mask 12586 // loop1MBB: 12587 // lwarx tmpDest, ptr 12588 // and tmp, tmpDest, mask 12589 // cmpw tmp, oldval3 12590 // bne- midMBB 12591 // loop2MBB: 12592 // andc tmp2, tmpDest, mask 12593 // or tmp4, tmp2, newval3 12594 // stwcx. tmp4, ptr 12595 // bne- loop1MBB 12596 // b exitBB 12597 // midMBB: 12598 // stwcx. tmpDest, ptr 12599 // exitBB: 12600 // srw dest, tmpDest, shift 12601 if (ptrA != ZeroReg) { 12602 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12603 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12604 .addReg(ptrA) 12605 .addReg(ptrB); 12606 } else { 12607 Ptr1Reg = ptrB; 12608 } 12609 12610 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12611 // mode. 12612 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12613 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12614 .addImm(3) 12615 .addImm(27) 12616 .addImm(is8bit ? 28 : 27); 12617 if (!isLittleEndian) 12618 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12619 .addReg(Shift1Reg) 12620 .addImm(is8bit ? 24 : 16); 12621 if (is64bit) 12622 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12623 .addReg(Ptr1Reg) 12624 .addImm(0) 12625 .addImm(61); 12626 else 12627 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12628 .addReg(Ptr1Reg) 12629 .addImm(0) 12630 .addImm(0) 12631 .addImm(29); 12632 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12633 .addReg(newval) 12634 .addReg(ShiftReg); 12635 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12636 .addReg(oldval) 12637 .addReg(ShiftReg); 12638 if (is8bit) 12639 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12640 else { 12641 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12642 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12643 .addReg(Mask3Reg) 12644 .addImm(65535); 12645 } 12646 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12647 .addReg(Mask2Reg) 12648 .addReg(ShiftReg); 12649 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12650 .addReg(NewVal2Reg) 12651 .addReg(MaskReg); 12652 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12653 .addReg(OldVal2Reg) 12654 .addReg(MaskReg); 12655 12656 BB = loop1MBB; 12657 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12658 .addReg(ZeroReg) 12659 .addReg(PtrReg); 12660 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12661 .addReg(TmpDestReg) 12662 .addReg(MaskReg); 12663 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12664 .addReg(TmpReg) 12665 .addReg(OldVal3Reg); 12666 BuildMI(BB, dl, TII->get(PPC::BCC)) 12667 .addImm(PPC::PRED_NE) 12668 .addReg(PPC::CR0) 12669 .addMBB(midMBB); 12670 BB->addSuccessor(loop2MBB); 12671 BB->addSuccessor(midMBB); 12672 12673 BB = loop2MBB; 12674 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12675 .addReg(TmpDestReg) 12676 .addReg(MaskReg); 12677 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12678 .addReg(Tmp2Reg) 12679 .addReg(NewVal3Reg); 12680 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12681 .addReg(Tmp4Reg) 12682 .addReg(ZeroReg) 12683 .addReg(PtrReg); 12684 BuildMI(BB, dl, TII->get(PPC::BCC)) 12685 .addImm(PPC::PRED_NE) 12686 .addReg(PPC::CR0) 12687 .addMBB(loop1MBB); 12688 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12689 BB->addSuccessor(loop1MBB); 12690 BB->addSuccessor(exitMBB); 12691 12692 BB = midMBB; 12693 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12694 .addReg(TmpDestReg) 12695 .addReg(ZeroReg) 12696 .addReg(PtrReg); 12697 BB->addSuccessor(exitMBB); 12698 12699 // exitMBB: 12700 // ... 12701 BB = exitMBB; 12702 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12703 .addReg(TmpReg) 12704 .addReg(ShiftReg); 12705 } else if (MI.getOpcode() == PPC::FADDrtz) { 12706 // This pseudo performs an FADD with rounding mode temporarily forced 12707 // to round-to-zero. We emit this via custom inserter since the FPSCR 12708 // is not modeled at the SelectionDAG level. 12709 Register Dest = MI.getOperand(0).getReg(); 12710 Register Src1 = MI.getOperand(1).getReg(); 12711 Register Src2 = MI.getOperand(2).getReg(); 12712 DebugLoc dl = MI.getDebugLoc(); 12713 12714 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12715 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12716 12717 // Save FPSCR value. 12718 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12719 12720 // Set rounding mode to round-to-zero. 12721 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12722 .addImm(31) 12723 .addReg(PPC::RM, RegState::ImplicitDefine); 12724 12725 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12726 .addImm(30) 12727 .addReg(PPC::RM, RegState::ImplicitDefine); 12728 12729 // Perform addition. 12730 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12731 .addReg(Src1) 12732 .addReg(Src2); 12733 if (MI.getFlag(MachineInstr::NoFPExcept)) 12734 MIB.setMIFlag(MachineInstr::NoFPExcept); 12735 12736 // Restore FPSCR value. 12737 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12738 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12739 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12740 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12741 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12742 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12743 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12744 ? PPC::ANDI8_rec 12745 : PPC::ANDI_rec; 12746 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12747 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12748 12749 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12750 Register Dest = RegInfo.createVirtualRegister( 12751 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12752 12753 DebugLoc Dl = MI.getDebugLoc(); 12754 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12755 .addReg(MI.getOperand(1).getReg()) 12756 .addImm(1); 12757 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12758 MI.getOperand(0).getReg()) 12759 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12760 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12761 DebugLoc Dl = MI.getDebugLoc(); 12762 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12763 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12764 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12765 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12766 MI.getOperand(0).getReg()) 12767 .addReg(CRReg); 12768 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12769 DebugLoc Dl = MI.getDebugLoc(); 12770 unsigned Imm = MI.getOperand(1).getImm(); 12771 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12772 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12773 MI.getOperand(0).getReg()) 12774 .addReg(PPC::CR0EQ); 12775 } else if (MI.getOpcode() == PPC::SETRNDi) { 12776 DebugLoc dl = MI.getDebugLoc(); 12777 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12778 12779 // Save FPSCR value. 12780 if (MRI.use_empty(OldFPSCRReg)) 12781 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12782 else 12783 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12784 12785 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12786 // the following settings: 12787 // 00 Round to nearest 12788 // 01 Round to 0 12789 // 10 Round to +inf 12790 // 11 Round to -inf 12791 12792 // When the operand is immediate, using the two least significant bits of 12793 // the immediate to set the bits 62:63 of FPSCR. 12794 unsigned Mode = MI.getOperand(1).getImm(); 12795 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12796 .addImm(31) 12797 .addReg(PPC::RM, RegState::ImplicitDefine); 12798 12799 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12800 .addImm(30) 12801 .addReg(PPC::RM, RegState::ImplicitDefine); 12802 } else if (MI.getOpcode() == PPC::SETRND) { 12803 DebugLoc dl = MI.getDebugLoc(); 12804 12805 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12806 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12807 // If the target doesn't have DirectMove, we should use stack to do the 12808 // conversion, because the target doesn't have the instructions like mtvsrd 12809 // or mfvsrd to do this conversion directly. 12810 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12811 if (Subtarget.hasDirectMove()) { 12812 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12813 .addReg(SrcReg); 12814 } else { 12815 // Use stack to do the register copy. 12816 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12817 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12818 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12819 if (RC == &PPC::F8RCRegClass) { 12820 // Copy register from F8RCRegClass to G8RCRegclass. 12821 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12822 "Unsupported RegClass."); 12823 12824 StoreOp = PPC::STFD; 12825 LoadOp = PPC::LD; 12826 } else { 12827 // Copy register from G8RCRegClass to F8RCRegclass. 12828 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12829 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12830 "Unsupported RegClass."); 12831 } 12832 12833 MachineFrameInfo &MFI = F->getFrameInfo(); 12834 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12835 12836 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12837 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12838 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12839 MFI.getObjectAlign(FrameIdx)); 12840 12841 // Store the SrcReg into the stack. 12842 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12843 .addReg(SrcReg) 12844 .addImm(0) 12845 .addFrameIndex(FrameIdx) 12846 .addMemOperand(MMOStore); 12847 12848 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12849 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12850 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12851 MFI.getObjectAlign(FrameIdx)); 12852 12853 // Load from the stack where SrcReg is stored, and save to DestReg, 12854 // so we have done the RegClass conversion from RegClass::SrcReg to 12855 // RegClass::DestReg. 12856 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12857 .addImm(0) 12858 .addFrameIndex(FrameIdx) 12859 .addMemOperand(MMOLoad); 12860 } 12861 }; 12862 12863 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12864 12865 // Save FPSCR value. 12866 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12867 12868 // When the operand is gprc register, use two least significant bits of the 12869 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12870 // 12871 // copy OldFPSCRTmpReg, OldFPSCRReg 12872 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12873 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12874 // copy NewFPSCRReg, NewFPSCRTmpReg 12875 // mtfsf 255, NewFPSCRReg 12876 MachineOperand SrcOp = MI.getOperand(1); 12877 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12878 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12879 12880 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12881 12882 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12883 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12884 12885 // The first operand of INSERT_SUBREG should be a register which has 12886 // subregisters, we only care about its RegClass, so we should use an 12887 // IMPLICIT_DEF register. 12888 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12889 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12890 .addReg(ImDefReg) 12891 .add(SrcOp) 12892 .addImm(1); 12893 12894 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12895 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12896 .addReg(OldFPSCRTmpReg) 12897 .addReg(ExtSrcReg) 12898 .addImm(0) 12899 .addImm(62); 12900 12901 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12902 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12903 12904 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12905 // bits of FPSCR. 12906 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12907 .addImm(255) 12908 .addReg(NewFPSCRReg) 12909 .addImm(0) 12910 .addImm(0); 12911 } else if (MI.getOpcode() == PPC::SETFLM) { 12912 DebugLoc Dl = MI.getDebugLoc(); 12913 12914 // Result of setflm is previous FPSCR content, so we need to save it first. 12915 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12916 if (MRI.use_empty(OldFPSCRReg)) 12917 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12918 else 12919 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12920 12921 // Put bits in 32:63 to FPSCR. 12922 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12923 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12924 .addImm(255) 12925 .addReg(NewFPSCRReg) 12926 .addImm(0) 12927 .addImm(0); 12928 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12929 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12930 return emitProbedAlloca(MI, BB); 12931 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) { 12932 DebugLoc DL = MI.getDebugLoc(); 12933 Register Src = MI.getOperand(2).getReg(); 12934 Register Lo = MI.getOperand(0).getReg(); 12935 Register Hi = MI.getOperand(1).getReg(); 12936 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12937 .addDef(Lo) 12938 .addUse(Src, 0, PPC::sub_gp8_x1); 12939 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12940 .addDef(Hi) 12941 .addUse(Src, 0, PPC::sub_gp8_x0); 12942 } else if (MI.getOpcode() == PPC::LQX_PSEUDO || 12943 MI.getOpcode() == PPC::STQX_PSEUDO) { 12944 DebugLoc DL = MI.getDebugLoc(); 12945 // Ptr is used as the ptr_rc_no_r0 part 12946 // of LQ/STQ's memory operand and adding result of RA and RB, 12947 // so it has to be g8rc_and_g8rc_nox0. 12948 Register Ptr = 12949 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 12950 Register Val = MI.getOperand(0).getReg(); 12951 Register RA = MI.getOperand(1).getReg(); 12952 Register RB = MI.getOperand(2).getReg(); 12953 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB); 12954 BuildMI(*BB, MI, DL, 12955 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ) 12956 : TII->get(PPC::STQ)) 12957 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0) 12958 .addImm(0) 12959 .addReg(Ptr); 12960 } else { 12961 llvm_unreachable("Unexpected instr type to insert"); 12962 } 12963 12964 MI.eraseFromParent(); // The pseudo instruction is gone now. 12965 return BB; 12966 } 12967 12968 //===----------------------------------------------------------------------===// 12969 // Target Optimization Hooks 12970 //===----------------------------------------------------------------------===// 12971 12972 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12973 // For the estimates, convergence is quadratic, so we essentially double the 12974 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12975 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12976 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12977 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12978 if (VT.getScalarType() == MVT::f64) 12979 RefinementSteps++; 12980 return RefinementSteps; 12981 } 12982 12983 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12984 const DenormalMode &Mode) const { 12985 // We only have VSX Vector Test for software Square Root. 12986 EVT VT = Op.getValueType(); 12987 if (!isTypeLegal(MVT::i1) || 12988 (VT != MVT::f64 && 12989 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12990 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12991 12992 SDLoc DL(Op); 12993 // The output register of FTSQRT is CR field. 12994 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12995 // ftsqrt BF,FRB 12996 // Let e_b be the unbiased exponent of the double-precision 12997 // floating-point operand in register FRB. 12998 // fe_flag is set to 1 if either of the following conditions occurs. 12999 // - The double-precision floating-point operand in register FRB is a zero, 13000 // a NaN, or an infinity, or a negative value. 13001 // - e_b is less than or equal to -970. 13002 // Otherwise fe_flag is set to 0. 13003 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 13004 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 13005 // exponent is less than -970) 13006 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 13007 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 13008 FTSQRT, SRIdxVal), 13009 0); 13010 } 13011 13012 SDValue 13013 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 13014 SelectionDAG &DAG) const { 13015 // We only have VSX Vector Square Root. 13016 EVT VT = Op.getValueType(); 13017 if (VT != MVT::f64 && 13018 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 13019 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 13020 13021 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 13022 } 13023 13024 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 13025 int Enabled, int &RefinementSteps, 13026 bool &UseOneConstNR, 13027 bool Reciprocal) const { 13028 EVT VT = Operand.getValueType(); 13029 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 13030 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 13031 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13032 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13033 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13034 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13035 13036 // The Newton-Raphson computation with a single constant does not provide 13037 // enough accuracy on some CPUs. 13038 UseOneConstNR = !Subtarget.needsTwoConstNR(); 13039 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 13040 } 13041 return SDValue(); 13042 } 13043 13044 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 13045 int Enabled, 13046 int &RefinementSteps) const { 13047 EVT VT = Operand.getValueType(); 13048 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 13049 (VT == MVT::f64 && Subtarget.hasFRE()) || 13050 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13051 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13052 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13053 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13054 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 13055 } 13056 return SDValue(); 13057 } 13058 13059 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 13060 // Note: This functionality is used only when unsafe-fp-math is enabled, and 13061 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 13062 // enabled for division), this functionality is redundant with the default 13063 // combiner logic (once the division -> reciprocal/multiply transformation 13064 // has taken place). As a result, this matters more for older cores than for 13065 // newer ones. 13066 13067 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13068 // reciprocal if there are two or more FDIVs (for embedded cores with only 13069 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 13070 switch (Subtarget.getCPUDirective()) { 13071 default: 13072 return 3; 13073 case PPC::DIR_440: 13074 case PPC::DIR_A2: 13075 case PPC::DIR_E500: 13076 case PPC::DIR_E500mc: 13077 case PPC::DIR_E5500: 13078 return 2; 13079 } 13080 } 13081 13082 // isConsecutiveLSLoc needs to work even if all adds have not yet been 13083 // collapsed, and so we need to look through chains of them. 13084 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 13085 int64_t& Offset, SelectionDAG &DAG) { 13086 if (DAG.isBaseWithConstantOffset(Loc)) { 13087 Base = Loc.getOperand(0); 13088 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 13089 13090 // The base might itself be a base plus an offset, and if so, accumulate 13091 // that as well. 13092 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 13093 } 13094 } 13095 13096 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 13097 unsigned Bytes, int Dist, 13098 SelectionDAG &DAG) { 13099 if (VT.getSizeInBits() / 8 != Bytes) 13100 return false; 13101 13102 SDValue BaseLoc = Base->getBasePtr(); 13103 if (Loc.getOpcode() == ISD::FrameIndex) { 13104 if (BaseLoc.getOpcode() != ISD::FrameIndex) 13105 return false; 13106 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 13107 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 13108 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 13109 int FS = MFI.getObjectSize(FI); 13110 int BFS = MFI.getObjectSize(BFI); 13111 if (FS != BFS || FS != (int)Bytes) return false; 13112 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 13113 } 13114 13115 SDValue Base1 = Loc, Base2 = BaseLoc; 13116 int64_t Offset1 = 0, Offset2 = 0; 13117 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 13118 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 13119 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 13120 return true; 13121 13122 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13123 const GlobalValue *GV1 = nullptr; 13124 const GlobalValue *GV2 = nullptr; 13125 Offset1 = 0; 13126 Offset2 = 0; 13127 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 13128 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 13129 if (isGA1 && isGA2 && GV1 == GV2) 13130 return Offset1 == (Offset2 + Dist*Bytes); 13131 return false; 13132 } 13133 13134 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 13135 // not enforce equality of the chain operands. 13136 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 13137 unsigned Bytes, int Dist, 13138 SelectionDAG &DAG) { 13139 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 13140 EVT VT = LS->getMemoryVT(); 13141 SDValue Loc = LS->getBasePtr(); 13142 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 13143 } 13144 13145 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 13146 EVT VT; 13147 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13148 default: return false; 13149 case Intrinsic::ppc_altivec_lvx: 13150 case Intrinsic::ppc_altivec_lvxl: 13151 case Intrinsic::ppc_vsx_lxvw4x: 13152 case Intrinsic::ppc_vsx_lxvw4x_be: 13153 VT = MVT::v4i32; 13154 break; 13155 case Intrinsic::ppc_vsx_lxvd2x: 13156 case Intrinsic::ppc_vsx_lxvd2x_be: 13157 VT = MVT::v2f64; 13158 break; 13159 case Intrinsic::ppc_altivec_lvebx: 13160 VT = MVT::i8; 13161 break; 13162 case Intrinsic::ppc_altivec_lvehx: 13163 VT = MVT::i16; 13164 break; 13165 case Intrinsic::ppc_altivec_lvewx: 13166 VT = MVT::i32; 13167 break; 13168 } 13169 13170 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 13171 } 13172 13173 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 13174 EVT VT; 13175 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13176 default: return false; 13177 case Intrinsic::ppc_altivec_stvx: 13178 case Intrinsic::ppc_altivec_stvxl: 13179 case Intrinsic::ppc_vsx_stxvw4x: 13180 VT = MVT::v4i32; 13181 break; 13182 case Intrinsic::ppc_vsx_stxvd2x: 13183 VT = MVT::v2f64; 13184 break; 13185 case Intrinsic::ppc_vsx_stxvw4x_be: 13186 VT = MVT::v4i32; 13187 break; 13188 case Intrinsic::ppc_vsx_stxvd2x_be: 13189 VT = MVT::v2f64; 13190 break; 13191 case Intrinsic::ppc_altivec_stvebx: 13192 VT = MVT::i8; 13193 break; 13194 case Intrinsic::ppc_altivec_stvehx: 13195 VT = MVT::i16; 13196 break; 13197 case Intrinsic::ppc_altivec_stvewx: 13198 VT = MVT::i32; 13199 break; 13200 } 13201 13202 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13203 } 13204 13205 return false; 13206 } 13207 13208 // Return true is there is a nearyby consecutive load to the one provided 13209 // (regardless of alignment). We search up and down the chain, looking though 13210 // token factors and other loads (but nothing else). As a result, a true result 13211 // indicates that it is safe to create a new consecutive load adjacent to the 13212 // load provided. 13213 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13214 SDValue Chain = LD->getChain(); 13215 EVT VT = LD->getMemoryVT(); 13216 13217 SmallSet<SDNode *, 16> LoadRoots; 13218 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13219 SmallSet<SDNode *, 16> Visited; 13220 13221 // First, search up the chain, branching to follow all token-factor operands. 13222 // If we find a consecutive load, then we're done, otherwise, record all 13223 // nodes just above the top-level loads and token factors. 13224 while (!Queue.empty()) { 13225 SDNode *ChainNext = Queue.pop_back_val(); 13226 if (!Visited.insert(ChainNext).second) 13227 continue; 13228 13229 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13230 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13231 return true; 13232 13233 if (!Visited.count(ChainLD->getChain().getNode())) 13234 Queue.push_back(ChainLD->getChain().getNode()); 13235 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13236 for (const SDUse &O : ChainNext->ops()) 13237 if (!Visited.count(O.getNode())) 13238 Queue.push_back(O.getNode()); 13239 } else 13240 LoadRoots.insert(ChainNext); 13241 } 13242 13243 // Second, search down the chain, starting from the top-level nodes recorded 13244 // in the first phase. These top-level nodes are the nodes just above all 13245 // loads and token factors. Starting with their uses, recursively look though 13246 // all loads (just the chain uses) and token factors to find a consecutive 13247 // load. 13248 Visited.clear(); 13249 Queue.clear(); 13250 13251 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 13252 IE = LoadRoots.end(); I != IE; ++I) { 13253 Queue.push_back(*I); 13254 13255 while (!Queue.empty()) { 13256 SDNode *LoadRoot = Queue.pop_back_val(); 13257 if (!Visited.insert(LoadRoot).second) 13258 continue; 13259 13260 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13261 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13262 return true; 13263 13264 for (SDNode *U : LoadRoot->uses()) 13265 if (((isa<MemSDNode>(U) && 13266 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) || 13267 U->getOpcode() == ISD::TokenFactor) && 13268 !Visited.count(U)) 13269 Queue.push_back(U); 13270 } 13271 } 13272 13273 return false; 13274 } 13275 13276 /// This function is called when we have proved that a SETCC node can be replaced 13277 /// by subtraction (and other supporting instructions) so that the result of 13278 /// comparison is kept in a GPR instead of CR. This function is purely for 13279 /// codegen purposes and has some flags to guide the codegen process. 13280 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13281 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13282 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13283 13284 // Zero extend the operands to the largest legal integer. Originally, they 13285 // must be of a strictly smaller size. 13286 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13287 DAG.getConstant(Size, DL, MVT::i32)); 13288 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13289 DAG.getConstant(Size, DL, MVT::i32)); 13290 13291 // Swap if needed. Depends on the condition code. 13292 if (Swap) 13293 std::swap(Op0, Op1); 13294 13295 // Subtract extended integers. 13296 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13297 13298 // Move the sign bit to the least significant position and zero out the rest. 13299 // Now the least significant bit carries the result of original comparison. 13300 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13301 DAG.getConstant(Size - 1, DL, MVT::i32)); 13302 auto Final = Shifted; 13303 13304 // Complement the result if needed. Based on the condition code. 13305 if (Complement) 13306 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13307 DAG.getConstant(1, DL, MVT::i64)); 13308 13309 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13310 } 13311 13312 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13313 DAGCombinerInfo &DCI) const { 13314 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13315 13316 SelectionDAG &DAG = DCI.DAG; 13317 SDLoc DL(N); 13318 13319 // Size of integers being compared has a critical role in the following 13320 // analysis, so we prefer to do this when all types are legal. 13321 if (!DCI.isAfterLegalizeDAG()) 13322 return SDValue(); 13323 13324 // If all users of SETCC extend its value to a legal integer type 13325 // then we replace SETCC with a subtraction 13326 for (const SDNode *U : N->uses()) 13327 if (U->getOpcode() != ISD::ZERO_EXTEND) 13328 return SDValue(); 13329 13330 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13331 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13332 13333 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13334 13335 if (OpSize < Size) { 13336 switch (CC) { 13337 default: break; 13338 case ISD::SETULT: 13339 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13340 case ISD::SETULE: 13341 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13342 case ISD::SETUGT: 13343 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13344 case ISD::SETUGE: 13345 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13346 } 13347 } 13348 13349 return SDValue(); 13350 } 13351 13352 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13353 DAGCombinerInfo &DCI) const { 13354 SelectionDAG &DAG = DCI.DAG; 13355 SDLoc dl(N); 13356 13357 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13358 // If we're tracking CR bits, we need to be careful that we don't have: 13359 // trunc(binary-ops(zext(x), zext(y))) 13360 // or 13361 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13362 // such that we're unnecessarily moving things into GPRs when it would be 13363 // better to keep them in CR bits. 13364 13365 // Note that trunc here can be an actual i1 trunc, or can be the effective 13366 // truncation that comes from a setcc or select_cc. 13367 if (N->getOpcode() == ISD::TRUNCATE && 13368 N->getValueType(0) != MVT::i1) 13369 return SDValue(); 13370 13371 if (N->getOperand(0).getValueType() != MVT::i32 && 13372 N->getOperand(0).getValueType() != MVT::i64) 13373 return SDValue(); 13374 13375 if (N->getOpcode() == ISD::SETCC || 13376 N->getOpcode() == ISD::SELECT_CC) { 13377 // If we're looking at a comparison, then we need to make sure that the 13378 // high bits (all except for the first) don't matter the result. 13379 ISD::CondCode CC = 13380 cast<CondCodeSDNode>(N->getOperand( 13381 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13382 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13383 13384 if (ISD::isSignedIntSetCC(CC)) { 13385 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13386 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13387 return SDValue(); 13388 } else if (ISD::isUnsignedIntSetCC(CC)) { 13389 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13390 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13391 !DAG.MaskedValueIsZero(N->getOperand(1), 13392 APInt::getHighBitsSet(OpBits, OpBits-1))) 13393 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13394 : SDValue()); 13395 } else { 13396 // This is neither a signed nor an unsigned comparison, just make sure 13397 // that the high bits are equal. 13398 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13399 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13400 13401 // We don't really care about what is known about the first bit (if 13402 // anything), so pretend that it is known zero for both to ensure they can 13403 // be compared as constants. 13404 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13405 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13406 13407 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13408 Op1Known.getConstant() != Op2Known.getConstant()) 13409 return SDValue(); 13410 } 13411 } 13412 13413 // We now know that the higher-order bits are irrelevant, we just need to 13414 // make sure that all of the intermediate operations are bit operations, and 13415 // all inputs are extensions. 13416 if (N->getOperand(0).getOpcode() != ISD::AND && 13417 N->getOperand(0).getOpcode() != ISD::OR && 13418 N->getOperand(0).getOpcode() != ISD::XOR && 13419 N->getOperand(0).getOpcode() != ISD::SELECT && 13420 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13421 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13422 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13423 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13424 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13425 return SDValue(); 13426 13427 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13428 N->getOperand(1).getOpcode() != ISD::AND && 13429 N->getOperand(1).getOpcode() != ISD::OR && 13430 N->getOperand(1).getOpcode() != ISD::XOR && 13431 N->getOperand(1).getOpcode() != ISD::SELECT && 13432 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13433 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13434 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13435 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13436 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13437 return SDValue(); 13438 13439 SmallVector<SDValue, 4> Inputs; 13440 SmallVector<SDValue, 8> BinOps, PromOps; 13441 SmallPtrSet<SDNode *, 16> Visited; 13442 13443 for (unsigned i = 0; i < 2; ++i) { 13444 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13445 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13446 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13447 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13448 isa<ConstantSDNode>(N->getOperand(i))) 13449 Inputs.push_back(N->getOperand(i)); 13450 else 13451 BinOps.push_back(N->getOperand(i)); 13452 13453 if (N->getOpcode() == ISD::TRUNCATE) 13454 break; 13455 } 13456 13457 // Visit all inputs, collect all binary operations (and, or, xor and 13458 // select) that are all fed by extensions. 13459 while (!BinOps.empty()) { 13460 SDValue BinOp = BinOps.pop_back_val(); 13461 13462 if (!Visited.insert(BinOp.getNode()).second) 13463 continue; 13464 13465 PromOps.push_back(BinOp); 13466 13467 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13468 // The condition of the select is not promoted. 13469 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13470 continue; 13471 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13472 continue; 13473 13474 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13475 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13476 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13477 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13478 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13479 Inputs.push_back(BinOp.getOperand(i)); 13480 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13481 BinOp.getOperand(i).getOpcode() == ISD::OR || 13482 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13483 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13484 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13485 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13486 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13487 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13488 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13489 BinOps.push_back(BinOp.getOperand(i)); 13490 } else { 13491 // We have an input that is not an extension or another binary 13492 // operation; we'll abort this transformation. 13493 return SDValue(); 13494 } 13495 } 13496 } 13497 13498 // Make sure that this is a self-contained cluster of operations (which 13499 // is not quite the same thing as saying that everything has only one 13500 // use). 13501 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13502 if (isa<ConstantSDNode>(Inputs[i])) 13503 continue; 13504 13505 for (const SDNode *User : Inputs[i].getNode()->uses()) { 13506 if (User != N && !Visited.count(User)) 13507 return SDValue(); 13508 13509 // Make sure that we're not going to promote the non-output-value 13510 // operand(s) or SELECT or SELECT_CC. 13511 // FIXME: Although we could sometimes handle this, and it does occur in 13512 // practice that one of the condition inputs to the select is also one of 13513 // the outputs, we currently can't deal with this. 13514 if (User->getOpcode() == ISD::SELECT) { 13515 if (User->getOperand(0) == Inputs[i]) 13516 return SDValue(); 13517 } else if (User->getOpcode() == ISD::SELECT_CC) { 13518 if (User->getOperand(0) == Inputs[i] || 13519 User->getOperand(1) == Inputs[i]) 13520 return SDValue(); 13521 } 13522 } 13523 } 13524 13525 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13526 for (const SDNode *User : PromOps[i].getNode()->uses()) { 13527 if (User != N && !Visited.count(User)) 13528 return SDValue(); 13529 13530 // Make sure that we're not going to promote the non-output-value 13531 // operand(s) or SELECT or SELECT_CC. 13532 // FIXME: Although we could sometimes handle this, and it does occur in 13533 // practice that one of the condition inputs to the select is also one of 13534 // the outputs, we currently can't deal with this. 13535 if (User->getOpcode() == ISD::SELECT) { 13536 if (User->getOperand(0) == PromOps[i]) 13537 return SDValue(); 13538 } else if (User->getOpcode() == ISD::SELECT_CC) { 13539 if (User->getOperand(0) == PromOps[i] || 13540 User->getOperand(1) == PromOps[i]) 13541 return SDValue(); 13542 } 13543 } 13544 } 13545 13546 // Replace all inputs with the extension operand. 13547 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13548 // Constants may have users outside the cluster of to-be-promoted nodes, 13549 // and so we need to replace those as we do the promotions. 13550 if (isa<ConstantSDNode>(Inputs[i])) 13551 continue; 13552 else 13553 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13554 } 13555 13556 std::list<HandleSDNode> PromOpHandles; 13557 for (auto &PromOp : PromOps) 13558 PromOpHandles.emplace_back(PromOp); 13559 13560 // Replace all operations (these are all the same, but have a different 13561 // (i1) return type). DAG.getNode will validate that the types of 13562 // a binary operator match, so go through the list in reverse so that 13563 // we've likely promoted both operands first. Any intermediate truncations or 13564 // extensions disappear. 13565 while (!PromOpHandles.empty()) { 13566 SDValue PromOp = PromOpHandles.back().getValue(); 13567 PromOpHandles.pop_back(); 13568 13569 if (PromOp.getOpcode() == ISD::TRUNCATE || 13570 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13571 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13572 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13573 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13574 PromOp.getOperand(0).getValueType() != MVT::i1) { 13575 // The operand is not yet ready (see comment below). 13576 PromOpHandles.emplace_front(PromOp); 13577 continue; 13578 } 13579 13580 SDValue RepValue = PromOp.getOperand(0); 13581 if (isa<ConstantSDNode>(RepValue)) 13582 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13583 13584 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13585 continue; 13586 } 13587 13588 unsigned C; 13589 switch (PromOp.getOpcode()) { 13590 default: C = 0; break; 13591 case ISD::SELECT: C = 1; break; 13592 case ISD::SELECT_CC: C = 2; break; 13593 } 13594 13595 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13596 PromOp.getOperand(C).getValueType() != MVT::i1) || 13597 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13598 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13599 // The to-be-promoted operands of this node have not yet been 13600 // promoted (this should be rare because we're going through the 13601 // list backward, but if one of the operands has several users in 13602 // this cluster of to-be-promoted nodes, it is possible). 13603 PromOpHandles.emplace_front(PromOp); 13604 continue; 13605 } 13606 13607 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13608 PromOp.getNode()->op_end()); 13609 13610 // If there are any constant inputs, make sure they're replaced now. 13611 for (unsigned i = 0; i < 2; ++i) 13612 if (isa<ConstantSDNode>(Ops[C+i])) 13613 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13614 13615 DAG.ReplaceAllUsesOfValueWith(PromOp, 13616 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13617 } 13618 13619 // Now we're left with the initial truncation itself. 13620 if (N->getOpcode() == ISD::TRUNCATE) 13621 return N->getOperand(0); 13622 13623 // Otherwise, this is a comparison. The operands to be compared have just 13624 // changed type (to i1), but everything else is the same. 13625 return SDValue(N, 0); 13626 } 13627 13628 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13629 DAGCombinerInfo &DCI) const { 13630 SelectionDAG &DAG = DCI.DAG; 13631 SDLoc dl(N); 13632 13633 // If we're tracking CR bits, we need to be careful that we don't have: 13634 // zext(binary-ops(trunc(x), trunc(y))) 13635 // or 13636 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13637 // such that we're unnecessarily moving things into CR bits that can more 13638 // efficiently stay in GPRs. Note that if we're not certain that the high 13639 // bits are set as required by the final extension, we still may need to do 13640 // some masking to get the proper behavior. 13641 13642 // This same functionality is important on PPC64 when dealing with 13643 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13644 // the return values of functions. Because it is so similar, it is handled 13645 // here as well. 13646 13647 if (N->getValueType(0) != MVT::i32 && 13648 N->getValueType(0) != MVT::i64) 13649 return SDValue(); 13650 13651 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13652 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13653 return SDValue(); 13654 13655 if (N->getOperand(0).getOpcode() != ISD::AND && 13656 N->getOperand(0).getOpcode() != ISD::OR && 13657 N->getOperand(0).getOpcode() != ISD::XOR && 13658 N->getOperand(0).getOpcode() != ISD::SELECT && 13659 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13660 return SDValue(); 13661 13662 SmallVector<SDValue, 4> Inputs; 13663 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13664 SmallPtrSet<SDNode *, 16> Visited; 13665 13666 // Visit all inputs, collect all binary operations (and, or, xor and 13667 // select) that are all fed by truncations. 13668 while (!BinOps.empty()) { 13669 SDValue BinOp = BinOps.pop_back_val(); 13670 13671 if (!Visited.insert(BinOp.getNode()).second) 13672 continue; 13673 13674 PromOps.push_back(BinOp); 13675 13676 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13677 // The condition of the select is not promoted. 13678 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13679 continue; 13680 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13681 continue; 13682 13683 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 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 BinOps.push_back(BinOp.getOperand(i)); 13692 } else { 13693 // We have an input that is not a truncation or another binary 13694 // operation; we'll abort this transformation. 13695 return SDValue(); 13696 } 13697 } 13698 } 13699 13700 // The operands of a select that must be truncated when the select is 13701 // promoted because the operand is actually part of the to-be-promoted set. 13702 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 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 (SDNode *User : Inputs[i].getNode()->uses()) { 13712 if (User != N && !Visited.count(User)) 13713 return SDValue(); 13714 13715 // If we're going to promote the non-output-value operand(s) or SELECT or 13716 // SELECT_CC, record them for truncation. 13717 if (User->getOpcode() == ISD::SELECT) { 13718 if (User->getOperand(0) == Inputs[i]) 13719 SelectTruncOp[0].insert(std::make_pair(User, 13720 User->getOperand(0).getValueType())); 13721 } else if (User->getOpcode() == ISD::SELECT_CC) { 13722 if (User->getOperand(0) == Inputs[i]) 13723 SelectTruncOp[0].insert(std::make_pair(User, 13724 User->getOperand(0).getValueType())); 13725 if (User->getOperand(1) == Inputs[i]) 13726 SelectTruncOp[1].insert(std::make_pair(User, 13727 User->getOperand(1).getValueType())); 13728 } 13729 } 13730 } 13731 13732 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13733 for (SDNode *User : PromOps[i].getNode()->uses()) { 13734 if (User != N && !Visited.count(User)) 13735 return SDValue(); 13736 13737 // If we're going to promote the non-output-value operand(s) or SELECT or 13738 // SELECT_CC, record them for truncation. 13739 if (User->getOpcode() == ISD::SELECT) { 13740 if (User->getOperand(0) == PromOps[i]) 13741 SelectTruncOp[0].insert(std::make_pair(User, 13742 User->getOperand(0).getValueType())); 13743 } else if (User->getOpcode() == ISD::SELECT_CC) { 13744 if (User->getOperand(0) == PromOps[i]) 13745 SelectTruncOp[0].insert(std::make_pair(User, 13746 User->getOperand(0).getValueType())); 13747 if (User->getOperand(1) == PromOps[i]) 13748 SelectTruncOp[1].insert(std::make_pair(User, 13749 User->getOperand(1).getValueType())); 13750 } 13751 } 13752 } 13753 13754 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13755 bool ReallyNeedsExt = false; 13756 if (N->getOpcode() != ISD::ANY_EXTEND) { 13757 // If all of the inputs are not already sign/zero extended, then 13758 // we'll still need to do that at the end. 13759 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13760 if (isa<ConstantSDNode>(Inputs[i])) 13761 continue; 13762 13763 unsigned OpBits = 13764 Inputs[i].getOperand(0).getValueSizeInBits(); 13765 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13766 13767 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13768 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13769 APInt::getHighBitsSet(OpBits, 13770 OpBits-PromBits))) || 13771 (N->getOpcode() == ISD::SIGN_EXTEND && 13772 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13773 (OpBits-(PromBits-1)))) { 13774 ReallyNeedsExt = true; 13775 break; 13776 } 13777 } 13778 } 13779 13780 // Replace all inputs, either with the truncation operand, or a 13781 // truncation or extension to the final output type. 13782 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13783 // Constant inputs need to be replaced with the to-be-promoted nodes that 13784 // use them because they might have users outside of the cluster of 13785 // promoted nodes. 13786 if (isa<ConstantSDNode>(Inputs[i])) 13787 continue; 13788 13789 SDValue InSrc = Inputs[i].getOperand(0); 13790 if (Inputs[i].getValueType() == N->getValueType(0)) 13791 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13792 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13793 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13794 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13795 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13796 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13797 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13798 else 13799 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13800 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13801 } 13802 13803 std::list<HandleSDNode> PromOpHandles; 13804 for (auto &PromOp : PromOps) 13805 PromOpHandles.emplace_back(PromOp); 13806 13807 // Replace all operations (these are all the same, but have a different 13808 // (promoted) return type). DAG.getNode will validate that the types of 13809 // a binary operator match, so go through the list in reverse so that 13810 // we've likely promoted both operands first. 13811 while (!PromOpHandles.empty()) { 13812 SDValue PromOp = PromOpHandles.back().getValue(); 13813 PromOpHandles.pop_back(); 13814 13815 unsigned C; 13816 switch (PromOp.getOpcode()) { 13817 default: C = 0; break; 13818 case ISD::SELECT: C = 1; break; 13819 case ISD::SELECT_CC: C = 2; break; 13820 } 13821 13822 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13823 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13824 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13825 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13826 // The to-be-promoted operands of this node have not yet been 13827 // promoted (this should be rare because we're going through the 13828 // list backward, but if one of the operands has several users in 13829 // this cluster of to-be-promoted nodes, it is possible). 13830 PromOpHandles.emplace_front(PromOp); 13831 continue; 13832 } 13833 13834 // For SELECT and SELECT_CC nodes, we do a similar check for any 13835 // to-be-promoted comparison inputs. 13836 if (PromOp.getOpcode() == ISD::SELECT || 13837 PromOp.getOpcode() == ISD::SELECT_CC) { 13838 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13839 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13840 (SelectTruncOp[1].count(PromOp.getNode()) && 13841 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13842 PromOpHandles.emplace_front(PromOp); 13843 continue; 13844 } 13845 } 13846 13847 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13848 PromOp.getNode()->op_end()); 13849 13850 // If this node has constant inputs, then they'll need to be promoted here. 13851 for (unsigned i = 0; i < 2; ++i) { 13852 if (!isa<ConstantSDNode>(Ops[C+i])) 13853 continue; 13854 if (Ops[C+i].getValueType() == N->getValueType(0)) 13855 continue; 13856 13857 if (N->getOpcode() == ISD::SIGN_EXTEND) 13858 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13859 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13860 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13861 else 13862 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13863 } 13864 13865 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13866 // truncate them again to the original value type. 13867 if (PromOp.getOpcode() == ISD::SELECT || 13868 PromOp.getOpcode() == ISD::SELECT_CC) { 13869 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13870 if (SI0 != SelectTruncOp[0].end()) 13871 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13872 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13873 if (SI1 != SelectTruncOp[1].end()) 13874 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13875 } 13876 13877 DAG.ReplaceAllUsesOfValueWith(PromOp, 13878 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13879 } 13880 13881 // Now we're left with the initial extension itself. 13882 if (!ReallyNeedsExt) 13883 return N->getOperand(0); 13884 13885 // To zero extend, just mask off everything except for the first bit (in the 13886 // i1 case). 13887 if (N->getOpcode() == ISD::ZERO_EXTEND) 13888 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13889 DAG.getConstant(APInt::getLowBitsSet( 13890 N->getValueSizeInBits(0), PromBits), 13891 dl, N->getValueType(0))); 13892 13893 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13894 "Invalid extension type"); 13895 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13896 SDValue ShiftCst = 13897 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13898 return DAG.getNode( 13899 ISD::SRA, dl, N->getValueType(0), 13900 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13901 ShiftCst); 13902 } 13903 13904 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13905 DAGCombinerInfo &DCI) const { 13906 assert(N->getOpcode() == ISD::SETCC && 13907 "Should be called with a SETCC node"); 13908 13909 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13910 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13911 SDValue LHS = N->getOperand(0); 13912 SDValue RHS = N->getOperand(1); 13913 13914 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13915 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13916 LHS.hasOneUse()) 13917 std::swap(LHS, RHS); 13918 13919 // x == 0-y --> x+y == 0 13920 // x != 0-y --> x+y != 0 13921 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13922 RHS.hasOneUse()) { 13923 SDLoc DL(N); 13924 SelectionDAG &DAG = DCI.DAG; 13925 EVT VT = N->getValueType(0); 13926 EVT OpVT = LHS.getValueType(); 13927 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13928 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13929 } 13930 } 13931 13932 return DAGCombineTruncBoolExt(N, DCI); 13933 } 13934 13935 // Is this an extending load from an f32 to an f64? 13936 static bool isFPExtLoad(SDValue Op) { 13937 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13938 return LD->getExtensionType() == ISD::EXTLOAD && 13939 Op.getValueType() == MVT::f64; 13940 return false; 13941 } 13942 13943 /// Reduces the number of fp-to-int conversion when building a vector. 13944 /// 13945 /// If this vector is built out of floating to integer conversions, 13946 /// transform it to a vector built out of floating point values followed by a 13947 /// single floating to integer conversion of the vector. 13948 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13949 /// becomes (fptosi (build_vector ($A, $B, ...))) 13950 SDValue PPCTargetLowering:: 13951 combineElementTruncationToVectorTruncation(SDNode *N, 13952 DAGCombinerInfo &DCI) const { 13953 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13954 "Should be called with a BUILD_VECTOR node"); 13955 13956 SelectionDAG &DAG = DCI.DAG; 13957 SDLoc dl(N); 13958 13959 SDValue FirstInput = N->getOperand(0); 13960 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13961 "The input operand must be an fp-to-int conversion."); 13962 13963 // This combine happens after legalization so the fp_to_[su]i nodes are 13964 // already converted to PPCSISD nodes. 13965 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13966 if (FirstConversion == PPCISD::FCTIDZ || 13967 FirstConversion == PPCISD::FCTIDUZ || 13968 FirstConversion == PPCISD::FCTIWZ || 13969 FirstConversion == PPCISD::FCTIWUZ) { 13970 bool IsSplat = true; 13971 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13972 FirstConversion == PPCISD::FCTIWUZ; 13973 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13974 SmallVector<SDValue, 4> Ops; 13975 EVT TargetVT = N->getValueType(0); 13976 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13977 SDValue NextOp = N->getOperand(i); 13978 if (NextOp.getOpcode() != PPCISD::MFVSR) 13979 return SDValue(); 13980 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13981 if (NextConversion != FirstConversion) 13982 return SDValue(); 13983 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13984 // This is not valid if the input was originally double precision. It is 13985 // also not profitable to do unless this is an extending load in which 13986 // case doing this combine will allow us to combine consecutive loads. 13987 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13988 return SDValue(); 13989 if (N->getOperand(i) != FirstInput) 13990 IsSplat = false; 13991 } 13992 13993 // If this is a splat, we leave it as-is since there will be only a single 13994 // fp-to-int conversion followed by a splat of the integer. This is better 13995 // for 32-bit and smaller ints and neutral for 64-bit ints. 13996 if (IsSplat) 13997 return SDValue(); 13998 13999 // Now that we know we have the right type of node, get its operands 14000 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14001 SDValue In = N->getOperand(i).getOperand(0); 14002 if (Is32Bit) { 14003 // For 32-bit values, we need to add an FP_ROUND node (if we made it 14004 // here, we know that all inputs are extending loads so this is safe). 14005 if (In.isUndef()) 14006 Ops.push_back(DAG.getUNDEF(SrcVT)); 14007 else { 14008 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 14009 MVT::f32, In.getOperand(0), 14010 DAG.getIntPtrConstant(1, dl)); 14011 Ops.push_back(Trunc); 14012 } 14013 } else 14014 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 14015 } 14016 14017 unsigned Opcode; 14018 if (FirstConversion == PPCISD::FCTIDZ || 14019 FirstConversion == PPCISD::FCTIWZ) 14020 Opcode = ISD::FP_TO_SINT; 14021 else 14022 Opcode = ISD::FP_TO_UINT; 14023 14024 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 14025 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 14026 return DAG.getNode(Opcode, dl, TargetVT, BV); 14027 } 14028 return SDValue(); 14029 } 14030 14031 /// Reduce the number of loads when building a vector. 14032 /// 14033 /// Building a vector out of multiple loads can be converted to a load 14034 /// of the vector type if the loads are consecutive. If the loads are 14035 /// consecutive but in descending order, a shuffle is added at the end 14036 /// to reorder the vector. 14037 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 14038 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14039 "Should be called with a BUILD_VECTOR node"); 14040 14041 SDLoc dl(N); 14042 14043 // Return early for non byte-sized type, as they can't be consecutive. 14044 if (!N->getValueType(0).getVectorElementType().isByteSized()) 14045 return SDValue(); 14046 14047 bool InputsAreConsecutiveLoads = true; 14048 bool InputsAreReverseConsecutive = true; 14049 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 14050 SDValue FirstInput = N->getOperand(0); 14051 bool IsRoundOfExtLoad = false; 14052 14053 if (FirstInput.getOpcode() == ISD::FP_ROUND && 14054 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 14055 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 14056 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 14057 } 14058 // Not a build vector of (possibly fp_rounded) loads. 14059 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 14060 N->getNumOperands() == 1) 14061 return SDValue(); 14062 14063 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 14064 // If any inputs are fp_round(extload), they all must be. 14065 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 14066 return SDValue(); 14067 14068 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 14069 N->getOperand(i); 14070 if (NextInput.getOpcode() != ISD::LOAD) 14071 return SDValue(); 14072 14073 SDValue PreviousInput = 14074 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 14075 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 14076 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 14077 14078 // If any inputs are fp_round(extload), they all must be. 14079 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 14080 return SDValue(); 14081 14082 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 14083 InputsAreConsecutiveLoads = false; 14084 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 14085 InputsAreReverseConsecutive = false; 14086 14087 // Exit early if the loads are neither consecutive nor reverse consecutive. 14088 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 14089 return SDValue(); 14090 } 14091 14092 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 14093 "The loads cannot be both consecutive and reverse consecutive."); 14094 14095 SDValue FirstLoadOp = 14096 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 14097 SDValue LastLoadOp = 14098 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 14099 N->getOperand(N->getNumOperands()-1); 14100 14101 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 14102 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 14103 if (InputsAreConsecutiveLoads) { 14104 assert(LD1 && "Input needs to be a LoadSDNode."); 14105 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 14106 LD1->getBasePtr(), LD1->getPointerInfo(), 14107 LD1->getAlignment()); 14108 } 14109 if (InputsAreReverseConsecutive) { 14110 assert(LDL && "Input needs to be a LoadSDNode."); 14111 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 14112 LDL->getBasePtr(), LDL->getPointerInfo(), 14113 LDL->getAlignment()); 14114 SmallVector<int, 16> Ops; 14115 for (int i = N->getNumOperands() - 1; i >= 0; i--) 14116 Ops.push_back(i); 14117 14118 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 14119 DAG.getUNDEF(N->getValueType(0)), Ops); 14120 } 14121 return SDValue(); 14122 } 14123 14124 // This function adds the required vector_shuffle needed to get 14125 // the elements of the vector extract in the correct position 14126 // as specified by the CorrectElems encoding. 14127 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 14128 SDValue Input, uint64_t Elems, 14129 uint64_t CorrectElems) { 14130 SDLoc dl(N); 14131 14132 unsigned NumElems = Input.getValueType().getVectorNumElements(); 14133 SmallVector<int, 16> ShuffleMask(NumElems, -1); 14134 14135 // Knowing the element indices being extracted from the original 14136 // vector and the order in which they're being inserted, just put 14137 // them at element indices required for the instruction. 14138 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14139 if (DAG.getDataLayout().isLittleEndian()) 14140 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 14141 else 14142 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 14143 CorrectElems = CorrectElems >> 8; 14144 Elems = Elems >> 8; 14145 } 14146 14147 SDValue Shuffle = 14148 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 14149 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 14150 14151 EVT VT = N->getValueType(0); 14152 SDValue Conv = DAG.getBitcast(VT, Shuffle); 14153 14154 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 14155 Input.getValueType().getVectorElementType(), 14156 VT.getVectorNumElements()); 14157 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 14158 DAG.getValueType(ExtVT)); 14159 } 14160 14161 // Look for build vector patterns where input operands come from sign 14162 // extended vector_extract elements of specific indices. If the correct indices 14163 // aren't used, add a vector shuffle to fix up the indices and create 14164 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14165 // during instruction selection. 14166 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14167 // This array encodes the indices that the vector sign extend instructions 14168 // extract from when extending from one type to another for both BE and LE. 14169 // The right nibble of each byte corresponds to the LE incides. 14170 // and the left nibble of each byte corresponds to the BE incides. 14171 // For example: 0x3074B8FC byte->word 14172 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14173 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14174 // For example: 0x000070F8 byte->double word 14175 // For LE: the allowed indices are: 0x0,0x8 14176 // For BE: the allowed indices are: 0x7,0xF 14177 uint64_t TargetElems[] = { 14178 0x3074B8FC, // b->w 14179 0x000070F8, // b->d 14180 0x10325476, // h->w 14181 0x00003074, // h->d 14182 0x00001032, // w->d 14183 }; 14184 14185 uint64_t Elems = 0; 14186 int Index; 14187 SDValue Input; 14188 14189 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14190 if (!Op) 14191 return false; 14192 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14193 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14194 return false; 14195 14196 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14197 // of the right width. 14198 SDValue Extract = Op.getOperand(0); 14199 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14200 Extract = Extract.getOperand(0); 14201 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14202 return false; 14203 14204 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14205 if (!ExtOp) 14206 return false; 14207 14208 Index = ExtOp->getZExtValue(); 14209 if (Input && Input != Extract.getOperand(0)) 14210 return false; 14211 14212 if (!Input) 14213 Input = Extract.getOperand(0); 14214 14215 Elems = Elems << 8; 14216 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14217 Elems |= Index; 14218 14219 return true; 14220 }; 14221 14222 // If the build vector operands aren't sign extended vector extracts, 14223 // of the same input vector, then return. 14224 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14225 if (!isSExtOfVecExtract(N->getOperand(i))) { 14226 return SDValue(); 14227 } 14228 } 14229 14230 // If the vector extract indicies are not correct, add the appropriate 14231 // vector_shuffle. 14232 int TgtElemArrayIdx; 14233 int InputSize = Input.getValueType().getScalarSizeInBits(); 14234 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14235 if (InputSize + OutputSize == 40) 14236 TgtElemArrayIdx = 0; 14237 else if (InputSize + OutputSize == 72) 14238 TgtElemArrayIdx = 1; 14239 else if (InputSize + OutputSize == 48) 14240 TgtElemArrayIdx = 2; 14241 else if (InputSize + OutputSize == 80) 14242 TgtElemArrayIdx = 3; 14243 else if (InputSize + OutputSize == 96) 14244 TgtElemArrayIdx = 4; 14245 else 14246 return SDValue(); 14247 14248 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14249 CorrectElems = DAG.getDataLayout().isLittleEndian() 14250 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14251 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14252 if (Elems != CorrectElems) { 14253 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14254 } 14255 14256 // Regular lowering will catch cases where a shuffle is not needed. 14257 return SDValue(); 14258 } 14259 14260 // Look for the pattern of a load from a narrow width to i128, feeding 14261 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14262 // (LXVRZX). This node represents a zero extending load that will be matched 14263 // to the Load VSX Vector Rightmost instructions. 14264 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14265 SDLoc DL(N); 14266 14267 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14268 if (N->getValueType(0) != MVT::v1i128) 14269 return SDValue(); 14270 14271 SDValue Operand = N->getOperand(0); 14272 // Proceed with the transformation if the operand to the BUILD_VECTOR 14273 // is a load instruction. 14274 if (Operand.getOpcode() != ISD::LOAD) 14275 return SDValue(); 14276 14277 auto *LD = cast<LoadSDNode>(Operand); 14278 EVT MemoryType = LD->getMemoryVT(); 14279 14280 // This transformation is only valid if the we are loading either a byte, 14281 // halfword, word, or doubleword. 14282 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14283 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14284 14285 // Ensure that the load from the narrow width is being zero extended to i128. 14286 if (!ValidLDType || 14287 (LD->getExtensionType() != ISD::ZEXTLOAD && 14288 LD->getExtensionType() != ISD::EXTLOAD)) 14289 return SDValue(); 14290 14291 SDValue LoadOps[] = { 14292 LD->getChain(), LD->getBasePtr(), 14293 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14294 14295 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14296 DAG.getVTList(MVT::v1i128, MVT::Other), 14297 LoadOps, MemoryType, LD->getMemOperand()); 14298 } 14299 14300 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14301 DAGCombinerInfo &DCI) const { 14302 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14303 "Should be called with a BUILD_VECTOR node"); 14304 14305 SelectionDAG &DAG = DCI.DAG; 14306 SDLoc dl(N); 14307 14308 if (!Subtarget.hasVSX()) 14309 return SDValue(); 14310 14311 // The target independent DAG combiner will leave a build_vector of 14312 // float-to-int conversions intact. We can generate MUCH better code for 14313 // a float-to-int conversion of a vector of floats. 14314 SDValue FirstInput = N->getOperand(0); 14315 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14316 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14317 if (Reduced) 14318 return Reduced; 14319 } 14320 14321 // If we're building a vector out of consecutive loads, just load that 14322 // vector type. 14323 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14324 if (Reduced) 14325 return Reduced; 14326 14327 // If we're building a vector out of extended elements from another vector 14328 // we have P9 vector integer extend instructions. The code assumes legal 14329 // input types (i.e. it can't handle things like v4i16) so do not run before 14330 // legalization. 14331 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14332 Reduced = combineBVOfVecSExt(N, DAG); 14333 if (Reduced) 14334 return Reduced; 14335 } 14336 14337 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14338 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14339 // is a load from <valid narrow width> to i128. 14340 if (Subtarget.isISA3_1()) { 14341 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14342 if (BVOfZLoad) 14343 return BVOfZLoad; 14344 } 14345 14346 if (N->getValueType(0) != MVT::v2f64) 14347 return SDValue(); 14348 14349 // Looking for: 14350 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14351 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14352 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14353 return SDValue(); 14354 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14355 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14356 return SDValue(); 14357 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14358 return SDValue(); 14359 14360 SDValue Ext1 = FirstInput.getOperand(0); 14361 SDValue Ext2 = N->getOperand(1).getOperand(0); 14362 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14363 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14364 return SDValue(); 14365 14366 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14367 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14368 if (!Ext1Op || !Ext2Op) 14369 return SDValue(); 14370 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14371 Ext1.getOperand(0) != Ext2.getOperand(0)) 14372 return SDValue(); 14373 14374 int FirstElem = Ext1Op->getZExtValue(); 14375 int SecondElem = Ext2Op->getZExtValue(); 14376 int SubvecIdx; 14377 if (FirstElem == 0 && SecondElem == 1) 14378 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14379 else if (FirstElem == 2 && SecondElem == 3) 14380 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14381 else 14382 return SDValue(); 14383 14384 SDValue SrcVec = Ext1.getOperand(0); 14385 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14386 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14387 return DAG.getNode(NodeType, dl, MVT::v2f64, 14388 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14389 } 14390 14391 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14392 DAGCombinerInfo &DCI) const { 14393 assert((N->getOpcode() == ISD::SINT_TO_FP || 14394 N->getOpcode() == ISD::UINT_TO_FP) && 14395 "Need an int -> FP conversion node here"); 14396 14397 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14398 return SDValue(); 14399 14400 SelectionDAG &DAG = DCI.DAG; 14401 SDLoc dl(N); 14402 SDValue Op(N, 0); 14403 14404 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14405 // from the hardware. 14406 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14407 return SDValue(); 14408 if (!Op.getOperand(0).getValueType().isSimple()) 14409 return SDValue(); 14410 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14411 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14412 return SDValue(); 14413 14414 SDValue FirstOperand(Op.getOperand(0)); 14415 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14416 (FirstOperand.getValueType() == MVT::i8 || 14417 FirstOperand.getValueType() == MVT::i16); 14418 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14419 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14420 bool DstDouble = Op.getValueType() == MVT::f64; 14421 unsigned ConvOp = Signed ? 14422 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14423 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14424 SDValue WidthConst = 14425 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14426 dl, false); 14427 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14428 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14429 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14430 DAG.getVTList(MVT::f64, MVT::Other), 14431 Ops, MVT::i8, LDN->getMemOperand()); 14432 14433 // For signed conversion, we need to sign-extend the value in the VSR 14434 if (Signed) { 14435 SDValue ExtOps[] = { Ld, WidthConst }; 14436 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14437 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14438 } else 14439 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14440 } 14441 14442 14443 // For i32 intermediate values, unfortunately, the conversion functions 14444 // leave the upper 32 bits of the value are undefined. Within the set of 14445 // scalar instructions, we have no method for zero- or sign-extending the 14446 // value. Thus, we cannot handle i32 intermediate values here. 14447 if (Op.getOperand(0).getValueType() == MVT::i32) 14448 return SDValue(); 14449 14450 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14451 "UINT_TO_FP is supported only with FPCVT"); 14452 14453 // If we have FCFIDS, then use it when converting to single-precision. 14454 // Otherwise, convert to double-precision and then round. 14455 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14456 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14457 : PPCISD::FCFIDS) 14458 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14459 : PPCISD::FCFID); 14460 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14461 ? MVT::f32 14462 : MVT::f64; 14463 14464 // If we're converting from a float, to an int, and back to a float again, 14465 // then we don't need the store/load pair at all. 14466 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14467 Subtarget.hasFPCVT()) || 14468 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14469 SDValue Src = Op.getOperand(0).getOperand(0); 14470 if (Src.getValueType() == MVT::f32) { 14471 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14472 DCI.AddToWorklist(Src.getNode()); 14473 } else if (Src.getValueType() != MVT::f64) { 14474 // Make sure that we don't pick up a ppc_fp128 source value. 14475 return SDValue(); 14476 } 14477 14478 unsigned FCTOp = 14479 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14480 PPCISD::FCTIDUZ; 14481 14482 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14483 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14484 14485 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14486 FP = DAG.getNode(ISD::FP_ROUND, dl, 14487 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14488 DCI.AddToWorklist(FP.getNode()); 14489 } 14490 14491 return FP; 14492 } 14493 14494 return SDValue(); 14495 } 14496 14497 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14498 // builtins) into loads with swaps. 14499 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14500 DAGCombinerInfo &DCI) const { 14501 SelectionDAG &DAG = DCI.DAG; 14502 SDLoc dl(N); 14503 SDValue Chain; 14504 SDValue Base; 14505 MachineMemOperand *MMO; 14506 14507 switch (N->getOpcode()) { 14508 default: 14509 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14510 case ISD::LOAD: { 14511 LoadSDNode *LD = cast<LoadSDNode>(N); 14512 Chain = LD->getChain(); 14513 Base = LD->getBasePtr(); 14514 MMO = LD->getMemOperand(); 14515 // If the MMO suggests this isn't a load of a full vector, leave 14516 // things alone. For a built-in, we have to make the change for 14517 // correctness, so if there is a size problem that will be a bug. 14518 if (MMO->getSize() < 16) 14519 return SDValue(); 14520 break; 14521 } 14522 case ISD::INTRINSIC_W_CHAIN: { 14523 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14524 Chain = Intrin->getChain(); 14525 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14526 // us what we want. Get operand 2 instead. 14527 Base = Intrin->getOperand(2); 14528 MMO = Intrin->getMemOperand(); 14529 break; 14530 } 14531 } 14532 14533 MVT VecTy = N->getValueType(0).getSimpleVT(); 14534 14535 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14536 // aligned and the type is a vector with elements up to 4 bytes 14537 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14538 VecTy.getScalarSizeInBits() <= 32) { 14539 return SDValue(); 14540 } 14541 14542 SDValue LoadOps[] = { Chain, Base }; 14543 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14544 DAG.getVTList(MVT::v2f64, MVT::Other), 14545 LoadOps, MVT::v2f64, MMO); 14546 14547 DCI.AddToWorklist(Load.getNode()); 14548 Chain = Load.getValue(1); 14549 SDValue Swap = DAG.getNode( 14550 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14551 DCI.AddToWorklist(Swap.getNode()); 14552 14553 // Add a bitcast if the resulting load type doesn't match v2f64. 14554 if (VecTy != MVT::v2f64) { 14555 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14556 DCI.AddToWorklist(N.getNode()); 14557 // Package {bitcast value, swap's chain} to match Load's shape. 14558 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14559 N, Swap.getValue(1)); 14560 } 14561 14562 return Swap; 14563 } 14564 14565 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14566 // builtins) into stores with swaps. 14567 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14568 DAGCombinerInfo &DCI) const { 14569 SelectionDAG &DAG = DCI.DAG; 14570 SDLoc dl(N); 14571 SDValue Chain; 14572 SDValue Base; 14573 unsigned SrcOpnd; 14574 MachineMemOperand *MMO; 14575 14576 switch (N->getOpcode()) { 14577 default: 14578 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14579 case ISD::STORE: { 14580 StoreSDNode *ST = cast<StoreSDNode>(N); 14581 Chain = ST->getChain(); 14582 Base = ST->getBasePtr(); 14583 MMO = ST->getMemOperand(); 14584 SrcOpnd = 1; 14585 // If the MMO suggests this isn't a store of a full vector, leave 14586 // things alone. For a built-in, we have to make the change for 14587 // correctness, so if there is a size problem that will be a bug. 14588 if (MMO->getSize() < 16) 14589 return SDValue(); 14590 break; 14591 } 14592 case ISD::INTRINSIC_VOID: { 14593 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14594 Chain = Intrin->getChain(); 14595 // Intrin->getBasePtr() oddly does not get what we want. 14596 Base = Intrin->getOperand(3); 14597 MMO = Intrin->getMemOperand(); 14598 SrcOpnd = 2; 14599 break; 14600 } 14601 } 14602 14603 SDValue Src = N->getOperand(SrcOpnd); 14604 MVT VecTy = Src.getValueType().getSimpleVT(); 14605 14606 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14607 // aligned and the type is a vector with elements up to 4 bytes 14608 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14609 VecTy.getScalarSizeInBits() <= 32) { 14610 return SDValue(); 14611 } 14612 14613 // All stores are done as v2f64 and possible bit cast. 14614 if (VecTy != MVT::v2f64) { 14615 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14616 DCI.AddToWorklist(Src.getNode()); 14617 } 14618 14619 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14620 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14621 DCI.AddToWorklist(Swap.getNode()); 14622 Chain = Swap.getValue(1); 14623 SDValue StoreOps[] = { Chain, Swap, Base }; 14624 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14625 DAG.getVTList(MVT::Other), 14626 StoreOps, VecTy, MMO); 14627 DCI.AddToWorklist(Store.getNode()); 14628 return Store; 14629 } 14630 14631 // Handle DAG combine for STORE (FP_TO_INT F). 14632 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14633 DAGCombinerInfo &DCI) const { 14634 14635 SelectionDAG &DAG = DCI.DAG; 14636 SDLoc dl(N); 14637 unsigned Opcode = N->getOperand(1).getOpcode(); 14638 14639 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14640 && "Not a FP_TO_INT Instruction!"); 14641 14642 SDValue Val = N->getOperand(1).getOperand(0); 14643 EVT Op1VT = N->getOperand(1).getValueType(); 14644 EVT ResVT = Val.getValueType(); 14645 14646 if (!isTypeLegal(ResVT)) 14647 return SDValue(); 14648 14649 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14650 bool ValidTypeForStoreFltAsInt = 14651 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14652 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14653 14654 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14655 return SDValue(); 14656 14657 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14658 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14659 return SDValue(); 14660 14661 // Extend f32 values to f64 14662 if (ResVT.getScalarSizeInBits() == 32) { 14663 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14664 DCI.AddToWorklist(Val.getNode()); 14665 } 14666 14667 // Set signed or unsigned conversion opcode. 14668 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14669 PPCISD::FP_TO_SINT_IN_VSR : 14670 PPCISD::FP_TO_UINT_IN_VSR; 14671 14672 Val = DAG.getNode(ConvOpcode, 14673 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14674 DCI.AddToWorklist(Val.getNode()); 14675 14676 // Set number of bytes being converted. 14677 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14678 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14679 DAG.getIntPtrConstant(ByteSize, dl, false), 14680 DAG.getValueType(Op1VT) }; 14681 14682 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14683 DAG.getVTList(MVT::Other), Ops, 14684 cast<StoreSDNode>(N)->getMemoryVT(), 14685 cast<StoreSDNode>(N)->getMemOperand()); 14686 14687 DCI.AddToWorklist(Val.getNode()); 14688 return Val; 14689 } 14690 14691 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14692 // Check that the source of the element keeps flipping 14693 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14694 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14695 for (int i = 1, e = Mask.size(); i < e; i++) { 14696 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14697 return false; 14698 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14699 return false; 14700 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14701 } 14702 return true; 14703 } 14704 14705 static bool isSplatBV(SDValue Op) { 14706 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14707 return false; 14708 SDValue FirstOp; 14709 14710 // Find first non-undef input. 14711 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14712 FirstOp = Op.getOperand(i); 14713 if (!FirstOp.isUndef()) 14714 break; 14715 } 14716 14717 // All inputs are undef or the same as the first non-undef input. 14718 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14719 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14720 return false; 14721 return true; 14722 } 14723 14724 static SDValue isScalarToVec(SDValue Op) { 14725 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14726 return Op; 14727 if (Op.getOpcode() != ISD::BITCAST) 14728 return SDValue(); 14729 Op = Op.getOperand(0); 14730 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14731 return Op; 14732 return SDValue(); 14733 } 14734 14735 // Fix up the shuffle mask to account for the fact that the result of 14736 // scalar_to_vector is not in lane zero. This just takes all values in 14737 // the ranges specified by the min/max indices and adds the number of 14738 // elements required to ensure each element comes from the respective 14739 // position in the valid lane. 14740 // On little endian, that's just the corresponding element in the other 14741 // half of the vector. On big endian, it is in the same half but right 14742 // justified rather than left justified in that half. 14743 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14744 int LHSMaxIdx, int RHSMinIdx, 14745 int RHSMaxIdx, int HalfVec, 14746 unsigned ValidLaneWidth, 14747 const PPCSubtarget &Subtarget) { 14748 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14749 int Idx = ShuffV[i]; 14750 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14751 ShuffV[i] += 14752 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14753 } 14754 } 14755 14756 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14757 // the original is: 14758 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14759 // In such a case, just change the shuffle mask to extract the element 14760 // from the permuted index. 14761 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14762 const PPCSubtarget &Subtarget) { 14763 SDLoc dl(OrigSToV); 14764 EVT VT = OrigSToV.getValueType(); 14765 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14766 "Expecting a SCALAR_TO_VECTOR here"); 14767 SDValue Input = OrigSToV.getOperand(0); 14768 14769 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14770 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14771 SDValue OrigVector = Input.getOperand(0); 14772 14773 // Can't handle non-const element indices or different vector types 14774 // for the input to the extract and the output of the scalar_to_vector. 14775 if (Idx && VT == OrigVector.getValueType()) { 14776 unsigned NumElts = VT.getVectorNumElements(); 14777 assert( 14778 NumElts > 1 && 14779 "Cannot produce a permuted scalar_to_vector for one element vector"); 14780 SmallVector<int, 16> NewMask(NumElts, -1); 14781 unsigned ResultInElt = NumElts / 2; 14782 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14783 NewMask[ResultInElt] = Idx->getZExtValue(); 14784 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14785 } 14786 } 14787 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14788 OrigSToV.getOperand(0)); 14789 } 14790 14791 // On little endian subtargets, combine shuffles such as: 14792 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14793 // into: 14794 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14795 // because the latter can be matched to a single instruction merge. 14796 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14797 // to put the value into element zero. Adjust the shuffle mask so that the 14798 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14799 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14800 // nodes with elements smaller than doubleword because all the ways 14801 // of getting scalar data into a vector register put the value in the 14802 // rightmost element of the left half of the vector. 14803 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14804 SelectionDAG &DAG) const { 14805 SDValue LHS = SVN->getOperand(0); 14806 SDValue RHS = SVN->getOperand(1); 14807 auto Mask = SVN->getMask(); 14808 int NumElts = LHS.getValueType().getVectorNumElements(); 14809 SDValue Res(SVN, 0); 14810 SDLoc dl(SVN); 14811 bool IsLittleEndian = Subtarget.isLittleEndian(); 14812 14813 // On big endian targets this is only useful for subtargets with direct moves. 14814 // On little endian targets it would be useful for all subtargets with VSX. 14815 // However adding special handling for LE subtargets without direct moves 14816 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8) 14817 // which includes direct moves. 14818 if (!Subtarget.hasDirectMove()) 14819 return Res; 14820 14821 // If this is not a shuffle of a shuffle and the first element comes from 14822 // the second vector, canonicalize to the commuted form. This will make it 14823 // more likely to match one of the single instruction patterns. 14824 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14825 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14826 std::swap(LHS, RHS); 14827 Res = DAG.getCommutedVectorShuffle(*SVN); 14828 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14829 } 14830 14831 // Adjust the shuffle mask if either input vector comes from a 14832 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14833 // form (to prevent the need for a swap). 14834 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14835 SDValue SToVLHS = isScalarToVec(LHS); 14836 SDValue SToVRHS = isScalarToVec(RHS); 14837 if (SToVLHS || SToVRHS) { 14838 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14839 : SToVRHS.getValueType().getVectorNumElements(); 14840 int NumEltsOut = ShuffV.size(); 14841 // The width of the "valid lane" (i.e. the lane that contains the value that 14842 // is vectorized) needs to be expressed in terms of the number of elements 14843 // of the shuffle. It is thereby the ratio of the values before and after 14844 // any bitcast. 14845 unsigned ValidLaneWidth = 14846 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() / 14847 LHS.getValueType().getScalarSizeInBits() 14848 : SToVRHS.getValueType().getScalarSizeInBits() / 14849 RHS.getValueType().getScalarSizeInBits(); 14850 14851 // Initially assume that neither input is permuted. These will be adjusted 14852 // accordingly if either input is. 14853 int LHSMaxIdx = -1; 14854 int RHSMinIdx = -1; 14855 int RHSMaxIdx = -1; 14856 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14857 14858 // Get the permuted scalar to vector nodes for the source(s) that come from 14859 // ISD::SCALAR_TO_VECTOR. 14860 // On big endian systems, this only makes sense for element sizes smaller 14861 // than 64 bits since for 64-bit elements, all instructions already put 14862 // the value into element zero. Since scalar size of LHS and RHS may differ 14863 // after isScalarToVec, this should be checked using their own sizes. 14864 if (SToVLHS) { 14865 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64) 14866 return Res; 14867 // Set up the values for the shuffle vector fixup. 14868 LHSMaxIdx = NumEltsOut / NumEltsIn; 14869 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14870 if (SToVLHS.getValueType() != LHS.getValueType()) 14871 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14872 LHS = SToVLHS; 14873 } 14874 if (SToVRHS) { 14875 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64) 14876 return Res; 14877 RHSMinIdx = NumEltsOut; 14878 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14879 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14880 if (SToVRHS.getValueType() != RHS.getValueType()) 14881 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14882 RHS = SToVRHS; 14883 } 14884 14885 // Fix up the shuffle mask to reflect where the desired element actually is. 14886 // The minimum and maximum indices that correspond to element zero for both 14887 // the LHS and RHS are computed and will control which shuffle mask entries 14888 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14889 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14890 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14891 HalfVec, ValidLaneWidth, Subtarget); 14892 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14893 14894 // We may have simplified away the shuffle. We won't be able to do anything 14895 // further with it here. 14896 if (!isa<ShuffleVectorSDNode>(Res)) 14897 return Res; 14898 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14899 } 14900 14901 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14902 // The common case after we commuted the shuffle is that the RHS is a splat 14903 // and we have elements coming in from the splat at indices that are not 14904 // conducive to using a merge. 14905 // Example: 14906 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14907 if (!isSplatBV(TheSplat)) 14908 return Res; 14909 14910 // We are looking for a mask such that all even elements are from 14911 // one vector and all odd elements from the other. 14912 if (!isAlternatingShuffMask(Mask, NumElts)) 14913 return Res; 14914 14915 // Adjust the mask so we are pulling in the same index from the splat 14916 // as the index from the interesting vector in consecutive elements. 14917 if (IsLittleEndian) { 14918 // Example (even elements from first vector): 14919 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14920 if (Mask[0] < NumElts) 14921 for (int i = 1, e = Mask.size(); i < e; i += 2) 14922 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14923 // Example (odd elements from first vector): 14924 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14925 else 14926 for (int i = 0, e = Mask.size(); i < e; i += 2) 14927 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14928 } else { 14929 // Example (even elements from first vector): 14930 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14931 if (Mask[0] < NumElts) 14932 for (int i = 0, e = Mask.size(); i < e; i += 2) 14933 ShuffV[i] = ShuffV[i + 1] - NumElts; 14934 // Example (odd elements from first vector): 14935 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14936 else 14937 for (int i = 1, e = Mask.size(); i < e; i += 2) 14938 ShuffV[i] = ShuffV[i - 1] - NumElts; 14939 } 14940 14941 // If the RHS has undefs, we need to remove them since we may have created 14942 // a shuffle that adds those instead of the splat value. 14943 SDValue SplatVal = 14944 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14945 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 14946 14947 if (IsLittleEndian) 14948 RHS = TheSplat; 14949 else 14950 LHS = TheSplat; 14951 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14952 } 14953 14954 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14955 LSBaseSDNode *LSBase, 14956 DAGCombinerInfo &DCI) const { 14957 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14958 "Not a reverse memop pattern!"); 14959 14960 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14961 auto Mask = SVN->getMask(); 14962 int i = 0; 14963 auto I = Mask.rbegin(); 14964 auto E = Mask.rend(); 14965 14966 for (; I != E; ++I) { 14967 if (*I != i) 14968 return false; 14969 i++; 14970 } 14971 return true; 14972 }; 14973 14974 SelectionDAG &DAG = DCI.DAG; 14975 EVT VT = SVN->getValueType(0); 14976 14977 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14978 return SDValue(); 14979 14980 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14981 // See comment in PPCVSXSwapRemoval.cpp. 14982 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14983 if (!Subtarget.hasP9Vector()) 14984 return SDValue(); 14985 14986 if(!IsElementReverse(SVN)) 14987 return SDValue(); 14988 14989 if (LSBase->getOpcode() == ISD::LOAD) { 14990 // If the load return value 0 has more than one user except the 14991 // shufflevector instruction, it is not profitable to replace the 14992 // shufflevector with a reverse load. 14993 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 14994 UI != UE; ++UI) 14995 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 14996 return SDValue(); 14997 14998 SDLoc dl(LSBase); 14999 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 15000 return DAG.getMemIntrinsicNode( 15001 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 15002 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15003 } 15004 15005 if (LSBase->getOpcode() == ISD::STORE) { 15006 // If there are other uses of the shuffle, the swap cannot be avoided. 15007 // Forcing the use of an X-Form (since swapped stores only have 15008 // X-Forms) without removing the swap is unprofitable. 15009 if (!SVN->hasOneUse()) 15010 return SDValue(); 15011 15012 SDLoc dl(LSBase); 15013 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 15014 LSBase->getBasePtr()}; 15015 return DAG.getMemIntrinsicNode( 15016 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 15017 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15018 } 15019 15020 llvm_unreachable("Expected a load or store node here"); 15021 } 15022 15023 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 15024 DAGCombinerInfo &DCI) const { 15025 SelectionDAG &DAG = DCI.DAG; 15026 SDLoc dl(N); 15027 switch (N->getOpcode()) { 15028 default: break; 15029 case ISD::ADD: 15030 return combineADD(N, DCI); 15031 case ISD::SHL: 15032 return combineSHL(N, DCI); 15033 case ISD::SRA: 15034 return combineSRA(N, DCI); 15035 case ISD::SRL: 15036 return combineSRL(N, DCI); 15037 case ISD::MUL: 15038 return combineMUL(N, DCI); 15039 case ISD::FMA: 15040 case PPCISD::FNMSUB: 15041 return combineFMALike(N, DCI); 15042 case PPCISD::SHL: 15043 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 15044 return N->getOperand(0); 15045 break; 15046 case PPCISD::SRL: 15047 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 15048 return N->getOperand(0); 15049 break; 15050 case PPCISD::SRA: 15051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 15052 if (C->isZero() || // 0 >>s V -> 0. 15053 C->isAllOnes()) // -1 >>s V -> -1. 15054 return N->getOperand(0); 15055 } 15056 break; 15057 case ISD::SIGN_EXTEND: 15058 case ISD::ZERO_EXTEND: 15059 case ISD::ANY_EXTEND: 15060 return DAGCombineExtBoolTrunc(N, DCI); 15061 case ISD::TRUNCATE: 15062 return combineTRUNCATE(N, DCI); 15063 case ISD::SETCC: 15064 if (SDValue CSCC = combineSetCC(N, DCI)) 15065 return CSCC; 15066 LLVM_FALLTHROUGH; 15067 case ISD::SELECT_CC: 15068 return DAGCombineTruncBoolExt(N, DCI); 15069 case ISD::SINT_TO_FP: 15070 case ISD::UINT_TO_FP: 15071 return combineFPToIntToFP(N, DCI); 15072 case ISD::VECTOR_SHUFFLE: 15073 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 15074 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 15075 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 15076 } 15077 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 15078 case ISD::STORE: { 15079 15080 EVT Op1VT = N->getOperand(1).getValueType(); 15081 unsigned Opcode = N->getOperand(1).getOpcode(); 15082 15083 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 15084 SDValue Val= combineStoreFPToInt(N, DCI); 15085 if (Val) 15086 return Val; 15087 } 15088 15089 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 15090 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 15091 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 15092 if (Val) 15093 return Val; 15094 } 15095 15096 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 15097 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 15098 N->getOperand(1).getNode()->hasOneUse() && 15099 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 15100 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 15101 15102 // STBRX can only handle simple types and it makes no sense to store less 15103 // two bytes in byte-reversed order. 15104 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 15105 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 15106 break; 15107 15108 SDValue BSwapOp = N->getOperand(1).getOperand(0); 15109 // Do an any-extend to 32-bits if this is a half-word input. 15110 if (BSwapOp.getValueType() == MVT::i16) 15111 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 15112 15113 // If the type of BSWAP operand is wider than stored memory width 15114 // it need to be shifted to the right side before STBRX. 15115 if (Op1VT.bitsGT(mVT)) { 15116 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 15117 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 15118 DAG.getConstant(Shift, dl, MVT::i32)); 15119 // Need to truncate if this is a bswap of i64 stored as i32/i16. 15120 if (Op1VT == MVT::i64) 15121 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 15122 } 15123 15124 SDValue Ops[] = { 15125 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 15126 }; 15127 return 15128 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 15129 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 15130 cast<StoreSDNode>(N)->getMemOperand()); 15131 } 15132 15133 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 15134 // So it can increase the chance of CSE constant construction. 15135 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 15136 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 15137 // Need to sign-extended to 64-bits to handle negative values. 15138 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 15139 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 15140 MemVT.getSizeInBits()); 15141 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 15142 15143 // DAG.getTruncStore() can't be used here because it doesn't accept 15144 // the general (base + offset) addressing mode. 15145 // So we use UpdateNodeOperands and setTruncatingStore instead. 15146 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 15147 N->getOperand(3)); 15148 cast<StoreSDNode>(N)->setTruncatingStore(true); 15149 return SDValue(N, 0); 15150 } 15151 15152 // For little endian, VSX stores require generating xxswapd/lxvd2x. 15153 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15154 if (Op1VT.isSimple()) { 15155 MVT StoreVT = Op1VT.getSimpleVT(); 15156 if (Subtarget.needsSwapsForVSXMemOps() && 15157 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 15158 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 15159 return expandVSXStoreForLE(N, DCI); 15160 } 15161 break; 15162 } 15163 case ISD::LOAD: { 15164 LoadSDNode *LD = cast<LoadSDNode>(N); 15165 EVT VT = LD->getValueType(0); 15166 15167 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15168 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15169 if (VT.isSimple()) { 15170 MVT LoadVT = VT.getSimpleVT(); 15171 if (Subtarget.needsSwapsForVSXMemOps() && 15172 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 15173 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 15174 return expandVSXLoadForLE(N, DCI); 15175 } 15176 15177 // We sometimes end up with a 64-bit integer load, from which we extract 15178 // two single-precision floating-point numbers. This happens with 15179 // std::complex<float>, and other similar structures, because of the way we 15180 // canonicalize structure copies. However, if we lack direct moves, 15181 // then the final bitcasts from the extracted integer values to the 15182 // floating-point numbers turn into store/load pairs. Even with direct moves, 15183 // just loading the two floating-point numbers is likely better. 15184 auto ReplaceTwoFloatLoad = [&]() { 15185 if (VT != MVT::i64) 15186 return false; 15187 15188 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 15189 LD->isVolatile()) 15190 return false; 15191 15192 // We're looking for a sequence like this: 15193 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 15194 // t16: i64 = srl t13, Constant:i32<32> 15195 // t17: i32 = truncate t16 15196 // t18: f32 = bitcast t17 15197 // t19: i32 = truncate t13 15198 // t20: f32 = bitcast t19 15199 15200 if (!LD->hasNUsesOfValue(2, 0)) 15201 return false; 15202 15203 auto UI = LD->use_begin(); 15204 while (UI.getUse().getResNo() != 0) ++UI; 15205 SDNode *Trunc = *UI++; 15206 while (UI.getUse().getResNo() != 0) ++UI; 15207 SDNode *RightShift = *UI; 15208 if (Trunc->getOpcode() != ISD::TRUNCATE) 15209 std::swap(Trunc, RightShift); 15210 15211 if (Trunc->getOpcode() != ISD::TRUNCATE || 15212 Trunc->getValueType(0) != MVT::i32 || 15213 !Trunc->hasOneUse()) 15214 return false; 15215 if (RightShift->getOpcode() != ISD::SRL || 15216 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 15217 RightShift->getConstantOperandVal(1) != 32 || 15218 !RightShift->hasOneUse()) 15219 return false; 15220 15221 SDNode *Trunc2 = *RightShift->use_begin(); 15222 if (Trunc2->getOpcode() != ISD::TRUNCATE || 15223 Trunc2->getValueType(0) != MVT::i32 || 15224 !Trunc2->hasOneUse()) 15225 return false; 15226 15227 SDNode *Bitcast = *Trunc->use_begin(); 15228 SDNode *Bitcast2 = *Trunc2->use_begin(); 15229 15230 if (Bitcast->getOpcode() != ISD::BITCAST || 15231 Bitcast->getValueType(0) != MVT::f32) 15232 return false; 15233 if (Bitcast2->getOpcode() != ISD::BITCAST || 15234 Bitcast2->getValueType(0) != MVT::f32) 15235 return false; 15236 15237 if (Subtarget.isLittleEndian()) 15238 std::swap(Bitcast, Bitcast2); 15239 15240 // Bitcast has the second float (in memory-layout order) and Bitcast2 15241 // has the first one. 15242 15243 SDValue BasePtr = LD->getBasePtr(); 15244 if (LD->isIndexed()) { 15245 assert(LD->getAddressingMode() == ISD::PRE_INC && 15246 "Non-pre-inc AM on PPC?"); 15247 BasePtr = 15248 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15249 LD->getOffset()); 15250 } 15251 15252 auto MMOFlags = 15253 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15254 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15255 LD->getPointerInfo(), LD->getAlignment(), 15256 MMOFlags, LD->getAAInfo()); 15257 SDValue AddPtr = 15258 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15259 BasePtr, DAG.getIntPtrConstant(4, dl)); 15260 SDValue FloatLoad2 = DAG.getLoad( 15261 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15262 LD->getPointerInfo().getWithOffset(4), 15263 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 15264 15265 if (LD->isIndexed()) { 15266 // Note that DAGCombine should re-form any pre-increment load(s) from 15267 // what is produced here if that makes sense. 15268 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15269 } 15270 15271 DCI.CombineTo(Bitcast2, FloatLoad); 15272 DCI.CombineTo(Bitcast, FloatLoad2); 15273 15274 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15275 SDValue(FloatLoad2.getNode(), 1)); 15276 return true; 15277 }; 15278 15279 if (ReplaceTwoFloatLoad()) 15280 return SDValue(N, 0); 15281 15282 EVT MemVT = LD->getMemoryVT(); 15283 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15284 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15285 if (LD->isUnindexed() && VT.isVector() && 15286 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15287 // P8 and later hardware should just use LOAD. 15288 !Subtarget.hasP8Vector() && 15289 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15290 VT == MVT::v4f32))) && 15291 LD->getAlign() < ABIAlignment) { 15292 // This is a type-legal unaligned Altivec load. 15293 SDValue Chain = LD->getChain(); 15294 SDValue Ptr = LD->getBasePtr(); 15295 bool isLittleEndian = Subtarget.isLittleEndian(); 15296 15297 // This implements the loading of unaligned vectors as described in 15298 // the venerable Apple Velocity Engine overview. Specifically: 15299 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15300 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15301 // 15302 // The general idea is to expand a sequence of one or more unaligned 15303 // loads into an alignment-based permutation-control instruction (lvsl 15304 // or lvsr), a series of regular vector loads (which always truncate 15305 // their input address to an aligned address), and a series of 15306 // permutations. The results of these permutations are the requested 15307 // loaded values. The trick is that the last "extra" load is not taken 15308 // from the address you might suspect (sizeof(vector) bytes after the 15309 // last requested load), but rather sizeof(vector) - 1 bytes after the 15310 // last requested vector. The point of this is to avoid a page fault if 15311 // the base address happened to be aligned. This works because if the 15312 // base address is aligned, then adding less than a full vector length 15313 // will cause the last vector in the sequence to be (re)loaded. 15314 // Otherwise, the next vector will be fetched as you might suspect was 15315 // necessary. 15316 15317 // We might be able to reuse the permutation generation from 15318 // a different base address offset from this one by an aligned amount. 15319 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15320 // optimization later. 15321 Intrinsic::ID Intr, IntrLD, IntrPerm; 15322 MVT PermCntlTy, PermTy, LDTy; 15323 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15324 : Intrinsic::ppc_altivec_lvsl; 15325 IntrLD = Intrinsic::ppc_altivec_lvx; 15326 IntrPerm = Intrinsic::ppc_altivec_vperm; 15327 PermCntlTy = MVT::v16i8; 15328 PermTy = MVT::v4i32; 15329 LDTy = MVT::v4i32; 15330 15331 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15332 15333 // Create the new MMO for the new base load. It is like the original MMO, 15334 // but represents an area in memory almost twice the vector size centered 15335 // on the original address. If the address is unaligned, we might start 15336 // reading up to (sizeof(vector)-1) bytes below the address of the 15337 // original unaligned load. 15338 MachineFunction &MF = DAG.getMachineFunction(); 15339 MachineMemOperand *BaseMMO = 15340 MF.getMachineMemOperand(LD->getMemOperand(), 15341 -(long)MemVT.getStoreSize()+1, 15342 2*MemVT.getStoreSize()-1); 15343 15344 // Create the new base load. 15345 SDValue LDXIntID = 15346 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15347 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15348 SDValue BaseLoad = 15349 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15350 DAG.getVTList(PermTy, MVT::Other), 15351 BaseLoadOps, LDTy, BaseMMO); 15352 15353 // Note that the value of IncOffset (which is provided to the next 15354 // load's pointer info offset value, and thus used to calculate the 15355 // alignment), and the value of IncValue (which is actually used to 15356 // increment the pointer value) are different! This is because we 15357 // require the next load to appear to be aligned, even though it 15358 // is actually offset from the base pointer by a lesser amount. 15359 int IncOffset = VT.getSizeInBits() / 8; 15360 int IncValue = IncOffset; 15361 15362 // Walk (both up and down) the chain looking for another load at the real 15363 // (aligned) offset (the alignment of the other load does not matter in 15364 // this case). If found, then do not use the offset reduction trick, as 15365 // that will prevent the loads from being later combined (as they would 15366 // otherwise be duplicates). 15367 if (!findConsecutiveLoad(LD, DAG)) 15368 --IncValue; 15369 15370 SDValue Increment = 15371 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15372 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15373 15374 MachineMemOperand *ExtraMMO = 15375 MF.getMachineMemOperand(LD->getMemOperand(), 15376 1, 2*MemVT.getStoreSize()-1); 15377 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15378 SDValue ExtraLoad = 15379 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15380 DAG.getVTList(PermTy, MVT::Other), 15381 ExtraLoadOps, LDTy, ExtraMMO); 15382 15383 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15384 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15385 15386 // Because vperm has a big-endian bias, we must reverse the order 15387 // of the input vectors and complement the permute control vector 15388 // when generating little endian code. We have already handled the 15389 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15390 // and ExtraLoad here. 15391 SDValue Perm; 15392 if (isLittleEndian) 15393 Perm = BuildIntrinsicOp(IntrPerm, 15394 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15395 else 15396 Perm = BuildIntrinsicOp(IntrPerm, 15397 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15398 15399 if (VT != PermTy) 15400 Perm = Subtarget.hasAltivec() 15401 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15402 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15403 DAG.getTargetConstant(1, dl, MVT::i64)); 15404 // second argument is 1 because this rounding 15405 // is always exact. 15406 15407 // The output of the permutation is our loaded result, the TokenFactor is 15408 // our new chain. 15409 DCI.CombineTo(N, Perm, TF); 15410 return SDValue(N, 0); 15411 } 15412 } 15413 break; 15414 case ISD::INTRINSIC_WO_CHAIN: { 15415 bool isLittleEndian = Subtarget.isLittleEndian(); 15416 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15417 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15418 : Intrinsic::ppc_altivec_lvsl); 15419 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15420 SDValue Add = N->getOperand(1); 15421 15422 int Bits = 4 /* 16 byte alignment */; 15423 15424 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15425 APInt::getAllOnes(Bits /* alignment */) 15426 .zext(Add.getScalarValueSizeInBits()))) { 15427 SDNode *BasePtr = Add->getOperand(0).getNode(); 15428 for (SDNode *U : BasePtr->uses()) { 15429 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15430 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) { 15431 // We've found another LVSL/LVSR, and this address is an aligned 15432 // multiple of that one. The results will be the same, so use the 15433 // one we've just found instead. 15434 15435 return SDValue(U, 0); 15436 } 15437 } 15438 } 15439 15440 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15441 SDNode *BasePtr = Add->getOperand(0).getNode(); 15442 for (SDNode *U : BasePtr->uses()) { 15443 if (U->getOpcode() == ISD::ADD && 15444 isa<ConstantSDNode>(U->getOperand(1)) && 15445 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15446 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) % 15447 (1ULL << Bits) == 15448 0) { 15449 SDNode *OtherAdd = U; 15450 for (SDNode *V : OtherAdd->uses()) { 15451 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15452 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() == 15453 IID) { 15454 return SDValue(V, 0); 15455 } 15456 } 15457 } 15458 } 15459 } 15460 } 15461 15462 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15463 // Expose the vabsduw/h/b opportunity for down stream 15464 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15465 (IID == Intrinsic::ppc_altivec_vmaxsw || 15466 IID == Intrinsic::ppc_altivec_vmaxsh || 15467 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15468 SDValue V1 = N->getOperand(1); 15469 SDValue V2 = N->getOperand(2); 15470 if ((V1.getSimpleValueType() == MVT::v4i32 || 15471 V1.getSimpleValueType() == MVT::v8i16 || 15472 V1.getSimpleValueType() == MVT::v16i8) && 15473 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15474 // (0-a, a) 15475 if (V1.getOpcode() == ISD::SUB && 15476 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15477 V1.getOperand(1) == V2) { 15478 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15479 } 15480 // (a, 0-a) 15481 if (V2.getOpcode() == ISD::SUB && 15482 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15483 V2.getOperand(1) == V1) { 15484 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15485 } 15486 // (x-y, y-x) 15487 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15488 V1.getOperand(0) == V2.getOperand(1) && 15489 V1.getOperand(1) == V2.getOperand(0)) { 15490 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15491 } 15492 } 15493 } 15494 } 15495 15496 break; 15497 case ISD::INTRINSIC_W_CHAIN: 15498 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15499 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15500 if (Subtarget.needsSwapsForVSXMemOps()) { 15501 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15502 default: 15503 break; 15504 case Intrinsic::ppc_vsx_lxvw4x: 15505 case Intrinsic::ppc_vsx_lxvd2x: 15506 return expandVSXLoadForLE(N, DCI); 15507 } 15508 } 15509 break; 15510 case ISD::INTRINSIC_VOID: 15511 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15512 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15513 if (Subtarget.needsSwapsForVSXMemOps()) { 15514 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15515 default: 15516 break; 15517 case Intrinsic::ppc_vsx_stxvw4x: 15518 case Intrinsic::ppc_vsx_stxvd2x: 15519 return expandVSXStoreForLE(N, DCI); 15520 } 15521 } 15522 break; 15523 case ISD::BSWAP: { 15524 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15525 // For subtargets without LDBRX, we can still do better than the default 15526 // expansion even for 64-bit BSWAP (LOAD). 15527 bool Is64BitBswapOn64BitTgt = 15528 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64; 15529 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) && 15530 N->getOperand(0).hasOneUse(); 15531 if (IsSingleUseNormalLd && 15532 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15533 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) { 15534 SDValue Load = N->getOperand(0); 15535 LoadSDNode *LD = cast<LoadSDNode>(Load); 15536 // Create the byte-swapping load. 15537 SDValue Ops[] = { 15538 LD->getChain(), // Chain 15539 LD->getBasePtr(), // Ptr 15540 DAG.getValueType(N->getValueType(0)) // VT 15541 }; 15542 SDValue BSLoad = 15543 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15544 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15545 MVT::i64 : MVT::i32, MVT::Other), 15546 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15547 15548 // If this is an i16 load, insert the truncate. 15549 SDValue ResVal = BSLoad; 15550 if (N->getValueType(0) == MVT::i16) 15551 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15552 15553 // First, combine the bswap away. This makes the value produced by the 15554 // load dead. 15555 DCI.CombineTo(N, ResVal); 15556 15557 // Next, combine the load away, we give it a bogus result value but a real 15558 // chain result. The result value is dead because the bswap is dead. 15559 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15560 15561 // Return N so it doesn't get rechecked! 15562 return SDValue(N, 0); 15563 } 15564 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only 15565 // before legalization so that the BUILD_PAIR is handled correctly. 15566 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt || 15567 !IsSingleUseNormalLd) 15568 return SDValue(); 15569 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0)); 15570 15571 // Can't split volatile or atomic loads. 15572 if (!LD->isSimple()) 15573 return SDValue(); 15574 SDValue BasePtr = LD->getBasePtr(); 15575 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, 15576 LD->getPointerInfo(), LD->getAlignment()); 15577 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo); 15578 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15579 DAG.getIntPtrConstant(4, dl)); 15580 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand( 15581 LD->getMemOperand(), 4, 4); 15582 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO); 15583 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi); 15584 SDValue Res; 15585 if (Subtarget.isLittleEndian()) 15586 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo); 15587 else 15588 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 15589 SDValue TF = 15590 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15591 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1)); 15592 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF); 15593 return Res; 15594 } 15595 case PPCISD::VCMP: 15596 // If a VCMP_rec node already exists with exactly the same operands as this 15597 // node, use its result instead of this node (VCMP_rec computes both a CR6 15598 // and a normal output). 15599 // 15600 if (!N->getOperand(0).hasOneUse() && 15601 !N->getOperand(1).hasOneUse() && 15602 !N->getOperand(2).hasOneUse()) { 15603 15604 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15605 SDNode *VCMPrecNode = nullptr; 15606 15607 SDNode *LHSN = N->getOperand(0).getNode(); 15608 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15609 UI != E; ++UI) 15610 if (UI->getOpcode() == PPCISD::VCMP_rec && 15611 UI->getOperand(1) == N->getOperand(1) && 15612 UI->getOperand(2) == N->getOperand(2) && 15613 UI->getOperand(0) == N->getOperand(0)) { 15614 VCMPrecNode = *UI; 15615 break; 15616 } 15617 15618 // If there is no VCMP_rec node, or if the flag value has a single use, 15619 // don't transform this. 15620 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15621 break; 15622 15623 // Look at the (necessarily single) use of the flag value. If it has a 15624 // chain, this transformation is more complex. Note that multiple things 15625 // could use the value result, which we should ignore. 15626 SDNode *FlagUser = nullptr; 15627 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15628 FlagUser == nullptr; ++UI) { 15629 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15630 SDNode *User = *UI; 15631 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15632 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15633 FlagUser = User; 15634 break; 15635 } 15636 } 15637 } 15638 15639 // If the user is a MFOCRF instruction, we know this is safe. 15640 // Otherwise we give up for right now. 15641 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15642 return SDValue(VCMPrecNode, 0); 15643 } 15644 break; 15645 case ISD::BRCOND: { 15646 SDValue Cond = N->getOperand(1); 15647 SDValue Target = N->getOperand(2); 15648 15649 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15650 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15651 Intrinsic::loop_decrement) { 15652 15653 // We now need to make the intrinsic dead (it cannot be instruction 15654 // selected). 15655 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15656 assert(Cond.getNode()->hasOneUse() && 15657 "Counter decrement has more than one use"); 15658 15659 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15660 N->getOperand(0), Target); 15661 } 15662 } 15663 break; 15664 case ISD::BR_CC: { 15665 // If this is a branch on an altivec predicate comparison, lower this so 15666 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15667 // lowering is done pre-legalize, because the legalizer lowers the predicate 15668 // compare down to code that is difficult to reassemble. 15669 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15670 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15671 15672 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15673 // value. If so, pass-through the AND to get to the intrinsic. 15674 if (LHS.getOpcode() == ISD::AND && 15675 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15676 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15677 Intrinsic::loop_decrement && 15678 isa<ConstantSDNode>(LHS.getOperand(1)) && 15679 !isNullConstant(LHS.getOperand(1))) 15680 LHS = LHS.getOperand(0); 15681 15682 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15683 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15684 Intrinsic::loop_decrement && 15685 isa<ConstantSDNode>(RHS)) { 15686 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15687 "Counter decrement comparison is not EQ or NE"); 15688 15689 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15690 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15691 (CC == ISD::SETNE && !Val); 15692 15693 // We now need to make the intrinsic dead (it cannot be instruction 15694 // selected). 15695 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15696 assert(LHS.getNode()->hasOneUse() && 15697 "Counter decrement has more than one use"); 15698 15699 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15700 N->getOperand(0), N->getOperand(4)); 15701 } 15702 15703 int CompareOpc; 15704 bool isDot; 15705 15706 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15707 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15708 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15709 assert(isDot && "Can't compare against a vector result!"); 15710 15711 // If this is a comparison against something other than 0/1, then we know 15712 // that the condition is never/always true. 15713 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15714 if (Val != 0 && Val != 1) { 15715 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15716 return N->getOperand(0); 15717 // Always !=, turn it into an unconditional branch. 15718 return DAG.getNode(ISD::BR, dl, MVT::Other, 15719 N->getOperand(0), N->getOperand(4)); 15720 } 15721 15722 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15723 15724 // Create the PPCISD altivec 'dot' comparison node. 15725 SDValue Ops[] = { 15726 LHS.getOperand(2), // LHS of compare 15727 LHS.getOperand(3), // RHS of compare 15728 DAG.getConstant(CompareOpc, dl, MVT::i32) 15729 }; 15730 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15731 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15732 15733 // Unpack the result based on how the target uses it. 15734 PPC::Predicate CompOpc; 15735 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15736 default: // Can't happen, don't crash on invalid number though. 15737 case 0: // Branch on the value of the EQ bit of CR6. 15738 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15739 break; 15740 case 1: // Branch on the inverted value of the EQ bit of CR6. 15741 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15742 break; 15743 case 2: // Branch on the value of the LT bit of CR6. 15744 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15745 break; 15746 case 3: // Branch on the inverted value of the LT bit of CR6. 15747 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15748 break; 15749 } 15750 15751 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15752 DAG.getConstant(CompOpc, dl, MVT::i32), 15753 DAG.getRegister(PPC::CR6, MVT::i32), 15754 N->getOperand(4), CompNode.getValue(1)); 15755 } 15756 break; 15757 } 15758 case ISD::BUILD_VECTOR: 15759 return DAGCombineBuildVector(N, DCI); 15760 case ISD::ABS: 15761 return combineABS(N, DCI); 15762 case ISD::VSELECT: 15763 return combineVSelect(N, DCI); 15764 } 15765 15766 return SDValue(); 15767 } 15768 15769 SDValue 15770 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15771 SelectionDAG &DAG, 15772 SmallVectorImpl<SDNode *> &Created) const { 15773 // fold (sdiv X, pow2) 15774 EVT VT = N->getValueType(0); 15775 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15776 return SDValue(); 15777 if ((VT != MVT::i32 && VT != MVT::i64) || 15778 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2())) 15779 return SDValue(); 15780 15781 SDLoc DL(N); 15782 SDValue N0 = N->getOperand(0); 15783 15784 bool IsNegPow2 = Divisor.isNegatedPowerOf2(); 15785 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15786 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15787 15788 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15789 Created.push_back(Op.getNode()); 15790 15791 if (IsNegPow2) { 15792 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15793 Created.push_back(Op.getNode()); 15794 } 15795 15796 return Op; 15797 } 15798 15799 //===----------------------------------------------------------------------===// 15800 // Inline Assembly Support 15801 //===----------------------------------------------------------------------===// 15802 15803 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15804 KnownBits &Known, 15805 const APInt &DemandedElts, 15806 const SelectionDAG &DAG, 15807 unsigned Depth) const { 15808 Known.resetAll(); 15809 switch (Op.getOpcode()) { 15810 default: break; 15811 case PPCISD::LBRX: { 15812 // lhbrx is known to have the top bits cleared out. 15813 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15814 Known.Zero = 0xFFFF0000; 15815 break; 15816 } 15817 case ISD::INTRINSIC_WO_CHAIN: { 15818 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15819 default: break; 15820 case Intrinsic::ppc_altivec_vcmpbfp_p: 15821 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15822 case Intrinsic::ppc_altivec_vcmpequb_p: 15823 case Intrinsic::ppc_altivec_vcmpequh_p: 15824 case Intrinsic::ppc_altivec_vcmpequw_p: 15825 case Intrinsic::ppc_altivec_vcmpequd_p: 15826 case Intrinsic::ppc_altivec_vcmpequq_p: 15827 case Intrinsic::ppc_altivec_vcmpgefp_p: 15828 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15829 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15830 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15831 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15832 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15833 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15834 case Intrinsic::ppc_altivec_vcmpgtub_p: 15835 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15836 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15837 case Intrinsic::ppc_altivec_vcmpgtud_p: 15838 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15839 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15840 break; 15841 } 15842 break; 15843 } 15844 case ISD::INTRINSIC_W_CHAIN: { 15845 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 15846 default: 15847 break; 15848 case Intrinsic::ppc_load2r: 15849 // Top bits are cleared for load2r (which is the same as lhbrx). 15850 Known.Zero = 0xFFFF0000; 15851 break; 15852 } 15853 break; 15854 } 15855 } 15856 } 15857 15858 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15859 switch (Subtarget.getCPUDirective()) { 15860 default: break; 15861 case PPC::DIR_970: 15862 case PPC::DIR_PWR4: 15863 case PPC::DIR_PWR5: 15864 case PPC::DIR_PWR5X: 15865 case PPC::DIR_PWR6: 15866 case PPC::DIR_PWR6X: 15867 case PPC::DIR_PWR7: 15868 case PPC::DIR_PWR8: 15869 case PPC::DIR_PWR9: 15870 case PPC::DIR_PWR10: 15871 case PPC::DIR_PWR_FUTURE: { 15872 if (!ML) 15873 break; 15874 15875 if (!DisableInnermostLoopAlign32) { 15876 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15877 // so that we can decrease cache misses and branch-prediction misses. 15878 // Actual alignment of the loop will depend on the hotness check and other 15879 // logic in alignBlocks. 15880 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15881 return Align(32); 15882 } 15883 15884 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15885 15886 // For small loops (between 5 and 8 instructions), align to a 32-byte 15887 // boundary so that the entire loop fits in one instruction-cache line. 15888 uint64_t LoopSize = 0; 15889 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15890 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15891 LoopSize += TII->getInstSizeInBytes(*J); 15892 if (LoopSize > 32) 15893 break; 15894 } 15895 15896 if (LoopSize > 16 && LoopSize <= 32) 15897 return Align(32); 15898 15899 break; 15900 } 15901 } 15902 15903 return TargetLowering::getPrefLoopAlignment(ML); 15904 } 15905 15906 /// getConstraintType - Given a constraint, return the type of 15907 /// constraint it is for this target. 15908 PPCTargetLowering::ConstraintType 15909 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15910 if (Constraint.size() == 1) { 15911 switch (Constraint[0]) { 15912 default: break; 15913 case 'b': 15914 case 'r': 15915 case 'f': 15916 case 'd': 15917 case 'v': 15918 case 'y': 15919 return C_RegisterClass; 15920 case 'Z': 15921 // FIXME: While Z does indicate a memory constraint, it specifically 15922 // indicates an r+r address (used in conjunction with the 'y' modifier 15923 // in the replacement string). Currently, we're forcing the base 15924 // register to be r0 in the asm printer (which is interpreted as zero) 15925 // and forming the complete address in the second register. This is 15926 // suboptimal. 15927 return C_Memory; 15928 } 15929 } else if (Constraint == "wc") { // individual CR bits. 15930 return C_RegisterClass; 15931 } else if (Constraint == "wa" || Constraint == "wd" || 15932 Constraint == "wf" || Constraint == "ws" || 15933 Constraint == "wi" || Constraint == "ww") { 15934 return C_RegisterClass; // VSX registers. 15935 } 15936 return TargetLowering::getConstraintType(Constraint); 15937 } 15938 15939 /// Examine constraint type and operand type and determine a weight value. 15940 /// This object must already have been set up with the operand type 15941 /// and the current alternative constraint selected. 15942 TargetLowering::ConstraintWeight 15943 PPCTargetLowering::getSingleConstraintMatchWeight( 15944 AsmOperandInfo &info, const char *constraint) const { 15945 ConstraintWeight weight = CW_Invalid; 15946 Value *CallOperandVal = info.CallOperandVal; 15947 // If we don't have a value, we can't do a match, 15948 // but allow it at the lowest weight. 15949 if (!CallOperandVal) 15950 return CW_Default; 15951 Type *type = CallOperandVal->getType(); 15952 15953 // Look at the constraint type. 15954 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15955 return CW_Register; // an individual CR bit. 15956 else if ((StringRef(constraint) == "wa" || 15957 StringRef(constraint) == "wd" || 15958 StringRef(constraint) == "wf") && 15959 type->isVectorTy()) 15960 return CW_Register; 15961 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15962 return CW_Register; // just hold 64-bit integers data. 15963 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15964 return CW_Register; 15965 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15966 return CW_Register; 15967 15968 switch (*constraint) { 15969 default: 15970 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15971 break; 15972 case 'b': 15973 if (type->isIntegerTy()) 15974 weight = CW_Register; 15975 break; 15976 case 'f': 15977 if (type->isFloatTy()) 15978 weight = CW_Register; 15979 break; 15980 case 'd': 15981 if (type->isDoubleTy()) 15982 weight = CW_Register; 15983 break; 15984 case 'v': 15985 if (type->isVectorTy()) 15986 weight = CW_Register; 15987 break; 15988 case 'y': 15989 weight = CW_Register; 15990 break; 15991 case 'Z': 15992 weight = CW_Memory; 15993 break; 15994 } 15995 return weight; 15996 } 15997 15998 std::pair<unsigned, const TargetRegisterClass *> 15999 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 16000 StringRef Constraint, 16001 MVT VT) const { 16002 if (Constraint.size() == 1) { 16003 // GCC RS6000 Constraint Letters 16004 switch (Constraint[0]) { 16005 case 'b': // R1-R31 16006 if (VT == MVT::i64 && Subtarget.isPPC64()) 16007 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 16008 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 16009 case 'r': // R0-R31 16010 if (VT == MVT::i64 && Subtarget.isPPC64()) 16011 return std::make_pair(0U, &PPC::G8RCRegClass); 16012 return std::make_pair(0U, &PPC::GPRCRegClass); 16013 // 'd' and 'f' constraints are both defined to be "the floating point 16014 // registers", where one is for 32-bit and the other for 64-bit. We don't 16015 // really care overly much here so just give them all the same reg classes. 16016 case 'd': 16017 case 'f': 16018 if (Subtarget.hasSPE()) { 16019 if (VT == MVT::f32 || VT == MVT::i32) 16020 return std::make_pair(0U, &PPC::GPRCRegClass); 16021 if (VT == MVT::f64 || VT == MVT::i64) 16022 return std::make_pair(0U, &PPC::SPERCRegClass); 16023 } else { 16024 if (VT == MVT::f32 || VT == MVT::i32) 16025 return std::make_pair(0U, &PPC::F4RCRegClass); 16026 if (VT == MVT::f64 || VT == MVT::i64) 16027 return std::make_pair(0U, &PPC::F8RCRegClass); 16028 } 16029 break; 16030 case 'v': 16031 if (Subtarget.hasAltivec() && VT.isVector()) 16032 return std::make_pair(0U, &PPC::VRRCRegClass); 16033 else if (Subtarget.hasVSX()) 16034 // Scalars in Altivec registers only make sense with VSX. 16035 return std::make_pair(0U, &PPC::VFRCRegClass); 16036 break; 16037 case 'y': // crrc 16038 return std::make_pair(0U, &PPC::CRRCRegClass); 16039 } 16040 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 16041 // An individual CR bit. 16042 return std::make_pair(0U, &PPC::CRBITRCRegClass); 16043 } else if ((Constraint == "wa" || Constraint == "wd" || 16044 Constraint == "wf" || Constraint == "wi") && 16045 Subtarget.hasVSX()) { 16046 // A VSX register for either a scalar (FP) or vector. There is no 16047 // support for single precision scalars on subtargets prior to Power8. 16048 if (VT.isVector()) 16049 return std::make_pair(0U, &PPC::VSRCRegClass); 16050 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16051 return std::make_pair(0U, &PPC::VSSRCRegClass); 16052 return std::make_pair(0U, &PPC::VSFRCRegClass); 16053 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 16054 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16055 return std::make_pair(0U, &PPC::VSSRCRegClass); 16056 else 16057 return std::make_pair(0U, &PPC::VSFRCRegClass); 16058 } else if (Constraint == "lr") { 16059 if (VT == MVT::i64) 16060 return std::make_pair(0U, &PPC::LR8RCRegClass); 16061 else 16062 return std::make_pair(0U, &PPC::LRRCRegClass); 16063 } 16064 16065 // Handle special cases of physical registers that are not properly handled 16066 // by the base class. 16067 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 16068 // If we name a VSX register, we can't defer to the base class because it 16069 // will not recognize the correct register (their names will be VSL{0-31} 16070 // and V{0-31} so they won't match). So we match them here. 16071 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 16072 int VSNum = atoi(Constraint.data() + 3); 16073 assert(VSNum >= 0 && VSNum <= 63 && 16074 "Attempted to access a vsr out of range"); 16075 if (VSNum < 32) 16076 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 16077 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 16078 } 16079 16080 // For float registers, we can't defer to the base class as it will match 16081 // the SPILLTOVSRRC class. 16082 if (Constraint.size() > 3 && Constraint[1] == 'f') { 16083 int RegNum = atoi(Constraint.data() + 2); 16084 if (RegNum > 31 || RegNum < 0) 16085 report_fatal_error("Invalid floating point register number"); 16086 if (VT == MVT::f32 || VT == MVT::i32) 16087 return Subtarget.hasSPE() 16088 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 16089 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 16090 if (VT == MVT::f64 || VT == MVT::i64) 16091 return Subtarget.hasSPE() 16092 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 16093 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 16094 } 16095 } 16096 16097 std::pair<unsigned, const TargetRegisterClass *> R = 16098 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16099 16100 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 16101 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 16102 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 16103 // register. 16104 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 16105 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 16106 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 16107 PPC::GPRCRegClass.contains(R.first)) 16108 return std::make_pair(TRI->getMatchingSuperReg(R.first, 16109 PPC::sub_32, &PPC::G8RCRegClass), 16110 &PPC::G8RCRegClass); 16111 16112 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 16113 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) { 16114 R.first = PPC::CR0; 16115 R.second = &PPC::CRRCRegClass; 16116 } 16117 // FIXME: This warning should ideally be emitted in the front end. 16118 const auto &TM = getTargetMachine(); 16119 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 16120 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 16121 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 16122 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 16123 errs() << "warning: vector registers 20 to 32 are reserved in the " 16124 "default AIX AltiVec ABI and cannot be used\n"; 16125 } 16126 16127 return R; 16128 } 16129 16130 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16131 /// vector. If it is invalid, don't add anything to Ops. 16132 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16133 std::string &Constraint, 16134 std::vector<SDValue>&Ops, 16135 SelectionDAG &DAG) const { 16136 SDValue Result; 16137 16138 // Only support length 1 constraints. 16139 if (Constraint.length() > 1) return; 16140 16141 char Letter = Constraint[0]; 16142 switch (Letter) { 16143 default: break; 16144 case 'I': 16145 case 'J': 16146 case 'K': 16147 case 'L': 16148 case 'M': 16149 case 'N': 16150 case 'O': 16151 case 'P': { 16152 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 16153 if (!CST) return; // Must be an immediate to match. 16154 SDLoc dl(Op); 16155 int64_t Value = CST->getSExtValue(); 16156 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 16157 // numbers are printed as such. 16158 switch (Letter) { 16159 default: llvm_unreachable("Unknown constraint letter!"); 16160 case 'I': // "I" is a signed 16-bit constant. 16161 if (isInt<16>(Value)) 16162 Result = DAG.getTargetConstant(Value, dl, TCVT); 16163 break; 16164 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 16165 if (isShiftedUInt<16, 16>(Value)) 16166 Result = DAG.getTargetConstant(Value, dl, TCVT); 16167 break; 16168 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 16169 if (isShiftedInt<16, 16>(Value)) 16170 Result = DAG.getTargetConstant(Value, dl, TCVT); 16171 break; 16172 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 16173 if (isUInt<16>(Value)) 16174 Result = DAG.getTargetConstant(Value, dl, TCVT); 16175 break; 16176 case 'M': // "M" is a constant that is greater than 31. 16177 if (Value > 31) 16178 Result = DAG.getTargetConstant(Value, dl, TCVT); 16179 break; 16180 case 'N': // "N" is a positive constant that is an exact power of two. 16181 if (Value > 0 && isPowerOf2_64(Value)) 16182 Result = DAG.getTargetConstant(Value, dl, TCVT); 16183 break; 16184 case 'O': // "O" is the constant zero. 16185 if (Value == 0) 16186 Result = DAG.getTargetConstant(Value, dl, TCVT); 16187 break; 16188 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 16189 if (isInt<16>(-Value)) 16190 Result = DAG.getTargetConstant(Value, dl, TCVT); 16191 break; 16192 } 16193 break; 16194 } 16195 } 16196 16197 if (Result.getNode()) { 16198 Ops.push_back(Result); 16199 return; 16200 } 16201 16202 // Handle standard constraint letters. 16203 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16204 } 16205 16206 // isLegalAddressingMode - Return true if the addressing mode represented 16207 // by AM is legal for this target, for a load/store of the specified type. 16208 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16209 const AddrMode &AM, Type *Ty, 16210 unsigned AS, 16211 Instruction *I) const { 16212 // Vector type r+i form is supported since power9 as DQ form. We don't check 16213 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 16214 // imm form is preferred and the offset can be adjusted to use imm form later 16215 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 16216 // max offset to check legal addressing mode, we should be a little aggressive 16217 // to contain other offsets for that LSRUse. 16218 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 16219 return false; 16220 16221 // PPC allows a sign-extended 16-bit immediate field. 16222 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 16223 return false; 16224 16225 // No global is ever allowed as a base. 16226 if (AM.BaseGV) 16227 return false; 16228 16229 // PPC only support r+r, 16230 switch (AM.Scale) { 16231 case 0: // "r+i" or just "i", depending on HasBaseReg. 16232 break; 16233 case 1: 16234 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 16235 return false; 16236 // Otherwise we have r+r or r+i. 16237 break; 16238 case 2: 16239 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 16240 return false; 16241 // Allow 2*r as r+r. 16242 break; 16243 default: 16244 // No other scales are supported. 16245 return false; 16246 } 16247 16248 return true; 16249 } 16250 16251 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 16252 SelectionDAG &DAG) const { 16253 MachineFunction &MF = DAG.getMachineFunction(); 16254 MachineFrameInfo &MFI = MF.getFrameInfo(); 16255 MFI.setReturnAddressIsTaken(true); 16256 16257 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 16258 return SDValue(); 16259 16260 SDLoc dl(Op); 16261 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16262 16263 // Make sure the function does not optimize away the store of the RA to 16264 // the stack. 16265 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 16266 FuncInfo->setLRStoreRequired(); 16267 bool isPPC64 = Subtarget.isPPC64(); 16268 auto PtrVT = getPointerTy(MF.getDataLayout()); 16269 16270 if (Depth > 0) { 16271 // The link register (return address) is saved in the caller's frame 16272 // not the callee's stack frame. So we must get the caller's frame 16273 // address and load the return address at the LR offset from there. 16274 SDValue FrameAddr = 16275 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16276 LowerFRAMEADDR(Op, DAG), MachinePointerInfo()); 16277 SDValue Offset = 16278 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 16279 isPPC64 ? MVT::i64 : MVT::i32); 16280 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 16281 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 16282 MachinePointerInfo()); 16283 } 16284 16285 // Just load the return address off the stack. 16286 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 16287 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 16288 MachinePointerInfo()); 16289 } 16290 16291 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 16292 SelectionDAG &DAG) const { 16293 SDLoc dl(Op); 16294 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16295 16296 MachineFunction &MF = DAG.getMachineFunction(); 16297 MachineFrameInfo &MFI = MF.getFrameInfo(); 16298 MFI.setFrameAddressIsTaken(true); 16299 16300 EVT PtrVT = getPointerTy(MF.getDataLayout()); 16301 bool isPPC64 = PtrVT == MVT::i64; 16302 16303 // Naked functions never have a frame pointer, and so we use r1. For all 16304 // other functions, this decision must be delayed until during PEI. 16305 unsigned FrameReg; 16306 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 16307 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 16308 else 16309 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 16310 16311 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 16312 PtrVT); 16313 while (Depth--) 16314 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16315 FrameAddr, MachinePointerInfo()); 16316 return FrameAddr; 16317 } 16318 16319 // FIXME? Maybe this could be a TableGen attribute on some registers and 16320 // this table could be generated automatically from RegInfo. 16321 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 16322 const MachineFunction &MF) const { 16323 bool isPPC64 = Subtarget.isPPC64(); 16324 16325 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 16326 if (!is64Bit && VT != LLT::scalar(32)) 16327 report_fatal_error("Invalid register global variable type"); 16328 16329 Register Reg = StringSwitch<Register>(RegName) 16330 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16331 .Case("r2", isPPC64 ? Register() : PPC::R2) 16332 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16333 .Default(Register()); 16334 16335 if (Reg) 16336 return Reg; 16337 report_fatal_error("Invalid register name global variable"); 16338 } 16339 16340 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16341 // 32-bit SVR4 ABI access everything as got-indirect. 16342 if (Subtarget.is32BitELFABI()) 16343 return true; 16344 16345 // AIX accesses everything indirectly through the TOC, which is similar to 16346 // the GOT. 16347 if (Subtarget.isAIXABI()) 16348 return true; 16349 16350 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16351 // If it is small or large code model, module locals are accessed 16352 // indirectly by loading their address from .toc/.got. 16353 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16354 return true; 16355 16356 // JumpTable and BlockAddress are accessed as got-indirect. 16357 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16358 return true; 16359 16360 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16361 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16362 16363 return false; 16364 } 16365 16366 bool 16367 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16368 // The PowerPC target isn't yet aware of offsets. 16369 return false; 16370 } 16371 16372 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16373 const CallInst &I, 16374 MachineFunction &MF, 16375 unsigned Intrinsic) const { 16376 switch (Intrinsic) { 16377 case Intrinsic::ppc_atomicrmw_xchg_i128: 16378 case Intrinsic::ppc_atomicrmw_add_i128: 16379 case Intrinsic::ppc_atomicrmw_sub_i128: 16380 case Intrinsic::ppc_atomicrmw_nand_i128: 16381 case Intrinsic::ppc_atomicrmw_and_i128: 16382 case Intrinsic::ppc_atomicrmw_or_i128: 16383 case Intrinsic::ppc_atomicrmw_xor_i128: 16384 case Intrinsic::ppc_cmpxchg_i128: 16385 Info.opc = ISD::INTRINSIC_W_CHAIN; 16386 Info.memVT = MVT::i128; 16387 Info.ptrVal = I.getArgOperand(0); 16388 Info.offset = 0; 16389 Info.align = Align(16); 16390 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 16391 MachineMemOperand::MOVolatile; 16392 return true; 16393 case Intrinsic::ppc_atomic_load_i128: 16394 Info.opc = ISD::INTRINSIC_W_CHAIN; 16395 Info.memVT = MVT::i128; 16396 Info.ptrVal = I.getArgOperand(0); 16397 Info.offset = 0; 16398 Info.align = Align(16); 16399 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16400 return true; 16401 case Intrinsic::ppc_atomic_store_i128: 16402 Info.opc = ISD::INTRINSIC_VOID; 16403 Info.memVT = MVT::i128; 16404 Info.ptrVal = I.getArgOperand(2); 16405 Info.offset = 0; 16406 Info.align = Align(16); 16407 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16408 return true; 16409 case Intrinsic::ppc_altivec_lvx: 16410 case Intrinsic::ppc_altivec_lvxl: 16411 case Intrinsic::ppc_altivec_lvebx: 16412 case Intrinsic::ppc_altivec_lvehx: 16413 case Intrinsic::ppc_altivec_lvewx: 16414 case Intrinsic::ppc_vsx_lxvd2x: 16415 case Intrinsic::ppc_vsx_lxvw4x: 16416 case Intrinsic::ppc_vsx_lxvd2x_be: 16417 case Intrinsic::ppc_vsx_lxvw4x_be: 16418 case Intrinsic::ppc_vsx_lxvl: 16419 case Intrinsic::ppc_vsx_lxvll: { 16420 EVT VT; 16421 switch (Intrinsic) { 16422 case Intrinsic::ppc_altivec_lvebx: 16423 VT = MVT::i8; 16424 break; 16425 case Intrinsic::ppc_altivec_lvehx: 16426 VT = MVT::i16; 16427 break; 16428 case Intrinsic::ppc_altivec_lvewx: 16429 VT = MVT::i32; 16430 break; 16431 case Intrinsic::ppc_vsx_lxvd2x: 16432 case Intrinsic::ppc_vsx_lxvd2x_be: 16433 VT = MVT::v2f64; 16434 break; 16435 default: 16436 VT = MVT::v4i32; 16437 break; 16438 } 16439 16440 Info.opc = ISD::INTRINSIC_W_CHAIN; 16441 Info.memVT = VT; 16442 Info.ptrVal = I.getArgOperand(0); 16443 Info.offset = -VT.getStoreSize()+1; 16444 Info.size = 2*VT.getStoreSize()-1; 16445 Info.align = Align(1); 16446 Info.flags = MachineMemOperand::MOLoad; 16447 return true; 16448 } 16449 case Intrinsic::ppc_altivec_stvx: 16450 case Intrinsic::ppc_altivec_stvxl: 16451 case Intrinsic::ppc_altivec_stvebx: 16452 case Intrinsic::ppc_altivec_stvehx: 16453 case Intrinsic::ppc_altivec_stvewx: 16454 case Intrinsic::ppc_vsx_stxvd2x: 16455 case Intrinsic::ppc_vsx_stxvw4x: 16456 case Intrinsic::ppc_vsx_stxvd2x_be: 16457 case Intrinsic::ppc_vsx_stxvw4x_be: 16458 case Intrinsic::ppc_vsx_stxvl: 16459 case Intrinsic::ppc_vsx_stxvll: { 16460 EVT VT; 16461 switch (Intrinsic) { 16462 case Intrinsic::ppc_altivec_stvebx: 16463 VT = MVT::i8; 16464 break; 16465 case Intrinsic::ppc_altivec_stvehx: 16466 VT = MVT::i16; 16467 break; 16468 case Intrinsic::ppc_altivec_stvewx: 16469 VT = MVT::i32; 16470 break; 16471 case Intrinsic::ppc_vsx_stxvd2x: 16472 case Intrinsic::ppc_vsx_stxvd2x_be: 16473 VT = MVT::v2f64; 16474 break; 16475 default: 16476 VT = MVT::v4i32; 16477 break; 16478 } 16479 16480 Info.opc = ISD::INTRINSIC_VOID; 16481 Info.memVT = VT; 16482 Info.ptrVal = I.getArgOperand(1); 16483 Info.offset = -VT.getStoreSize()+1; 16484 Info.size = 2*VT.getStoreSize()-1; 16485 Info.align = Align(1); 16486 Info.flags = MachineMemOperand::MOStore; 16487 return true; 16488 } 16489 default: 16490 break; 16491 } 16492 16493 return false; 16494 } 16495 16496 /// It returns EVT::Other if the type should be determined using generic 16497 /// target-independent logic. 16498 EVT PPCTargetLowering::getOptimalMemOpType( 16499 const MemOp &Op, const AttributeList &FuncAttributes) const { 16500 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16501 // We should use Altivec/VSX loads and stores when available. For unaligned 16502 // addresses, unaligned VSX loads are only fast starting with the P8. 16503 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16504 (Op.isAligned(Align(16)) || 16505 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16506 return MVT::v4i32; 16507 } 16508 16509 if (Subtarget.isPPC64()) { 16510 return MVT::i64; 16511 } 16512 16513 return MVT::i32; 16514 } 16515 16516 /// Returns true if it is beneficial to convert a load of a constant 16517 /// to just the constant itself. 16518 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16519 Type *Ty) const { 16520 assert(Ty->isIntegerTy()); 16521 16522 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16523 return !(BitSize == 0 || BitSize > 64); 16524 } 16525 16526 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16527 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16528 return false; 16529 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16530 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16531 return NumBits1 == 64 && NumBits2 == 32; 16532 } 16533 16534 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16535 if (!VT1.isInteger() || !VT2.isInteger()) 16536 return false; 16537 unsigned NumBits1 = VT1.getSizeInBits(); 16538 unsigned NumBits2 = VT2.getSizeInBits(); 16539 return NumBits1 == 64 && NumBits2 == 32; 16540 } 16541 16542 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16543 // Generally speaking, zexts are not free, but they are free when they can be 16544 // folded with other operations. 16545 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16546 EVT MemVT = LD->getMemoryVT(); 16547 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16548 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16549 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16550 LD->getExtensionType() == ISD::ZEXTLOAD)) 16551 return true; 16552 } 16553 16554 // FIXME: Add other cases... 16555 // - 32-bit shifts with a zext to i64 16556 // - zext after ctlz, bswap, etc. 16557 // - zext after and by a constant mask 16558 16559 return TargetLowering::isZExtFree(Val, VT2); 16560 } 16561 16562 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16563 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16564 "invalid fpext types"); 16565 // Extending to float128 is not free. 16566 if (DestVT == MVT::f128) 16567 return false; 16568 return true; 16569 } 16570 16571 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16572 return isInt<16>(Imm) || isUInt<16>(Imm); 16573 } 16574 16575 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16576 return isInt<16>(Imm) || isUInt<16>(Imm); 16577 } 16578 16579 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16580 MachineMemOperand::Flags, 16581 bool *Fast) const { 16582 if (DisablePPCUnaligned) 16583 return false; 16584 16585 // PowerPC supports unaligned memory access for simple non-vector types. 16586 // Although accessing unaligned addresses is not as efficient as accessing 16587 // aligned addresses, it is generally more efficient than manual expansion, 16588 // and generally only traps for software emulation when crossing page 16589 // boundaries. 16590 16591 if (!VT.isSimple()) 16592 return false; 16593 16594 if (VT.isFloatingPoint() && !VT.isVector() && 16595 !Subtarget.allowsUnalignedFPAccess()) 16596 return false; 16597 16598 if (VT.getSimpleVT().isVector()) { 16599 if (Subtarget.hasVSX()) { 16600 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16601 VT != MVT::v4f32 && VT != MVT::v4i32) 16602 return false; 16603 } else { 16604 return false; 16605 } 16606 } 16607 16608 if (VT == MVT::ppcf128) 16609 return false; 16610 16611 if (Fast) 16612 *Fast = true; 16613 16614 return true; 16615 } 16616 16617 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16618 SDValue C) const { 16619 // Check integral scalar types. 16620 if (!VT.isScalarInteger()) 16621 return false; 16622 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16623 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16624 return false; 16625 // This transformation will generate >= 2 operations. But the following 16626 // cases will generate <= 2 instructions during ISEL. So exclude them. 16627 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16628 // HW instruction, ie. MULLI 16629 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16630 // instruction is needed than case 1, ie. MULLI and RLDICR 16631 int64_t Imm = ConstNode->getSExtValue(); 16632 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16633 Imm >>= Shift; 16634 if (isInt<16>(Imm)) 16635 return false; 16636 uint64_t UImm = static_cast<uint64_t>(Imm); 16637 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16638 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16639 return true; 16640 } 16641 return false; 16642 } 16643 16644 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16645 EVT VT) const { 16646 return isFMAFasterThanFMulAndFAdd( 16647 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16648 } 16649 16650 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16651 Type *Ty) const { 16652 switch (Ty->getScalarType()->getTypeID()) { 16653 case Type::FloatTyID: 16654 case Type::DoubleTyID: 16655 return true; 16656 case Type::FP128TyID: 16657 return Subtarget.hasP9Vector(); 16658 default: 16659 return false; 16660 } 16661 } 16662 16663 // FIXME: add more patterns which are not profitable to hoist. 16664 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16665 if (!I->hasOneUse()) 16666 return true; 16667 16668 Instruction *User = I->user_back(); 16669 assert(User && "A single use instruction with no uses."); 16670 16671 switch (I->getOpcode()) { 16672 case Instruction::FMul: { 16673 // Don't break FMA, PowerPC prefers FMA. 16674 if (User->getOpcode() != Instruction::FSub && 16675 User->getOpcode() != Instruction::FAdd) 16676 return true; 16677 16678 const TargetOptions &Options = getTargetMachine().Options; 16679 const Function *F = I->getFunction(); 16680 const DataLayout &DL = F->getParent()->getDataLayout(); 16681 Type *Ty = User->getOperand(0)->getType(); 16682 16683 return !( 16684 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16685 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16686 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16687 } 16688 case Instruction::Load: { 16689 // Don't break "store (load float*)" pattern, this pattern will be combined 16690 // to "store (load int32)" in later InstCombine pass. See function 16691 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16692 // cycles than loading a 32 bit integer. 16693 LoadInst *LI = cast<LoadInst>(I); 16694 // For the loads that combineLoadToOperationType does nothing, like 16695 // ordered load, it should be profitable to hoist them. 16696 // For swifterror load, it can only be used for pointer to pointer type, so 16697 // later type check should get rid of this case. 16698 if (!LI->isUnordered()) 16699 return true; 16700 16701 if (User->getOpcode() != Instruction::Store) 16702 return true; 16703 16704 if (I->getType()->getTypeID() != Type::FloatTyID) 16705 return true; 16706 16707 return false; 16708 } 16709 default: 16710 return true; 16711 } 16712 return true; 16713 } 16714 16715 const MCPhysReg * 16716 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16717 // LR is a callee-save register, but we must treat it as clobbered by any call 16718 // site. Hence we include LR in the scratch registers, which are in turn added 16719 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16720 // to CTR, which is used by any indirect call. 16721 static const MCPhysReg ScratchRegs[] = { 16722 PPC::X12, PPC::LR8, PPC::CTR8, 0 16723 }; 16724 16725 return ScratchRegs; 16726 } 16727 16728 Register PPCTargetLowering::getExceptionPointerRegister( 16729 const Constant *PersonalityFn) const { 16730 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16731 } 16732 16733 Register PPCTargetLowering::getExceptionSelectorRegister( 16734 const Constant *PersonalityFn) const { 16735 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16736 } 16737 16738 bool 16739 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16740 EVT VT , unsigned DefinedValues) const { 16741 if (VT == MVT::v2i64) 16742 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16743 16744 if (Subtarget.hasVSX()) 16745 return true; 16746 16747 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16748 } 16749 16750 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16751 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16752 return TargetLowering::getSchedulingPreference(N); 16753 16754 return Sched::ILP; 16755 } 16756 16757 // Create a fast isel object. 16758 FastISel * 16759 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16760 const TargetLibraryInfo *LibInfo) const { 16761 return PPC::createFastISel(FuncInfo, LibInfo); 16762 } 16763 16764 // 'Inverted' means the FMA opcode after negating one multiplicand. 16765 // For example, (fma -a b c) = (fnmsub a b c) 16766 static unsigned invertFMAOpcode(unsigned Opc) { 16767 switch (Opc) { 16768 default: 16769 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16770 case ISD::FMA: 16771 return PPCISD::FNMSUB; 16772 case PPCISD::FNMSUB: 16773 return ISD::FMA; 16774 } 16775 } 16776 16777 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16778 bool LegalOps, bool OptForSize, 16779 NegatibleCost &Cost, 16780 unsigned Depth) const { 16781 if (Depth > SelectionDAG::MaxRecursionDepth) 16782 return SDValue(); 16783 16784 unsigned Opc = Op.getOpcode(); 16785 EVT VT = Op.getValueType(); 16786 SDNodeFlags Flags = Op.getNode()->getFlags(); 16787 16788 switch (Opc) { 16789 case PPCISD::FNMSUB: 16790 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16791 break; 16792 16793 const TargetOptions &Options = getTargetMachine().Options; 16794 SDValue N0 = Op.getOperand(0); 16795 SDValue N1 = Op.getOperand(1); 16796 SDValue N2 = Op.getOperand(2); 16797 SDLoc Loc(Op); 16798 16799 NegatibleCost N2Cost = NegatibleCost::Expensive; 16800 SDValue NegN2 = 16801 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16802 16803 if (!NegN2) 16804 return SDValue(); 16805 16806 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16807 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16808 // These transformations may change sign of zeroes. For example, 16809 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16810 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16811 // Try and choose the cheaper one to negate. 16812 NegatibleCost N0Cost = NegatibleCost::Expensive; 16813 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16814 N0Cost, Depth + 1); 16815 16816 NegatibleCost N1Cost = NegatibleCost::Expensive; 16817 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16818 N1Cost, Depth + 1); 16819 16820 if (NegN0 && N0Cost <= N1Cost) { 16821 Cost = std::min(N0Cost, N2Cost); 16822 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16823 } else if (NegN1) { 16824 Cost = std::min(N1Cost, N2Cost); 16825 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16826 } 16827 } 16828 16829 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16830 if (isOperationLegal(ISD::FMA, VT)) { 16831 Cost = N2Cost; 16832 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16833 } 16834 16835 break; 16836 } 16837 16838 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16839 Cost, Depth); 16840 } 16841 16842 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16843 bool PPCTargetLowering::useLoadStackGuardNode() const { 16844 if (!Subtarget.isTargetLinux()) 16845 return TargetLowering::useLoadStackGuardNode(); 16846 return true; 16847 } 16848 16849 // Override to disable global variable loading on Linux and insert AIX canary 16850 // word declaration. 16851 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16852 if (Subtarget.isAIXABI()) { 16853 M.getOrInsertGlobal(AIXSSPCanaryWordName, 16854 Type::getInt8PtrTy(M.getContext())); 16855 return; 16856 } 16857 if (!Subtarget.isTargetLinux()) 16858 return TargetLowering::insertSSPDeclarations(M); 16859 } 16860 16861 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 16862 if (Subtarget.isAIXABI()) 16863 return M.getGlobalVariable(AIXSSPCanaryWordName); 16864 return TargetLowering::getSDagStackGuard(M); 16865 } 16866 16867 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16868 bool ForCodeSize) const { 16869 if (!VT.isSimple() || !Subtarget.hasVSX()) 16870 return false; 16871 16872 switch(VT.getSimpleVT().SimpleTy) { 16873 default: 16874 // For FP types that are currently not supported by PPC backend, return 16875 // false. Examples: f16, f80. 16876 return false; 16877 case MVT::f32: 16878 case MVT::f64: 16879 if (Subtarget.hasPrefixInstrs()) { 16880 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16881 return true; 16882 } 16883 LLVM_FALLTHROUGH; 16884 case MVT::ppcf128: 16885 return Imm.isPosZero(); 16886 } 16887 } 16888 16889 // For vector shift operation op, fold 16890 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16891 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16892 SelectionDAG &DAG) { 16893 SDValue N0 = N->getOperand(0); 16894 SDValue N1 = N->getOperand(1); 16895 EVT VT = N0.getValueType(); 16896 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16897 unsigned Opcode = N->getOpcode(); 16898 unsigned TargetOpcode; 16899 16900 switch (Opcode) { 16901 default: 16902 llvm_unreachable("Unexpected shift operation"); 16903 case ISD::SHL: 16904 TargetOpcode = PPCISD::SHL; 16905 break; 16906 case ISD::SRL: 16907 TargetOpcode = PPCISD::SRL; 16908 break; 16909 case ISD::SRA: 16910 TargetOpcode = PPCISD::SRA; 16911 break; 16912 } 16913 16914 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16915 N1->getOpcode() == ISD::AND) 16916 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16917 if (Mask->getZExtValue() == OpSizeInBits - 1) 16918 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16919 16920 return SDValue(); 16921 } 16922 16923 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16924 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16925 return Value; 16926 16927 SDValue N0 = N->getOperand(0); 16928 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16929 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16930 N0.getOpcode() != ISD::SIGN_EXTEND || 16931 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16932 N->getValueType(0) != MVT::i64) 16933 return SDValue(); 16934 16935 // We can't save an operation here if the value is already extended, and 16936 // the existing shift is easier to combine. 16937 SDValue ExtsSrc = N0.getOperand(0); 16938 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16939 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16940 return SDValue(); 16941 16942 SDLoc DL(N0); 16943 SDValue ShiftBy = SDValue(CN1, 0); 16944 // We want the shift amount to be i32 on the extswli, but the shift could 16945 // have an i64. 16946 if (ShiftBy.getValueType() == MVT::i64) 16947 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16948 16949 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16950 ShiftBy); 16951 } 16952 16953 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16954 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16955 return Value; 16956 16957 return SDValue(); 16958 } 16959 16960 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16961 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16962 return Value; 16963 16964 return SDValue(); 16965 } 16966 16967 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16968 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16969 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16970 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16971 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16972 const PPCSubtarget &Subtarget) { 16973 if (!Subtarget.isPPC64()) 16974 return SDValue(); 16975 16976 SDValue LHS = N->getOperand(0); 16977 SDValue RHS = N->getOperand(1); 16978 16979 auto isZextOfCompareWithConstant = [](SDValue Op) { 16980 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16981 Op.getValueType() != MVT::i64) 16982 return false; 16983 16984 SDValue Cmp = Op.getOperand(0); 16985 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16986 Cmp.getOperand(0).getValueType() != MVT::i64) 16987 return false; 16988 16989 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16990 int64_t NegConstant = 0 - Constant->getSExtValue(); 16991 // Due to the limitations of the addi instruction, 16992 // -C is required to be [-32768, 32767]. 16993 return isInt<16>(NegConstant); 16994 } 16995 16996 return false; 16997 }; 16998 16999 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 17000 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 17001 17002 // If there is a pattern, canonicalize a zext operand to the RHS. 17003 if (LHSHasPattern && !RHSHasPattern) 17004 std::swap(LHS, RHS); 17005 else if (!LHSHasPattern && !RHSHasPattern) 17006 return SDValue(); 17007 17008 SDLoc DL(N); 17009 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 17010 SDValue Cmp = RHS.getOperand(0); 17011 SDValue Z = Cmp.getOperand(0); 17012 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 17013 int64_t NegConstant = 0 - Constant->getSExtValue(); 17014 17015 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 17016 default: break; 17017 case ISD::SETNE: { 17018 // when C == 0 17019 // --> addze X, (addic Z, -1).carry 17020 // / 17021 // add X, (zext(setne Z, C))-- 17022 // \ when -32768 <= -C <= 32767 && C != 0 17023 // --> addze X, (addic (addi Z, -C), -1).carry 17024 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17025 DAG.getConstant(NegConstant, DL, MVT::i64)); 17026 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17027 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17028 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 17029 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17030 SDValue(Addc.getNode(), 1)); 17031 } 17032 case ISD::SETEQ: { 17033 // when C == 0 17034 // --> addze X, (subfic Z, 0).carry 17035 // / 17036 // add X, (zext(sete Z, C))-- 17037 // \ when -32768 <= -C <= 32767 && C != 0 17038 // --> addze X, (subfic (addi Z, -C), 0).carry 17039 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17040 DAG.getConstant(NegConstant, DL, MVT::i64)); 17041 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17042 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17043 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 17044 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17045 SDValue(Subc.getNode(), 1)); 17046 } 17047 } 17048 17049 return SDValue(); 17050 } 17051 17052 // Transform 17053 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 17054 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 17055 // In this case both C1 and C2 must be known constants. 17056 // C1+C2 must fit into a 34 bit signed integer. 17057 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 17058 const PPCSubtarget &Subtarget) { 17059 if (!Subtarget.isUsingPCRelativeCalls()) 17060 return SDValue(); 17061 17062 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 17063 // If we find that node try to cast the Global Address and the Constant. 17064 SDValue LHS = N->getOperand(0); 17065 SDValue RHS = N->getOperand(1); 17066 17067 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17068 std::swap(LHS, RHS); 17069 17070 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17071 return SDValue(); 17072 17073 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 17074 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 17075 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 17076 17077 // Check that both casts succeeded. 17078 if (!GSDN || !ConstNode) 17079 return SDValue(); 17080 17081 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 17082 SDLoc DL(GSDN); 17083 17084 // The signed int offset needs to fit in 34 bits. 17085 if (!isInt<34>(NewOffset)) 17086 return SDValue(); 17087 17088 // The new global address is a copy of the old global address except 17089 // that it has the updated Offset. 17090 SDValue GA = 17091 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 17092 NewOffset, GSDN->getTargetFlags()); 17093 SDValue MatPCRel = 17094 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 17095 return MatPCRel; 17096 } 17097 17098 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 17099 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 17100 return Value; 17101 17102 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 17103 return Value; 17104 17105 return SDValue(); 17106 } 17107 17108 // Detect TRUNCATE operations on bitcasts of float128 values. 17109 // What we are looking for here is the situtation where we extract a subset 17110 // of bits from a 128 bit float. 17111 // This can be of two forms: 17112 // 1) BITCAST of f128 feeding TRUNCATE 17113 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 17114 // The reason this is required is because we do not have a legal i128 type 17115 // and so we want to prevent having to store the f128 and then reload part 17116 // of it. 17117 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 17118 DAGCombinerInfo &DCI) const { 17119 // If we are using CRBits then try that first. 17120 if (Subtarget.useCRBits()) { 17121 // Check if CRBits did anything and return that if it did. 17122 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 17123 return CRTruncValue; 17124 } 17125 17126 SDLoc dl(N); 17127 SDValue Op0 = N->getOperand(0); 17128 17129 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 17130 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 17131 EVT VT = N->getValueType(0); 17132 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17133 return SDValue(); 17134 SDValue Sub = Op0.getOperand(0); 17135 if (Sub.getOpcode() == ISD::SUB) { 17136 SDValue SubOp0 = Sub.getOperand(0); 17137 SDValue SubOp1 = Sub.getOperand(1); 17138 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 17139 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 17140 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 17141 SubOp1.getOperand(0), 17142 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 17143 } 17144 } 17145 } 17146 17147 // Looking for a truncate of i128 to i64. 17148 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 17149 return SDValue(); 17150 17151 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 17152 17153 // SRL feeding TRUNCATE. 17154 if (Op0.getOpcode() == ISD::SRL) { 17155 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 17156 // The right shift has to be by 64 bits. 17157 if (!ConstNode || ConstNode->getZExtValue() != 64) 17158 return SDValue(); 17159 17160 // Switch the element number to extract. 17161 EltToExtract = EltToExtract ? 0 : 1; 17162 // Update Op0 past the SRL. 17163 Op0 = Op0.getOperand(0); 17164 } 17165 17166 // BITCAST feeding a TRUNCATE possibly via SRL. 17167 if (Op0.getOpcode() == ISD::BITCAST && 17168 Op0.getValueType() == MVT::i128 && 17169 Op0.getOperand(0).getValueType() == MVT::f128) { 17170 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 17171 return DCI.DAG.getNode( 17172 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 17173 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 17174 } 17175 return SDValue(); 17176 } 17177 17178 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 17179 SelectionDAG &DAG = DCI.DAG; 17180 17181 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 17182 if (!ConstOpOrElement) 17183 return SDValue(); 17184 17185 // An imul is usually smaller than the alternative sequence for legal type. 17186 if (DAG.getMachineFunction().getFunction().hasMinSize() && 17187 isOperationLegal(ISD::MUL, N->getValueType(0))) 17188 return SDValue(); 17189 17190 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 17191 switch (this->Subtarget.getCPUDirective()) { 17192 default: 17193 // TODO: enhance the condition for subtarget before pwr8 17194 return false; 17195 case PPC::DIR_PWR8: 17196 // type mul add shl 17197 // scalar 4 1 1 17198 // vector 7 2 2 17199 return true; 17200 case PPC::DIR_PWR9: 17201 case PPC::DIR_PWR10: 17202 case PPC::DIR_PWR_FUTURE: 17203 // type mul add shl 17204 // scalar 5 2 2 17205 // vector 7 2 2 17206 17207 // The cycle RATIO of related operations are showed as a table above. 17208 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 17209 // scalar and vector type. For 2 instrs patterns, add/sub + shl 17210 // are 4, it is always profitable; but for 3 instrs patterns 17211 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 17212 // So we should only do it for vector type. 17213 return IsAddOne && IsNeg ? VT.isVector() : true; 17214 } 17215 }; 17216 17217 EVT VT = N->getValueType(0); 17218 SDLoc DL(N); 17219 17220 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 17221 bool IsNeg = MulAmt.isNegative(); 17222 APInt MulAmtAbs = MulAmt.abs(); 17223 17224 if ((MulAmtAbs - 1).isPowerOf2()) { 17225 // (mul x, 2^N + 1) => (add (shl x, N), x) 17226 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 17227 17228 if (!IsProfitable(IsNeg, true, VT)) 17229 return SDValue(); 17230 17231 SDValue Op0 = N->getOperand(0); 17232 SDValue Op1 = 17233 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17234 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 17235 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 17236 17237 if (!IsNeg) 17238 return Res; 17239 17240 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 17241 } else if ((MulAmtAbs + 1).isPowerOf2()) { 17242 // (mul x, 2^N - 1) => (sub (shl x, N), x) 17243 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 17244 17245 if (!IsProfitable(IsNeg, false, VT)) 17246 return SDValue(); 17247 17248 SDValue Op0 = N->getOperand(0); 17249 SDValue Op1 = 17250 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17251 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 17252 17253 if (!IsNeg) 17254 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 17255 else 17256 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 17257 17258 } else { 17259 return SDValue(); 17260 } 17261 } 17262 17263 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 17264 // in combiner since we need to check SD flags and other subtarget features. 17265 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 17266 DAGCombinerInfo &DCI) const { 17267 SDValue N0 = N->getOperand(0); 17268 SDValue N1 = N->getOperand(1); 17269 SDValue N2 = N->getOperand(2); 17270 SDNodeFlags Flags = N->getFlags(); 17271 EVT VT = N->getValueType(0); 17272 SelectionDAG &DAG = DCI.DAG; 17273 const TargetOptions &Options = getTargetMachine().Options; 17274 unsigned Opc = N->getOpcode(); 17275 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 17276 bool LegalOps = !DCI.isBeforeLegalizeOps(); 17277 SDLoc Loc(N); 17278 17279 if (!isOperationLegal(ISD::FMA, VT)) 17280 return SDValue(); 17281 17282 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 17283 // since (fnmsub a b c)=-0 while c-ab=+0. 17284 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 17285 return SDValue(); 17286 17287 // (fma (fneg a) b c) => (fnmsub a b c) 17288 // (fnmsub (fneg a) b c) => (fma a b c) 17289 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 17290 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 17291 17292 // (fma a (fneg b) c) => (fnmsub a b c) 17293 // (fnmsub a (fneg b) c) => (fma a b c) 17294 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 17295 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 17296 17297 return SDValue(); 17298 } 17299 17300 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 17301 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 17302 if (!Subtarget.is64BitELFABI()) 17303 return false; 17304 17305 // If not a tail call then no need to proceed. 17306 if (!CI->isTailCall()) 17307 return false; 17308 17309 // If sibling calls have been disabled and tail-calls aren't guaranteed 17310 // there is no reason to duplicate. 17311 auto &TM = getTargetMachine(); 17312 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 17313 return false; 17314 17315 // Can't tail call a function called indirectly, or if it has variadic args. 17316 const Function *Callee = CI->getCalledFunction(); 17317 if (!Callee || Callee->isVarArg()) 17318 return false; 17319 17320 // Make sure the callee and caller calling conventions are eligible for tco. 17321 const Function *Caller = CI->getParent()->getParent(); 17322 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 17323 CI->getCallingConv())) 17324 return false; 17325 17326 // If the function is local then we have a good chance at tail-calling it 17327 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 17328 } 17329 17330 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 17331 if (!Subtarget.hasVSX()) 17332 return false; 17333 if (Subtarget.hasP9Vector() && VT == MVT::f128) 17334 return true; 17335 return VT == MVT::f32 || VT == MVT::f64 || 17336 VT == MVT::v4f32 || VT == MVT::v2f64; 17337 } 17338 17339 bool PPCTargetLowering:: 17340 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 17341 const Value *Mask = AndI.getOperand(1); 17342 // If the mask is suitable for andi. or andis. we should sink the and. 17343 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 17344 // Can't handle constants wider than 64-bits. 17345 if (CI->getBitWidth() > 64) 17346 return false; 17347 int64_t ConstVal = CI->getZExtValue(); 17348 return isUInt<16>(ConstVal) || 17349 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 17350 } 17351 17352 // For non-constant masks, we can always use the record-form and. 17353 return true; 17354 } 17355 17356 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 17357 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 17358 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 17359 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 17360 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 17361 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 17362 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 17363 assert(Subtarget.hasP9Altivec() && 17364 "Only combine this when P9 altivec supported!"); 17365 EVT VT = N->getValueType(0); 17366 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17367 return SDValue(); 17368 17369 SelectionDAG &DAG = DCI.DAG; 17370 SDLoc dl(N); 17371 if (N->getOperand(0).getOpcode() == ISD::SUB) { 17372 // Even for signed integers, if it's known to be positive (as signed 17373 // integer) due to zero-extended inputs. 17374 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 17375 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 17376 if ((SubOpcd0 == ISD::ZERO_EXTEND || 17377 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 17378 (SubOpcd1 == ISD::ZERO_EXTEND || 17379 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 17380 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17381 N->getOperand(0)->getOperand(0), 17382 N->getOperand(0)->getOperand(1), 17383 DAG.getTargetConstant(0, dl, MVT::i32)); 17384 } 17385 17386 // For type v4i32, it can be optimized with xvnegsp + vabsduw 17387 if (N->getOperand(0).getValueType() == MVT::v4i32 && 17388 N->getOperand(0).hasOneUse()) { 17389 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17390 N->getOperand(0)->getOperand(0), 17391 N->getOperand(0)->getOperand(1), 17392 DAG.getTargetConstant(1, dl, MVT::i32)); 17393 } 17394 } 17395 17396 return SDValue(); 17397 } 17398 17399 // For type v4i32/v8ii16/v16i8, transform 17400 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 17401 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 17402 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 17403 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 17404 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17405 DAGCombinerInfo &DCI) const { 17406 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17407 assert(Subtarget.hasP9Altivec() && 17408 "Only combine this when P9 altivec supported!"); 17409 17410 SelectionDAG &DAG = DCI.DAG; 17411 SDLoc dl(N); 17412 SDValue Cond = N->getOperand(0); 17413 SDValue TrueOpnd = N->getOperand(1); 17414 SDValue FalseOpnd = N->getOperand(2); 17415 EVT VT = N->getOperand(1).getValueType(); 17416 17417 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17418 FalseOpnd.getOpcode() != ISD::SUB) 17419 return SDValue(); 17420 17421 // ABSD only available for type v4i32/v8i16/v16i8 17422 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17423 return SDValue(); 17424 17425 // At least to save one more dependent computation 17426 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17427 return SDValue(); 17428 17429 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17430 17431 // Can only handle unsigned comparison here 17432 switch (CC) { 17433 default: 17434 return SDValue(); 17435 case ISD::SETUGT: 17436 case ISD::SETUGE: 17437 break; 17438 case ISD::SETULT: 17439 case ISD::SETULE: 17440 std::swap(TrueOpnd, FalseOpnd); 17441 break; 17442 } 17443 17444 SDValue CmpOpnd1 = Cond.getOperand(0); 17445 SDValue CmpOpnd2 = Cond.getOperand(1); 17446 17447 // SETCC CmpOpnd1 CmpOpnd2 cond 17448 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17449 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17450 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17451 TrueOpnd.getOperand(1) == CmpOpnd2 && 17452 FalseOpnd.getOperand(0) == CmpOpnd2 && 17453 FalseOpnd.getOperand(1) == CmpOpnd1) { 17454 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17455 CmpOpnd1, CmpOpnd2, 17456 DAG.getTargetConstant(0, dl, MVT::i32)); 17457 } 17458 17459 return SDValue(); 17460 } 17461 17462 /// getAddrModeForFlags - Based on the set of address flags, select the most 17463 /// optimal instruction format to match by. 17464 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17465 // This is not a node we should be handling here. 17466 if (Flags == PPC::MOF_None) 17467 return PPC::AM_None; 17468 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17469 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17470 if ((Flags & FlagSet) == FlagSet) 17471 return PPC::AM_DForm; 17472 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17473 if ((Flags & FlagSet) == FlagSet) 17474 return PPC::AM_DSForm; 17475 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17476 if ((Flags & FlagSet) == FlagSet) 17477 return PPC::AM_DQForm; 17478 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm)) 17479 if ((Flags & FlagSet) == FlagSet) 17480 return PPC::AM_PrefixDForm; 17481 // If no other forms are selected, return an X-Form as it is the most 17482 // general addressing mode. 17483 return PPC::AM_XForm; 17484 } 17485 17486 /// Set alignment flags based on whether or not the Frame Index is aligned. 17487 /// Utilized when computing flags for address computation when selecting 17488 /// load and store instructions. 17489 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17490 SelectionDAG &DAG) { 17491 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17492 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17493 if (!FI) 17494 return; 17495 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17496 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17497 // If this is (add $FI, $S16Imm), the alignment flags are already set 17498 // based on the immediate. We just need to clear the alignment flags 17499 // if the FI alignment is weaker. 17500 if ((FrameIndexAlign % 4) != 0) 17501 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17502 if ((FrameIndexAlign % 16) != 0) 17503 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17504 // If the address is a plain FrameIndex, set alignment flags based on 17505 // FI alignment. 17506 if (!IsAdd) { 17507 if ((FrameIndexAlign % 4) == 0) 17508 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17509 if ((FrameIndexAlign % 16) == 0) 17510 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17511 } 17512 } 17513 17514 /// Given a node, compute flags that are used for address computation when 17515 /// selecting load and store instructions. The flags computed are stored in 17516 /// FlagSet. This function takes into account whether the node is a constant, 17517 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17518 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17519 SelectionDAG &DAG) { 17520 // Set the alignment flags for the node depending on if the node is 17521 // 4-byte or 16-byte aligned. 17522 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17523 if ((Imm & 0x3) == 0) 17524 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17525 if ((Imm & 0xf) == 0) 17526 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17527 }; 17528 17529 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17530 // All 32-bit constants can be computed as LIS + Disp. 17531 const APInt &ConstImm = CN->getAPIntValue(); 17532 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17533 FlagSet |= PPC::MOF_AddrIsSImm32; 17534 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17535 setAlignFlagsForFI(N, FlagSet, DAG); 17536 } 17537 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17538 FlagSet |= PPC::MOF_RPlusSImm34; 17539 else // Let constant materialization handle large constants. 17540 FlagSet |= PPC::MOF_NotAddNorCst; 17541 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17542 // This address can be represented as an addition of: 17543 // - Register + Imm16 (possibly a multiple of 4/16) 17544 // - Register + Imm34 17545 // - Register + PPCISD::Lo 17546 // - Register + Register 17547 // In any case, we won't have to match this as Base + Zero. 17548 SDValue RHS = N.getOperand(1); 17549 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17550 const APInt &ConstImm = CN->getAPIntValue(); 17551 if (ConstImm.isSignedIntN(16)) { 17552 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17553 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17554 setAlignFlagsForFI(N, FlagSet, DAG); 17555 } 17556 if (ConstImm.isSignedIntN(34)) 17557 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17558 else 17559 FlagSet |= PPC::MOF_RPlusR; // Register. 17560 } else if (RHS.getOpcode() == PPCISD::Lo && 17561 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17562 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17563 else 17564 FlagSet |= PPC::MOF_RPlusR; 17565 } else { // The address computation is not a constant or an addition. 17566 setAlignFlagsForFI(N, FlagSet, DAG); 17567 FlagSet |= PPC::MOF_NotAddNorCst; 17568 } 17569 } 17570 17571 static bool isPCRelNode(SDValue N) { 17572 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR || 17573 isValidPCRelNode<ConstantPoolSDNode>(N) || 17574 isValidPCRelNode<GlobalAddressSDNode>(N) || 17575 isValidPCRelNode<JumpTableSDNode>(N) || 17576 isValidPCRelNode<BlockAddressSDNode>(N)); 17577 } 17578 17579 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17580 /// the address flags of the load/store instruction that is to be matched. 17581 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17582 SelectionDAG &DAG) const { 17583 unsigned FlagSet = PPC::MOF_None; 17584 17585 // Compute subtarget flags. 17586 if (!Subtarget.hasP9Vector()) 17587 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17588 else { 17589 FlagSet |= PPC::MOF_SubtargetP9; 17590 if (Subtarget.hasPrefixInstrs()) 17591 FlagSet |= PPC::MOF_SubtargetP10; 17592 } 17593 if (Subtarget.hasSPE()) 17594 FlagSet |= PPC::MOF_SubtargetSPE; 17595 17596 // Check if we have a PCRel node and return early. 17597 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N)) 17598 return FlagSet; 17599 17600 // If the node is the paired load/store intrinsics, compute flags for 17601 // address computation and return early. 17602 unsigned ParentOp = Parent->getOpcode(); 17603 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) || 17604 (ParentOp == ISD::INTRINSIC_VOID))) { 17605 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue(); 17606 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) { 17607 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) 17608 ? Parent->getOperand(2) 17609 : Parent->getOperand(3); 17610 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG); 17611 FlagSet |= PPC::MOF_Vector; 17612 return FlagSet; 17613 } 17614 } 17615 17616 // Mark this as something we don't want to handle here if it is atomic 17617 // or pre-increment instruction. 17618 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17619 if (LSB->isIndexed()) 17620 return PPC::MOF_None; 17621 17622 // Compute in-memory type flags. This is based on if there are scalars, 17623 // floats or vectors. 17624 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17625 assert(MN && "Parent should be a MemSDNode!"); 17626 EVT MemVT = MN->getMemoryVT(); 17627 unsigned Size = MemVT.getSizeInBits(); 17628 if (MemVT.isScalarInteger()) { 17629 assert(Size <= 128 && 17630 "Not expecting scalar integers larger than 16 bytes!"); 17631 if (Size < 32) 17632 FlagSet |= PPC::MOF_SubWordInt; 17633 else if (Size == 32) 17634 FlagSet |= PPC::MOF_WordInt; 17635 else 17636 FlagSet |= PPC::MOF_DoubleWordInt; 17637 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17638 if (Size == 128) 17639 FlagSet |= PPC::MOF_Vector; 17640 else if (Size == 256) { 17641 assert(Subtarget.pairedVectorMemops() && 17642 "256-bit vectors are only available when paired vector memops is " 17643 "enabled!"); 17644 FlagSet |= PPC::MOF_Vector; 17645 } else 17646 llvm_unreachable("Not expecting illegal vectors!"); 17647 } else { // Floating point type: can be scalar, f128 or vector types. 17648 if (Size == 32 || Size == 64) 17649 FlagSet |= PPC::MOF_ScalarFloat; 17650 else if (MemVT == MVT::f128 || MemVT.isVector()) 17651 FlagSet |= PPC::MOF_Vector; 17652 else 17653 llvm_unreachable("Not expecting illegal scalar floats!"); 17654 } 17655 17656 // Compute flags for address computation. 17657 computeFlagsForAddressComputation(N, FlagSet, DAG); 17658 17659 // Compute type extension flags. 17660 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17661 switch (LN->getExtensionType()) { 17662 case ISD::SEXTLOAD: 17663 FlagSet |= PPC::MOF_SExt; 17664 break; 17665 case ISD::EXTLOAD: 17666 case ISD::ZEXTLOAD: 17667 FlagSet |= PPC::MOF_ZExt; 17668 break; 17669 case ISD::NON_EXTLOAD: 17670 FlagSet |= PPC::MOF_NoExt; 17671 break; 17672 } 17673 } else 17674 FlagSet |= PPC::MOF_NoExt; 17675 17676 // For integers, no extension is the same as zero extension. 17677 // We set the extension mode to zero extension so we don't have 17678 // to add separate entries in AddrModesMap for loads and stores. 17679 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17680 FlagSet |= PPC::MOF_ZExt; 17681 FlagSet &= ~PPC::MOF_NoExt; 17682 } 17683 17684 // If we don't have prefixed instructions, 34-bit constants should be 17685 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17686 bool IsNonP1034BitConst = 17687 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17688 FlagSet) == PPC::MOF_RPlusSImm34; 17689 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17690 IsNonP1034BitConst) 17691 FlagSet |= PPC::MOF_NotAddNorCst; 17692 17693 return FlagSet; 17694 } 17695 17696 /// SelectForceXFormMode - Given the specified address, force it to be 17697 /// represented as an indexed [r+r] operation (an XForm instruction). 17698 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17699 SDValue &Base, 17700 SelectionDAG &DAG) const { 17701 17702 PPC::AddrMode Mode = PPC::AM_XForm; 17703 int16_t ForceXFormImm = 0; 17704 if (provablyDisjointOr(DAG, N) && 17705 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17706 Disp = N.getOperand(0); 17707 Base = N.getOperand(1); 17708 return Mode; 17709 } 17710 17711 // If the address is the result of an add, we will utilize the fact that the 17712 // address calculation includes an implicit add. However, we can reduce 17713 // register pressure if we do not materialize a constant just for use as the 17714 // index register. We only get rid of the add if it is not an add of a 17715 // value and a 16-bit signed constant and both have a single use. 17716 if (N.getOpcode() == ISD::ADD && 17717 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17718 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17719 Disp = N.getOperand(0); 17720 Base = N.getOperand(1); 17721 return Mode; 17722 } 17723 17724 // Otherwise, use R0 as the base register. 17725 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17726 N.getValueType()); 17727 Base = N; 17728 17729 return Mode; 17730 } 17731 17732 bool PPCTargetLowering::splitValueIntoRegisterParts( 17733 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 17734 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 17735 EVT ValVT = Val.getValueType(); 17736 // If we are splitting a scalar integer into f64 parts (i.e. so they 17737 // can be placed into VFRC registers), we need to zero extend and 17738 // bitcast the values. This will ensure the value is placed into a 17739 // VSR using direct moves or stack operations as needed. 17740 if (PartVT == MVT::f64 && 17741 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) { 17742 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 17743 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val); 17744 Parts[0] = Val; 17745 return true; 17746 } 17747 return false; 17748 } 17749 17750 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op, 17751 SelectionDAG &DAG) const { 17752 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17753 TargetLowering::CallLoweringInfo CLI(DAG); 17754 EVT RetVT = Op.getValueType(); 17755 SDValue Callee = 17756 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout())); 17757 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false); 17758 TargetLowering::ArgListTy Args; 17759 TargetLowering::ArgListEntry Entry; 17760 for (const SDValue &N : Op->op_values()) { 17761 EVT ArgVT = N.getValueType(); 17762 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 17763 Entry.Node = N; 17764 Entry.Ty = ArgTy; 17765 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend); 17766 Entry.IsZExt = !Entry.IsSExt; 17767 Args.push_back(Entry); 17768 } 17769 CLI.setDebugLoc(SDLoc(Op)) 17770 .setChain(DAG.getEntryNode()) 17771 .setLibCallee(CallingConv::C, RetVT.getTypeForEVT(*DAG.getContext()), 17772 Callee, std::move(Args)) 17773 .setTailCall(true) 17774 .setSExtResult(SignExtend) 17775 .setZExtResult(!SignExtend) 17776 .setIsPostTypeLegalization(true); 17777 return TLI.LowerCallTo(CLI).first; 17778 } 17779 17780 SDValue PPCTargetLowering::lowerLibCallBasedOnType( 17781 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op, 17782 SelectionDAG &DAG) const { 17783 if (Op.getValueType() == MVT::f32) 17784 return lowerToLibCall(LibCallFloatName, Op, DAG); 17785 17786 if (Op.getValueType() == MVT::f64) 17787 return lowerToLibCall(LibCallDoubleName, Op, DAG); 17788 17789 return SDValue(); 17790 } 17791 17792 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const { 17793 SDNodeFlags Flags = Op.getNode()->getFlags(); 17794 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() && 17795 Flags.hasNoNaNs() && Flags.hasNoInfs(); 17796 } 17797 17798 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const { 17799 return Op.getNode()->getFlags().hasApproximateFuncs(); 17800 } 17801 17802 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName, 17803 const char *LibCallFloatName, 17804 const char *LibCallDoubleNameFinite, 17805 const char *LibCallFloatNameFinite, 17806 SDValue Op, 17807 SelectionDAG &DAG) const { 17808 if (!isLowringToMASSSafe(Op)) 17809 return SDValue(); 17810 17811 if (!isLowringToMASSFiniteSafe(Op)) 17812 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op, 17813 DAG); 17814 17815 return lowerLibCallBasedOnType(LibCallFloatNameFinite, 17816 LibCallDoubleNameFinite, Op, DAG); 17817 } 17818 17819 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const { 17820 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite", 17821 "__xl_powf_finite", Op, DAG); 17822 } 17823 17824 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const { 17825 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite", 17826 "__xl_sinf_finite", Op, DAG); 17827 } 17828 17829 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const { 17830 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite", 17831 "__xl_cosf_finite", Op, DAG); 17832 } 17833 17834 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const { 17835 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite", 17836 "__xl_logf_finite", Op, DAG); 17837 } 17838 17839 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const { 17840 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite", 17841 "__xl_log10f_finite", Op, DAG); 17842 } 17843 17844 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const { 17845 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite", 17846 "__xl_expf_finite", Op, DAG); 17847 } 17848 17849 // If we happen to match to an aligned D-Form, check if the Frame Index is 17850 // adequately aligned. If it is not, reset the mode to match to X-Form. 17851 static void setXFormForUnalignedFI(SDValue N, unsigned Flags, 17852 PPC::AddrMode &Mode) { 17853 if (!isa<FrameIndexSDNode>(N)) 17854 return; 17855 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) || 17856 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16))) 17857 Mode = PPC::AM_XForm; 17858 } 17859 17860 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 17861 /// compute the address flags of the node, get the optimal address mode based 17862 /// on the flags, and set the Base and Disp based on the address mode. 17863 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 17864 SDValue N, SDValue &Disp, 17865 SDValue &Base, 17866 SelectionDAG &DAG, 17867 MaybeAlign Align) const { 17868 SDLoc DL(Parent); 17869 17870 // Compute the address flags. 17871 unsigned Flags = computeMOFlags(Parent, N, DAG); 17872 17873 // Get the optimal address mode based on the Flags. 17874 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 17875 17876 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned. 17877 // Select an X-Form load if it is not. 17878 setXFormForUnalignedFI(N, Flags, Mode); 17879 17880 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node. 17881 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) { 17882 assert(Subtarget.isUsingPCRelativeCalls() && 17883 "Must be using PC-Relative calls when a valid PC-Relative node is " 17884 "present!"); 17885 Mode = PPC::AM_PCRel; 17886 } 17887 17888 // Set Base and Disp accordingly depending on the address mode. 17889 switch (Mode) { 17890 case PPC::AM_DForm: 17891 case PPC::AM_DSForm: 17892 case PPC::AM_DQForm: { 17893 // This is a register plus a 16-bit immediate. The base will be the 17894 // register and the displacement will be the immediate unless it 17895 // isn't sufficiently aligned. 17896 if (Flags & PPC::MOF_RPlusSImm16) { 17897 SDValue Op0 = N.getOperand(0); 17898 SDValue Op1 = N.getOperand(1); 17899 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 17900 if (!Align || isAligned(*Align, Imm)) { 17901 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 17902 Base = Op0; 17903 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 17904 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17905 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17906 } 17907 break; 17908 } 17909 } 17910 // This is a register plus the @lo relocation. The base is the register 17911 // and the displacement is the global address. 17912 else if (Flags & PPC::MOF_RPlusLo) { 17913 Disp = N.getOperand(1).getOperand(0); // The global address. 17914 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 17915 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 17916 Disp.getOpcode() == ISD::TargetConstantPool || 17917 Disp.getOpcode() == ISD::TargetJumpTable); 17918 Base = N.getOperand(0); 17919 break; 17920 } 17921 // This is a constant address at most 32 bits. The base will be 17922 // zero or load-immediate-shifted and the displacement will be 17923 // the low 16 bits of the address. 17924 else if (Flags & PPC::MOF_AddrIsSImm32) { 17925 auto *CN = cast<ConstantSDNode>(N); 17926 EVT CNType = CN->getValueType(0); 17927 uint64_t CNImm = CN->getZExtValue(); 17928 // If this address fits entirely in a 16-bit sext immediate field, codegen 17929 // this as "d, 0". 17930 int16_t Imm; 17931 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 17932 Disp = DAG.getTargetConstant(Imm, DL, CNType); 17933 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17934 CNType); 17935 break; 17936 } 17937 // Handle 32-bit sext immediate with LIS + Addr mode. 17938 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 17939 (!Align || isAligned(*Align, CNImm))) { 17940 int32_t Addr = (int32_t)CNImm; 17941 // Otherwise, break this down into LIS + Disp. 17942 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 17943 Base = 17944 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 17945 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 17946 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 17947 break; 17948 } 17949 } 17950 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 17951 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 17952 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 17953 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17954 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17955 } else 17956 Base = N; 17957 break; 17958 } 17959 case PPC::AM_PrefixDForm: { 17960 int64_t Imm34 = 0; 17961 unsigned Opcode = N.getOpcode(); 17962 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) && 17963 (isIntS34Immediate(N.getOperand(1), Imm34))) { 17964 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate. 17965 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 17966 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 17967 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17968 else 17969 Base = N.getOperand(0); 17970 } else if (isIntS34Immediate(N, Imm34)) { 17971 // The address is a 34-bit signed immediate. 17972 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 17973 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 17974 } 17975 break; 17976 } 17977 case PPC::AM_PCRel: { 17978 // When selecting PC-Relative instructions, "Base" is not utilized as 17979 // we select the address as [PC+imm]. 17980 Disp = N; 17981 break; 17982 } 17983 case PPC::AM_None: 17984 break; 17985 default: { // By default, X-Form is always available to be selected. 17986 // When a frame index is not aligned, we also match by XForm. 17987 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 17988 Base = FI ? N : N.getOperand(1); 17989 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17990 N.getValueType()) 17991 : N.getOperand(0); 17992 break; 17993 } 17994 } 17995 return Mode; 17996 } 17997 17998 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 17999 bool Return, 18000 bool IsVarArg) const { 18001 switch (CC) { 18002 case CallingConv::Cold: 18003 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 18004 default: 18005 return CC_PPC64_ELF_FIS; 18006 } 18007 } 18008 18009 TargetLowering::AtomicExpansionKind 18010 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18011 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18012 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128) 18013 return AtomicExpansionKind::MaskedIntrinsic; 18014 return TargetLowering::shouldExpandAtomicRMWInIR(AI); 18015 } 18016 18017 TargetLowering::AtomicExpansionKind 18018 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18019 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits(); 18020 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128) 18021 return AtomicExpansionKind::MaskedIntrinsic; 18022 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI); 18023 } 18024 18025 static Intrinsic::ID 18026 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) { 18027 switch (BinOp) { 18028 default: 18029 llvm_unreachable("Unexpected AtomicRMW BinOp"); 18030 case AtomicRMWInst::Xchg: 18031 return Intrinsic::ppc_atomicrmw_xchg_i128; 18032 case AtomicRMWInst::Add: 18033 return Intrinsic::ppc_atomicrmw_add_i128; 18034 case AtomicRMWInst::Sub: 18035 return Intrinsic::ppc_atomicrmw_sub_i128; 18036 case AtomicRMWInst::And: 18037 return Intrinsic::ppc_atomicrmw_and_i128; 18038 case AtomicRMWInst::Or: 18039 return Intrinsic::ppc_atomicrmw_or_i128; 18040 case AtomicRMWInst::Xor: 18041 return Intrinsic::ppc_atomicrmw_xor_i128; 18042 case AtomicRMWInst::Nand: 18043 return Intrinsic::ppc_atomicrmw_nand_i128; 18044 } 18045 } 18046 18047 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic( 18048 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 18049 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 18050 assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && 18051 "Only support quadword now"); 18052 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18053 Type *ValTy = Incr->getType(); 18054 assert(ValTy->getPrimitiveSizeInBits() == 128); 18055 Function *RMW = Intrinsic::getDeclaration( 18056 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation())); 18057 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18058 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo"); 18059 Value *IncrHi = 18060 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi"); 18061 Value *Addr = 18062 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18063 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi}); 18064 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18065 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18066 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18067 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18068 return Builder.CreateOr( 18069 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18070 } 18071 18072 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 18073 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 18074 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 18075 assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && 18076 "Only support quadword now"); 18077 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18078 Type *ValTy = CmpVal->getType(); 18079 assert(ValTy->getPrimitiveSizeInBits() == 128); 18080 Function *IntCmpXchg = 18081 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128); 18082 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18083 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo"); 18084 Value *CmpHi = 18085 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi"); 18086 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo"); 18087 Value *NewHi = 18088 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi"); 18089 Value *Addr = 18090 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18091 emitLeadingFence(Builder, CI, Ord); 18092 Value *LoHi = 18093 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi}); 18094 emitTrailingFence(Builder, CI, Ord); 18095 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18096 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18097 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18098 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18099 return Builder.CreateOr( 18100 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18101 } 18102