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 if (Subtarget.hasSPE()) { 383 setOperationAction(ISD::FMA , MVT::f64, Expand); 384 setOperationAction(ISD::FMA , MVT::f32, Expand); 385 } else { 386 setOperationAction(ISD::FMA , MVT::f64, Legal); 387 setOperationAction(ISD::FMA , MVT::f32, Legal); 388 } 389 390 if (Subtarget.hasSPE()) 391 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 392 393 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 394 395 // If we're enabling GP optimizations, use hardware square root 396 if (!Subtarget.hasFSQRT() && 397 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 398 Subtarget.hasFRE())) 399 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 400 401 if (!Subtarget.hasFSQRT() && 402 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 403 Subtarget.hasFRES())) 404 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 405 406 if (Subtarget.hasFCPSGN()) { 407 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 408 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 409 } else { 410 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 411 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 412 } 413 414 if (Subtarget.hasFPRND()) { 415 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 416 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 417 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 418 setOperationAction(ISD::FROUND, MVT::f64, Legal); 419 420 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 421 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 422 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 423 setOperationAction(ISD::FROUND, MVT::f32, Legal); 424 } 425 426 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 427 // to speed up scalar BSWAP64. 428 // CTPOP or CTTZ were introduced in P8/P9 respectively 429 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 430 if (Subtarget.hasP9Vector() && Subtarget.isPPC64()) 431 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 432 else 433 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 434 if (Subtarget.isISA3_0()) { 435 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 436 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 437 } else { 438 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 439 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 440 } 441 442 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 443 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 444 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 445 } else { 446 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 447 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 448 } 449 450 // PowerPC does not have ROTR 451 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 452 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 453 454 if (!Subtarget.useCRBits()) { 455 // PowerPC does not have Select 456 setOperationAction(ISD::SELECT, MVT::i32, Expand); 457 setOperationAction(ISD::SELECT, MVT::i64, Expand); 458 setOperationAction(ISD::SELECT, MVT::f32, Expand); 459 setOperationAction(ISD::SELECT, MVT::f64, Expand); 460 } 461 462 // PowerPC wants to turn select_cc of FP into fsel when possible. 463 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 464 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 465 466 // PowerPC wants to optimize integer setcc a bit 467 if (!Subtarget.useCRBits()) 468 setOperationAction(ISD::SETCC, MVT::i32, Custom); 469 470 if (Subtarget.hasFPU()) { 471 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 472 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 473 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 474 475 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 476 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 477 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 478 } 479 480 // PowerPC does not have BRCOND which requires SetCC 481 if (!Subtarget.useCRBits()) 482 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 483 484 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 485 486 if (Subtarget.hasSPE()) { 487 // SPE has built-in conversions 488 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 489 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 490 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 491 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 492 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 493 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 494 495 // SPE supports signaling compare of f32/f64. 496 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 497 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 498 } else { 499 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 500 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 501 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 502 503 // PowerPC does not have [U|S]INT_TO_FP 504 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 505 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 506 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 507 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 508 } 509 510 if (Subtarget.hasDirectMove() && isPPC64) { 511 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 512 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 513 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 514 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 515 if (TM.Options.UnsafeFPMath) { 516 setOperationAction(ISD::LRINT, MVT::f64, Legal); 517 setOperationAction(ISD::LRINT, MVT::f32, Legal); 518 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 519 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 520 setOperationAction(ISD::LROUND, MVT::f64, Legal); 521 setOperationAction(ISD::LROUND, MVT::f32, Legal); 522 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 523 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 524 } 525 } else { 526 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 527 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 528 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 529 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 530 } 531 532 // We cannot sextinreg(i1). Expand to shifts. 533 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 534 535 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 536 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 537 // support continuation, user-level threading, and etc.. As a result, no 538 // other SjLj exception interfaces are implemented and please don't build 539 // your own exception handling based on them. 540 // LLVM/Clang supports zero-cost DWARF exception handling. 541 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 542 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 543 544 // We want to legalize GlobalAddress and ConstantPool nodes into the 545 // appropriate instructions to materialize the address. 546 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 547 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 548 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 549 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 550 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 551 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 552 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 553 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 554 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 555 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 556 557 // TRAP is legal. 558 setOperationAction(ISD::TRAP, MVT::Other, Legal); 559 560 // TRAMPOLINE is custom lowered. 561 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 562 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 563 564 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 565 setOperationAction(ISD::VASTART , MVT::Other, Custom); 566 567 if (Subtarget.is64BitELFABI()) { 568 // VAARG always uses double-word chunks, so promote anything smaller. 569 setOperationAction(ISD::VAARG, MVT::i1, Promote); 570 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 571 setOperationAction(ISD::VAARG, MVT::i8, Promote); 572 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 573 setOperationAction(ISD::VAARG, MVT::i16, Promote); 574 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 575 setOperationAction(ISD::VAARG, MVT::i32, Promote); 576 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 577 setOperationAction(ISD::VAARG, MVT::Other, Expand); 578 } else if (Subtarget.is32BitELFABI()) { 579 // VAARG is custom lowered with the 32-bit SVR4 ABI. 580 setOperationAction(ISD::VAARG, MVT::Other, Custom); 581 setOperationAction(ISD::VAARG, MVT::i64, Custom); 582 } else 583 setOperationAction(ISD::VAARG, MVT::Other, Expand); 584 585 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 586 if (Subtarget.is32BitELFABI()) 587 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 588 else 589 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 590 591 // Use the default implementation. 592 setOperationAction(ISD::VAEND , MVT::Other, Expand); 593 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 594 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 595 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 596 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 597 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 598 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 599 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 600 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 601 602 // We want to custom lower some of our intrinsics. 603 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 604 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom); 605 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom); 606 607 // To handle counter-based loop conditions. 608 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 609 610 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 611 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 612 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 613 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 614 615 // Comparisons that require checking two conditions. 616 if (Subtarget.hasSPE()) { 617 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 618 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 619 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 620 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 621 } 622 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 623 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 624 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 625 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 626 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 627 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 628 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 629 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 630 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 631 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 632 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 633 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 634 635 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 636 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 637 638 if (Subtarget.has64BitSupport()) { 639 // They also have instructions for converting between i64 and fp. 640 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 641 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 642 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 643 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 644 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 645 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 646 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 647 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 648 // This is just the low 32 bits of a (signed) fp->i64 conversion. 649 // We cannot do this with Promote because i64 is not a legal type. 650 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 651 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 652 653 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 654 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 655 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 656 } 657 } else { 658 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 659 if (Subtarget.hasSPE()) { 660 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 661 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 662 } else { 663 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 664 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 665 } 666 } 667 668 // With the instructions enabled under FPCVT, we can do everything. 669 if (Subtarget.hasFPCVT()) { 670 if (Subtarget.has64BitSupport()) { 671 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 672 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 673 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 674 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 675 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 676 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 677 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 678 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 679 } 680 681 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 682 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 683 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 684 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 685 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 686 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 687 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 688 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 689 } 690 691 if (Subtarget.use64BitRegs()) { 692 // 64-bit PowerPC implementations can support i64 types directly 693 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 694 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 695 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 696 // 64-bit PowerPC wants to expand i128 shifts itself. 697 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 698 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 699 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 700 } else { 701 // 32-bit PowerPC wants to expand i64 shifts itself. 702 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 703 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 704 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 705 } 706 707 // PowerPC has better expansions for funnel shifts than the generic 708 // TargetLowering::expandFunnelShift. 709 if (Subtarget.has64BitSupport()) { 710 setOperationAction(ISD::FSHL, MVT::i64, Custom); 711 setOperationAction(ISD::FSHR, MVT::i64, Custom); 712 } 713 setOperationAction(ISD::FSHL, MVT::i32, Custom); 714 setOperationAction(ISD::FSHR, MVT::i32, Custom); 715 716 if (Subtarget.hasVSX()) { 717 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 718 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 719 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 720 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 721 } 722 723 if (Subtarget.hasAltivec()) { 724 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 725 setOperationAction(ISD::SADDSAT, VT, Legal); 726 setOperationAction(ISD::SSUBSAT, VT, Legal); 727 setOperationAction(ISD::UADDSAT, VT, Legal); 728 setOperationAction(ISD::USUBSAT, VT, Legal); 729 } 730 // First set operation action for all vector types to expand. Then we 731 // will selectively turn on ones that can be effectively codegen'd. 732 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 733 // add/sub are legal for all supported vector VT's. 734 setOperationAction(ISD::ADD, VT, Legal); 735 setOperationAction(ISD::SUB, VT, Legal); 736 737 // For v2i64, these are only valid with P8Vector. This is corrected after 738 // the loop. 739 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 740 setOperationAction(ISD::SMAX, VT, Legal); 741 setOperationAction(ISD::SMIN, VT, Legal); 742 setOperationAction(ISD::UMAX, VT, Legal); 743 setOperationAction(ISD::UMIN, VT, Legal); 744 } 745 else { 746 setOperationAction(ISD::SMAX, VT, Expand); 747 setOperationAction(ISD::SMIN, VT, Expand); 748 setOperationAction(ISD::UMAX, VT, Expand); 749 setOperationAction(ISD::UMIN, VT, Expand); 750 } 751 752 if (Subtarget.hasVSX()) { 753 setOperationAction(ISD::FMAXNUM, VT, Legal); 754 setOperationAction(ISD::FMINNUM, VT, Legal); 755 } 756 757 // Vector instructions introduced in P8 758 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 759 setOperationAction(ISD::CTPOP, VT, Legal); 760 setOperationAction(ISD::CTLZ, VT, Legal); 761 } 762 else { 763 setOperationAction(ISD::CTPOP, VT, Expand); 764 setOperationAction(ISD::CTLZ, VT, Expand); 765 } 766 767 // Vector instructions introduced in P9 768 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 769 setOperationAction(ISD::CTTZ, VT, Legal); 770 else 771 setOperationAction(ISD::CTTZ, VT, Expand); 772 773 // We promote all shuffles to v16i8. 774 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 775 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 776 777 // We promote all non-typed operations to v4i32. 778 setOperationAction(ISD::AND , VT, Promote); 779 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 780 setOperationAction(ISD::OR , VT, Promote); 781 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 782 setOperationAction(ISD::XOR , VT, Promote); 783 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 784 setOperationAction(ISD::LOAD , VT, Promote); 785 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 786 setOperationAction(ISD::SELECT, VT, Promote); 787 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 788 setOperationAction(ISD::VSELECT, VT, Legal); 789 setOperationAction(ISD::SELECT_CC, VT, Promote); 790 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 791 setOperationAction(ISD::STORE, VT, Promote); 792 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 793 794 // No other operations are legal. 795 setOperationAction(ISD::MUL , VT, Expand); 796 setOperationAction(ISD::SDIV, VT, Expand); 797 setOperationAction(ISD::SREM, VT, Expand); 798 setOperationAction(ISD::UDIV, VT, Expand); 799 setOperationAction(ISD::UREM, VT, Expand); 800 setOperationAction(ISD::FDIV, VT, Expand); 801 setOperationAction(ISD::FREM, VT, Expand); 802 setOperationAction(ISD::FNEG, VT, Expand); 803 setOperationAction(ISD::FSQRT, VT, Expand); 804 setOperationAction(ISD::FLOG, VT, Expand); 805 setOperationAction(ISD::FLOG10, VT, Expand); 806 setOperationAction(ISD::FLOG2, VT, Expand); 807 setOperationAction(ISD::FEXP, VT, Expand); 808 setOperationAction(ISD::FEXP2, VT, Expand); 809 setOperationAction(ISD::FSIN, VT, Expand); 810 setOperationAction(ISD::FCOS, VT, Expand); 811 setOperationAction(ISD::FABS, VT, Expand); 812 setOperationAction(ISD::FFLOOR, VT, Expand); 813 setOperationAction(ISD::FCEIL, VT, Expand); 814 setOperationAction(ISD::FTRUNC, VT, Expand); 815 setOperationAction(ISD::FRINT, VT, Expand); 816 setOperationAction(ISD::FNEARBYINT, VT, Expand); 817 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 818 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 819 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 820 setOperationAction(ISD::MULHU, VT, Expand); 821 setOperationAction(ISD::MULHS, VT, Expand); 822 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 823 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 824 setOperationAction(ISD::UDIVREM, VT, Expand); 825 setOperationAction(ISD::SDIVREM, VT, Expand); 826 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 827 setOperationAction(ISD::FPOW, VT, Expand); 828 setOperationAction(ISD::BSWAP, VT, Expand); 829 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 830 setOperationAction(ISD::ROTL, VT, Expand); 831 setOperationAction(ISD::ROTR, VT, Expand); 832 833 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 834 setTruncStoreAction(VT, InnerVT, Expand); 835 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 836 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 837 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 838 } 839 } 840 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 841 if (!Subtarget.hasP8Vector()) { 842 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 843 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 844 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 845 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 846 } 847 848 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 849 // with merges, splats, etc. 850 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 851 852 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 853 // are cheap, so handle them before they get expanded to scalar. 854 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 855 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 856 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 857 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 858 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 859 860 setOperationAction(ISD::AND , MVT::v4i32, Legal); 861 setOperationAction(ISD::OR , MVT::v4i32, Legal); 862 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 863 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 864 setOperationAction(ISD::SELECT, MVT::v4i32, 865 Subtarget.useCRBits() ? Legal : Expand); 866 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 867 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 868 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 869 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 870 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 871 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 872 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 873 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 874 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 875 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 876 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 877 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 878 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 879 880 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 881 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 882 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 883 if (Subtarget.hasAltivec()) 884 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 885 setOperationAction(ISD::ROTL, VT, Legal); 886 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 887 if (Subtarget.hasP8Altivec()) 888 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 889 890 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 891 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 892 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 893 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 894 895 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 896 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 897 898 if (Subtarget.hasVSX()) { 899 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 900 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 902 } 903 904 if (Subtarget.hasP8Altivec()) 905 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 906 else 907 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 908 909 if (Subtarget.isISA3_1()) { 910 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 911 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 912 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 913 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 914 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 915 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 916 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 917 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 918 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 919 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 920 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 921 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 922 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 923 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 924 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 925 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 926 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 927 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 928 } 929 930 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 931 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 932 933 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 934 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 935 936 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 937 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 938 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 939 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 940 941 // Altivec does not contain unordered floating-point compare instructions 942 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 943 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 944 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 945 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 946 947 if (Subtarget.hasVSX()) { 948 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 949 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 950 if (Subtarget.hasP8Vector()) { 951 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 953 } 954 if (Subtarget.hasDirectMove() && isPPC64) { 955 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 956 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 957 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 958 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 959 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 961 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 962 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 963 } 964 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 965 966 // The nearbyint variants are not allowed to raise the inexact exception 967 // so we can only code-gen them with unsafe math. 968 if (TM.Options.UnsafeFPMath) { 969 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 970 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 971 } 972 973 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 974 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 975 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 976 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 977 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 978 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 979 setOperationAction(ISD::FROUND, MVT::f64, Legal); 980 setOperationAction(ISD::FRINT, MVT::f64, Legal); 981 982 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 983 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 984 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 985 setOperationAction(ISD::FROUND, MVT::f32, Legal); 986 setOperationAction(ISD::FRINT, MVT::f32, Legal); 987 988 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 989 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 990 991 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 992 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 993 994 // Share the Altivec comparison restrictions. 995 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 996 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 997 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 998 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 999 1000 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1001 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 1002 1003 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 1004 1005 if (Subtarget.hasP8Vector()) 1006 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1007 1008 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1009 1010 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1011 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1012 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1013 1014 if (Subtarget.hasP8Altivec()) { 1015 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1016 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1017 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1018 1019 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1020 // SRL, but not for SRA because of the instructions available: 1021 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1022 // doing 1023 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1024 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1025 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1026 1027 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1028 } 1029 else { 1030 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1031 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1032 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1033 1034 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1035 1036 // VSX v2i64 only supports non-arithmetic operations. 1037 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1038 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1039 } 1040 1041 if (Subtarget.isISA3_1()) 1042 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1043 else 1044 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1045 1046 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1047 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1048 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1049 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1050 1051 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1052 1053 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1054 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1055 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1056 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1057 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1058 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1059 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1060 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1061 1062 // Custom handling for partial vectors of integers converted to 1063 // floating point. We already have optimal handling for v2i32 through 1064 // the DAG combine, so those aren't necessary. 1065 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1066 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1067 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1068 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1069 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1070 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1071 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1072 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1073 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1074 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1075 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1076 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1077 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1078 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1079 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1080 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1081 1082 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1083 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1084 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1085 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1086 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1087 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1088 1089 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1090 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1091 1092 // Handle constrained floating-point operations of vector. 1093 // The predictor is `hasVSX` because altivec instruction has 1094 // no exception but VSX vector instruction has. 1095 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1096 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1097 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1098 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1099 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1100 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1101 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1102 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1103 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1104 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1105 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1106 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1107 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1108 1109 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1110 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1111 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1112 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1113 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1114 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1115 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1116 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1117 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1118 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1119 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1120 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1121 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1122 1123 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1124 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1125 1126 for (MVT FPT : MVT::fp_valuetypes()) 1127 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1128 1129 // Expand the SELECT to SELECT_CC 1130 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1131 1132 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1133 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1134 1135 // No implementation for these ops for PowerPC. 1136 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1137 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1138 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1139 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1140 setOperationAction(ISD::FREM, MVT::f128, Expand); 1141 } 1142 1143 if (Subtarget.hasP8Altivec()) { 1144 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1145 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1146 } 1147 1148 if (Subtarget.hasP9Vector()) { 1149 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1150 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1151 1152 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1153 // SRL, but not for SRA because of the instructions available: 1154 // VS{RL} and VS{RL}O. 1155 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1156 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1157 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1158 1159 setOperationAction(ISD::FADD, MVT::f128, Legal); 1160 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1161 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1162 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1163 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1164 1165 setOperationAction(ISD::FMA, MVT::f128, Legal); 1166 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1167 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1168 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1169 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1170 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1171 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1172 1173 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1174 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1175 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1176 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1177 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1178 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1179 1180 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1181 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1182 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1183 1184 // Handle constrained floating-point operations of fp128 1185 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1186 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1187 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1188 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1189 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1190 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1191 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1192 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1193 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1194 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1195 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1196 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1197 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1198 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1199 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1200 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1201 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1202 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1203 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1204 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1205 } else if (Subtarget.hasVSX()) { 1206 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1207 setOperationAction(ISD::STORE, MVT::f128, Promote); 1208 1209 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1210 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1211 1212 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1213 // fp_to_uint and int_to_fp. 1214 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1215 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1216 1217 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1218 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1219 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1220 setOperationAction(ISD::FABS, MVT::f128, Expand); 1221 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1222 setOperationAction(ISD::FMA, MVT::f128, Expand); 1223 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1224 1225 // Expand the fp_extend if the target type is fp128. 1226 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1227 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1228 1229 // Expand the fp_round if the source type is fp128. 1230 for (MVT VT : {MVT::f32, MVT::f64}) { 1231 setOperationAction(ISD::FP_ROUND, VT, Custom); 1232 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1233 } 1234 1235 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1236 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1237 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1238 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1239 1240 // Lower following f128 select_cc pattern: 1241 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1242 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1243 1244 // We need to handle f128 SELECT_CC with integer result type. 1245 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1246 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1247 } 1248 1249 if (Subtarget.hasP9Altivec()) { 1250 if (Subtarget.isISA3_1()) { 1251 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 1252 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal); 1253 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal); 1254 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal); 1255 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Legal); 1256 } else { 1257 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1258 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1259 } 1260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1267 } 1268 } 1269 1270 if (Subtarget.pairedVectorMemops()) { 1271 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1272 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1273 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1274 } 1275 if (Subtarget.hasMMA()) { 1276 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1277 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1278 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1279 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1280 } 1281 1282 if (Subtarget.has64BitSupport()) 1283 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1284 1285 if (Subtarget.isISA3_1()) 1286 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1287 1288 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1289 1290 if (!isPPC64) { 1291 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1292 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1293 } 1294 1295 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) { 1296 setMaxAtomicSizeInBitsSupported(128); 1297 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 1298 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 1299 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom); 1300 } 1301 1302 setBooleanContents(ZeroOrOneBooleanContent); 1303 1304 if (Subtarget.hasAltivec()) { 1305 // Altivec instructions set fields to all zeros or all ones. 1306 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1307 } 1308 1309 if (!isPPC64) { 1310 // These libcalls are not available in 32-bit. 1311 setLibcallName(RTLIB::SHL_I128, nullptr); 1312 setLibcallName(RTLIB::SRL_I128, nullptr); 1313 setLibcallName(RTLIB::SRA_I128, nullptr); 1314 setLibcallName(RTLIB::MULO_I64, nullptr); 1315 } 1316 1317 if (!isPPC64) 1318 setMaxAtomicSizeInBitsSupported(32); 1319 1320 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1321 1322 // We have target-specific dag combine patterns for the following nodes: 1323 setTargetDAGCombine(ISD::ADD); 1324 setTargetDAGCombine(ISD::SHL); 1325 setTargetDAGCombine(ISD::SRA); 1326 setTargetDAGCombine(ISD::SRL); 1327 setTargetDAGCombine(ISD::MUL); 1328 setTargetDAGCombine(ISD::FMA); 1329 setTargetDAGCombine(ISD::SINT_TO_FP); 1330 setTargetDAGCombine(ISD::BUILD_VECTOR); 1331 if (Subtarget.hasFPCVT()) 1332 setTargetDAGCombine(ISD::UINT_TO_FP); 1333 setTargetDAGCombine(ISD::LOAD); 1334 setTargetDAGCombine(ISD::STORE); 1335 setTargetDAGCombine(ISD::BR_CC); 1336 if (Subtarget.useCRBits()) 1337 setTargetDAGCombine(ISD::BRCOND); 1338 setTargetDAGCombine(ISD::BSWAP); 1339 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1340 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1341 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1342 1343 setTargetDAGCombine(ISD::SIGN_EXTEND); 1344 setTargetDAGCombine(ISD::ZERO_EXTEND); 1345 setTargetDAGCombine(ISD::ANY_EXTEND); 1346 1347 setTargetDAGCombine(ISD::TRUNCATE); 1348 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1349 1350 1351 if (Subtarget.useCRBits()) { 1352 setTargetDAGCombine(ISD::TRUNCATE); 1353 setTargetDAGCombine(ISD::SETCC); 1354 setTargetDAGCombine(ISD::SELECT_CC); 1355 } 1356 1357 if (Subtarget.hasP9Altivec()) { 1358 setTargetDAGCombine(ISD::ABS); 1359 setTargetDAGCombine(ISD::VSELECT); 1360 } 1361 1362 setLibcallName(RTLIB::LOG_F128, "logf128"); 1363 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1364 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1365 setLibcallName(RTLIB::EXP_F128, "expf128"); 1366 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1367 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1368 setLibcallName(RTLIB::COS_F128, "cosf128"); 1369 setLibcallName(RTLIB::POW_F128, "powf128"); 1370 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1371 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1372 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1373 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1374 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1375 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1376 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1377 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1378 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1379 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1380 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1381 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1382 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1383 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1384 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1385 1386 // With 32 condition bits, we don't need to sink (and duplicate) compares 1387 // aggressively in CodeGenPrep. 1388 if (Subtarget.useCRBits()) { 1389 setHasMultipleConditionRegisters(); 1390 setJumpIsExpensive(); 1391 } 1392 1393 setMinFunctionAlignment(Align(4)); 1394 1395 switch (Subtarget.getCPUDirective()) { 1396 default: break; 1397 case PPC::DIR_970: 1398 case PPC::DIR_A2: 1399 case PPC::DIR_E500: 1400 case PPC::DIR_E500mc: 1401 case PPC::DIR_E5500: 1402 case PPC::DIR_PWR4: 1403 case PPC::DIR_PWR5: 1404 case PPC::DIR_PWR5X: 1405 case PPC::DIR_PWR6: 1406 case PPC::DIR_PWR6X: 1407 case PPC::DIR_PWR7: 1408 case PPC::DIR_PWR8: 1409 case PPC::DIR_PWR9: 1410 case PPC::DIR_PWR10: 1411 case PPC::DIR_PWR_FUTURE: 1412 setPrefLoopAlignment(Align(16)); 1413 setPrefFunctionAlignment(Align(16)); 1414 break; 1415 } 1416 1417 if (Subtarget.enableMachineScheduler()) 1418 setSchedulingPreference(Sched::Source); 1419 else 1420 setSchedulingPreference(Sched::Hybrid); 1421 1422 computeRegisterProperties(STI.getRegisterInfo()); 1423 1424 // The Freescale cores do better with aggressive inlining of memcpy and 1425 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1426 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1427 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1428 MaxStoresPerMemset = 32; 1429 MaxStoresPerMemsetOptSize = 16; 1430 MaxStoresPerMemcpy = 32; 1431 MaxStoresPerMemcpyOptSize = 8; 1432 MaxStoresPerMemmove = 32; 1433 MaxStoresPerMemmoveOptSize = 8; 1434 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1435 // The A2 also benefits from (very) aggressive inlining of memcpy and 1436 // friends. The overhead of a the function call, even when warm, can be 1437 // over one hundred cycles. 1438 MaxStoresPerMemset = 128; 1439 MaxStoresPerMemcpy = 128; 1440 MaxStoresPerMemmove = 128; 1441 MaxLoadsPerMemcmp = 128; 1442 } else { 1443 MaxLoadsPerMemcmp = 8; 1444 MaxLoadsPerMemcmpOptSize = 4; 1445 } 1446 1447 IsStrictFPEnabled = true; 1448 1449 // Let the subtarget (CPU) decide if a predictable select is more expensive 1450 // than the corresponding branch. This information is used in CGP to decide 1451 // when to convert selects into branches. 1452 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1453 } 1454 1455 // *********************************** NOTE ************************************ 1456 // For selecting load and store instructions, the addressing modes are defined 1457 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD 1458 // patterns to match the load the store instructions. 1459 // 1460 // The TD definitions for the addressing modes correspond to their respective 1461 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely 1462 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the 1463 // address mode flags of a particular node. Afterwards, the computed address 1464 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal 1465 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement 1466 // accordingly, based on the preferred addressing mode. 1467 // 1468 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode. 1469 // MemOpFlags contains all the possible flags that can be used to compute the 1470 // optimal addressing mode for load and store instructions. 1471 // AddrMode contains all the possible load and store addressing modes available 1472 // on Power (such as DForm, DSForm, DQForm, XForm, etc.) 1473 // 1474 // When adding new load and store instructions, it is possible that new address 1475 // flags may need to be added into MemOpFlags, and a new addressing mode will 1476 // need to be added to AddrMode. An entry of the new addressing mode (consisting 1477 // of the minimal and main distinguishing address flags for the new load/store 1478 // instructions) will need to be added into initializeAddrModeMap() below. 1479 // Finally, when adding new addressing modes, the getAddrModeForFlags() will 1480 // need to be updated to account for selecting the optimal addressing mode. 1481 // ***************************************************************************** 1482 /// Initialize the map that relates the different addressing modes of the load 1483 /// and store instructions to a set of flags. This ensures the load/store 1484 /// instruction is correctly matched during instruction selection. 1485 void PPCTargetLowering::initializeAddrModeMap() { 1486 AddrModesMap[PPC::AM_DForm] = { 1487 // LWZ, STW 1488 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt, 1489 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt, 1490 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1491 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1492 // LBZ, LHZ, STB, STH 1493 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1494 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1495 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1496 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1497 // LHA 1498 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1499 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1500 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1501 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1502 // LFS, LFD, STFS, STFD 1503 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1504 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1505 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1506 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1507 }; 1508 AddrModesMap[PPC::AM_DSForm] = { 1509 // LWA 1510 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt, 1511 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1512 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1513 // LD, STD 1514 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt, 1515 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt, 1516 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt, 1517 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64 1518 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1519 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1520 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1521 }; 1522 AddrModesMap[PPC::AM_DQForm] = { 1523 // LXV, STXV 1524 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1525 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1526 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1527 }; 1528 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 | 1529 PPC::MOF_SubtargetP10}; 1530 // TODO: Add mapping for quadword load/store. 1531 } 1532 1533 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1534 /// the desired ByVal argument alignment. 1535 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1536 if (MaxAlign == MaxMaxAlign) 1537 return; 1538 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1539 if (MaxMaxAlign >= 32 && 1540 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1541 MaxAlign = Align(32); 1542 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1543 MaxAlign < 16) 1544 MaxAlign = Align(16); 1545 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1546 Align EltAlign; 1547 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1548 if (EltAlign > MaxAlign) 1549 MaxAlign = EltAlign; 1550 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1551 for (auto *EltTy : STy->elements()) { 1552 Align EltAlign; 1553 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1554 if (EltAlign > MaxAlign) 1555 MaxAlign = EltAlign; 1556 if (MaxAlign == MaxMaxAlign) 1557 break; 1558 } 1559 } 1560 } 1561 1562 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1563 /// function arguments in the caller parameter area. 1564 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1565 const DataLayout &DL) const { 1566 // 16byte and wider vectors are passed on 16byte boundary. 1567 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1568 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1569 if (Subtarget.hasAltivec()) 1570 getMaxByValAlign(Ty, Alignment, Align(16)); 1571 return Alignment.value(); 1572 } 1573 1574 bool PPCTargetLowering::useSoftFloat() const { 1575 return Subtarget.useSoftFloat(); 1576 } 1577 1578 bool PPCTargetLowering::hasSPE() const { 1579 return Subtarget.hasSPE(); 1580 } 1581 1582 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1583 return VT.isScalarInteger(); 1584 } 1585 1586 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1587 switch ((PPCISD::NodeType)Opcode) { 1588 case PPCISD::FIRST_NUMBER: break; 1589 case PPCISD::FSEL: return "PPCISD::FSEL"; 1590 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1591 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1592 case PPCISD::FCFID: return "PPCISD::FCFID"; 1593 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1594 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1595 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1596 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1597 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1598 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1599 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1600 case PPCISD::FP_TO_UINT_IN_VSR: 1601 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1602 case PPCISD::FP_TO_SINT_IN_VSR: 1603 return "PPCISD::FP_TO_SINT_IN_VSR"; 1604 case PPCISD::FRE: return "PPCISD::FRE"; 1605 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1606 case PPCISD::FTSQRT: 1607 return "PPCISD::FTSQRT"; 1608 case PPCISD::FSQRT: 1609 return "PPCISD::FSQRT"; 1610 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1611 case PPCISD::VPERM: return "PPCISD::VPERM"; 1612 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1613 case PPCISD::XXSPLTI_SP_TO_DP: 1614 return "PPCISD::XXSPLTI_SP_TO_DP"; 1615 case PPCISD::XXSPLTI32DX: 1616 return "PPCISD::XXSPLTI32DX"; 1617 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1618 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1619 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1620 case PPCISD::CMPB: return "PPCISD::CMPB"; 1621 case PPCISD::Hi: return "PPCISD::Hi"; 1622 case PPCISD::Lo: return "PPCISD::Lo"; 1623 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1624 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1625 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1626 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1627 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1628 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1629 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1630 case PPCISD::SRL: return "PPCISD::SRL"; 1631 case PPCISD::SRA: return "PPCISD::SRA"; 1632 case PPCISD::SHL: return "PPCISD::SHL"; 1633 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1634 case PPCISD::CALL: return "PPCISD::CALL"; 1635 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1636 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1637 case PPCISD::CALL_RM: 1638 return "PPCISD::CALL_RM"; 1639 case PPCISD::CALL_NOP_RM: 1640 return "PPCISD::CALL_NOP_RM"; 1641 case PPCISD::CALL_NOTOC_RM: 1642 return "PPCISD::CALL_NOTOC_RM"; 1643 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1644 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1645 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1646 case PPCISD::BCTRL_RM: 1647 return "PPCISD::BCTRL_RM"; 1648 case PPCISD::BCTRL_LOAD_TOC_RM: 1649 return "PPCISD::BCTRL_LOAD_TOC_RM"; 1650 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1651 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1652 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1653 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1654 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1655 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1656 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1657 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1658 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1659 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1660 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1661 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1662 case PPCISD::ANDI_rec_1_EQ_BIT: 1663 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1664 case PPCISD::ANDI_rec_1_GT_BIT: 1665 return "PPCISD::ANDI_rec_1_GT_BIT"; 1666 case PPCISD::VCMP: return "PPCISD::VCMP"; 1667 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1668 case PPCISD::LBRX: return "PPCISD::LBRX"; 1669 case PPCISD::STBRX: return "PPCISD::STBRX"; 1670 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1671 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1672 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1673 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1674 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1675 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1676 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1677 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1678 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1679 case PPCISD::ST_VSR_SCAL_INT: 1680 return "PPCISD::ST_VSR_SCAL_INT"; 1681 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1682 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1683 case PPCISD::BDZ: return "PPCISD::BDZ"; 1684 case PPCISD::MFFS: return "PPCISD::MFFS"; 1685 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1686 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1687 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1688 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1689 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1690 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1691 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1692 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1693 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1694 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1695 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1696 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1697 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1698 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1699 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1700 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1701 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1702 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1703 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1704 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1705 case PPCISD::PADDI_DTPREL: 1706 return "PPCISD::PADDI_DTPREL"; 1707 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1708 case PPCISD::SC: return "PPCISD::SC"; 1709 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1710 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1711 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1712 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1713 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1714 case PPCISD::VABSD: return "PPCISD::VABSD"; 1715 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1716 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1717 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1718 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1719 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1720 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1721 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1722 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1723 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1724 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1725 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1726 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1727 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1728 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1729 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1730 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1731 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT"; 1732 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT"; 1733 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1734 case PPCISD::STRICT_FADDRTZ: 1735 return "PPCISD::STRICT_FADDRTZ"; 1736 case PPCISD::STRICT_FCTIDZ: 1737 return "PPCISD::STRICT_FCTIDZ"; 1738 case PPCISD::STRICT_FCTIWZ: 1739 return "PPCISD::STRICT_FCTIWZ"; 1740 case PPCISD::STRICT_FCTIDUZ: 1741 return "PPCISD::STRICT_FCTIDUZ"; 1742 case PPCISD::STRICT_FCTIWUZ: 1743 return "PPCISD::STRICT_FCTIWUZ"; 1744 case PPCISD::STRICT_FCFID: 1745 return "PPCISD::STRICT_FCFID"; 1746 case PPCISD::STRICT_FCFIDU: 1747 return "PPCISD::STRICT_FCFIDU"; 1748 case PPCISD::STRICT_FCFIDS: 1749 return "PPCISD::STRICT_FCFIDS"; 1750 case PPCISD::STRICT_FCFIDUS: 1751 return "PPCISD::STRICT_FCFIDUS"; 1752 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1753 } 1754 return nullptr; 1755 } 1756 1757 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1758 EVT VT) const { 1759 if (!VT.isVector()) 1760 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1761 1762 return VT.changeVectorElementTypeToInteger(); 1763 } 1764 1765 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1766 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1767 return true; 1768 } 1769 1770 //===----------------------------------------------------------------------===// 1771 // Node matching predicates, for use by the tblgen matching code. 1772 //===----------------------------------------------------------------------===// 1773 1774 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1775 static bool isFloatingPointZero(SDValue Op) { 1776 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1777 return CFP->getValueAPF().isZero(); 1778 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1779 // Maybe this has already been legalized into the constant pool? 1780 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1781 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1782 return CFP->getValueAPF().isZero(); 1783 } 1784 return false; 1785 } 1786 1787 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1788 /// true if Op is undef or if it matches the specified value. 1789 static bool isConstantOrUndef(int Op, int Val) { 1790 return Op < 0 || Op == Val; 1791 } 1792 1793 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1794 /// VPKUHUM instruction. 1795 /// The ShuffleKind distinguishes between big-endian operations with 1796 /// two different inputs (0), either-endian operations with two identical 1797 /// inputs (1), and little-endian operations with two different inputs (2). 1798 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1799 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1800 SelectionDAG &DAG) { 1801 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1802 if (ShuffleKind == 0) { 1803 if (IsLE) 1804 return false; 1805 for (unsigned i = 0; i != 16; ++i) 1806 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1807 return false; 1808 } else if (ShuffleKind == 2) { 1809 if (!IsLE) 1810 return false; 1811 for (unsigned i = 0; i != 16; ++i) 1812 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1813 return false; 1814 } else if (ShuffleKind == 1) { 1815 unsigned j = IsLE ? 0 : 1; 1816 for (unsigned i = 0; i != 8; ++i) 1817 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1818 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1819 return false; 1820 } 1821 return true; 1822 } 1823 1824 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1825 /// VPKUWUM instruction. 1826 /// The ShuffleKind distinguishes between big-endian operations with 1827 /// two different inputs (0), either-endian operations with two identical 1828 /// inputs (1), and little-endian operations with two different inputs (2). 1829 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1830 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1831 SelectionDAG &DAG) { 1832 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1833 if (ShuffleKind == 0) { 1834 if (IsLE) 1835 return false; 1836 for (unsigned i = 0; i != 16; i += 2) 1837 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1838 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1839 return false; 1840 } else if (ShuffleKind == 2) { 1841 if (!IsLE) 1842 return false; 1843 for (unsigned i = 0; i != 16; i += 2) 1844 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1845 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1846 return false; 1847 } else if (ShuffleKind == 1) { 1848 unsigned j = IsLE ? 0 : 2; 1849 for (unsigned i = 0; i != 8; i += 2) 1850 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1851 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1852 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1853 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1854 return false; 1855 } 1856 return true; 1857 } 1858 1859 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1860 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1861 /// current subtarget. 1862 /// 1863 /// The ShuffleKind distinguishes between big-endian operations with 1864 /// two different inputs (0), either-endian operations with two identical 1865 /// inputs (1), and little-endian operations with two different inputs (2). 1866 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1867 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1868 SelectionDAG &DAG) { 1869 const PPCSubtarget& Subtarget = 1870 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1871 if (!Subtarget.hasP8Vector()) 1872 return false; 1873 1874 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1875 if (ShuffleKind == 0) { 1876 if (IsLE) 1877 return false; 1878 for (unsigned i = 0; i != 16; i += 4) 1879 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1880 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1881 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1882 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1883 return false; 1884 } else if (ShuffleKind == 2) { 1885 if (!IsLE) 1886 return false; 1887 for (unsigned i = 0; i != 16; i += 4) 1888 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1889 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1890 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1891 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1892 return false; 1893 } else if (ShuffleKind == 1) { 1894 unsigned j = IsLE ? 0 : 4; 1895 for (unsigned i = 0; i != 8; i += 4) 1896 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1897 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1898 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1899 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1900 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1901 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1902 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1903 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1904 return false; 1905 } 1906 return true; 1907 } 1908 1909 /// isVMerge - Common function, used to match vmrg* shuffles. 1910 /// 1911 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1912 unsigned LHSStart, unsigned RHSStart) { 1913 if (N->getValueType(0) != MVT::v16i8) 1914 return false; 1915 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1916 "Unsupported merge size!"); 1917 1918 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1919 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1920 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1921 LHSStart+j+i*UnitSize) || 1922 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1923 RHSStart+j+i*UnitSize)) 1924 return false; 1925 } 1926 return true; 1927 } 1928 1929 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1930 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1931 /// The ShuffleKind distinguishes between big-endian merges with two 1932 /// different inputs (0), either-endian merges with two identical inputs (1), 1933 /// and little-endian merges with two different inputs (2). For the latter, 1934 /// the input operands are swapped (see PPCInstrAltivec.td). 1935 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1936 unsigned ShuffleKind, SelectionDAG &DAG) { 1937 if (DAG.getDataLayout().isLittleEndian()) { 1938 if (ShuffleKind == 1) // unary 1939 return isVMerge(N, UnitSize, 0, 0); 1940 else if (ShuffleKind == 2) // swapped 1941 return isVMerge(N, UnitSize, 0, 16); 1942 else 1943 return false; 1944 } else { 1945 if (ShuffleKind == 1) // unary 1946 return isVMerge(N, UnitSize, 8, 8); 1947 else if (ShuffleKind == 0) // normal 1948 return isVMerge(N, UnitSize, 8, 24); 1949 else 1950 return false; 1951 } 1952 } 1953 1954 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1955 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1956 /// The ShuffleKind distinguishes between big-endian merges with two 1957 /// different inputs (0), either-endian merges with two identical inputs (1), 1958 /// and little-endian merges with two different inputs (2). For the latter, 1959 /// the input operands are swapped (see PPCInstrAltivec.td). 1960 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1961 unsigned ShuffleKind, SelectionDAG &DAG) { 1962 if (DAG.getDataLayout().isLittleEndian()) { 1963 if (ShuffleKind == 1) // unary 1964 return isVMerge(N, UnitSize, 8, 8); 1965 else if (ShuffleKind == 2) // swapped 1966 return isVMerge(N, UnitSize, 8, 24); 1967 else 1968 return false; 1969 } else { 1970 if (ShuffleKind == 1) // unary 1971 return isVMerge(N, UnitSize, 0, 0); 1972 else if (ShuffleKind == 0) // normal 1973 return isVMerge(N, UnitSize, 0, 16); 1974 else 1975 return false; 1976 } 1977 } 1978 1979 /** 1980 * Common function used to match vmrgew and vmrgow shuffles 1981 * 1982 * The indexOffset determines whether to look for even or odd words in 1983 * the shuffle mask. This is based on the of the endianness of the target 1984 * machine. 1985 * - Little Endian: 1986 * - Use offset of 0 to check for odd elements 1987 * - Use offset of 4 to check for even elements 1988 * - Big Endian: 1989 * - Use offset of 0 to check for even elements 1990 * - Use offset of 4 to check for odd elements 1991 * A detailed description of the vector element ordering for little endian and 1992 * big endian can be found at 1993 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1994 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1995 * compiler differences mean to you 1996 * 1997 * The mask to the shuffle vector instruction specifies the indices of the 1998 * elements from the two input vectors to place in the result. The elements are 1999 * numbered in array-access order, starting with the first vector. These vectors 2000 * are always of type v16i8, thus each vector will contain 16 elements of size 2001 * 8. More info on the shuffle vector can be found in the 2002 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 2003 * Language Reference. 2004 * 2005 * The RHSStartValue indicates whether the same input vectors are used (unary) 2006 * or two different input vectors are used, based on the following: 2007 * - If the instruction uses the same vector for both inputs, the range of the 2008 * indices will be 0 to 15. In this case, the RHSStart value passed should 2009 * be 0. 2010 * - If the instruction has two different vectors then the range of the 2011 * indices will be 0 to 31. In this case, the RHSStart value passed should 2012 * be 16 (indices 0-15 specify elements in the first vector while indices 16 2013 * to 31 specify elements in the second vector). 2014 * 2015 * \param[in] N The shuffle vector SD Node to analyze 2016 * \param[in] IndexOffset Specifies whether to look for even or odd elements 2017 * \param[in] RHSStartValue Specifies the starting index for the righthand input 2018 * vector to the shuffle_vector instruction 2019 * \return true iff this shuffle vector represents an even or odd word merge 2020 */ 2021 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 2022 unsigned RHSStartValue) { 2023 if (N->getValueType(0) != MVT::v16i8) 2024 return false; 2025 2026 for (unsigned i = 0; i < 2; ++i) 2027 for (unsigned j = 0; j < 4; ++j) 2028 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 2029 i*RHSStartValue+j+IndexOffset) || 2030 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2031 i*RHSStartValue+j+IndexOffset+8)) 2032 return false; 2033 return true; 2034 } 2035 2036 /** 2037 * Determine if the specified shuffle mask is suitable for the vmrgew or 2038 * vmrgow instructions. 2039 * 2040 * \param[in] N The shuffle vector SD Node to analyze 2041 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2042 * \param[in] ShuffleKind Identify the type of merge: 2043 * - 0 = big-endian merge with two different inputs; 2044 * - 1 = either-endian merge with two identical inputs; 2045 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2046 * little-endian merges). 2047 * \param[in] DAG The current SelectionDAG 2048 * \return true iff this shuffle mask 2049 */ 2050 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2051 unsigned ShuffleKind, SelectionDAG &DAG) { 2052 if (DAG.getDataLayout().isLittleEndian()) { 2053 unsigned indexOffset = CheckEven ? 4 : 0; 2054 if (ShuffleKind == 1) // Unary 2055 return isVMerge(N, indexOffset, 0); 2056 else if (ShuffleKind == 2) // swapped 2057 return isVMerge(N, indexOffset, 16); 2058 else 2059 return false; 2060 } 2061 else { 2062 unsigned indexOffset = CheckEven ? 0 : 4; 2063 if (ShuffleKind == 1) // Unary 2064 return isVMerge(N, indexOffset, 0); 2065 else if (ShuffleKind == 0) // Normal 2066 return isVMerge(N, indexOffset, 16); 2067 else 2068 return false; 2069 } 2070 return false; 2071 } 2072 2073 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2074 /// amount, otherwise return -1. 2075 /// The ShuffleKind distinguishes between big-endian operations with two 2076 /// different inputs (0), either-endian operations with two identical inputs 2077 /// (1), and little-endian operations with two different inputs (2). For the 2078 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2079 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2080 SelectionDAG &DAG) { 2081 if (N->getValueType(0) != MVT::v16i8) 2082 return -1; 2083 2084 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2085 2086 // Find the first non-undef value in the shuffle mask. 2087 unsigned i; 2088 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2089 /*search*/; 2090 2091 if (i == 16) return -1; // all undef. 2092 2093 // Otherwise, check to see if the rest of the elements are consecutively 2094 // numbered from this value. 2095 unsigned ShiftAmt = SVOp->getMaskElt(i); 2096 if (ShiftAmt < i) return -1; 2097 2098 ShiftAmt -= i; 2099 bool isLE = DAG.getDataLayout().isLittleEndian(); 2100 2101 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2102 // Check the rest of the elements to see if they are consecutive. 2103 for (++i; i != 16; ++i) 2104 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2105 return -1; 2106 } else if (ShuffleKind == 1) { 2107 // Check the rest of the elements to see if they are consecutive. 2108 for (++i; i != 16; ++i) 2109 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2110 return -1; 2111 } else 2112 return -1; 2113 2114 if (isLE) 2115 ShiftAmt = 16 - ShiftAmt; 2116 2117 return ShiftAmt; 2118 } 2119 2120 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2121 /// specifies a splat of a single element that is suitable for input to 2122 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2123 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2124 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 2125 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2126 2127 // The consecutive indices need to specify an element, not part of two 2128 // different elements. So abandon ship early if this isn't the case. 2129 if (N->getMaskElt(0) % EltSize != 0) 2130 return false; 2131 2132 // This is a splat operation if each element of the permute is the same, and 2133 // if the value doesn't reference the second vector. 2134 unsigned ElementBase = N->getMaskElt(0); 2135 2136 // FIXME: Handle UNDEF elements too! 2137 if (ElementBase >= 16) 2138 return false; 2139 2140 // Check that the indices are consecutive, in the case of a multi-byte element 2141 // splatted with a v16i8 mask. 2142 for (unsigned i = 1; i != EltSize; ++i) 2143 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2144 return false; 2145 2146 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2147 if (N->getMaskElt(i) < 0) continue; 2148 for (unsigned j = 0; j != EltSize; ++j) 2149 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2150 return false; 2151 } 2152 return true; 2153 } 2154 2155 /// Check that the mask is shuffling N byte elements. Within each N byte 2156 /// element of the mask, the indices could be either in increasing or 2157 /// decreasing order as long as they are consecutive. 2158 /// \param[in] N the shuffle vector SD Node to analyze 2159 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2160 /// Word/DoubleWord/QuadWord). 2161 /// \param[in] StepLen the delta indices number among the N byte element, if 2162 /// the mask is in increasing/decreasing order then it is 1/-1. 2163 /// \return true iff the mask is shuffling N byte elements. 2164 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2165 int StepLen) { 2166 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2167 "Unexpected element width."); 2168 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2169 2170 unsigned NumOfElem = 16 / Width; 2171 unsigned MaskVal[16]; // Width is never greater than 16 2172 for (unsigned i = 0; i < NumOfElem; ++i) { 2173 MaskVal[0] = N->getMaskElt(i * Width); 2174 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2175 return false; 2176 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2177 return false; 2178 } 2179 2180 for (unsigned int j = 1; j < Width; ++j) { 2181 MaskVal[j] = N->getMaskElt(i * Width + j); 2182 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2183 return false; 2184 } 2185 } 2186 } 2187 2188 return true; 2189 } 2190 2191 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2192 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2193 if (!isNByteElemShuffleMask(N, 4, 1)) 2194 return false; 2195 2196 // Now we look at mask elements 0,4,8,12 2197 unsigned M0 = N->getMaskElt(0) / 4; 2198 unsigned M1 = N->getMaskElt(4) / 4; 2199 unsigned M2 = N->getMaskElt(8) / 4; 2200 unsigned M3 = N->getMaskElt(12) / 4; 2201 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2202 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2203 2204 // Below, let H and L be arbitrary elements of the shuffle mask 2205 // where H is in the range [4,7] and L is in the range [0,3]. 2206 // H, 1, 2, 3 or L, 5, 6, 7 2207 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2208 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2209 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2210 InsertAtByte = IsLE ? 12 : 0; 2211 Swap = M0 < 4; 2212 return true; 2213 } 2214 // 0, H, 2, 3 or 4, L, 6, 7 2215 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2216 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2217 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2218 InsertAtByte = IsLE ? 8 : 4; 2219 Swap = M1 < 4; 2220 return true; 2221 } 2222 // 0, 1, H, 3 or 4, 5, L, 7 2223 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2224 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2225 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2226 InsertAtByte = IsLE ? 4 : 8; 2227 Swap = M2 < 4; 2228 return true; 2229 } 2230 // 0, 1, 2, H or 4, 5, 6, L 2231 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2232 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2233 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2234 InsertAtByte = IsLE ? 0 : 12; 2235 Swap = M3 < 4; 2236 return true; 2237 } 2238 2239 // If both vector operands for the shuffle are the same vector, the mask will 2240 // contain only elements from the first one and the second one will be undef. 2241 if (N->getOperand(1).isUndef()) { 2242 ShiftElts = 0; 2243 Swap = true; 2244 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2245 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2246 InsertAtByte = IsLE ? 12 : 0; 2247 return true; 2248 } 2249 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2250 InsertAtByte = IsLE ? 8 : 4; 2251 return true; 2252 } 2253 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2254 InsertAtByte = IsLE ? 4 : 8; 2255 return true; 2256 } 2257 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2258 InsertAtByte = IsLE ? 0 : 12; 2259 return true; 2260 } 2261 } 2262 2263 return false; 2264 } 2265 2266 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2267 bool &Swap, bool IsLE) { 2268 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2269 // Ensure each byte index of the word is consecutive. 2270 if (!isNByteElemShuffleMask(N, 4, 1)) 2271 return false; 2272 2273 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2274 unsigned M0 = N->getMaskElt(0) / 4; 2275 unsigned M1 = N->getMaskElt(4) / 4; 2276 unsigned M2 = N->getMaskElt(8) / 4; 2277 unsigned M3 = N->getMaskElt(12) / 4; 2278 2279 // If both vector operands for the shuffle are the same vector, the mask will 2280 // contain only elements from the first one and the second one will be undef. 2281 if (N->getOperand(1).isUndef()) { 2282 assert(M0 < 4 && "Indexing into an undef vector?"); 2283 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2284 return false; 2285 2286 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2287 Swap = false; 2288 return true; 2289 } 2290 2291 // Ensure each word index of the ShuffleVector Mask is consecutive. 2292 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2293 return false; 2294 2295 if (IsLE) { 2296 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2297 // Input vectors don't need to be swapped if the leading element 2298 // of the result is one of the 3 left elements of the second vector 2299 // (or if there is no shift to be done at all). 2300 Swap = false; 2301 ShiftElts = (8 - M0) % 8; 2302 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2303 // Input vectors need to be swapped if the leading element 2304 // of the result is one of the 3 left elements of the first vector 2305 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2306 Swap = true; 2307 ShiftElts = (4 - M0) % 4; 2308 } 2309 2310 return true; 2311 } else { // BE 2312 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2313 // Input vectors don't need to be swapped if the leading element 2314 // of the result is one of the 4 elements of the first vector. 2315 Swap = false; 2316 ShiftElts = M0; 2317 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2318 // Input vectors need to be swapped if the leading element 2319 // of the result is one of the 4 elements of the right vector. 2320 Swap = true; 2321 ShiftElts = M0 - 4; 2322 } 2323 2324 return true; 2325 } 2326 } 2327 2328 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2329 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2330 2331 if (!isNByteElemShuffleMask(N, Width, -1)) 2332 return false; 2333 2334 for (int i = 0; i < 16; i += Width) 2335 if (N->getMaskElt(i) != i + Width - 1) 2336 return false; 2337 2338 return true; 2339 } 2340 2341 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2342 return isXXBRShuffleMaskHelper(N, 2); 2343 } 2344 2345 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2346 return isXXBRShuffleMaskHelper(N, 4); 2347 } 2348 2349 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2350 return isXXBRShuffleMaskHelper(N, 8); 2351 } 2352 2353 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2354 return isXXBRShuffleMaskHelper(N, 16); 2355 } 2356 2357 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2358 /// if the inputs to the instruction should be swapped and set \p DM to the 2359 /// value for the immediate. 2360 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2361 /// AND element 0 of the result comes from the first input (LE) or second input 2362 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2363 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2364 /// mask. 2365 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2366 bool &Swap, bool IsLE) { 2367 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2368 2369 // Ensure each byte index of the double word is consecutive. 2370 if (!isNByteElemShuffleMask(N, 8, 1)) 2371 return false; 2372 2373 unsigned M0 = N->getMaskElt(0) / 8; 2374 unsigned M1 = N->getMaskElt(8) / 8; 2375 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2376 2377 // If both vector operands for the shuffle are the same vector, the mask will 2378 // contain only elements from the first one and the second one will be undef. 2379 if (N->getOperand(1).isUndef()) { 2380 if ((M0 | M1) < 2) { 2381 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2382 Swap = false; 2383 return true; 2384 } else 2385 return false; 2386 } 2387 2388 if (IsLE) { 2389 if (M0 > 1 && M1 < 2) { 2390 Swap = false; 2391 } else if (M0 < 2 && M1 > 1) { 2392 M0 = (M0 + 2) % 4; 2393 M1 = (M1 + 2) % 4; 2394 Swap = true; 2395 } else 2396 return false; 2397 2398 // Note: if control flow comes here that means Swap is already set above 2399 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2400 return true; 2401 } else { // BE 2402 if (M0 < 2 && M1 > 1) { 2403 Swap = false; 2404 } else if (M0 > 1 && M1 < 2) { 2405 M0 = (M0 + 2) % 4; 2406 M1 = (M1 + 2) % 4; 2407 Swap = true; 2408 } else 2409 return false; 2410 2411 // Note: if control flow comes here that means Swap is already set above 2412 DM = (M0 << 1) + (M1 & 1); 2413 return true; 2414 } 2415 } 2416 2417 2418 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2419 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2420 /// elements are counted from the left of the vector register). 2421 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2422 SelectionDAG &DAG) { 2423 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2424 assert(isSplatShuffleMask(SVOp, EltSize)); 2425 if (DAG.getDataLayout().isLittleEndian()) 2426 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2427 else 2428 return SVOp->getMaskElt(0) / EltSize; 2429 } 2430 2431 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2432 /// by using a vspltis[bhw] instruction of the specified element size, return 2433 /// the constant being splatted. The ByteSize field indicates the number of 2434 /// bytes of each element [124] -> [bhw]. 2435 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2436 SDValue OpVal(nullptr, 0); 2437 2438 // If ByteSize of the splat is bigger than the element size of the 2439 // build_vector, then we have a case where we are checking for a splat where 2440 // multiple elements of the buildvector are folded together into a single 2441 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2442 unsigned EltSize = 16/N->getNumOperands(); 2443 if (EltSize < ByteSize) { 2444 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2445 SDValue UniquedVals[4]; 2446 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2447 2448 // See if all of the elements in the buildvector agree across. 2449 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2450 if (N->getOperand(i).isUndef()) continue; 2451 // If the element isn't a constant, bail fully out. 2452 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2453 2454 if (!UniquedVals[i&(Multiple-1)].getNode()) 2455 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2456 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2457 return SDValue(); // no match. 2458 } 2459 2460 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2461 // either constant or undef values that are identical for each chunk. See 2462 // if these chunks can form into a larger vspltis*. 2463 2464 // Check to see if all of the leading entries are either 0 or -1. If 2465 // neither, then this won't fit into the immediate field. 2466 bool LeadingZero = true; 2467 bool LeadingOnes = true; 2468 for (unsigned i = 0; i != Multiple-1; ++i) { 2469 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2470 2471 LeadingZero &= isNullConstant(UniquedVals[i]); 2472 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2473 } 2474 // Finally, check the least significant entry. 2475 if (LeadingZero) { 2476 if (!UniquedVals[Multiple-1].getNode()) 2477 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2478 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2479 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2480 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2481 } 2482 if (LeadingOnes) { 2483 if (!UniquedVals[Multiple-1].getNode()) 2484 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2485 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2486 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2487 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2488 } 2489 2490 return SDValue(); 2491 } 2492 2493 // Check to see if this buildvec has a single non-undef value in its elements. 2494 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2495 if (N->getOperand(i).isUndef()) continue; 2496 if (!OpVal.getNode()) 2497 OpVal = N->getOperand(i); 2498 else if (OpVal != N->getOperand(i)) 2499 return SDValue(); 2500 } 2501 2502 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2503 2504 unsigned ValSizeInBytes = EltSize; 2505 uint64_t Value = 0; 2506 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2507 Value = CN->getZExtValue(); 2508 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2509 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2510 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2511 } 2512 2513 // If the splat value is larger than the element value, then we can never do 2514 // this splat. The only case that we could fit the replicated bits into our 2515 // immediate field for would be zero, and we prefer to use vxor for it. 2516 if (ValSizeInBytes < ByteSize) return SDValue(); 2517 2518 // If the element value is larger than the splat value, check if it consists 2519 // of a repeated bit pattern of size ByteSize. 2520 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2521 return SDValue(); 2522 2523 // Properly sign extend the value. 2524 int MaskVal = SignExtend32(Value, ByteSize * 8); 2525 2526 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2527 if (MaskVal == 0) return SDValue(); 2528 2529 // Finally, if this value fits in a 5 bit sext field, return it 2530 if (SignExtend32<5>(MaskVal) == MaskVal) 2531 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2532 return SDValue(); 2533 } 2534 2535 //===----------------------------------------------------------------------===// 2536 // Addressing Mode Selection 2537 //===----------------------------------------------------------------------===// 2538 2539 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2540 /// or 64-bit immediate, and if the value can be accurately represented as a 2541 /// sign extension from a 16-bit value. If so, this returns true and the 2542 /// immediate. 2543 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2544 if (!isa<ConstantSDNode>(N)) 2545 return false; 2546 2547 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2548 if (N->getValueType(0) == MVT::i32) 2549 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2550 else 2551 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2552 } 2553 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2554 return isIntS16Immediate(Op.getNode(), Imm); 2555 } 2556 2557 /// Used when computing address flags for selecting loads and stores. 2558 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2559 /// An OR of two provably disjoint values is equivalent to an ADD. 2560 /// Most PPC load/store instructions compute the effective address as a sum, 2561 /// so doing this conversion is useful. 2562 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2563 if (N.getOpcode() != ISD::OR) 2564 return false; 2565 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2566 if (!LHSKnown.Zero.getBoolValue()) 2567 return false; 2568 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2569 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2570 } 2571 2572 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2573 /// be represented as an indexed [r+r] operation. 2574 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2575 SDValue &Index, 2576 SelectionDAG &DAG) const { 2577 for (SDNode *U : N->uses()) { 2578 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) { 2579 if (Memop->getMemoryVT() == MVT::f64) { 2580 Base = N.getOperand(0); 2581 Index = N.getOperand(1); 2582 return true; 2583 } 2584 } 2585 } 2586 return false; 2587 } 2588 2589 /// isIntS34Immediate - This method tests if value of node given can be 2590 /// accurately represented as a sign extension from a 34-bit value. If so, 2591 /// this returns true and the immediate. 2592 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2593 if (!isa<ConstantSDNode>(N)) 2594 return false; 2595 2596 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2597 return isInt<34>(Imm); 2598 } 2599 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2600 return isIntS34Immediate(Op.getNode(), Imm); 2601 } 2602 2603 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2604 /// can be represented as an indexed [r+r] operation. Returns false if it 2605 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2606 /// non-zero and N can be represented by a base register plus a signed 16-bit 2607 /// displacement, make a more precise judgement by checking (displacement % \p 2608 /// EncodingAlignment). 2609 bool PPCTargetLowering::SelectAddressRegReg( 2610 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2611 MaybeAlign EncodingAlignment) const { 2612 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2613 // a [pc+imm]. 2614 if (SelectAddressPCRel(N, Base)) 2615 return false; 2616 2617 int16_t Imm = 0; 2618 if (N.getOpcode() == ISD::ADD) { 2619 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2620 // SPE load/store can only handle 8-bit offsets. 2621 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2622 return true; 2623 if (isIntS16Immediate(N.getOperand(1), Imm) && 2624 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2625 return false; // r+i 2626 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2627 return false; // r+i 2628 2629 Base = N.getOperand(0); 2630 Index = N.getOperand(1); 2631 return true; 2632 } else if (N.getOpcode() == ISD::OR) { 2633 if (isIntS16Immediate(N.getOperand(1), Imm) && 2634 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2635 return false; // r+i can fold it if we can. 2636 2637 // If this is an or of disjoint bitfields, we can codegen this as an add 2638 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2639 // disjoint. 2640 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2641 2642 if (LHSKnown.Zero.getBoolValue()) { 2643 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2644 // If all of the bits are known zero on the LHS or RHS, the add won't 2645 // carry. 2646 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2647 Base = N.getOperand(0); 2648 Index = N.getOperand(1); 2649 return true; 2650 } 2651 } 2652 } 2653 2654 return false; 2655 } 2656 2657 // If we happen to be doing an i64 load or store into a stack slot that has 2658 // less than a 4-byte alignment, then the frame-index elimination may need to 2659 // use an indexed load or store instruction (because the offset may not be a 2660 // multiple of 4). The extra register needed to hold the offset comes from the 2661 // register scavenger, and it is possible that the scavenger will need to use 2662 // an emergency spill slot. As a result, we need to make sure that a spill slot 2663 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2664 // stack slot. 2665 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2666 // FIXME: This does not handle the LWA case. 2667 if (VT != MVT::i64) 2668 return; 2669 2670 // NOTE: We'll exclude negative FIs here, which come from argument 2671 // lowering, because there are no known test cases triggering this problem 2672 // using packed structures (or similar). We can remove this exclusion if 2673 // we find such a test case. The reason why this is so test-case driven is 2674 // because this entire 'fixup' is only to prevent crashes (from the 2675 // register scavenger) on not-really-valid inputs. For example, if we have: 2676 // %a = alloca i1 2677 // %b = bitcast i1* %a to i64* 2678 // store i64* a, i64 b 2679 // then the store should really be marked as 'align 1', but is not. If it 2680 // were marked as 'align 1' then the indexed form would have been 2681 // instruction-selected initially, and the problem this 'fixup' is preventing 2682 // won't happen regardless. 2683 if (FrameIdx < 0) 2684 return; 2685 2686 MachineFunction &MF = DAG.getMachineFunction(); 2687 MachineFrameInfo &MFI = MF.getFrameInfo(); 2688 2689 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2690 return; 2691 2692 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2693 FuncInfo->setHasNonRISpills(); 2694 } 2695 2696 /// Returns true if the address N can be represented by a base register plus 2697 /// a signed 16-bit displacement [r+imm], and if it is not better 2698 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2699 /// displacements that are multiples of that value. 2700 bool PPCTargetLowering::SelectAddressRegImm( 2701 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2702 MaybeAlign EncodingAlignment) const { 2703 // FIXME dl should come from parent load or store, not from address 2704 SDLoc dl(N); 2705 2706 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2707 // a [pc+imm]. 2708 if (SelectAddressPCRel(N, Base)) 2709 return false; 2710 2711 // If this can be more profitably realized as r+r, fail. 2712 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2713 return false; 2714 2715 if (N.getOpcode() == ISD::ADD) { 2716 int16_t imm = 0; 2717 if (isIntS16Immediate(N.getOperand(1), imm) && 2718 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2719 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2720 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2721 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2722 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2723 } else { 2724 Base = N.getOperand(0); 2725 } 2726 return true; // [r+i] 2727 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2728 // Match LOAD (ADD (X, Lo(G))). 2729 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2730 && "Cannot handle constant offsets yet!"); 2731 Disp = N.getOperand(1).getOperand(0); // The global address. 2732 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2733 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2734 Disp.getOpcode() == ISD::TargetConstantPool || 2735 Disp.getOpcode() == ISD::TargetJumpTable); 2736 Base = N.getOperand(0); 2737 return true; // [&g+r] 2738 } 2739 } else if (N.getOpcode() == ISD::OR) { 2740 int16_t imm = 0; 2741 if (isIntS16Immediate(N.getOperand(1), imm) && 2742 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2743 // If this is an or of disjoint bitfields, we can codegen this as an add 2744 // (for better address arithmetic) if the LHS and RHS of the OR are 2745 // provably disjoint. 2746 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2747 2748 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2749 // If all of the bits are known zero on the LHS or RHS, the add won't 2750 // carry. 2751 if (FrameIndexSDNode *FI = 2752 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2753 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2754 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2755 } else { 2756 Base = N.getOperand(0); 2757 } 2758 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2759 return true; 2760 } 2761 } 2762 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2763 // Loading from a constant address. 2764 2765 // If this address fits entirely in a 16-bit sext immediate field, codegen 2766 // this as "d, 0" 2767 int16_t Imm; 2768 if (isIntS16Immediate(CN, Imm) && 2769 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2770 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2771 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2772 CN->getValueType(0)); 2773 return true; 2774 } 2775 2776 // Handle 32-bit sext immediates with LIS + addr mode. 2777 if ((CN->getValueType(0) == MVT::i32 || 2778 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2779 (!EncodingAlignment || 2780 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2781 int Addr = (int)CN->getZExtValue(); 2782 2783 // Otherwise, break this down into an LIS + disp. 2784 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2785 2786 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2787 MVT::i32); 2788 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2789 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2790 return true; 2791 } 2792 } 2793 2794 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2795 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2796 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2797 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2798 } else 2799 Base = N; 2800 return true; // [r+0] 2801 } 2802 2803 /// Similar to the 16-bit case but for instructions that take a 34-bit 2804 /// displacement field (prefixed loads/stores). 2805 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2806 SDValue &Base, 2807 SelectionDAG &DAG) const { 2808 // Only on 64-bit targets. 2809 if (N.getValueType() != MVT::i64) 2810 return false; 2811 2812 SDLoc dl(N); 2813 int64_t Imm = 0; 2814 2815 if (N.getOpcode() == ISD::ADD) { 2816 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2817 return false; 2818 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2819 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2820 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2821 else 2822 Base = N.getOperand(0); 2823 return true; 2824 } 2825 2826 if (N.getOpcode() == ISD::OR) { 2827 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2828 return false; 2829 // If this is an or of disjoint bitfields, we can codegen this as an add 2830 // (for better address arithmetic) if the LHS and RHS of the OR are 2831 // provably disjoint. 2832 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2833 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2834 return false; 2835 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2836 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2837 else 2838 Base = N.getOperand(0); 2839 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2840 return true; 2841 } 2842 2843 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2844 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2845 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2846 return true; 2847 } 2848 2849 return false; 2850 } 2851 2852 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2853 /// represented as an indexed [r+r] operation. 2854 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2855 SDValue &Index, 2856 SelectionDAG &DAG) const { 2857 // Check to see if we can easily represent this as an [r+r] address. This 2858 // will fail if it thinks that the address is more profitably represented as 2859 // reg+imm, e.g. where imm = 0. 2860 if (SelectAddressRegReg(N, Base, Index, DAG)) 2861 return true; 2862 2863 // If the address is the result of an add, we will utilize the fact that the 2864 // address calculation includes an implicit add. However, we can reduce 2865 // register pressure if we do not materialize a constant just for use as the 2866 // index register. We only get rid of the add if it is not an add of a 2867 // value and a 16-bit signed constant and both have a single use. 2868 int16_t imm = 0; 2869 if (N.getOpcode() == ISD::ADD && 2870 (!isIntS16Immediate(N.getOperand(1), imm) || 2871 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2872 Base = N.getOperand(0); 2873 Index = N.getOperand(1); 2874 return true; 2875 } 2876 2877 // Otherwise, do it the hard way, using R0 as the base register. 2878 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2879 N.getValueType()); 2880 Index = N; 2881 return true; 2882 } 2883 2884 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2885 Ty *PCRelCand = dyn_cast<Ty>(N); 2886 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2887 } 2888 2889 /// Returns true if this address is a PC Relative address. 2890 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2891 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2892 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2893 // This is a materialize PC Relative node. Always select this as PC Relative. 2894 Base = N; 2895 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2896 return true; 2897 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2898 isValidPCRelNode<GlobalAddressSDNode>(N) || 2899 isValidPCRelNode<JumpTableSDNode>(N) || 2900 isValidPCRelNode<BlockAddressSDNode>(N)) 2901 return true; 2902 return false; 2903 } 2904 2905 /// Returns true if we should use a direct load into vector instruction 2906 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2907 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2908 2909 // If there are any other uses other than scalar to vector, then we should 2910 // keep it as a scalar load -> direct move pattern to prevent multiple 2911 // loads. 2912 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2913 if (!LD) 2914 return false; 2915 2916 EVT MemVT = LD->getMemoryVT(); 2917 if (!MemVT.isSimple()) 2918 return false; 2919 switch(MemVT.getSimpleVT().SimpleTy) { 2920 case MVT::i64: 2921 break; 2922 case MVT::i32: 2923 if (!ST.hasP8Vector()) 2924 return false; 2925 break; 2926 case MVT::i16: 2927 case MVT::i8: 2928 if (!ST.hasP9Vector()) 2929 return false; 2930 break; 2931 default: 2932 return false; 2933 } 2934 2935 SDValue LoadedVal(N, 0); 2936 if (!LoadedVal.hasOneUse()) 2937 return false; 2938 2939 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2940 UI != UE; ++UI) 2941 if (UI.getUse().get().getResNo() == 0 && 2942 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2943 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2944 return false; 2945 2946 return true; 2947 } 2948 2949 /// getPreIndexedAddressParts - returns true by value, base pointer and 2950 /// offset pointer and addressing mode by reference if the node's address 2951 /// can be legally represented as pre-indexed load / store address. 2952 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2953 SDValue &Offset, 2954 ISD::MemIndexedMode &AM, 2955 SelectionDAG &DAG) const { 2956 if (DisablePPCPreinc) return false; 2957 2958 bool isLoad = true; 2959 SDValue Ptr; 2960 EVT VT; 2961 unsigned Alignment; 2962 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2963 Ptr = LD->getBasePtr(); 2964 VT = LD->getMemoryVT(); 2965 Alignment = LD->getAlignment(); 2966 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2967 Ptr = ST->getBasePtr(); 2968 VT = ST->getMemoryVT(); 2969 Alignment = ST->getAlignment(); 2970 isLoad = false; 2971 } else 2972 return false; 2973 2974 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2975 // instructions because we can fold these into a more efficient instruction 2976 // instead, (such as LXSD). 2977 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2978 return false; 2979 } 2980 2981 // PowerPC doesn't have preinc load/store instructions for vectors 2982 if (VT.isVector()) 2983 return false; 2984 2985 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2986 // Common code will reject creating a pre-inc form if the base pointer 2987 // is a frame index, or if N is a store and the base pointer is either 2988 // the same as or a predecessor of the value being stored. Check for 2989 // those situations here, and try with swapped Base/Offset instead. 2990 bool Swap = false; 2991 2992 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2993 Swap = true; 2994 else if (!isLoad) { 2995 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2996 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2997 Swap = true; 2998 } 2999 3000 if (Swap) 3001 std::swap(Base, Offset); 3002 3003 AM = ISD::PRE_INC; 3004 return true; 3005 } 3006 3007 // LDU/STU can only handle immediates that are a multiple of 4. 3008 if (VT != MVT::i64) { 3009 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 3010 return false; 3011 } else { 3012 // LDU/STU need an address with at least 4-byte alignment. 3013 if (Alignment < 4) 3014 return false; 3015 3016 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 3017 return false; 3018 } 3019 3020 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3021 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 3022 // sext i32 to i64 when addr mode is r+i. 3023 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 3024 LD->getExtensionType() == ISD::SEXTLOAD && 3025 isa<ConstantSDNode>(Offset)) 3026 return false; 3027 } 3028 3029 AM = ISD::PRE_INC; 3030 return true; 3031 } 3032 3033 //===----------------------------------------------------------------------===// 3034 // LowerOperation implementation 3035 //===----------------------------------------------------------------------===// 3036 3037 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3038 /// and LoOpFlags to the target MO flags. 3039 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3040 unsigned &HiOpFlags, unsigned &LoOpFlags, 3041 const GlobalValue *GV = nullptr) { 3042 HiOpFlags = PPCII::MO_HA; 3043 LoOpFlags = PPCII::MO_LO; 3044 3045 // Don't use the pic base if not in PIC relocation model. 3046 if (IsPIC) { 3047 HiOpFlags |= PPCII::MO_PIC_FLAG; 3048 LoOpFlags |= PPCII::MO_PIC_FLAG; 3049 } 3050 } 3051 3052 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3053 SelectionDAG &DAG) { 3054 SDLoc DL(HiPart); 3055 EVT PtrVT = HiPart.getValueType(); 3056 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3057 3058 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3059 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3060 3061 // With PIC, the first instruction is actually "GR+hi(&G)". 3062 if (isPIC) 3063 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3064 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3065 3066 // Generate non-pic code that has direct accesses to the constant pool. 3067 // The address of the global is just (hi(&g)+lo(&g)). 3068 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3069 } 3070 3071 static void setUsesTOCBasePtr(MachineFunction &MF) { 3072 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3073 FuncInfo->setUsesTOCBasePtr(); 3074 } 3075 3076 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3077 setUsesTOCBasePtr(DAG.getMachineFunction()); 3078 } 3079 3080 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3081 SDValue GA) const { 3082 const bool Is64Bit = Subtarget.isPPC64(); 3083 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3084 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3085 : Subtarget.isAIXABI() 3086 ? DAG.getRegister(PPC::R2, VT) 3087 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3088 SDValue Ops[] = { GA, Reg }; 3089 return DAG.getMemIntrinsicNode( 3090 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3091 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 3092 MachineMemOperand::MOLoad); 3093 } 3094 3095 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3096 SelectionDAG &DAG) const { 3097 EVT PtrVT = Op.getValueType(); 3098 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3099 const Constant *C = CP->getConstVal(); 3100 3101 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3102 // The actual address of the GlobalValue is stored in the TOC. 3103 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3104 if (Subtarget.isUsingPCRelativeCalls()) { 3105 SDLoc DL(CP); 3106 EVT Ty = getPointerTy(DAG.getDataLayout()); 3107 SDValue ConstPool = DAG.getTargetConstantPool( 3108 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3109 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3110 } 3111 setUsesTOCBasePtr(DAG); 3112 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3113 return getTOCEntry(DAG, SDLoc(CP), GA); 3114 } 3115 3116 unsigned MOHiFlag, MOLoFlag; 3117 bool IsPIC = isPositionIndependent(); 3118 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3119 3120 if (IsPIC && Subtarget.isSVR4ABI()) { 3121 SDValue GA = 3122 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3123 return getTOCEntry(DAG, SDLoc(CP), GA); 3124 } 3125 3126 SDValue CPIHi = 3127 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3128 SDValue CPILo = 3129 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3130 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3131 } 3132 3133 // For 64-bit PowerPC, prefer the more compact relative encodings. 3134 // This trades 32 bits per jump table entry for one or two instructions 3135 // on the jump site. 3136 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3137 if (isJumpTableRelative()) 3138 return MachineJumpTableInfo::EK_LabelDifference32; 3139 3140 return TargetLowering::getJumpTableEncoding(); 3141 } 3142 3143 bool PPCTargetLowering::isJumpTableRelative() const { 3144 if (UseAbsoluteJumpTables) 3145 return false; 3146 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3147 return true; 3148 return TargetLowering::isJumpTableRelative(); 3149 } 3150 3151 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3152 SelectionDAG &DAG) const { 3153 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3154 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3155 3156 switch (getTargetMachine().getCodeModel()) { 3157 case CodeModel::Small: 3158 case CodeModel::Medium: 3159 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3160 default: 3161 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3162 getPointerTy(DAG.getDataLayout())); 3163 } 3164 } 3165 3166 const MCExpr * 3167 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3168 unsigned JTI, 3169 MCContext &Ctx) const { 3170 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3171 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3172 3173 switch (getTargetMachine().getCodeModel()) { 3174 case CodeModel::Small: 3175 case CodeModel::Medium: 3176 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3177 default: 3178 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3179 } 3180 } 3181 3182 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3183 EVT PtrVT = Op.getValueType(); 3184 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3185 3186 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3187 if (Subtarget.isUsingPCRelativeCalls()) { 3188 SDLoc DL(JT); 3189 EVT Ty = getPointerTy(DAG.getDataLayout()); 3190 SDValue GA = 3191 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3192 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3193 return MatAddr; 3194 } 3195 3196 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3197 // The actual address of the GlobalValue is stored in the TOC. 3198 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3199 setUsesTOCBasePtr(DAG); 3200 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3201 return getTOCEntry(DAG, SDLoc(JT), GA); 3202 } 3203 3204 unsigned MOHiFlag, MOLoFlag; 3205 bool IsPIC = isPositionIndependent(); 3206 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3207 3208 if (IsPIC && Subtarget.isSVR4ABI()) { 3209 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3210 PPCII::MO_PIC_FLAG); 3211 return getTOCEntry(DAG, SDLoc(GA), GA); 3212 } 3213 3214 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3215 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3216 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3217 } 3218 3219 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3220 SelectionDAG &DAG) const { 3221 EVT PtrVT = Op.getValueType(); 3222 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3223 const BlockAddress *BA = BASDN->getBlockAddress(); 3224 3225 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3226 if (Subtarget.isUsingPCRelativeCalls()) { 3227 SDLoc DL(BASDN); 3228 EVT Ty = getPointerTy(DAG.getDataLayout()); 3229 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3230 PPCII::MO_PCREL_FLAG); 3231 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3232 return MatAddr; 3233 } 3234 3235 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3236 // The actual BlockAddress is stored in the TOC. 3237 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3238 setUsesTOCBasePtr(DAG); 3239 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3240 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3241 } 3242 3243 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3244 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3245 return getTOCEntry( 3246 DAG, SDLoc(BASDN), 3247 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3248 3249 unsigned MOHiFlag, MOLoFlag; 3250 bool IsPIC = isPositionIndependent(); 3251 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3252 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3253 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3254 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3255 } 3256 3257 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3258 SelectionDAG &DAG) const { 3259 if (Subtarget.isAIXABI()) 3260 return LowerGlobalTLSAddressAIX(Op, DAG); 3261 3262 return LowerGlobalTLSAddressLinux(Op, DAG); 3263 } 3264 3265 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3266 SelectionDAG &DAG) const { 3267 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3268 3269 if (DAG.getTarget().useEmulatedTLS()) 3270 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3271 3272 SDLoc dl(GA); 3273 const GlobalValue *GV = GA->getGlobal(); 3274 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3275 3276 // The general-dynamic model is the only access model supported for now, so 3277 // all the GlobalTLSAddress nodes are lowered with this model. 3278 // We need to generate two TOC entries, one for the variable offset, one for 3279 // the region handle. The global address for the TOC entry of the region 3280 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3281 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3282 SDValue VariableOffsetTGA = 3283 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3284 SDValue RegionHandleTGA = 3285 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3286 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3287 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3288 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3289 RegionHandle); 3290 } 3291 3292 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3293 SelectionDAG &DAG) const { 3294 // FIXME: TLS addresses currently use medium model code sequences, 3295 // which is the most useful form. Eventually support for small and 3296 // large models could be added if users need it, at the cost of 3297 // additional complexity. 3298 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3299 if (DAG.getTarget().useEmulatedTLS()) 3300 return LowerToTLSEmulatedModel(GA, DAG); 3301 3302 SDLoc dl(GA); 3303 const GlobalValue *GV = GA->getGlobal(); 3304 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3305 bool is64bit = Subtarget.isPPC64(); 3306 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3307 PICLevel::Level picLevel = M->getPICLevel(); 3308 3309 const TargetMachine &TM = getTargetMachine(); 3310 TLSModel::Model Model = TM.getTLSModel(GV); 3311 3312 if (Model == TLSModel::LocalExec) { 3313 if (Subtarget.isUsingPCRelativeCalls()) { 3314 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3315 SDValue TGA = DAG.getTargetGlobalAddress( 3316 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3317 SDValue MatAddr = 3318 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3319 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3320 } 3321 3322 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3323 PPCII::MO_TPREL_HA); 3324 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3325 PPCII::MO_TPREL_LO); 3326 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3327 : DAG.getRegister(PPC::R2, MVT::i32); 3328 3329 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3330 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3331 } 3332 3333 if (Model == TLSModel::InitialExec) { 3334 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3335 SDValue TGA = DAG.getTargetGlobalAddress( 3336 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3337 SDValue TGATLS = DAG.getTargetGlobalAddress( 3338 GV, dl, PtrVT, 0, 3339 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3340 SDValue TPOffset; 3341 if (IsPCRel) { 3342 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3343 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3344 MachinePointerInfo()); 3345 } else { 3346 SDValue GOTPtr; 3347 if (is64bit) { 3348 setUsesTOCBasePtr(DAG); 3349 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3350 GOTPtr = 3351 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3352 } else { 3353 if (!TM.isPositionIndependent()) 3354 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3355 else if (picLevel == PICLevel::SmallPIC) 3356 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3357 else 3358 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3359 } 3360 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3361 } 3362 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3363 } 3364 3365 if (Model == TLSModel::GeneralDynamic) { 3366 if (Subtarget.isUsingPCRelativeCalls()) { 3367 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3368 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3369 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3370 } 3371 3372 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3373 SDValue GOTPtr; 3374 if (is64bit) { 3375 setUsesTOCBasePtr(DAG); 3376 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3377 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3378 GOTReg, TGA); 3379 } else { 3380 if (picLevel == PICLevel::SmallPIC) 3381 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3382 else 3383 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3384 } 3385 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3386 GOTPtr, TGA, TGA); 3387 } 3388 3389 if (Model == TLSModel::LocalDynamic) { 3390 if (Subtarget.isUsingPCRelativeCalls()) { 3391 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3392 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3393 SDValue MatPCRel = 3394 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3395 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3396 } 3397 3398 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3399 SDValue GOTPtr; 3400 if (is64bit) { 3401 setUsesTOCBasePtr(DAG); 3402 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3403 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3404 GOTReg, TGA); 3405 } else { 3406 if (picLevel == PICLevel::SmallPIC) 3407 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3408 else 3409 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3410 } 3411 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3412 PtrVT, GOTPtr, TGA, TGA); 3413 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3414 PtrVT, TLSAddr, TGA); 3415 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3416 } 3417 3418 llvm_unreachable("Unknown TLS model!"); 3419 } 3420 3421 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3422 SelectionDAG &DAG) const { 3423 EVT PtrVT = Op.getValueType(); 3424 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3425 SDLoc DL(GSDN); 3426 const GlobalValue *GV = GSDN->getGlobal(); 3427 3428 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3429 // The actual address of the GlobalValue is stored in the TOC. 3430 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3431 if (Subtarget.isUsingPCRelativeCalls()) { 3432 EVT Ty = getPointerTy(DAG.getDataLayout()); 3433 if (isAccessedAsGotIndirect(Op)) { 3434 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3435 PPCII::MO_PCREL_FLAG | 3436 PPCII::MO_GOT_FLAG); 3437 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3438 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3439 MachinePointerInfo()); 3440 return Load; 3441 } else { 3442 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3443 PPCII::MO_PCREL_FLAG); 3444 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3445 } 3446 } 3447 setUsesTOCBasePtr(DAG); 3448 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3449 return getTOCEntry(DAG, DL, GA); 3450 } 3451 3452 unsigned MOHiFlag, MOLoFlag; 3453 bool IsPIC = isPositionIndependent(); 3454 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3455 3456 if (IsPIC && Subtarget.isSVR4ABI()) { 3457 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3458 GSDN->getOffset(), 3459 PPCII::MO_PIC_FLAG); 3460 return getTOCEntry(DAG, DL, GA); 3461 } 3462 3463 SDValue GAHi = 3464 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3465 SDValue GALo = 3466 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3467 3468 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3469 } 3470 3471 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3472 bool IsStrict = Op->isStrictFPOpcode(); 3473 ISD::CondCode CC = 3474 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3475 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3476 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3477 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3478 EVT LHSVT = LHS.getValueType(); 3479 SDLoc dl(Op); 3480 3481 // Soften the setcc with libcall if it is fp128. 3482 if (LHSVT == MVT::f128) { 3483 assert(!Subtarget.hasP9Vector() && 3484 "SETCC for f128 is already legal under Power9!"); 3485 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3486 Op->getOpcode() == ISD::STRICT_FSETCCS); 3487 if (RHS.getNode()) 3488 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3489 DAG.getCondCode(CC)); 3490 if (IsStrict) 3491 return DAG.getMergeValues({LHS, Chain}, dl); 3492 return LHS; 3493 } 3494 3495 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3496 3497 if (Op.getValueType() == MVT::v2i64) { 3498 // When the operands themselves are v2i64 values, we need to do something 3499 // special because VSX has no underlying comparison operations for these. 3500 if (LHS.getValueType() == MVT::v2i64) { 3501 // Equality can be handled by casting to the legal type for Altivec 3502 // comparisons, everything else needs to be expanded. 3503 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3504 return DAG.getNode( 3505 ISD::BITCAST, dl, MVT::v2i64, 3506 DAG.getSetCC(dl, MVT::v4i32, 3507 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3508 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC)); 3509 } 3510 3511 return SDValue(); 3512 } 3513 3514 // We handle most of these in the usual way. 3515 return Op; 3516 } 3517 3518 // If we're comparing for equality to zero, expose the fact that this is 3519 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3520 // fold the new nodes. 3521 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3522 return V; 3523 3524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3525 // Leave comparisons against 0 and -1 alone for now, since they're usually 3526 // optimized. FIXME: revisit this when we can custom lower all setcc 3527 // optimizations. 3528 if (C->isAllOnes() || C->isZero()) 3529 return SDValue(); 3530 } 3531 3532 // If we have an integer seteq/setne, turn it into a compare against zero 3533 // by xor'ing the rhs with the lhs, which is faster than setting a 3534 // condition register, reading it back out, and masking the correct bit. The 3535 // normal approach here uses sub to do this instead of xor. Using xor exposes 3536 // the result to other bit-twiddling opportunities. 3537 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3538 EVT VT = Op.getValueType(); 3539 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3540 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3541 } 3542 return SDValue(); 3543 } 3544 3545 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3546 SDNode *Node = Op.getNode(); 3547 EVT VT = Node->getValueType(0); 3548 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3549 SDValue InChain = Node->getOperand(0); 3550 SDValue VAListPtr = Node->getOperand(1); 3551 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3552 SDLoc dl(Node); 3553 3554 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3555 3556 // gpr_index 3557 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3558 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3559 InChain = GprIndex.getValue(1); 3560 3561 if (VT == MVT::i64) { 3562 // Check if GprIndex is even 3563 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3564 DAG.getConstant(1, dl, MVT::i32)); 3565 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3566 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3567 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3568 DAG.getConstant(1, dl, MVT::i32)); 3569 // Align GprIndex to be even if it isn't 3570 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3571 GprIndex); 3572 } 3573 3574 // fpr index is 1 byte after gpr 3575 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3576 DAG.getConstant(1, dl, MVT::i32)); 3577 3578 // fpr 3579 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3580 FprPtr, MachinePointerInfo(SV), MVT::i8); 3581 InChain = FprIndex.getValue(1); 3582 3583 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3584 DAG.getConstant(8, dl, MVT::i32)); 3585 3586 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3587 DAG.getConstant(4, dl, MVT::i32)); 3588 3589 // areas 3590 SDValue OverflowArea = 3591 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3592 InChain = OverflowArea.getValue(1); 3593 3594 SDValue RegSaveArea = 3595 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3596 InChain = RegSaveArea.getValue(1); 3597 3598 // select overflow_area if index > 8 3599 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3600 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3601 3602 // adjustment constant gpr_index * 4/8 3603 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3604 VT.isInteger() ? GprIndex : FprIndex, 3605 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3606 MVT::i32)); 3607 3608 // OurReg = RegSaveArea + RegConstant 3609 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3610 RegConstant); 3611 3612 // Floating types are 32 bytes into RegSaveArea 3613 if (VT.isFloatingPoint()) 3614 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3615 DAG.getConstant(32, dl, MVT::i32)); 3616 3617 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3618 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3619 VT.isInteger() ? GprIndex : FprIndex, 3620 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3621 MVT::i32)); 3622 3623 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3624 VT.isInteger() ? VAListPtr : FprPtr, 3625 MachinePointerInfo(SV), MVT::i8); 3626 3627 // determine if we should load from reg_save_area or overflow_area 3628 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3629 3630 // increase overflow_area by 4/8 if gpr/fpr > 8 3631 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3632 DAG.getConstant(VT.isInteger() ? 4 : 8, 3633 dl, MVT::i32)); 3634 3635 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3636 OverflowAreaPlusN); 3637 3638 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3639 MachinePointerInfo(), MVT::i32); 3640 3641 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3642 } 3643 3644 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3645 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3646 3647 // We have to copy the entire va_list struct: 3648 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3649 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3650 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3651 false, true, false, MachinePointerInfo(), 3652 MachinePointerInfo()); 3653 } 3654 3655 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3656 SelectionDAG &DAG) const { 3657 if (Subtarget.isAIXABI()) 3658 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3659 3660 return Op.getOperand(0); 3661 } 3662 3663 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3664 MachineFunction &MF = DAG.getMachineFunction(); 3665 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3666 3667 assert((Op.getOpcode() == ISD::INLINEASM || 3668 Op.getOpcode() == ISD::INLINEASM_BR) && 3669 "Expecting Inline ASM node."); 3670 3671 // If an LR store is already known to be required then there is not point in 3672 // checking this ASM as well. 3673 if (MFI.isLRStoreRequired()) 3674 return Op; 3675 3676 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3677 // type MVT::Glue. We want to ignore this last operand if that is the case. 3678 unsigned NumOps = Op.getNumOperands(); 3679 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3680 --NumOps; 3681 3682 // Check all operands that may contain the LR. 3683 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3684 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3685 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3686 ++i; // Skip the ID value. 3687 3688 switch (InlineAsm::getKind(Flags)) { 3689 default: 3690 llvm_unreachable("Bad flags!"); 3691 case InlineAsm::Kind_RegUse: 3692 case InlineAsm::Kind_Imm: 3693 case InlineAsm::Kind_Mem: 3694 i += NumVals; 3695 break; 3696 case InlineAsm::Kind_Clobber: 3697 case InlineAsm::Kind_RegDef: 3698 case InlineAsm::Kind_RegDefEarlyClobber: { 3699 for (; NumVals; --NumVals, ++i) { 3700 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3701 if (Reg != PPC::LR && Reg != PPC::LR8) 3702 continue; 3703 MFI.setLRStoreRequired(); 3704 return Op; 3705 } 3706 break; 3707 } 3708 } 3709 } 3710 3711 return Op; 3712 } 3713 3714 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3715 SelectionDAG &DAG) const { 3716 if (Subtarget.isAIXABI()) 3717 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3718 3719 SDValue Chain = Op.getOperand(0); 3720 SDValue Trmp = Op.getOperand(1); // trampoline 3721 SDValue FPtr = Op.getOperand(2); // nested function 3722 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3723 SDLoc dl(Op); 3724 3725 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3726 bool isPPC64 = (PtrVT == MVT::i64); 3727 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3728 3729 TargetLowering::ArgListTy Args; 3730 TargetLowering::ArgListEntry Entry; 3731 3732 Entry.Ty = IntPtrTy; 3733 Entry.Node = Trmp; Args.push_back(Entry); 3734 3735 // TrampSize == (isPPC64 ? 48 : 40); 3736 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3737 isPPC64 ? MVT::i64 : MVT::i32); 3738 Args.push_back(Entry); 3739 3740 Entry.Node = FPtr; Args.push_back(Entry); 3741 Entry.Node = Nest; Args.push_back(Entry); 3742 3743 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3744 TargetLowering::CallLoweringInfo CLI(DAG); 3745 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3746 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3747 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3748 3749 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3750 return CallResult.second; 3751 } 3752 3753 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3754 MachineFunction &MF = DAG.getMachineFunction(); 3755 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3756 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3757 3758 SDLoc dl(Op); 3759 3760 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3761 // vastart just stores the address of the VarArgsFrameIndex slot into the 3762 // memory location argument. 3763 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3764 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3765 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3766 MachinePointerInfo(SV)); 3767 } 3768 3769 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3770 // We suppose the given va_list is already allocated. 3771 // 3772 // typedef struct { 3773 // char gpr; /* index into the array of 8 GPRs 3774 // * stored in the register save area 3775 // * gpr=0 corresponds to r3, 3776 // * gpr=1 to r4, etc. 3777 // */ 3778 // char fpr; /* index into the array of 8 FPRs 3779 // * stored in the register save area 3780 // * fpr=0 corresponds to f1, 3781 // * fpr=1 to f2, etc. 3782 // */ 3783 // char *overflow_arg_area; 3784 // /* location on stack that holds 3785 // * the next overflow argument 3786 // */ 3787 // char *reg_save_area; 3788 // /* where r3:r10 and f1:f8 (if saved) 3789 // * are stored 3790 // */ 3791 // } va_list[1]; 3792 3793 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3794 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3795 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3796 PtrVT); 3797 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3798 PtrVT); 3799 3800 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3801 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3802 3803 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3804 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3805 3806 uint64_t FPROffset = 1; 3807 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3808 3809 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3810 3811 // Store first byte : number of int regs 3812 SDValue firstStore = 3813 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3814 MachinePointerInfo(SV), MVT::i8); 3815 uint64_t nextOffset = FPROffset; 3816 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3817 ConstFPROffset); 3818 3819 // Store second byte : number of float regs 3820 SDValue secondStore = 3821 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3822 MachinePointerInfo(SV, nextOffset), MVT::i8); 3823 nextOffset += StackOffset; 3824 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3825 3826 // Store second word : arguments given on stack 3827 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3828 MachinePointerInfo(SV, nextOffset)); 3829 nextOffset += FrameOffset; 3830 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3831 3832 // Store third word : arguments given in registers 3833 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3834 MachinePointerInfo(SV, nextOffset)); 3835 } 3836 3837 /// FPR - The set of FP registers that should be allocated for arguments 3838 /// on Darwin and AIX. 3839 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3840 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3841 PPC::F11, PPC::F12, PPC::F13}; 3842 3843 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3844 /// the stack. 3845 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3846 unsigned PtrByteSize) { 3847 unsigned ArgSize = ArgVT.getStoreSize(); 3848 if (Flags.isByVal()) 3849 ArgSize = Flags.getByValSize(); 3850 3851 // Round up to multiples of the pointer size, except for array members, 3852 // which are always packed. 3853 if (!Flags.isInConsecutiveRegs()) 3854 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3855 3856 return ArgSize; 3857 } 3858 3859 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3860 /// on the stack. 3861 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3862 ISD::ArgFlagsTy Flags, 3863 unsigned PtrByteSize) { 3864 Align Alignment(PtrByteSize); 3865 3866 // Altivec parameters are padded to a 16 byte boundary. 3867 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3868 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3869 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3870 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3871 Alignment = Align(16); 3872 3873 // ByVal parameters are aligned as requested. 3874 if (Flags.isByVal()) { 3875 auto BVAlign = Flags.getNonZeroByValAlign(); 3876 if (BVAlign > PtrByteSize) { 3877 if (BVAlign.value() % PtrByteSize != 0) 3878 llvm_unreachable( 3879 "ByVal alignment is not a multiple of the pointer size"); 3880 3881 Alignment = BVAlign; 3882 } 3883 } 3884 3885 // Array members are always packed to their original alignment. 3886 if (Flags.isInConsecutiveRegs()) { 3887 // If the array member was split into multiple registers, the first 3888 // needs to be aligned to the size of the full type. (Except for 3889 // ppcf128, which is only aligned as its f64 components.) 3890 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3891 Alignment = Align(OrigVT.getStoreSize()); 3892 else 3893 Alignment = Align(ArgVT.getStoreSize()); 3894 } 3895 3896 return Alignment; 3897 } 3898 3899 /// CalculateStackSlotUsed - Return whether this argument will use its 3900 /// stack slot (instead of being passed in registers). ArgOffset, 3901 /// AvailableFPRs, and AvailableVRs must hold the current argument 3902 /// position, and will be updated to account for this argument. 3903 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3904 unsigned PtrByteSize, unsigned LinkageSize, 3905 unsigned ParamAreaSize, unsigned &ArgOffset, 3906 unsigned &AvailableFPRs, 3907 unsigned &AvailableVRs) { 3908 bool UseMemory = false; 3909 3910 // Respect alignment of argument on the stack. 3911 Align Alignment = 3912 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3913 ArgOffset = alignTo(ArgOffset, Alignment); 3914 // If there's no space left in the argument save area, we must 3915 // use memory (this check also catches zero-sized arguments). 3916 if (ArgOffset >= LinkageSize + ParamAreaSize) 3917 UseMemory = true; 3918 3919 // Allocate argument on the stack. 3920 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3921 if (Flags.isInConsecutiveRegsLast()) 3922 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3923 // If we overran the argument save area, we must use memory 3924 // (this check catches arguments passed partially in memory) 3925 if (ArgOffset > LinkageSize + ParamAreaSize) 3926 UseMemory = true; 3927 3928 // However, if the argument is actually passed in an FPR or a VR, 3929 // we don't use memory after all. 3930 if (!Flags.isByVal()) { 3931 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3932 if (AvailableFPRs > 0) { 3933 --AvailableFPRs; 3934 return false; 3935 } 3936 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3937 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3938 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3939 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3940 if (AvailableVRs > 0) { 3941 --AvailableVRs; 3942 return false; 3943 } 3944 } 3945 3946 return UseMemory; 3947 } 3948 3949 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3950 /// ensure minimum alignment required for target. 3951 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3952 unsigned NumBytes) { 3953 return alignTo(NumBytes, Lowering->getStackAlign()); 3954 } 3955 3956 SDValue PPCTargetLowering::LowerFormalArguments( 3957 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3958 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3959 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3960 if (Subtarget.isAIXABI()) 3961 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3962 InVals); 3963 if (Subtarget.is64BitELFABI()) 3964 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3965 InVals); 3966 assert(Subtarget.is32BitELFABI()); 3967 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3968 InVals); 3969 } 3970 3971 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3972 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3973 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3974 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3975 3976 // 32-bit SVR4 ABI Stack Frame Layout: 3977 // +-----------------------------------+ 3978 // +--> | Back chain | 3979 // | +-----------------------------------+ 3980 // | | Floating-point register save area | 3981 // | +-----------------------------------+ 3982 // | | General register save area | 3983 // | +-----------------------------------+ 3984 // | | CR save word | 3985 // | +-----------------------------------+ 3986 // | | VRSAVE save word | 3987 // | +-----------------------------------+ 3988 // | | Alignment padding | 3989 // | +-----------------------------------+ 3990 // | | Vector register save area | 3991 // | +-----------------------------------+ 3992 // | | Local variable space | 3993 // | +-----------------------------------+ 3994 // | | Parameter list area | 3995 // | +-----------------------------------+ 3996 // | | LR save word | 3997 // | +-----------------------------------+ 3998 // SP--> +--- | Back chain | 3999 // +-----------------------------------+ 4000 // 4001 // Specifications: 4002 // System V Application Binary Interface PowerPC Processor Supplement 4003 // AltiVec Technology Programming Interface Manual 4004 4005 MachineFunction &MF = DAG.getMachineFunction(); 4006 MachineFrameInfo &MFI = MF.getFrameInfo(); 4007 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4008 4009 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4010 // Potential tail calls could cause overwriting of argument stack slots. 4011 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4012 (CallConv == CallingConv::Fast)); 4013 const Align PtrAlign(4); 4014 4015 // Assign locations to all of the incoming arguments. 4016 SmallVector<CCValAssign, 16> ArgLocs; 4017 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4018 *DAG.getContext()); 4019 4020 // Reserve space for the linkage area on the stack. 4021 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4022 CCInfo.AllocateStack(LinkageSize, PtrAlign); 4023 if (useSoftFloat()) 4024 CCInfo.PreAnalyzeFormalArguments(Ins); 4025 4026 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 4027 CCInfo.clearWasPPCF128(); 4028 4029 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4030 CCValAssign &VA = ArgLocs[i]; 4031 4032 // Arguments stored in registers. 4033 if (VA.isRegLoc()) { 4034 const TargetRegisterClass *RC; 4035 EVT ValVT = VA.getValVT(); 4036 4037 switch (ValVT.getSimpleVT().SimpleTy) { 4038 default: 4039 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4040 case MVT::i1: 4041 case MVT::i32: 4042 RC = &PPC::GPRCRegClass; 4043 break; 4044 case MVT::f32: 4045 if (Subtarget.hasP8Vector()) 4046 RC = &PPC::VSSRCRegClass; 4047 else if (Subtarget.hasSPE()) 4048 RC = &PPC::GPRCRegClass; 4049 else 4050 RC = &PPC::F4RCRegClass; 4051 break; 4052 case MVT::f64: 4053 if (Subtarget.hasVSX()) 4054 RC = &PPC::VSFRCRegClass; 4055 else if (Subtarget.hasSPE()) 4056 // SPE passes doubles in GPR pairs. 4057 RC = &PPC::GPRCRegClass; 4058 else 4059 RC = &PPC::F8RCRegClass; 4060 break; 4061 case MVT::v16i8: 4062 case MVT::v8i16: 4063 case MVT::v4i32: 4064 RC = &PPC::VRRCRegClass; 4065 break; 4066 case MVT::v4f32: 4067 RC = &PPC::VRRCRegClass; 4068 break; 4069 case MVT::v2f64: 4070 case MVT::v2i64: 4071 RC = &PPC::VRRCRegClass; 4072 break; 4073 } 4074 4075 SDValue ArgValue; 4076 // Transform the arguments stored in physical registers into 4077 // virtual ones. 4078 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4079 assert(i + 1 < e && "No second half of double precision argument"); 4080 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4081 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4082 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4083 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4084 if (!Subtarget.isLittleEndian()) 4085 std::swap (ArgValueLo, ArgValueHi); 4086 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4087 ArgValueHi); 4088 } else { 4089 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4090 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4091 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4092 if (ValVT == MVT::i1) 4093 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4094 } 4095 4096 InVals.push_back(ArgValue); 4097 } else { 4098 // Argument stored in memory. 4099 assert(VA.isMemLoc()); 4100 4101 // Get the extended size of the argument type in stack 4102 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4103 // Get the actual size of the argument type 4104 unsigned ObjSize = VA.getValVT().getStoreSize(); 4105 unsigned ArgOffset = VA.getLocMemOffset(); 4106 // Stack objects in PPC32 are right justified. 4107 ArgOffset += ArgSize - ObjSize; 4108 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4109 4110 // Create load nodes to retrieve arguments from the stack. 4111 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4112 InVals.push_back( 4113 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4114 } 4115 } 4116 4117 // Assign locations to all of the incoming aggregate by value arguments. 4118 // Aggregates passed by value are stored in the local variable space of the 4119 // caller's stack frame, right above the parameter list area. 4120 SmallVector<CCValAssign, 16> ByValArgLocs; 4121 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4122 ByValArgLocs, *DAG.getContext()); 4123 4124 // Reserve stack space for the allocations in CCInfo. 4125 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4126 4127 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4128 4129 // Area that is at least reserved in the caller of this function. 4130 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4131 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4132 4133 // Set the size that is at least reserved in caller of this function. Tail 4134 // call optimized function's reserved stack space needs to be aligned so that 4135 // taking the difference between two stack areas will result in an aligned 4136 // stack. 4137 MinReservedArea = 4138 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4139 FuncInfo->setMinReservedArea(MinReservedArea); 4140 4141 SmallVector<SDValue, 8> MemOps; 4142 4143 // If the function takes variable number of arguments, make a frame index for 4144 // the start of the first vararg value... for expansion of llvm.va_start. 4145 if (isVarArg) { 4146 static const MCPhysReg GPArgRegs[] = { 4147 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4148 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4149 }; 4150 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 4151 4152 static const MCPhysReg FPArgRegs[] = { 4153 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4154 PPC::F8 4155 }; 4156 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 4157 4158 if (useSoftFloat() || hasSPE()) 4159 NumFPArgRegs = 0; 4160 4161 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4162 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4163 4164 // Make room for NumGPArgRegs and NumFPArgRegs. 4165 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4166 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4167 4168 FuncInfo->setVarArgsStackOffset( 4169 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4170 CCInfo.getNextStackOffset(), true)); 4171 4172 FuncInfo->setVarArgsFrameIndex( 4173 MFI.CreateStackObject(Depth, Align(8), false)); 4174 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4175 4176 // The fixed integer arguments of a variadic function are stored to the 4177 // VarArgsFrameIndex on the stack so that they may be loaded by 4178 // dereferencing the result of va_next. 4179 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4180 // Get an existing live-in vreg, or add a new one. 4181 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4182 if (!VReg) 4183 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4184 4185 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4186 SDValue Store = 4187 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4188 MemOps.push_back(Store); 4189 // Increment the address by four for the next argument to store 4190 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4191 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4192 } 4193 4194 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4195 // is set. 4196 // The double arguments are stored to the VarArgsFrameIndex 4197 // on the stack. 4198 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4199 // Get an existing live-in vreg, or add a new one. 4200 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4201 if (!VReg) 4202 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4203 4204 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4205 SDValue Store = 4206 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4207 MemOps.push_back(Store); 4208 // Increment the address by eight for the next argument to store 4209 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4210 PtrVT); 4211 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4212 } 4213 } 4214 4215 if (!MemOps.empty()) 4216 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4217 4218 return Chain; 4219 } 4220 4221 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4222 // value to MVT::i64 and then truncate to the correct register size. 4223 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4224 EVT ObjectVT, SelectionDAG &DAG, 4225 SDValue ArgVal, 4226 const SDLoc &dl) const { 4227 if (Flags.isSExt()) 4228 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4229 DAG.getValueType(ObjectVT)); 4230 else if (Flags.isZExt()) 4231 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4232 DAG.getValueType(ObjectVT)); 4233 4234 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4235 } 4236 4237 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4238 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4239 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4240 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4241 // TODO: add description of PPC stack frame format, or at least some docs. 4242 // 4243 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4244 bool isLittleEndian = Subtarget.isLittleEndian(); 4245 MachineFunction &MF = DAG.getMachineFunction(); 4246 MachineFrameInfo &MFI = MF.getFrameInfo(); 4247 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4248 4249 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4250 "fastcc not supported on varargs functions"); 4251 4252 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4253 // Potential tail calls could cause overwriting of argument stack slots. 4254 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4255 (CallConv == CallingConv::Fast)); 4256 unsigned PtrByteSize = 8; 4257 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4258 4259 static const MCPhysReg GPR[] = { 4260 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4261 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4262 }; 4263 static const MCPhysReg VR[] = { 4264 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4265 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4266 }; 4267 4268 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4269 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4270 const unsigned Num_VR_Regs = array_lengthof(VR); 4271 4272 // Do a first pass over the arguments to determine whether the ABI 4273 // guarantees that our caller has allocated the parameter save area 4274 // on its stack frame. In the ELFv1 ABI, this is always the case; 4275 // in the ELFv2 ABI, it is true if this is a vararg function or if 4276 // any parameter is located in a stack slot. 4277 4278 bool HasParameterArea = !isELFv2ABI || isVarArg; 4279 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4280 unsigned NumBytes = LinkageSize; 4281 unsigned AvailableFPRs = Num_FPR_Regs; 4282 unsigned AvailableVRs = Num_VR_Regs; 4283 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4284 if (Ins[i].Flags.isNest()) 4285 continue; 4286 4287 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4288 PtrByteSize, LinkageSize, ParamAreaSize, 4289 NumBytes, AvailableFPRs, AvailableVRs)) 4290 HasParameterArea = true; 4291 } 4292 4293 // Add DAG nodes to load the arguments or copy them out of registers. On 4294 // entry to a function on PPC, the arguments start after the linkage area, 4295 // although the first ones are often in registers. 4296 4297 unsigned ArgOffset = LinkageSize; 4298 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4299 SmallVector<SDValue, 8> MemOps; 4300 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4301 unsigned CurArgIdx = 0; 4302 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4303 SDValue ArgVal; 4304 bool needsLoad = false; 4305 EVT ObjectVT = Ins[ArgNo].VT; 4306 EVT OrigVT = Ins[ArgNo].ArgVT; 4307 unsigned ObjSize = ObjectVT.getStoreSize(); 4308 unsigned ArgSize = ObjSize; 4309 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4310 if (Ins[ArgNo].isOrigArg()) { 4311 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4312 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4313 } 4314 // We re-align the argument offset for each argument, except when using the 4315 // fast calling convention, when we need to make sure we do that only when 4316 // we'll actually use a stack slot. 4317 unsigned CurArgOffset; 4318 Align Alignment; 4319 auto ComputeArgOffset = [&]() { 4320 /* Respect alignment of argument on the stack. */ 4321 Alignment = 4322 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4323 ArgOffset = alignTo(ArgOffset, Alignment); 4324 CurArgOffset = ArgOffset; 4325 }; 4326 4327 if (CallConv != CallingConv::Fast) { 4328 ComputeArgOffset(); 4329 4330 /* Compute GPR index associated with argument offset. */ 4331 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4332 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4333 } 4334 4335 // FIXME the codegen can be much improved in some cases. 4336 // We do not have to keep everything in memory. 4337 if (Flags.isByVal()) { 4338 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4339 4340 if (CallConv == CallingConv::Fast) 4341 ComputeArgOffset(); 4342 4343 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4344 ObjSize = Flags.getByValSize(); 4345 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4346 // Empty aggregate parameters do not take up registers. Examples: 4347 // struct { } a; 4348 // union { } b; 4349 // int c[0]; 4350 // etc. However, we have to provide a place-holder in InVals, so 4351 // pretend we have an 8-byte item at the current address for that 4352 // purpose. 4353 if (!ObjSize) { 4354 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4355 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4356 InVals.push_back(FIN); 4357 continue; 4358 } 4359 4360 // Create a stack object covering all stack doublewords occupied 4361 // by the argument. If the argument is (fully or partially) on 4362 // the stack, or if the argument is fully in registers but the 4363 // caller has allocated the parameter save anyway, we can refer 4364 // directly to the caller's stack frame. Otherwise, create a 4365 // local copy in our own frame. 4366 int FI; 4367 if (HasParameterArea || 4368 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4369 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4370 else 4371 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4372 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4373 4374 // Handle aggregates smaller than 8 bytes. 4375 if (ObjSize < PtrByteSize) { 4376 // The value of the object is its address, which differs from the 4377 // address of the enclosing doubleword on big-endian systems. 4378 SDValue Arg = FIN; 4379 if (!isLittleEndian) { 4380 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4381 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4382 } 4383 InVals.push_back(Arg); 4384 4385 if (GPR_idx != Num_GPR_Regs) { 4386 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4387 FuncInfo->addLiveInAttr(VReg, Flags); 4388 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4389 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8); 4390 SDValue Store = 4391 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4392 MachinePointerInfo(&*FuncArg), ObjType); 4393 MemOps.push_back(Store); 4394 } 4395 // Whether we copied from a register or not, advance the offset 4396 // into the parameter save area by a full doubleword. 4397 ArgOffset += PtrByteSize; 4398 continue; 4399 } 4400 4401 // The value of the object is its address, which is the address of 4402 // its first stack doubleword. 4403 InVals.push_back(FIN); 4404 4405 // Store whatever pieces of the object are in registers to memory. 4406 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4407 if (GPR_idx == Num_GPR_Regs) 4408 break; 4409 4410 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4411 FuncInfo->addLiveInAttr(VReg, Flags); 4412 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4413 SDValue Addr = FIN; 4414 if (j) { 4415 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4416 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4417 } 4418 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4419 MachinePointerInfo(&*FuncArg, j)); 4420 MemOps.push_back(Store); 4421 ++GPR_idx; 4422 } 4423 ArgOffset += ArgSize; 4424 continue; 4425 } 4426 4427 switch (ObjectVT.getSimpleVT().SimpleTy) { 4428 default: llvm_unreachable("Unhandled argument type!"); 4429 case MVT::i1: 4430 case MVT::i32: 4431 case MVT::i64: 4432 if (Flags.isNest()) { 4433 // The 'nest' parameter, if any, is passed in R11. 4434 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4435 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4436 4437 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4438 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4439 4440 break; 4441 } 4442 4443 // These can be scalar arguments or elements of an integer array type 4444 // passed directly. Clang may use those instead of "byval" aggregate 4445 // types to avoid forcing arguments to memory unnecessarily. 4446 if (GPR_idx != Num_GPR_Regs) { 4447 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4448 FuncInfo->addLiveInAttr(VReg, Flags); 4449 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4450 4451 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4452 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4453 // value to MVT::i64 and then truncate to the correct register size. 4454 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4455 } else { 4456 if (CallConv == CallingConv::Fast) 4457 ComputeArgOffset(); 4458 4459 needsLoad = true; 4460 ArgSize = PtrByteSize; 4461 } 4462 if (CallConv != CallingConv::Fast || needsLoad) 4463 ArgOffset += 8; 4464 break; 4465 4466 case MVT::f32: 4467 case MVT::f64: 4468 // These can be scalar arguments or elements of a float array type 4469 // passed directly. The latter are used to implement ELFv2 homogenous 4470 // float aggregates. 4471 if (FPR_idx != Num_FPR_Regs) { 4472 unsigned VReg; 4473 4474 if (ObjectVT == MVT::f32) 4475 VReg = MF.addLiveIn(FPR[FPR_idx], 4476 Subtarget.hasP8Vector() 4477 ? &PPC::VSSRCRegClass 4478 : &PPC::F4RCRegClass); 4479 else 4480 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4481 ? &PPC::VSFRCRegClass 4482 : &PPC::F8RCRegClass); 4483 4484 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4485 ++FPR_idx; 4486 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4487 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4488 // once we support fp <-> gpr moves. 4489 4490 // This can only ever happen in the presence of f32 array types, 4491 // since otherwise we never run out of FPRs before running out 4492 // of GPRs. 4493 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4494 FuncInfo->addLiveInAttr(VReg, Flags); 4495 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4496 4497 if (ObjectVT == MVT::f32) { 4498 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4499 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4500 DAG.getConstant(32, dl, MVT::i32)); 4501 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4502 } 4503 4504 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4505 } else { 4506 if (CallConv == CallingConv::Fast) 4507 ComputeArgOffset(); 4508 4509 needsLoad = true; 4510 } 4511 4512 // When passing an array of floats, the array occupies consecutive 4513 // space in the argument area; only round up to the next doubleword 4514 // at the end of the array. Otherwise, each float takes 8 bytes. 4515 if (CallConv != CallingConv::Fast || needsLoad) { 4516 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4517 ArgOffset += ArgSize; 4518 if (Flags.isInConsecutiveRegsLast()) 4519 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4520 } 4521 break; 4522 case MVT::v4f32: 4523 case MVT::v4i32: 4524 case MVT::v8i16: 4525 case MVT::v16i8: 4526 case MVT::v2f64: 4527 case MVT::v2i64: 4528 case MVT::v1i128: 4529 case MVT::f128: 4530 // These can be scalar arguments or elements of a vector array type 4531 // passed directly. The latter are used to implement ELFv2 homogenous 4532 // vector aggregates. 4533 if (VR_idx != Num_VR_Regs) { 4534 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4535 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4536 ++VR_idx; 4537 } else { 4538 if (CallConv == CallingConv::Fast) 4539 ComputeArgOffset(); 4540 needsLoad = true; 4541 } 4542 if (CallConv != CallingConv::Fast || needsLoad) 4543 ArgOffset += 16; 4544 break; 4545 } 4546 4547 // We need to load the argument to a virtual register if we determined 4548 // above that we ran out of physical registers of the appropriate type. 4549 if (needsLoad) { 4550 if (ObjSize < ArgSize && !isLittleEndian) 4551 CurArgOffset += ArgSize - ObjSize; 4552 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4553 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4554 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4555 } 4556 4557 InVals.push_back(ArgVal); 4558 } 4559 4560 // Area that is at least reserved in the caller of this function. 4561 unsigned MinReservedArea; 4562 if (HasParameterArea) 4563 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4564 else 4565 MinReservedArea = LinkageSize; 4566 4567 // Set the size that is at least reserved in caller of this function. Tail 4568 // call optimized functions' reserved stack space needs to be aligned so that 4569 // taking the difference between two stack areas will result in an aligned 4570 // stack. 4571 MinReservedArea = 4572 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4573 FuncInfo->setMinReservedArea(MinReservedArea); 4574 4575 // If the function takes variable number of arguments, make a frame index for 4576 // the start of the first vararg value... for expansion of llvm.va_start. 4577 // On ELFv2ABI spec, it writes: 4578 // C programs that are intended to be *portable* across different compilers 4579 // and architectures must use the header file <stdarg.h> to deal with variable 4580 // argument lists. 4581 if (isVarArg && MFI.hasVAStart()) { 4582 int Depth = ArgOffset; 4583 4584 FuncInfo->setVarArgsFrameIndex( 4585 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4586 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4587 4588 // If this function is vararg, store any remaining integer argument regs 4589 // to their spots on the stack so that they may be loaded by dereferencing 4590 // the result of va_next. 4591 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4592 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4593 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4594 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4595 SDValue Store = 4596 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4597 MemOps.push_back(Store); 4598 // Increment the address by four for the next argument to store 4599 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4600 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4601 } 4602 } 4603 4604 if (!MemOps.empty()) 4605 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4606 4607 return Chain; 4608 } 4609 4610 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4611 /// adjusted to accommodate the arguments for the tailcall. 4612 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4613 unsigned ParamSize) { 4614 4615 if (!isTailCall) return 0; 4616 4617 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4618 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4619 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4620 // Remember only if the new adjustment is bigger. 4621 if (SPDiff < FI->getTailCallSPDelta()) 4622 FI->setTailCallSPDelta(SPDiff); 4623 4624 return SPDiff; 4625 } 4626 4627 static bool isFunctionGlobalAddress(SDValue Callee); 4628 4629 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4630 const TargetMachine &TM) { 4631 // It does not make sense to call callsShareTOCBase() with a caller that 4632 // is PC Relative since PC Relative callers do not have a TOC. 4633 #ifndef NDEBUG 4634 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4635 assert(!STICaller->isUsingPCRelativeCalls() && 4636 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4637 #endif 4638 4639 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4640 // don't have enough information to determine if the caller and callee share 4641 // the same TOC base, so we have to pessimistically assume they don't for 4642 // correctness. 4643 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4644 if (!G) 4645 return false; 4646 4647 const GlobalValue *GV = G->getGlobal(); 4648 4649 // If the callee is preemptable, then the static linker will use a plt-stub 4650 // which saves the toc to the stack, and needs a nop after the call 4651 // instruction to convert to a toc-restore. 4652 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4653 return false; 4654 4655 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4656 // We may need a TOC restore in the situation where the caller requires a 4657 // valid TOC but the callee is PC Relative and does not. 4658 const Function *F = dyn_cast<Function>(GV); 4659 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4660 4661 // If we have an Alias we can try to get the function from there. 4662 if (Alias) { 4663 const GlobalObject *GlobalObj = Alias->getAliaseeObject(); 4664 F = dyn_cast<Function>(GlobalObj); 4665 } 4666 4667 // If we still have no valid function pointer we do not have enough 4668 // information to determine if the callee uses PC Relative calls so we must 4669 // assume that it does. 4670 if (!F) 4671 return false; 4672 4673 // If the callee uses PC Relative we cannot guarantee that the callee won't 4674 // clobber the TOC of the caller and so we must assume that the two 4675 // functions do not share a TOC base. 4676 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4677 if (STICallee->isUsingPCRelativeCalls()) 4678 return false; 4679 4680 // If the GV is not a strong definition then we need to assume it can be 4681 // replaced by another function at link time. The function that replaces 4682 // it may not share the same TOC as the caller since the callee may be 4683 // replaced by a PC Relative version of the same function. 4684 if (!GV->isStrongDefinitionForLinker()) 4685 return false; 4686 4687 // The medium and large code models are expected to provide a sufficiently 4688 // large TOC to provide all data addressing needs of a module with a 4689 // single TOC. 4690 if (CodeModel::Medium == TM.getCodeModel() || 4691 CodeModel::Large == TM.getCodeModel()) 4692 return true; 4693 4694 // Any explicitly-specified sections and section prefixes must also match. 4695 // Also, if we're using -ffunction-sections, then each function is always in 4696 // a different section (the same is true for COMDAT functions). 4697 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4698 GV->getSection() != Caller->getSection()) 4699 return false; 4700 if (const auto *F = dyn_cast<Function>(GV)) { 4701 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4702 return false; 4703 } 4704 4705 return true; 4706 } 4707 4708 static bool 4709 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4710 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4711 assert(Subtarget.is64BitELFABI()); 4712 4713 const unsigned PtrByteSize = 8; 4714 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4715 4716 static const MCPhysReg GPR[] = { 4717 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4718 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4719 }; 4720 static const MCPhysReg VR[] = { 4721 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4722 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4723 }; 4724 4725 const unsigned NumGPRs = array_lengthof(GPR); 4726 const unsigned NumFPRs = 13; 4727 const unsigned NumVRs = array_lengthof(VR); 4728 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4729 4730 unsigned NumBytes = LinkageSize; 4731 unsigned AvailableFPRs = NumFPRs; 4732 unsigned AvailableVRs = NumVRs; 4733 4734 for (const ISD::OutputArg& Param : Outs) { 4735 if (Param.Flags.isNest()) continue; 4736 4737 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4738 LinkageSize, ParamAreaSize, NumBytes, 4739 AvailableFPRs, AvailableVRs)) 4740 return true; 4741 } 4742 return false; 4743 } 4744 4745 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4746 if (CB.arg_size() != CallerFn->arg_size()) 4747 return false; 4748 4749 auto CalleeArgIter = CB.arg_begin(); 4750 auto CalleeArgEnd = CB.arg_end(); 4751 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4752 4753 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4754 const Value* CalleeArg = *CalleeArgIter; 4755 const Value* CallerArg = &(*CallerArgIter); 4756 if (CalleeArg == CallerArg) 4757 continue; 4758 4759 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4760 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4761 // } 4762 // 1st argument of callee is undef and has the same type as caller. 4763 if (CalleeArg->getType() == CallerArg->getType() && 4764 isa<UndefValue>(CalleeArg)) 4765 continue; 4766 4767 return false; 4768 } 4769 4770 return true; 4771 } 4772 4773 // Returns true if TCO is possible between the callers and callees 4774 // calling conventions. 4775 static bool 4776 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4777 CallingConv::ID CalleeCC) { 4778 // Tail calls are possible with fastcc and ccc. 4779 auto isTailCallableCC = [] (CallingConv::ID CC){ 4780 return CC == CallingConv::C || CC == CallingConv::Fast; 4781 }; 4782 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4783 return false; 4784 4785 // We can safely tail call both fastcc and ccc callees from a c calling 4786 // convention caller. If the caller is fastcc, we may have less stack space 4787 // than a non-fastcc caller with the same signature so disable tail-calls in 4788 // that case. 4789 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4790 } 4791 4792 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4793 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4794 const SmallVectorImpl<ISD::OutputArg> &Outs, 4795 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4796 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4797 4798 if (DisableSCO && !TailCallOpt) return false; 4799 4800 // Variadic argument functions are not supported. 4801 if (isVarArg) return false; 4802 4803 auto &Caller = DAG.getMachineFunction().getFunction(); 4804 // Check that the calling conventions are compatible for tco. 4805 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4806 return false; 4807 4808 // Caller contains any byval parameter is not supported. 4809 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4810 return false; 4811 4812 // Callee contains any byval parameter is not supported, too. 4813 // Note: This is a quick work around, because in some cases, e.g. 4814 // caller's stack size > callee's stack size, we are still able to apply 4815 // sibling call optimization. For example, gcc is able to do SCO for caller1 4816 // in the following example, but not for caller2. 4817 // struct test { 4818 // long int a; 4819 // char ary[56]; 4820 // } gTest; 4821 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4822 // b->a = v.a; 4823 // return 0; 4824 // } 4825 // void caller1(struct test a, struct test c, struct test *b) { 4826 // callee(gTest, b); } 4827 // void caller2(struct test *b) { callee(gTest, b); } 4828 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4829 return false; 4830 4831 // If callee and caller use different calling conventions, we cannot pass 4832 // parameters on stack since offsets for the parameter area may be different. 4833 if (Caller.getCallingConv() != CalleeCC && 4834 needStackSlotPassParameters(Subtarget, Outs)) 4835 return false; 4836 4837 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4838 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4839 // callee potentially have different TOC bases then we cannot tail call since 4840 // we need to restore the TOC pointer after the call. 4841 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4842 // We cannot guarantee this for indirect calls or calls to external functions. 4843 // When PC-Relative addressing is used, the concept of the TOC is no longer 4844 // applicable so this check is not required. 4845 // Check first for indirect calls. 4846 if (!Subtarget.isUsingPCRelativeCalls() && 4847 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4848 return false; 4849 4850 // Check if we share the TOC base. 4851 if (!Subtarget.isUsingPCRelativeCalls() && 4852 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4853 return false; 4854 4855 // TCO allows altering callee ABI, so we don't have to check further. 4856 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4857 return true; 4858 4859 if (DisableSCO) return false; 4860 4861 // If callee use the same argument list that caller is using, then we can 4862 // apply SCO on this case. If it is not, then we need to check if callee needs 4863 // stack for passing arguments. 4864 // PC Relative tail calls may not have a CallBase. 4865 // If there is no CallBase we cannot verify if we have the same argument 4866 // list so assume that we don't have the same argument list. 4867 if (CB && !hasSameArgumentList(&Caller, *CB) && 4868 needStackSlotPassParameters(Subtarget, Outs)) 4869 return false; 4870 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4871 return false; 4872 4873 return true; 4874 } 4875 4876 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4877 /// for tail call optimization. Targets which want to do tail call 4878 /// optimization should implement this function. 4879 bool 4880 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4881 CallingConv::ID CalleeCC, 4882 bool isVarArg, 4883 const SmallVectorImpl<ISD::InputArg> &Ins, 4884 SelectionDAG& DAG) const { 4885 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4886 return false; 4887 4888 // Variable argument functions are not supported. 4889 if (isVarArg) 4890 return false; 4891 4892 MachineFunction &MF = DAG.getMachineFunction(); 4893 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4894 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4895 // Functions containing by val parameters are not supported. 4896 for (unsigned i = 0; i != Ins.size(); i++) { 4897 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4898 if (Flags.isByVal()) return false; 4899 } 4900 4901 // Non-PIC/GOT tail calls are supported. 4902 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4903 return true; 4904 4905 // At the moment we can only do local tail calls (in same module, hidden 4906 // or protected) if we are generating PIC. 4907 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4908 return G->getGlobal()->hasHiddenVisibility() 4909 || G->getGlobal()->hasProtectedVisibility(); 4910 } 4911 4912 return false; 4913 } 4914 4915 /// isCallCompatibleAddress - Return the immediate to use if the specified 4916 /// 32-bit value is representable in the immediate field of a BxA instruction. 4917 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4918 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4919 if (!C) return nullptr; 4920 4921 int Addr = C->getZExtValue(); 4922 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4923 SignExtend32<26>(Addr) != Addr) 4924 return nullptr; // Top 6 bits have to be sext of immediate. 4925 4926 return DAG 4927 .getConstant( 4928 (int)C->getZExtValue() >> 2, SDLoc(Op), 4929 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4930 .getNode(); 4931 } 4932 4933 namespace { 4934 4935 struct TailCallArgumentInfo { 4936 SDValue Arg; 4937 SDValue FrameIdxOp; 4938 int FrameIdx = 0; 4939 4940 TailCallArgumentInfo() = default; 4941 }; 4942 4943 } // end anonymous namespace 4944 4945 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4946 static void StoreTailCallArgumentsToStackSlot( 4947 SelectionDAG &DAG, SDValue Chain, 4948 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4949 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4950 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4951 SDValue Arg = TailCallArgs[i].Arg; 4952 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4953 int FI = TailCallArgs[i].FrameIdx; 4954 // Store relative to framepointer. 4955 MemOpChains.push_back(DAG.getStore( 4956 Chain, dl, Arg, FIN, 4957 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4958 } 4959 } 4960 4961 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4962 /// the appropriate stack slot for the tail call optimized function call. 4963 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4964 SDValue OldRetAddr, SDValue OldFP, 4965 int SPDiff, const SDLoc &dl) { 4966 if (SPDiff) { 4967 // Calculate the new stack slot for the return address. 4968 MachineFunction &MF = DAG.getMachineFunction(); 4969 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4970 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4971 bool isPPC64 = Subtarget.isPPC64(); 4972 int SlotSize = isPPC64 ? 8 : 4; 4973 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4974 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4975 NewRetAddrLoc, true); 4976 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4977 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4978 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4979 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4980 } 4981 return Chain; 4982 } 4983 4984 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4985 /// the position of the argument. 4986 static void 4987 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4988 SDValue Arg, int SPDiff, unsigned ArgOffset, 4989 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4990 int Offset = ArgOffset + SPDiff; 4991 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4992 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4993 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4994 SDValue FIN = DAG.getFrameIndex(FI, VT); 4995 TailCallArgumentInfo Info; 4996 Info.Arg = Arg; 4997 Info.FrameIdxOp = FIN; 4998 Info.FrameIdx = FI; 4999 TailCallArguments.push_back(Info); 5000 } 5001 5002 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5003 /// stack slot. Returns the chain as result and the loaded frame pointers in 5004 /// LROpOut/FPOpout. Used when tail calling. 5005 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5006 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5007 SDValue &FPOpOut, const SDLoc &dl) const { 5008 if (SPDiff) { 5009 // Load the LR and FP stack slot for later adjusting. 5010 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5011 LROpOut = getReturnAddrFrameIndex(DAG); 5012 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5013 Chain = SDValue(LROpOut.getNode(), 1); 5014 } 5015 return Chain; 5016 } 5017 5018 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5019 /// by "Src" to address "Dst" of size "Size". Alignment information is 5020 /// specified by the specific parameter attribute. The copy will be passed as 5021 /// a byval function parameter. 5022 /// Sometimes what we are copying is the end of a larger object, the part that 5023 /// does not fit in registers. 5024 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5025 SDValue Chain, ISD::ArgFlagsTy Flags, 5026 SelectionDAG &DAG, const SDLoc &dl) { 5027 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5028 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5029 Flags.getNonZeroByValAlign(), false, false, false, 5030 MachinePointerInfo(), MachinePointerInfo()); 5031 } 5032 5033 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5034 /// tail calls. 5035 static void LowerMemOpCallTo( 5036 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5037 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5038 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5039 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5040 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5041 if (!isTailCall) { 5042 if (isVector) { 5043 SDValue StackPtr; 5044 if (isPPC64) 5045 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5046 else 5047 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5048 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5049 DAG.getConstant(ArgOffset, dl, PtrVT)); 5050 } 5051 MemOpChains.push_back( 5052 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5053 // Calculate and remember argument location. 5054 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5055 TailCallArguments); 5056 } 5057 5058 static void 5059 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5060 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5061 SDValue FPOp, 5062 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5063 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5064 // might overwrite each other in case of tail call optimization. 5065 SmallVector<SDValue, 8> MemOpChains2; 5066 // Do not flag preceding copytoreg stuff together with the following stuff. 5067 InFlag = SDValue(); 5068 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5069 MemOpChains2, dl); 5070 if (!MemOpChains2.empty()) 5071 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5072 5073 // Store the return address to the appropriate stack slot. 5074 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5075 5076 // Emit callseq_end just before tailcall node. 5077 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5078 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5079 InFlag = Chain.getValue(1); 5080 } 5081 5082 // Is this global address that of a function that can be called by name? (as 5083 // opposed to something that must hold a descriptor for an indirect call). 5084 static bool isFunctionGlobalAddress(SDValue Callee) { 5085 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5086 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5087 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5088 return false; 5089 5090 return G->getGlobal()->getValueType()->isFunctionTy(); 5091 } 5092 5093 return false; 5094 } 5095 5096 SDValue PPCTargetLowering::LowerCallResult( 5097 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5098 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5099 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5100 SmallVector<CCValAssign, 16> RVLocs; 5101 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5102 *DAG.getContext()); 5103 5104 CCRetInfo.AnalyzeCallResult( 5105 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5106 ? RetCC_PPC_Cold 5107 : RetCC_PPC); 5108 5109 // Copy all of the result registers out of their specified physreg. 5110 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5111 CCValAssign &VA = RVLocs[i]; 5112 assert(VA.isRegLoc() && "Can only return in registers!"); 5113 5114 SDValue Val; 5115 5116 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5117 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5118 InFlag); 5119 Chain = Lo.getValue(1); 5120 InFlag = Lo.getValue(2); 5121 VA = RVLocs[++i]; // skip ahead to next loc 5122 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5123 InFlag); 5124 Chain = Hi.getValue(1); 5125 InFlag = Hi.getValue(2); 5126 if (!Subtarget.isLittleEndian()) 5127 std::swap (Lo, Hi); 5128 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5129 } else { 5130 Val = DAG.getCopyFromReg(Chain, dl, 5131 VA.getLocReg(), VA.getLocVT(), InFlag); 5132 Chain = Val.getValue(1); 5133 InFlag = Val.getValue(2); 5134 } 5135 5136 switch (VA.getLocInfo()) { 5137 default: llvm_unreachable("Unknown loc info!"); 5138 case CCValAssign::Full: break; 5139 case CCValAssign::AExt: 5140 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5141 break; 5142 case CCValAssign::ZExt: 5143 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5144 DAG.getValueType(VA.getValVT())); 5145 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5146 break; 5147 case CCValAssign::SExt: 5148 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5149 DAG.getValueType(VA.getValVT())); 5150 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5151 break; 5152 } 5153 5154 InVals.push_back(Val); 5155 } 5156 5157 return Chain; 5158 } 5159 5160 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5161 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5162 // PatchPoint calls are not indirect. 5163 if (isPatchPoint) 5164 return false; 5165 5166 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5167 return false; 5168 5169 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5170 // becuase the immediate function pointer points to a descriptor instead of 5171 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5172 // pointer immediate points to the global entry point, while the BLA would 5173 // need to jump to the local entry point (see rL211174). 5174 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5175 isBLACompatibleAddress(Callee, DAG)) 5176 return false; 5177 5178 return true; 5179 } 5180 5181 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5182 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5183 return Subtarget.isAIXABI() || 5184 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5185 } 5186 5187 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5188 const Function &Caller, const SDValue &Callee, 5189 const PPCSubtarget &Subtarget, 5190 const TargetMachine &TM, 5191 bool IsStrictFPCall = false) { 5192 if (CFlags.IsTailCall) 5193 return PPCISD::TC_RETURN; 5194 5195 unsigned RetOpc = 0; 5196 // This is a call through a function pointer. 5197 if (CFlags.IsIndirect) { 5198 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5199 // indirect calls. The save of the caller's TOC pointer to the stack will be 5200 // inserted into the DAG as part of call lowering. The restore of the TOC 5201 // pointer is modeled by using a pseudo instruction for the call opcode that 5202 // represents the 2 instruction sequence of an indirect branch and link, 5203 // immediately followed by a load of the TOC pointer from the the stack save 5204 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5205 // as it is not saved or used. 5206 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5207 : PPCISD::BCTRL; 5208 } else if (Subtarget.isUsingPCRelativeCalls()) { 5209 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5210 RetOpc = PPCISD::CALL_NOTOC; 5211 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5212 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5213 // immediately following the call instruction if the caller and callee may 5214 // have different TOC bases. At link time if the linker determines the calls 5215 // may not share a TOC base, the call is redirected to a trampoline inserted 5216 // by the linker. The trampoline will (among other things) save the callers 5217 // TOC pointer at an ABI designated offset in the linkage area and the 5218 // linker will rewrite the nop to be a load of the TOC pointer from the 5219 // linkage area into gpr2. 5220 RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5221 : PPCISD::CALL_NOP; 5222 else 5223 RetOpc = PPCISD::CALL; 5224 if (IsStrictFPCall) { 5225 switch (RetOpc) { 5226 default: 5227 llvm_unreachable("Unknown call opcode"); 5228 case PPCISD::BCTRL_LOAD_TOC: 5229 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM; 5230 break; 5231 case PPCISD::BCTRL: 5232 RetOpc = PPCISD::BCTRL_RM; 5233 break; 5234 case PPCISD::CALL_NOTOC: 5235 RetOpc = PPCISD::CALL_NOTOC_RM; 5236 break; 5237 case PPCISD::CALL: 5238 RetOpc = PPCISD::CALL_RM; 5239 break; 5240 case PPCISD::CALL_NOP: 5241 RetOpc = PPCISD::CALL_NOP_RM; 5242 break; 5243 } 5244 } 5245 return RetOpc; 5246 } 5247 5248 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5249 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5250 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5251 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5252 return SDValue(Dest, 0); 5253 5254 // Returns true if the callee is local, and false otherwise. 5255 auto isLocalCallee = [&]() { 5256 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5257 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5258 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5259 5260 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5261 !isa_and_nonnull<GlobalIFunc>(GV); 5262 }; 5263 5264 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5265 // a static relocation model causes some versions of GNU LD (2.17.50, at 5266 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5267 // built with secure-PLT. 5268 bool UsePlt = 5269 Subtarget.is32BitELFABI() && !isLocalCallee() && 5270 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5271 5272 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5273 const TargetMachine &TM = Subtarget.getTargetMachine(); 5274 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5275 MCSymbolXCOFF *S = 5276 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5277 5278 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5279 return DAG.getMCSymbol(S, PtrVT); 5280 }; 5281 5282 if (isFunctionGlobalAddress(Callee)) { 5283 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5284 5285 if (Subtarget.isAIXABI()) { 5286 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5287 return getAIXFuncEntryPointSymbolSDNode(GV); 5288 } 5289 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5290 UsePlt ? PPCII::MO_PLT : 0); 5291 } 5292 5293 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5294 const char *SymName = S->getSymbol(); 5295 if (Subtarget.isAIXABI()) { 5296 // If there exists a user-declared function whose name is the same as the 5297 // ExternalSymbol's, then we pick up the user-declared version. 5298 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5299 if (const Function *F = 5300 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5301 return getAIXFuncEntryPointSymbolSDNode(F); 5302 5303 // On AIX, direct function calls reference the symbol for the function's 5304 // entry point, which is named by prepending a "." before the function's 5305 // C-linkage name. A Qualname is returned here because an external 5306 // function entry point is a csect with XTY_ER property. 5307 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5308 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5309 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5310 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5311 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5312 return Sec->getQualNameSymbol(); 5313 }; 5314 5315 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5316 } 5317 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5318 UsePlt ? PPCII::MO_PLT : 0); 5319 } 5320 5321 // No transformation needed. 5322 assert(Callee.getNode() && "What no callee?"); 5323 return Callee; 5324 } 5325 5326 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5327 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5328 "Expected a CALLSEQ_STARTSDNode."); 5329 5330 // The last operand is the chain, except when the node has glue. If the node 5331 // has glue, then the last operand is the glue, and the chain is the second 5332 // last operand. 5333 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5334 if (LastValue.getValueType() != MVT::Glue) 5335 return LastValue; 5336 5337 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5338 } 5339 5340 // Creates the node that moves a functions address into the count register 5341 // to prepare for an indirect call instruction. 5342 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5343 SDValue &Glue, SDValue &Chain, 5344 const SDLoc &dl) { 5345 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5346 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5347 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5348 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5349 // The glue is the second value produced. 5350 Glue = Chain.getValue(1); 5351 } 5352 5353 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5354 SDValue &Glue, SDValue &Chain, 5355 SDValue CallSeqStart, 5356 const CallBase *CB, const SDLoc &dl, 5357 bool hasNest, 5358 const PPCSubtarget &Subtarget) { 5359 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5360 // entry point, but to the function descriptor (the function entry point 5361 // address is part of the function descriptor though). 5362 // The function descriptor is a three doubleword structure with the 5363 // following fields: function entry point, TOC base address and 5364 // environment pointer. 5365 // Thus for a call through a function pointer, the following actions need 5366 // to be performed: 5367 // 1. Save the TOC of the caller in the TOC save area of its stack 5368 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5369 // 2. Load the address of the function entry point from the function 5370 // descriptor. 5371 // 3. Load the TOC of the callee from the function descriptor into r2. 5372 // 4. Load the environment pointer from the function descriptor into 5373 // r11. 5374 // 5. Branch to the function entry point address. 5375 // 6. On return of the callee, the TOC of the caller needs to be 5376 // restored (this is done in FinishCall()). 5377 // 5378 // The loads are scheduled at the beginning of the call sequence, and the 5379 // register copies are flagged together to ensure that no other 5380 // operations can be scheduled in between. E.g. without flagging the 5381 // copies together, a TOC access in the caller could be scheduled between 5382 // the assignment of the callee TOC and the branch to the callee, which leads 5383 // to incorrect code. 5384 5385 // Start by loading the function address from the descriptor. 5386 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5387 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5388 ? (MachineMemOperand::MODereferenceable | 5389 MachineMemOperand::MOInvariant) 5390 : MachineMemOperand::MONone; 5391 5392 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5393 5394 // Registers used in building the DAG. 5395 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5396 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5397 5398 // Offsets of descriptor members. 5399 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5400 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5401 5402 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5403 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5404 5405 // One load for the functions entry point address. 5406 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5407 Alignment, MMOFlags); 5408 5409 // One for loading the TOC anchor for the module that contains the called 5410 // function. 5411 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5412 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5413 SDValue TOCPtr = 5414 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5415 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5416 5417 // One for loading the environment pointer. 5418 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5419 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5420 SDValue LoadEnvPtr = 5421 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5422 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5423 5424 5425 // Then copy the newly loaded TOC anchor to the TOC pointer. 5426 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5427 Chain = TOCVal.getValue(0); 5428 Glue = TOCVal.getValue(1); 5429 5430 // If the function call has an explicit 'nest' parameter, it takes the 5431 // place of the environment pointer. 5432 assert((!hasNest || !Subtarget.isAIXABI()) && 5433 "Nest parameter is not supported on AIX."); 5434 if (!hasNest) { 5435 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5436 Chain = EnvVal.getValue(0); 5437 Glue = EnvVal.getValue(1); 5438 } 5439 5440 // The rest of the indirect call sequence is the same as the non-descriptor 5441 // DAG. 5442 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5443 } 5444 5445 static void 5446 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5447 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5448 SelectionDAG &DAG, 5449 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5450 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5451 const PPCSubtarget &Subtarget) { 5452 const bool IsPPC64 = Subtarget.isPPC64(); 5453 // MVT for a general purpose register. 5454 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5455 5456 // First operand is always the chain. 5457 Ops.push_back(Chain); 5458 5459 // If it's a direct call pass the callee as the second operand. 5460 if (!CFlags.IsIndirect) 5461 Ops.push_back(Callee); 5462 else { 5463 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5464 5465 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5466 // on the stack (this would have been done in `LowerCall_64SVR4` or 5467 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5468 // represents both the indirect branch and a load that restores the TOC 5469 // pointer from the linkage area. The operand for the TOC restore is an add 5470 // of the TOC save offset to the stack pointer. This must be the second 5471 // operand: after the chain input but before any other variadic arguments. 5472 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5473 // saved or used. 5474 if (isTOCSaveRestoreRequired(Subtarget)) { 5475 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5476 5477 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5478 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5479 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5480 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5481 Ops.push_back(AddTOC); 5482 } 5483 5484 // Add the register used for the environment pointer. 5485 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5486 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5487 RegVT)); 5488 5489 5490 // Add CTR register as callee so a bctr can be emitted later. 5491 if (CFlags.IsTailCall) 5492 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5493 } 5494 5495 // If this is a tail call add stack pointer delta. 5496 if (CFlags.IsTailCall) 5497 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5498 5499 // Add argument registers to the end of the list so that they are known live 5500 // into the call. 5501 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5502 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5503 RegsToPass[i].second.getValueType())); 5504 5505 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5506 // no way to mark dependencies as implicit here. 5507 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5508 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5509 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5510 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5511 5512 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5513 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5514 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5515 5516 // Add a register mask operand representing the call-preserved registers. 5517 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5518 const uint32_t *Mask = 5519 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5520 assert(Mask && "Missing call preserved mask for calling convention"); 5521 Ops.push_back(DAG.getRegisterMask(Mask)); 5522 5523 // If the glue is valid, it is the last operand. 5524 if (Glue.getNode()) 5525 Ops.push_back(Glue); 5526 } 5527 5528 SDValue PPCTargetLowering::FinishCall( 5529 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5530 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5531 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5532 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5533 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5534 5535 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5536 Subtarget.isAIXABI()) 5537 setUsesTOCBasePtr(DAG); 5538 5539 unsigned CallOpc = 5540 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5541 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false); 5542 5543 if (!CFlags.IsIndirect) 5544 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5545 else if (Subtarget.usesFunctionDescriptors()) 5546 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5547 dl, CFlags.HasNest, Subtarget); 5548 else 5549 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5550 5551 // Build the operand list for the call instruction. 5552 SmallVector<SDValue, 8> Ops; 5553 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5554 SPDiff, Subtarget); 5555 5556 // Emit tail call. 5557 if (CFlags.IsTailCall) { 5558 // Indirect tail call when using PC Relative calls do not have the same 5559 // constraints. 5560 assert(((Callee.getOpcode() == ISD::Register && 5561 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5562 Callee.getOpcode() == ISD::TargetExternalSymbol || 5563 Callee.getOpcode() == ISD::TargetGlobalAddress || 5564 isa<ConstantSDNode>(Callee) || 5565 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5566 "Expecting a global address, external symbol, absolute value, " 5567 "register or an indirect tail call when PC Relative calls are " 5568 "used."); 5569 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5570 assert(CallOpc == PPCISD::TC_RETURN && 5571 "Unexpected call opcode for a tail call."); 5572 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5573 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5574 } 5575 5576 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5577 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5578 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5579 Glue = Chain.getValue(1); 5580 5581 // When performing tail call optimization the callee pops its arguments off 5582 // the stack. Account for this here so these bytes can be pushed back on in 5583 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5584 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5585 getTargetMachine().Options.GuaranteedTailCallOpt) 5586 ? NumBytes 5587 : 0; 5588 5589 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5590 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5591 Glue, dl); 5592 Glue = Chain.getValue(1); 5593 5594 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5595 DAG, InVals); 5596 } 5597 5598 SDValue 5599 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5600 SmallVectorImpl<SDValue> &InVals) const { 5601 SelectionDAG &DAG = CLI.DAG; 5602 SDLoc &dl = CLI.DL; 5603 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5604 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5605 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5606 SDValue Chain = CLI.Chain; 5607 SDValue Callee = CLI.Callee; 5608 bool &isTailCall = CLI.IsTailCall; 5609 CallingConv::ID CallConv = CLI.CallConv; 5610 bool isVarArg = CLI.IsVarArg; 5611 bool isPatchPoint = CLI.IsPatchPoint; 5612 const CallBase *CB = CLI.CB; 5613 5614 if (isTailCall) { 5615 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5616 isTailCall = false; 5617 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5618 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5619 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5620 else 5621 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5622 Ins, DAG); 5623 if (isTailCall) { 5624 ++NumTailCalls; 5625 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5626 ++NumSiblingCalls; 5627 5628 // PC Relative calls no longer guarantee that the callee is a Global 5629 // Address Node. The callee could be an indirect tail call in which 5630 // case the SDValue for the callee could be a load (to load the address 5631 // of a function pointer) or it may be a register copy (to move the 5632 // address of the callee from a function parameter into a virtual 5633 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5634 assert((Subtarget.isUsingPCRelativeCalls() || 5635 isa<GlobalAddressSDNode>(Callee)) && 5636 "Callee should be an llvm::Function object."); 5637 5638 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5639 << "\nTCO callee: "); 5640 LLVM_DEBUG(Callee.dump()); 5641 } 5642 } 5643 5644 if (!isTailCall && CB && CB->isMustTailCall()) 5645 report_fatal_error("failed to perform tail call elimination on a call " 5646 "site marked musttail"); 5647 5648 // When long calls (i.e. indirect calls) are always used, calls are always 5649 // made via function pointer. If we have a function name, first translate it 5650 // into a pointer. 5651 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5652 !isTailCall) 5653 Callee = LowerGlobalAddress(Callee, DAG); 5654 5655 CallFlags CFlags( 5656 CallConv, isTailCall, isVarArg, isPatchPoint, 5657 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5658 // hasNest 5659 Subtarget.is64BitELFABI() && 5660 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5661 CLI.NoMerge); 5662 5663 if (Subtarget.isAIXABI()) 5664 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5665 InVals, CB); 5666 5667 assert(Subtarget.isSVR4ABI()); 5668 if (Subtarget.isPPC64()) 5669 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5670 InVals, CB); 5671 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5672 InVals, CB); 5673 } 5674 5675 SDValue PPCTargetLowering::LowerCall_32SVR4( 5676 SDValue Chain, SDValue Callee, CallFlags CFlags, 5677 const SmallVectorImpl<ISD::OutputArg> &Outs, 5678 const SmallVectorImpl<SDValue> &OutVals, 5679 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5680 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5681 const CallBase *CB) const { 5682 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5683 // of the 32-bit SVR4 ABI stack frame layout. 5684 5685 const CallingConv::ID CallConv = CFlags.CallConv; 5686 const bool IsVarArg = CFlags.IsVarArg; 5687 const bool IsTailCall = CFlags.IsTailCall; 5688 5689 assert((CallConv == CallingConv::C || 5690 CallConv == CallingConv::Cold || 5691 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5692 5693 const Align PtrAlign(4); 5694 5695 MachineFunction &MF = DAG.getMachineFunction(); 5696 5697 // Mark this function as potentially containing a function that contains a 5698 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5699 // and restoring the callers stack pointer in this functions epilog. This is 5700 // done because by tail calling the called function might overwrite the value 5701 // in this function's (MF) stack pointer stack slot 0(SP). 5702 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5703 CallConv == CallingConv::Fast) 5704 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5705 5706 // Count how many bytes are to be pushed on the stack, including the linkage 5707 // area, parameter list area and the part of the local variable space which 5708 // contains copies of aggregates which are passed by value. 5709 5710 // Assign locations to all of the outgoing arguments. 5711 SmallVector<CCValAssign, 16> ArgLocs; 5712 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5713 5714 // Reserve space for the linkage area on the stack. 5715 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5716 PtrAlign); 5717 if (useSoftFloat()) 5718 CCInfo.PreAnalyzeCallOperands(Outs); 5719 5720 if (IsVarArg) { 5721 // Handle fixed and variable vector arguments differently. 5722 // Fixed vector arguments go into registers as long as registers are 5723 // available. Variable vector arguments always go into memory. 5724 unsigned NumArgs = Outs.size(); 5725 5726 for (unsigned i = 0; i != NumArgs; ++i) { 5727 MVT ArgVT = Outs[i].VT; 5728 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5729 bool Result; 5730 5731 if (Outs[i].IsFixed) { 5732 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5733 CCInfo); 5734 } else { 5735 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5736 ArgFlags, CCInfo); 5737 } 5738 5739 if (Result) { 5740 #ifndef NDEBUG 5741 errs() << "Call operand #" << i << " has unhandled type " 5742 << EVT(ArgVT).getEVTString() << "\n"; 5743 #endif 5744 llvm_unreachable(nullptr); 5745 } 5746 } 5747 } else { 5748 // All arguments are treated the same. 5749 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5750 } 5751 CCInfo.clearWasPPCF128(); 5752 5753 // Assign locations to all of the outgoing aggregate by value arguments. 5754 SmallVector<CCValAssign, 16> ByValArgLocs; 5755 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5756 5757 // Reserve stack space for the allocations in CCInfo. 5758 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5759 5760 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5761 5762 // Size of the linkage area, parameter list area and the part of the local 5763 // space variable where copies of aggregates which are passed by value are 5764 // stored. 5765 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5766 5767 // Calculate by how many bytes the stack has to be adjusted in case of tail 5768 // call optimization. 5769 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5770 5771 // Adjust the stack pointer for the new arguments... 5772 // These operations are automatically eliminated by the prolog/epilog pass 5773 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5774 SDValue CallSeqStart = Chain; 5775 5776 // Load the return address and frame pointer so it can be moved somewhere else 5777 // later. 5778 SDValue LROp, FPOp; 5779 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5780 5781 // Set up a copy of the stack pointer for use loading and storing any 5782 // arguments that may not fit in the registers available for argument 5783 // passing. 5784 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5785 5786 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5787 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5788 SmallVector<SDValue, 8> MemOpChains; 5789 5790 bool seenFloatArg = false; 5791 // Walk the register/memloc assignments, inserting copies/loads. 5792 // i - Tracks the index into the list of registers allocated for the call 5793 // RealArgIdx - Tracks the index into the list of actual function arguments 5794 // j - Tracks the index into the list of byval arguments 5795 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5796 i != e; 5797 ++i, ++RealArgIdx) { 5798 CCValAssign &VA = ArgLocs[i]; 5799 SDValue Arg = OutVals[RealArgIdx]; 5800 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5801 5802 if (Flags.isByVal()) { 5803 // Argument is an aggregate which is passed by value, thus we need to 5804 // create a copy of it in the local variable space of the current stack 5805 // frame (which is the stack frame of the caller) and pass the address of 5806 // this copy to the callee. 5807 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5808 CCValAssign &ByValVA = ByValArgLocs[j++]; 5809 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5810 5811 // Memory reserved in the local variable space of the callers stack frame. 5812 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5813 5814 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5815 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5816 StackPtr, PtrOff); 5817 5818 // Create a copy of the argument in the local area of the current 5819 // stack frame. 5820 SDValue MemcpyCall = 5821 CreateCopyOfByValArgument(Arg, PtrOff, 5822 CallSeqStart.getNode()->getOperand(0), 5823 Flags, DAG, dl); 5824 5825 // This must go outside the CALLSEQ_START..END. 5826 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5827 SDLoc(MemcpyCall)); 5828 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5829 NewCallSeqStart.getNode()); 5830 Chain = CallSeqStart = NewCallSeqStart; 5831 5832 // Pass the address of the aggregate copy on the stack either in a 5833 // physical register or in the parameter list area of the current stack 5834 // frame to the callee. 5835 Arg = PtrOff; 5836 } 5837 5838 // When useCRBits() is true, there can be i1 arguments. 5839 // It is because getRegisterType(MVT::i1) => MVT::i1, 5840 // and for other integer types getRegisterType() => MVT::i32. 5841 // Extend i1 and ensure callee will get i32. 5842 if (Arg.getValueType() == MVT::i1) 5843 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5844 dl, MVT::i32, Arg); 5845 5846 if (VA.isRegLoc()) { 5847 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5848 // Put argument in a physical register. 5849 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5850 bool IsLE = Subtarget.isLittleEndian(); 5851 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5852 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5853 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5854 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5855 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5856 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5857 SVal.getValue(0))); 5858 } else 5859 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5860 } else { 5861 // Put argument in the parameter list area of the current stack frame. 5862 assert(VA.isMemLoc()); 5863 unsigned LocMemOffset = VA.getLocMemOffset(); 5864 5865 if (!IsTailCall) { 5866 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5867 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5868 StackPtr, PtrOff); 5869 5870 MemOpChains.push_back( 5871 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5872 } else { 5873 // Calculate and remember argument location. 5874 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5875 TailCallArguments); 5876 } 5877 } 5878 } 5879 5880 if (!MemOpChains.empty()) 5881 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5882 5883 // Build a sequence of copy-to-reg nodes chained together with token chain 5884 // and flag operands which copy the outgoing args into the appropriate regs. 5885 SDValue InFlag; 5886 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5887 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5888 RegsToPass[i].second, InFlag); 5889 InFlag = Chain.getValue(1); 5890 } 5891 5892 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5893 // registers. 5894 if (IsVarArg) { 5895 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5896 SDValue Ops[] = { Chain, InFlag }; 5897 5898 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5899 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5900 5901 InFlag = Chain.getValue(1); 5902 } 5903 5904 if (IsTailCall) 5905 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5906 TailCallArguments); 5907 5908 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5909 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5910 } 5911 5912 // Copy an argument into memory, being careful to do this outside the 5913 // call sequence for the call to which the argument belongs. 5914 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5915 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5916 SelectionDAG &DAG, const SDLoc &dl) const { 5917 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5918 CallSeqStart.getNode()->getOperand(0), 5919 Flags, DAG, dl); 5920 // The MEMCPY must go outside the CALLSEQ_START..END. 5921 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5922 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5923 SDLoc(MemcpyCall)); 5924 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5925 NewCallSeqStart.getNode()); 5926 return NewCallSeqStart; 5927 } 5928 5929 SDValue PPCTargetLowering::LowerCall_64SVR4( 5930 SDValue Chain, SDValue Callee, CallFlags CFlags, 5931 const SmallVectorImpl<ISD::OutputArg> &Outs, 5932 const SmallVectorImpl<SDValue> &OutVals, 5933 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5934 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5935 const CallBase *CB) const { 5936 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5937 bool isLittleEndian = Subtarget.isLittleEndian(); 5938 unsigned NumOps = Outs.size(); 5939 bool IsSibCall = false; 5940 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5941 5942 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5943 unsigned PtrByteSize = 8; 5944 5945 MachineFunction &MF = DAG.getMachineFunction(); 5946 5947 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5948 IsSibCall = true; 5949 5950 // Mark this function as potentially containing a function that contains a 5951 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5952 // and restoring the callers stack pointer in this functions epilog. This is 5953 // done because by tail calling the called function might overwrite the value 5954 // in this function's (MF) stack pointer stack slot 0(SP). 5955 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5956 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5957 5958 assert(!(IsFastCall && CFlags.IsVarArg) && 5959 "fastcc not supported on varargs functions"); 5960 5961 // Count how many bytes are to be pushed on the stack, including the linkage 5962 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5963 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5964 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5965 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5966 unsigned NumBytes = LinkageSize; 5967 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5968 5969 static const MCPhysReg GPR[] = { 5970 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5971 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5972 }; 5973 static const MCPhysReg VR[] = { 5974 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5975 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5976 }; 5977 5978 const unsigned NumGPRs = array_lengthof(GPR); 5979 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5980 const unsigned NumVRs = array_lengthof(VR); 5981 5982 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5983 // can be passed to the callee in registers. 5984 // For the fast calling convention, there is another check below. 5985 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5986 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5987 if (!HasParameterArea) { 5988 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5989 unsigned AvailableFPRs = NumFPRs; 5990 unsigned AvailableVRs = NumVRs; 5991 unsigned NumBytesTmp = NumBytes; 5992 for (unsigned i = 0; i != NumOps; ++i) { 5993 if (Outs[i].Flags.isNest()) continue; 5994 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5995 PtrByteSize, LinkageSize, ParamAreaSize, 5996 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5997 HasParameterArea = true; 5998 } 5999 } 6000 6001 // When using the fast calling convention, we don't provide backing for 6002 // arguments that will be in registers. 6003 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6004 6005 // Avoid allocating parameter area for fastcc functions if all the arguments 6006 // can be passed in the registers. 6007 if (IsFastCall) 6008 HasParameterArea = false; 6009 6010 // Add up all the space actually used. 6011 for (unsigned i = 0; i != NumOps; ++i) { 6012 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6013 EVT ArgVT = Outs[i].VT; 6014 EVT OrigVT = Outs[i].ArgVT; 6015 6016 if (Flags.isNest()) 6017 continue; 6018 6019 if (IsFastCall) { 6020 if (Flags.isByVal()) { 6021 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6022 if (NumGPRsUsed > NumGPRs) 6023 HasParameterArea = true; 6024 } else { 6025 switch (ArgVT.getSimpleVT().SimpleTy) { 6026 default: llvm_unreachable("Unexpected ValueType for argument!"); 6027 case MVT::i1: 6028 case MVT::i32: 6029 case MVT::i64: 6030 if (++NumGPRsUsed <= NumGPRs) 6031 continue; 6032 break; 6033 case MVT::v4i32: 6034 case MVT::v8i16: 6035 case MVT::v16i8: 6036 case MVT::v2f64: 6037 case MVT::v2i64: 6038 case MVT::v1i128: 6039 case MVT::f128: 6040 if (++NumVRsUsed <= NumVRs) 6041 continue; 6042 break; 6043 case MVT::v4f32: 6044 if (++NumVRsUsed <= NumVRs) 6045 continue; 6046 break; 6047 case MVT::f32: 6048 case MVT::f64: 6049 if (++NumFPRsUsed <= NumFPRs) 6050 continue; 6051 break; 6052 } 6053 HasParameterArea = true; 6054 } 6055 } 6056 6057 /* Respect alignment of argument on the stack. */ 6058 auto Alignement = 6059 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6060 NumBytes = alignTo(NumBytes, Alignement); 6061 6062 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6063 if (Flags.isInConsecutiveRegsLast()) 6064 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6065 } 6066 6067 unsigned NumBytesActuallyUsed = NumBytes; 6068 6069 // In the old ELFv1 ABI, 6070 // the prolog code of the callee may store up to 8 GPR argument registers to 6071 // the stack, allowing va_start to index over them in memory if its varargs. 6072 // Because we cannot tell if this is needed on the caller side, we have to 6073 // conservatively assume that it is needed. As such, make sure we have at 6074 // least enough stack space for the caller to store the 8 GPRs. 6075 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6076 // really requires memory operands, e.g. a vararg function. 6077 if (HasParameterArea) 6078 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6079 else 6080 NumBytes = LinkageSize; 6081 6082 // Tail call needs the stack to be aligned. 6083 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6084 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6085 6086 int SPDiff = 0; 6087 6088 // Calculate by how many bytes the stack has to be adjusted in case of tail 6089 // call optimization. 6090 if (!IsSibCall) 6091 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6092 6093 // To protect arguments on the stack from being clobbered in a tail call, 6094 // force all the loads to happen before doing any other lowering. 6095 if (CFlags.IsTailCall) 6096 Chain = DAG.getStackArgumentTokenFactor(Chain); 6097 6098 // Adjust the stack pointer for the new arguments... 6099 // These operations are automatically eliminated by the prolog/epilog pass 6100 if (!IsSibCall) 6101 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6102 SDValue CallSeqStart = Chain; 6103 6104 // Load the return address and frame pointer so it can be move somewhere else 6105 // later. 6106 SDValue LROp, FPOp; 6107 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6108 6109 // Set up a copy of the stack pointer for use loading and storing any 6110 // arguments that may not fit in the registers available for argument 6111 // passing. 6112 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6113 6114 // Figure out which arguments are going to go in registers, and which in 6115 // memory. Also, if this is a vararg function, floating point operations 6116 // must be stored to our stack, and loaded into integer regs as well, if 6117 // any integer regs are available for argument passing. 6118 unsigned ArgOffset = LinkageSize; 6119 6120 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6121 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6122 6123 SmallVector<SDValue, 8> MemOpChains; 6124 for (unsigned i = 0; i != NumOps; ++i) { 6125 SDValue Arg = OutVals[i]; 6126 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6127 EVT ArgVT = Outs[i].VT; 6128 EVT OrigVT = Outs[i].ArgVT; 6129 6130 // PtrOff will be used to store the current argument to the stack if a 6131 // register cannot be found for it. 6132 SDValue PtrOff; 6133 6134 // We re-align the argument offset for each argument, except when using the 6135 // fast calling convention, when we need to make sure we do that only when 6136 // we'll actually use a stack slot. 6137 auto ComputePtrOff = [&]() { 6138 /* Respect alignment of argument on the stack. */ 6139 auto Alignment = 6140 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6141 ArgOffset = alignTo(ArgOffset, Alignment); 6142 6143 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6144 6145 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6146 }; 6147 6148 if (!IsFastCall) { 6149 ComputePtrOff(); 6150 6151 /* Compute GPR index associated with argument offset. */ 6152 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6153 GPR_idx = std::min(GPR_idx, NumGPRs); 6154 } 6155 6156 // Promote integers to 64-bit values. 6157 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6158 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6159 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6160 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6161 } 6162 6163 // FIXME memcpy is used way more than necessary. Correctness first. 6164 // Note: "by value" is code for passing a structure by value, not 6165 // basic types. 6166 if (Flags.isByVal()) { 6167 // Note: Size includes alignment padding, so 6168 // struct x { short a; char b; } 6169 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6170 // These are the proper values we need for right-justifying the 6171 // aggregate in a parameter register. 6172 unsigned Size = Flags.getByValSize(); 6173 6174 // An empty aggregate parameter takes up no storage and no 6175 // registers. 6176 if (Size == 0) 6177 continue; 6178 6179 if (IsFastCall) 6180 ComputePtrOff(); 6181 6182 // All aggregates smaller than 8 bytes must be passed right-justified. 6183 if (Size==1 || Size==2 || Size==4) { 6184 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6185 if (GPR_idx != NumGPRs) { 6186 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6187 MachinePointerInfo(), VT); 6188 MemOpChains.push_back(Load.getValue(1)); 6189 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6190 6191 ArgOffset += PtrByteSize; 6192 continue; 6193 } 6194 } 6195 6196 if (GPR_idx == NumGPRs && Size < 8) { 6197 SDValue AddPtr = PtrOff; 6198 if (!isLittleEndian) { 6199 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6200 PtrOff.getValueType()); 6201 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6202 } 6203 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6204 CallSeqStart, 6205 Flags, DAG, dl); 6206 ArgOffset += PtrByteSize; 6207 continue; 6208 } 6209 // Copy entire object into memory. There are cases where gcc-generated 6210 // code assumes it is there, even if it could be put entirely into 6211 // registers. (This is not what the doc says.) 6212 6213 // FIXME: The above statement is likely due to a misunderstanding of the 6214 // documents. All arguments must be copied into the parameter area BY 6215 // THE CALLEE in the event that the callee takes the address of any 6216 // formal argument. That has not yet been implemented. However, it is 6217 // reasonable to use the stack area as a staging area for the register 6218 // load. 6219 6220 // Skip this for small aggregates, as we will use the same slot for a 6221 // right-justified copy, below. 6222 if (Size >= 8) 6223 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6224 CallSeqStart, 6225 Flags, DAG, dl); 6226 6227 // When a register is available, pass a small aggregate right-justified. 6228 if (Size < 8 && GPR_idx != NumGPRs) { 6229 // The easiest way to get this right-justified in a register 6230 // is to copy the structure into the rightmost portion of a 6231 // local variable slot, then load the whole slot into the 6232 // register. 6233 // FIXME: The memcpy seems to produce pretty awful code for 6234 // small aggregates, particularly for packed ones. 6235 // FIXME: It would be preferable to use the slot in the 6236 // parameter save area instead of a new local variable. 6237 SDValue AddPtr = PtrOff; 6238 if (!isLittleEndian) { 6239 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6240 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6241 } 6242 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6243 CallSeqStart, 6244 Flags, DAG, dl); 6245 6246 // Load the slot into the register. 6247 SDValue Load = 6248 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6249 MemOpChains.push_back(Load.getValue(1)); 6250 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6251 6252 // Done with this argument. 6253 ArgOffset += PtrByteSize; 6254 continue; 6255 } 6256 6257 // For aggregates larger than PtrByteSize, copy the pieces of the 6258 // object that fit into registers from the parameter save area. 6259 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6260 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6261 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6262 if (GPR_idx != NumGPRs) { 6263 SDValue Load = 6264 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6265 MemOpChains.push_back(Load.getValue(1)); 6266 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6267 ArgOffset += PtrByteSize; 6268 } else { 6269 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6270 break; 6271 } 6272 } 6273 continue; 6274 } 6275 6276 switch (Arg.getSimpleValueType().SimpleTy) { 6277 default: llvm_unreachable("Unexpected ValueType for argument!"); 6278 case MVT::i1: 6279 case MVT::i32: 6280 case MVT::i64: 6281 if (Flags.isNest()) { 6282 // The 'nest' parameter, if any, is passed in R11. 6283 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6284 break; 6285 } 6286 6287 // These can be scalar arguments or elements of an integer array type 6288 // passed directly. Clang may use those instead of "byval" aggregate 6289 // types to avoid forcing arguments to memory unnecessarily. 6290 if (GPR_idx != NumGPRs) { 6291 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6292 } else { 6293 if (IsFastCall) 6294 ComputePtrOff(); 6295 6296 assert(HasParameterArea && 6297 "Parameter area must exist to pass an argument in memory."); 6298 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6299 true, CFlags.IsTailCall, false, MemOpChains, 6300 TailCallArguments, dl); 6301 if (IsFastCall) 6302 ArgOffset += PtrByteSize; 6303 } 6304 if (!IsFastCall) 6305 ArgOffset += PtrByteSize; 6306 break; 6307 case MVT::f32: 6308 case MVT::f64: { 6309 // These can be scalar arguments or elements of a float array type 6310 // passed directly. The latter are used to implement ELFv2 homogenous 6311 // float aggregates. 6312 6313 // Named arguments go into FPRs first, and once they overflow, the 6314 // remaining arguments go into GPRs and then the parameter save area. 6315 // Unnamed arguments for vararg functions always go to GPRs and 6316 // then the parameter save area. For now, put all arguments to vararg 6317 // routines always in both locations (FPR *and* GPR or stack slot). 6318 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6319 bool NeededLoad = false; 6320 6321 // First load the argument into the next available FPR. 6322 if (FPR_idx != NumFPRs) 6323 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6324 6325 // Next, load the argument into GPR or stack slot if needed. 6326 if (!NeedGPROrStack) 6327 ; 6328 else if (GPR_idx != NumGPRs && !IsFastCall) { 6329 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6330 // once we support fp <-> gpr moves. 6331 6332 // In the non-vararg case, this can only ever happen in the 6333 // presence of f32 array types, since otherwise we never run 6334 // out of FPRs before running out of GPRs. 6335 SDValue ArgVal; 6336 6337 // Double values are always passed in a single GPR. 6338 if (Arg.getValueType() != MVT::f32) { 6339 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6340 6341 // Non-array float values are extended and passed in a GPR. 6342 } else if (!Flags.isInConsecutiveRegs()) { 6343 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6344 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6345 6346 // If we have an array of floats, we collect every odd element 6347 // together with its predecessor into one GPR. 6348 } else if (ArgOffset % PtrByteSize != 0) { 6349 SDValue Lo, Hi; 6350 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6351 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6352 if (!isLittleEndian) 6353 std::swap(Lo, Hi); 6354 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6355 6356 // The final element, if even, goes into the first half of a GPR. 6357 } else if (Flags.isInConsecutiveRegsLast()) { 6358 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6359 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6360 if (!isLittleEndian) 6361 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6362 DAG.getConstant(32, dl, MVT::i32)); 6363 6364 // Non-final even elements are skipped; they will be handled 6365 // together the with subsequent argument on the next go-around. 6366 } else 6367 ArgVal = SDValue(); 6368 6369 if (ArgVal.getNode()) 6370 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6371 } else { 6372 if (IsFastCall) 6373 ComputePtrOff(); 6374 6375 // Single-precision floating-point values are mapped to the 6376 // second (rightmost) word of the stack doubleword. 6377 if (Arg.getValueType() == MVT::f32 && 6378 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6379 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6380 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6381 } 6382 6383 assert(HasParameterArea && 6384 "Parameter area must exist to pass an argument in memory."); 6385 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6386 true, CFlags.IsTailCall, false, MemOpChains, 6387 TailCallArguments, dl); 6388 6389 NeededLoad = true; 6390 } 6391 // When passing an array of floats, the array occupies consecutive 6392 // space in the argument area; only round up to the next doubleword 6393 // at the end of the array. Otherwise, each float takes 8 bytes. 6394 if (!IsFastCall || NeededLoad) { 6395 ArgOffset += (Arg.getValueType() == MVT::f32 && 6396 Flags.isInConsecutiveRegs()) ? 4 : 8; 6397 if (Flags.isInConsecutiveRegsLast()) 6398 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6399 } 6400 break; 6401 } 6402 case MVT::v4f32: 6403 case MVT::v4i32: 6404 case MVT::v8i16: 6405 case MVT::v16i8: 6406 case MVT::v2f64: 6407 case MVT::v2i64: 6408 case MVT::v1i128: 6409 case MVT::f128: 6410 // These can be scalar arguments or elements of a vector array type 6411 // passed directly. The latter are used to implement ELFv2 homogenous 6412 // vector aggregates. 6413 6414 // For a varargs call, named arguments go into VRs or on the stack as 6415 // usual; unnamed arguments always go to the stack or the corresponding 6416 // GPRs when within range. For now, we always put the value in both 6417 // locations (or even all three). 6418 if (CFlags.IsVarArg) { 6419 assert(HasParameterArea && 6420 "Parameter area must exist if we have a varargs call."); 6421 // We could elide this store in the case where the object fits 6422 // entirely in R registers. Maybe later. 6423 SDValue Store = 6424 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6425 MemOpChains.push_back(Store); 6426 if (VR_idx != NumVRs) { 6427 SDValue Load = 6428 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6429 MemOpChains.push_back(Load.getValue(1)); 6430 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6431 } 6432 ArgOffset += 16; 6433 for (unsigned i=0; i<16; i+=PtrByteSize) { 6434 if (GPR_idx == NumGPRs) 6435 break; 6436 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6437 DAG.getConstant(i, dl, PtrVT)); 6438 SDValue Load = 6439 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6440 MemOpChains.push_back(Load.getValue(1)); 6441 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6442 } 6443 break; 6444 } 6445 6446 // Non-varargs Altivec params go into VRs or on the stack. 6447 if (VR_idx != NumVRs) { 6448 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6449 } else { 6450 if (IsFastCall) 6451 ComputePtrOff(); 6452 6453 assert(HasParameterArea && 6454 "Parameter area must exist to pass an argument in memory."); 6455 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6456 true, CFlags.IsTailCall, true, MemOpChains, 6457 TailCallArguments, dl); 6458 if (IsFastCall) 6459 ArgOffset += 16; 6460 } 6461 6462 if (!IsFastCall) 6463 ArgOffset += 16; 6464 break; 6465 } 6466 } 6467 6468 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6469 "mismatch in size of parameter area"); 6470 (void)NumBytesActuallyUsed; 6471 6472 if (!MemOpChains.empty()) 6473 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6474 6475 // Check if this is an indirect call (MTCTR/BCTRL). 6476 // See prepareDescriptorIndirectCall and buildCallOperands for more 6477 // information about calls through function pointers in the 64-bit SVR4 ABI. 6478 if (CFlags.IsIndirect) { 6479 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6480 // caller in the TOC save area. 6481 if (isTOCSaveRestoreRequired(Subtarget)) { 6482 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6483 // Load r2 into a virtual register and store it to the TOC save area. 6484 setUsesTOCBasePtr(DAG); 6485 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6486 // TOC save area offset. 6487 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6488 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6489 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6490 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6491 MachinePointerInfo::getStack( 6492 DAG.getMachineFunction(), TOCSaveOffset)); 6493 } 6494 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6495 // This does not mean the MTCTR instruction must use R12; it's easier 6496 // to model this as an extra parameter, so do that. 6497 if (isELFv2ABI && !CFlags.IsPatchPoint) 6498 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6499 } 6500 6501 // Build a sequence of copy-to-reg nodes chained together with token chain 6502 // and flag operands which copy the outgoing args into the appropriate regs. 6503 SDValue InFlag; 6504 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6505 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6506 RegsToPass[i].second, InFlag); 6507 InFlag = Chain.getValue(1); 6508 } 6509 6510 if (CFlags.IsTailCall && !IsSibCall) 6511 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6512 TailCallArguments); 6513 6514 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6515 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6516 } 6517 6518 // Returns true when the shadow of a general purpose argument register 6519 // in the parameter save area is aligned to at least 'RequiredAlign'. 6520 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6521 assert(RequiredAlign.value() <= 16 && 6522 "Required alignment greater than stack alignment."); 6523 switch (Reg) { 6524 default: 6525 report_fatal_error("called on invalid register."); 6526 case PPC::R5: 6527 case PPC::R9: 6528 case PPC::X3: 6529 case PPC::X5: 6530 case PPC::X7: 6531 case PPC::X9: 6532 // These registers are 16 byte aligned which is the most strict aligment 6533 // we can support. 6534 return true; 6535 case PPC::R3: 6536 case PPC::R7: 6537 case PPC::X4: 6538 case PPC::X6: 6539 case PPC::X8: 6540 case PPC::X10: 6541 // The shadow of these registers in the PSA is 8 byte aligned. 6542 return RequiredAlign <= 8; 6543 case PPC::R4: 6544 case PPC::R6: 6545 case PPC::R8: 6546 case PPC::R10: 6547 return RequiredAlign <= 4; 6548 } 6549 } 6550 6551 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6552 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6553 CCState &S) { 6554 AIXCCState &State = static_cast<AIXCCState &>(S); 6555 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6556 State.getMachineFunction().getSubtarget()); 6557 const bool IsPPC64 = Subtarget.isPPC64(); 6558 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6559 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6560 6561 if (ValVT == MVT::f128) 6562 report_fatal_error("f128 is unimplemented on AIX."); 6563 6564 if (ArgFlags.isNest()) 6565 report_fatal_error("Nest arguments are unimplemented."); 6566 6567 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6568 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6569 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6570 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6571 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6572 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6573 6574 static const MCPhysReg VR[] = {// Vector registers. 6575 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6576 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6577 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6578 6579 if (ArgFlags.isByVal()) { 6580 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6581 report_fatal_error("Pass-by-value arguments with alignment greater than " 6582 "register width are not supported."); 6583 6584 const unsigned ByValSize = ArgFlags.getByValSize(); 6585 6586 // An empty aggregate parameter takes up no storage and no registers, 6587 // but needs a MemLoc for a stack slot for the formal arguments side. 6588 if (ByValSize == 0) { 6589 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6590 State.getNextStackOffset(), RegVT, 6591 LocInfo)); 6592 return false; 6593 } 6594 6595 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6596 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6597 for (const unsigned E = Offset + StackSize; Offset < E; 6598 Offset += PtrAlign.value()) { 6599 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6600 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6601 else { 6602 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6603 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6604 LocInfo)); 6605 break; 6606 } 6607 } 6608 return false; 6609 } 6610 6611 // Arguments always reserve parameter save area. 6612 switch (ValVT.SimpleTy) { 6613 default: 6614 report_fatal_error("Unhandled value type for argument."); 6615 case MVT::i64: 6616 // i64 arguments should have been split to i32 for PPC32. 6617 assert(IsPPC64 && "PPC32 should have split i64 values."); 6618 LLVM_FALLTHROUGH; 6619 case MVT::i1: 6620 case MVT::i32: { 6621 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6622 // AIX integer arguments are always passed in register width. 6623 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6624 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6625 : CCValAssign::LocInfo::ZExt; 6626 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6627 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6628 else 6629 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6630 6631 return false; 6632 } 6633 case MVT::f32: 6634 case MVT::f64: { 6635 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6636 const unsigned StoreSize = LocVT.getStoreSize(); 6637 // Floats are always 4-byte aligned in the PSA on AIX. 6638 // This includes f64 in 64-bit mode for ABI compatibility. 6639 const unsigned Offset = 6640 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6641 unsigned FReg = State.AllocateReg(FPR); 6642 if (FReg) 6643 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6644 6645 // Reserve and initialize GPRs or initialize the PSA as required. 6646 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6647 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6648 assert(FReg && "An FPR should be available when a GPR is reserved."); 6649 if (State.isVarArg()) { 6650 // Successfully reserved GPRs are only initialized for vararg calls. 6651 // Custom handling is required for: 6652 // f64 in PPC32 needs to be split into 2 GPRs. 6653 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6654 State.addLoc( 6655 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6656 } 6657 } else { 6658 // If there are insufficient GPRs, the PSA needs to be initialized. 6659 // Initialization occurs even if an FPR was initialized for 6660 // compatibility with the AIX XL compiler. The full memory for the 6661 // argument will be initialized even if a prior word is saved in GPR. 6662 // A custom memLoc is used when the argument also passes in FPR so 6663 // that the callee handling can skip over it easily. 6664 State.addLoc( 6665 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6666 LocInfo) 6667 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6668 break; 6669 } 6670 } 6671 6672 return false; 6673 } 6674 case MVT::v4f32: 6675 case MVT::v4i32: 6676 case MVT::v8i16: 6677 case MVT::v16i8: 6678 case MVT::v2i64: 6679 case MVT::v2f64: 6680 case MVT::v1i128: { 6681 const unsigned VecSize = 16; 6682 const Align VecAlign(VecSize); 6683 6684 if (!State.isVarArg()) { 6685 // If there are vector registers remaining we don't consume any stack 6686 // space. 6687 if (unsigned VReg = State.AllocateReg(VR)) { 6688 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6689 return false; 6690 } 6691 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6692 // might be allocated in the portion of the PSA that is shadowed by the 6693 // GPRs. 6694 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6695 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6696 return false; 6697 } 6698 6699 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6700 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6701 6702 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6703 // Burn any underaligned registers and their shadowed stack space until 6704 // we reach the required alignment. 6705 while (NextRegIndex != GPRs.size() && 6706 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6707 // Shadow allocate register and its stack shadow. 6708 unsigned Reg = State.AllocateReg(GPRs); 6709 State.AllocateStack(PtrSize, PtrAlign); 6710 assert(Reg && "Allocating register unexpectedly failed."); 6711 (void)Reg; 6712 NextRegIndex = State.getFirstUnallocated(GPRs); 6713 } 6714 6715 // Vectors that are passed as fixed arguments are handled differently. 6716 // They are passed in VRs if any are available (unlike arguments passed 6717 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6718 // functions) 6719 if (State.isFixed(ValNo)) { 6720 if (unsigned VReg = State.AllocateReg(VR)) { 6721 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6722 // Shadow allocate GPRs and stack space even though we pass in a VR. 6723 for (unsigned I = 0; I != VecSize; I += PtrSize) 6724 State.AllocateReg(GPRs); 6725 State.AllocateStack(VecSize, VecAlign); 6726 return false; 6727 } 6728 // No vector registers remain so pass on the stack. 6729 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6730 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6731 return false; 6732 } 6733 6734 // If all GPRS are consumed then we pass the argument fully on the stack. 6735 if (NextRegIndex == GPRs.size()) { 6736 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6737 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6738 return false; 6739 } 6740 6741 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6742 // half of the argument, and then need to pass the remaining half on the 6743 // stack. 6744 if (GPRs[NextRegIndex] == PPC::R9) { 6745 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6746 State.addLoc( 6747 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6748 6749 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6750 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6751 assert(FirstReg && SecondReg && 6752 "Allocating R9 or R10 unexpectedly failed."); 6753 State.addLoc( 6754 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6755 State.addLoc( 6756 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6757 return false; 6758 } 6759 6760 // We have enough GPRs to fully pass the vector argument, and we have 6761 // already consumed any underaligned registers. Start with the custom 6762 // MemLoc and then the custom RegLocs. 6763 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6764 State.addLoc( 6765 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6766 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6767 const unsigned Reg = State.AllocateReg(GPRs); 6768 assert(Reg && "Failed to allocated register for vararg vector argument"); 6769 State.addLoc( 6770 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6771 } 6772 return false; 6773 } 6774 } 6775 return true; 6776 } 6777 6778 // So far, this function is only used by LowerFormalArguments_AIX() 6779 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6780 bool IsPPC64, 6781 bool HasP8Vector, 6782 bool HasVSX) { 6783 assert((IsPPC64 || SVT != MVT::i64) && 6784 "i64 should have been split for 32-bit codegen."); 6785 6786 switch (SVT) { 6787 default: 6788 report_fatal_error("Unexpected value type for formal argument"); 6789 case MVT::i1: 6790 case MVT::i32: 6791 case MVT::i64: 6792 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6793 case MVT::f32: 6794 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass; 6795 case MVT::f64: 6796 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass; 6797 case MVT::v4f32: 6798 case MVT::v4i32: 6799 case MVT::v8i16: 6800 case MVT::v16i8: 6801 case MVT::v2i64: 6802 case MVT::v2f64: 6803 case MVT::v1i128: 6804 return &PPC::VRRCRegClass; 6805 } 6806 } 6807 6808 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6809 SelectionDAG &DAG, SDValue ArgValue, 6810 MVT LocVT, const SDLoc &dl) { 6811 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6812 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6813 6814 if (Flags.isSExt()) 6815 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6816 DAG.getValueType(ValVT)); 6817 else if (Flags.isZExt()) 6818 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6819 DAG.getValueType(ValVT)); 6820 6821 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6822 } 6823 6824 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6825 const unsigned LASize = FL->getLinkageSize(); 6826 6827 if (PPC::GPRCRegClass.contains(Reg)) { 6828 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6829 "Reg must be a valid argument register!"); 6830 return LASize + 4 * (Reg - PPC::R3); 6831 } 6832 6833 if (PPC::G8RCRegClass.contains(Reg)) { 6834 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6835 "Reg must be a valid argument register!"); 6836 return LASize + 8 * (Reg - PPC::X3); 6837 } 6838 6839 llvm_unreachable("Only general purpose registers expected."); 6840 } 6841 6842 // AIX ABI Stack Frame Layout: 6843 // 6844 // Low Memory +--------------------------------------------+ 6845 // SP +---> | Back chain | ---+ 6846 // | +--------------------------------------------+ | 6847 // | | Saved Condition Register | | 6848 // | +--------------------------------------------+ | 6849 // | | Saved Linkage Register | | 6850 // | +--------------------------------------------+ | Linkage Area 6851 // | | Reserved for compilers | | 6852 // | +--------------------------------------------+ | 6853 // | | Reserved for binders | | 6854 // | +--------------------------------------------+ | 6855 // | | Saved TOC pointer | ---+ 6856 // | +--------------------------------------------+ 6857 // | | Parameter save area | 6858 // | +--------------------------------------------+ 6859 // | | Alloca space | 6860 // | +--------------------------------------------+ 6861 // | | Local variable space | 6862 // | +--------------------------------------------+ 6863 // | | Float/int conversion temporary | 6864 // | +--------------------------------------------+ 6865 // | | Save area for AltiVec registers | 6866 // | +--------------------------------------------+ 6867 // | | AltiVec alignment padding | 6868 // | +--------------------------------------------+ 6869 // | | Save area for VRSAVE register | 6870 // | +--------------------------------------------+ 6871 // | | Save area for General Purpose registers | 6872 // | +--------------------------------------------+ 6873 // | | Save area for Floating Point registers | 6874 // | +--------------------------------------------+ 6875 // +---- | Back chain | 6876 // High Memory +--------------------------------------------+ 6877 // 6878 // Specifications: 6879 // AIX 7.2 Assembler Language Reference 6880 // Subroutine linkage convention 6881 6882 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6883 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6884 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6885 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6886 6887 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6888 CallConv == CallingConv::Fast) && 6889 "Unexpected calling convention!"); 6890 6891 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6892 report_fatal_error("Tail call support is unimplemented on AIX."); 6893 6894 if (useSoftFloat()) 6895 report_fatal_error("Soft float support is unimplemented on AIX."); 6896 6897 const PPCSubtarget &Subtarget = 6898 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6899 6900 const bool IsPPC64 = Subtarget.isPPC64(); 6901 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6902 6903 // Assign locations to all of the incoming arguments. 6904 SmallVector<CCValAssign, 16> ArgLocs; 6905 MachineFunction &MF = DAG.getMachineFunction(); 6906 MachineFrameInfo &MFI = MF.getFrameInfo(); 6907 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6908 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6909 6910 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6911 // Reserve space for the linkage area on the stack. 6912 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6913 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6914 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6915 6916 SmallVector<SDValue, 8> MemOps; 6917 6918 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6919 CCValAssign &VA = ArgLocs[I++]; 6920 MVT LocVT = VA.getLocVT(); 6921 MVT ValVT = VA.getValVT(); 6922 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6923 // For compatibility with the AIX XL compiler, the float args in the 6924 // parameter save area are initialized even if the argument is available 6925 // in register. The caller is required to initialize both the register 6926 // and memory, however, the callee can choose to expect it in either. 6927 // The memloc is dismissed here because the argument is retrieved from 6928 // the register. 6929 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6930 continue; 6931 6932 auto HandleMemLoc = [&]() { 6933 const unsigned LocSize = LocVT.getStoreSize(); 6934 const unsigned ValSize = ValVT.getStoreSize(); 6935 assert((ValSize <= LocSize) && 6936 "Object size is larger than size of MemLoc"); 6937 int CurArgOffset = VA.getLocMemOffset(); 6938 // Objects are right-justified because AIX is big-endian. 6939 if (LocSize > ValSize) 6940 CurArgOffset += LocSize - ValSize; 6941 // Potential tail calls could cause overwriting of argument stack slots. 6942 const bool IsImmutable = 6943 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6944 (CallConv == CallingConv::Fast)); 6945 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6946 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6947 SDValue ArgValue = 6948 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6949 InVals.push_back(ArgValue); 6950 }; 6951 6952 // Vector arguments to VaArg functions are passed both on the stack, and 6953 // in any available GPRs. Load the value from the stack and add the GPRs 6954 // as live ins. 6955 if (VA.isMemLoc() && VA.needsCustom()) { 6956 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6957 assert(isVarArg && "Only use custom memloc for vararg."); 6958 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6959 // matching custom RegLocs. 6960 const unsigned OriginalValNo = VA.getValNo(); 6961 (void)OriginalValNo; 6962 6963 auto HandleCustomVecRegLoc = [&]() { 6964 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6965 "Missing custom RegLoc."); 6966 VA = ArgLocs[I++]; 6967 assert(VA.getValVT().isVector() && 6968 "Unexpected Val type for custom RegLoc."); 6969 assert(VA.getValNo() == OriginalValNo && 6970 "ValNo mismatch between custom MemLoc and RegLoc."); 6971 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6972 MF.addLiveIn(VA.getLocReg(), 6973 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 6974 Subtarget.hasVSX())); 6975 }; 6976 6977 HandleMemLoc(); 6978 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6979 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6980 // R10. 6981 HandleCustomVecRegLoc(); 6982 HandleCustomVecRegLoc(); 6983 6984 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 6985 // we passed the vector in R5, R6, R7 and R8. 6986 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 6987 assert(!IsPPC64 && 6988 "Only 2 custom RegLocs expected for 64-bit codegen."); 6989 HandleCustomVecRegLoc(); 6990 HandleCustomVecRegLoc(); 6991 } 6992 6993 continue; 6994 } 6995 6996 if (VA.isRegLoc()) { 6997 if (VA.getValVT().isScalarInteger()) 6998 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6999 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 7000 switch (VA.getValVT().SimpleTy) { 7001 default: 7002 report_fatal_error("Unhandled value type for argument."); 7003 case MVT::f32: 7004 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 7005 break; 7006 case MVT::f64: 7007 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 7008 break; 7009 } 7010 } else if (VA.getValVT().isVector()) { 7011 switch (VA.getValVT().SimpleTy) { 7012 default: 7013 report_fatal_error("Unhandled value type for argument."); 7014 case MVT::v16i8: 7015 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 7016 break; 7017 case MVT::v8i16: 7018 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 7019 break; 7020 case MVT::v4i32: 7021 case MVT::v2i64: 7022 case MVT::v1i128: 7023 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 7024 break; 7025 case MVT::v4f32: 7026 case MVT::v2f64: 7027 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 7028 break; 7029 } 7030 } 7031 } 7032 7033 if (Flags.isByVal() && VA.isMemLoc()) { 7034 const unsigned Size = 7035 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7036 PtrByteSize); 7037 const int FI = MF.getFrameInfo().CreateFixedObject( 7038 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7039 /* IsAliased */ true); 7040 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7041 InVals.push_back(FIN); 7042 7043 continue; 7044 } 7045 7046 if (Flags.isByVal()) { 7047 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7048 7049 const MCPhysReg ArgReg = VA.getLocReg(); 7050 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7051 7052 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7053 report_fatal_error("Over aligned byvals not supported yet."); 7054 7055 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7056 const int FI = MF.getFrameInfo().CreateFixedObject( 7057 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7058 /* IsAliased */ true); 7059 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7060 InVals.push_back(FIN); 7061 7062 // Add live ins for all the RegLocs for the same ByVal. 7063 const TargetRegisterClass *RegClass = 7064 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7065 7066 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7067 unsigned Offset) { 7068 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7069 // Since the callers side has left justified the aggregate in the 7070 // register, we can simply store the entire register into the stack 7071 // slot. 7072 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7073 // The store to the fixedstack object is needed becuase accessing a 7074 // field of the ByVal will use a gep and load. Ideally we will optimize 7075 // to extracting the value from the register directly, and elide the 7076 // stores when the arguments address is not taken, but that will need to 7077 // be future work. 7078 SDValue Store = DAG.getStore( 7079 CopyFrom.getValue(1), dl, CopyFrom, 7080 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7081 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7082 7083 MemOps.push_back(Store); 7084 }; 7085 7086 unsigned Offset = 0; 7087 HandleRegLoc(VA.getLocReg(), Offset); 7088 Offset += PtrByteSize; 7089 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7090 Offset += PtrByteSize) { 7091 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7092 "RegLocs should be for ByVal argument."); 7093 7094 const CCValAssign RL = ArgLocs[I++]; 7095 HandleRegLoc(RL.getLocReg(), Offset); 7096 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7097 } 7098 7099 if (Offset != StackSize) { 7100 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7101 "Expected MemLoc for remaining bytes."); 7102 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7103 // Consume the MemLoc.The InVal has already been emitted, so nothing 7104 // more needs to be done. 7105 ++I; 7106 } 7107 7108 continue; 7109 } 7110 7111 if (VA.isRegLoc() && !VA.needsCustom()) { 7112 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7113 Register VReg = 7114 MF.addLiveIn(VA.getLocReg(), 7115 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7116 Subtarget.hasVSX())); 7117 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7118 if (ValVT.isScalarInteger() && 7119 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7120 ArgValue = 7121 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7122 } 7123 InVals.push_back(ArgValue); 7124 continue; 7125 } 7126 if (VA.isMemLoc()) { 7127 HandleMemLoc(); 7128 continue; 7129 } 7130 } 7131 7132 // On AIX a minimum of 8 words is saved to the parameter save area. 7133 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7134 // Area that is at least reserved in the caller of this function. 7135 unsigned CallerReservedArea = 7136 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7137 7138 // Set the size that is at least reserved in caller of this function. Tail 7139 // call optimized function's reserved stack space needs to be aligned so 7140 // that taking the difference between two stack areas will result in an 7141 // aligned stack. 7142 CallerReservedArea = 7143 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7144 FuncInfo->setMinReservedArea(CallerReservedArea); 7145 7146 if (isVarArg) { 7147 FuncInfo->setVarArgsFrameIndex( 7148 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7149 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7150 7151 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7152 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7153 7154 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7155 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7156 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7157 7158 // The fixed integer arguments of a variadic function are stored to the 7159 // VarArgsFrameIndex on the stack so that they may be loaded by 7160 // dereferencing the result of va_next. 7161 for (unsigned GPRIndex = 7162 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7163 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7164 7165 const unsigned VReg = 7166 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7167 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7168 7169 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7170 SDValue Store = 7171 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7172 MemOps.push_back(Store); 7173 // Increment the address for the next argument to store. 7174 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7175 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7176 } 7177 } 7178 7179 if (!MemOps.empty()) 7180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7181 7182 return Chain; 7183 } 7184 7185 SDValue PPCTargetLowering::LowerCall_AIX( 7186 SDValue Chain, SDValue Callee, CallFlags CFlags, 7187 const SmallVectorImpl<ISD::OutputArg> &Outs, 7188 const SmallVectorImpl<SDValue> &OutVals, 7189 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7190 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7191 const CallBase *CB) const { 7192 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7193 // AIX ABI stack frame layout. 7194 7195 assert((CFlags.CallConv == CallingConv::C || 7196 CFlags.CallConv == CallingConv::Cold || 7197 CFlags.CallConv == CallingConv::Fast) && 7198 "Unexpected calling convention!"); 7199 7200 if (CFlags.IsPatchPoint) 7201 report_fatal_error("This call type is unimplemented on AIX."); 7202 7203 const PPCSubtarget& Subtarget = 7204 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7205 7206 MachineFunction &MF = DAG.getMachineFunction(); 7207 SmallVector<CCValAssign, 16> ArgLocs; 7208 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7209 *DAG.getContext()); 7210 7211 // Reserve space for the linkage save area (LSA) on the stack. 7212 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7213 // [SP][CR][LR][2 x reserved][TOC]. 7214 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7215 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7216 const bool IsPPC64 = Subtarget.isPPC64(); 7217 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7218 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7219 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7220 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7221 7222 // The prolog code of the callee may store up to 8 GPR argument registers to 7223 // the stack, allowing va_start to index over them in memory if the callee 7224 // is variadic. 7225 // Because we cannot tell if this is needed on the caller side, we have to 7226 // conservatively assume that it is needed. As such, make sure we have at 7227 // least enough stack space for the caller to store the 8 GPRs. 7228 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7229 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7230 CCInfo.getNextStackOffset()); 7231 7232 // Adjust the stack pointer for the new arguments... 7233 // These operations are automatically eliminated by the prolog/epilog pass. 7234 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7235 SDValue CallSeqStart = Chain; 7236 7237 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7238 SmallVector<SDValue, 8> MemOpChains; 7239 7240 // Set up a copy of the stack pointer for loading and storing any 7241 // arguments that may not fit in the registers available for argument 7242 // passing. 7243 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7244 : DAG.getRegister(PPC::R1, MVT::i32); 7245 7246 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7247 const unsigned ValNo = ArgLocs[I].getValNo(); 7248 SDValue Arg = OutVals[ValNo]; 7249 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7250 7251 if (Flags.isByVal()) { 7252 const unsigned ByValSize = Flags.getByValSize(); 7253 7254 // Nothing to do for zero-sized ByVals on the caller side. 7255 if (!ByValSize) { 7256 ++I; 7257 continue; 7258 } 7259 7260 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7261 return DAG.getExtLoad( 7262 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7263 (LoadOffset != 0) 7264 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7265 : Arg, 7266 MachinePointerInfo(), VT); 7267 }; 7268 7269 unsigned LoadOffset = 0; 7270 7271 // Initialize registers, which are fully occupied by the by-val argument. 7272 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7273 SDValue Load = GetLoad(PtrVT, LoadOffset); 7274 MemOpChains.push_back(Load.getValue(1)); 7275 LoadOffset += PtrByteSize; 7276 const CCValAssign &ByValVA = ArgLocs[I++]; 7277 assert(ByValVA.getValNo() == ValNo && 7278 "Unexpected location for pass-by-value argument."); 7279 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7280 } 7281 7282 if (LoadOffset == ByValSize) 7283 continue; 7284 7285 // There must be one more loc to handle the remainder. 7286 assert(ArgLocs[I].getValNo() == ValNo && 7287 "Expected additional location for by-value argument."); 7288 7289 if (ArgLocs[I].isMemLoc()) { 7290 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7291 const CCValAssign &ByValVA = ArgLocs[I++]; 7292 ISD::ArgFlagsTy MemcpyFlags = Flags; 7293 // Only memcpy the bytes that don't pass in register. 7294 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7295 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7296 (LoadOffset != 0) 7297 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7298 : Arg, 7299 DAG.getObjectPtrOffset(dl, StackPtr, 7300 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7301 CallSeqStart, MemcpyFlags, DAG, dl); 7302 continue; 7303 } 7304 7305 // Initialize the final register residue. 7306 // Any residue that occupies the final by-val arg register must be 7307 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7308 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7309 // 2 and 1 byte loads. 7310 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7311 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7312 "Unexpected register residue for by-value argument."); 7313 SDValue ResidueVal; 7314 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7315 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7316 const MVT VT = 7317 N == 1 ? MVT::i8 7318 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7319 SDValue Load = GetLoad(VT, LoadOffset); 7320 MemOpChains.push_back(Load.getValue(1)); 7321 LoadOffset += N; 7322 Bytes += N; 7323 7324 // By-val arguments are passed left-justfied in register. 7325 // Every load here needs to be shifted, otherwise a full register load 7326 // should have been used. 7327 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7328 "Unexpected load emitted during handling of pass-by-value " 7329 "argument."); 7330 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7331 EVT ShiftAmountTy = 7332 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7333 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7334 SDValue ShiftedLoad = 7335 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7336 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7337 ShiftedLoad) 7338 : ShiftedLoad; 7339 } 7340 7341 const CCValAssign &ByValVA = ArgLocs[I++]; 7342 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7343 continue; 7344 } 7345 7346 CCValAssign &VA = ArgLocs[I++]; 7347 const MVT LocVT = VA.getLocVT(); 7348 const MVT ValVT = VA.getValVT(); 7349 7350 switch (VA.getLocInfo()) { 7351 default: 7352 report_fatal_error("Unexpected argument extension type."); 7353 case CCValAssign::Full: 7354 break; 7355 case CCValAssign::ZExt: 7356 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7357 break; 7358 case CCValAssign::SExt: 7359 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7360 break; 7361 } 7362 7363 if (VA.isRegLoc() && !VA.needsCustom()) { 7364 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7365 continue; 7366 } 7367 7368 // Vector arguments passed to VarArg functions need custom handling when 7369 // they are passed (at least partially) in GPRs. 7370 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7371 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7372 // Store value to its stack slot. 7373 SDValue PtrOff = 7374 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7375 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7376 SDValue Store = 7377 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7378 MemOpChains.push_back(Store); 7379 const unsigned OriginalValNo = VA.getValNo(); 7380 // Then load the GPRs from the stack 7381 unsigned LoadOffset = 0; 7382 auto HandleCustomVecRegLoc = [&]() { 7383 assert(I != E && "Unexpected end of CCvalAssigns."); 7384 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7385 "Expected custom RegLoc."); 7386 CCValAssign RegVA = ArgLocs[I++]; 7387 assert(RegVA.getValNo() == OriginalValNo && 7388 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7389 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7390 DAG.getConstant(LoadOffset, dl, PtrVT)); 7391 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7392 MemOpChains.push_back(Load.getValue(1)); 7393 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7394 LoadOffset += PtrByteSize; 7395 }; 7396 7397 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7398 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7399 // R10. 7400 HandleCustomVecRegLoc(); 7401 HandleCustomVecRegLoc(); 7402 7403 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7404 ArgLocs[I].getValNo() == OriginalValNo) { 7405 assert(!IsPPC64 && 7406 "Only 2 custom RegLocs expected for 64-bit codegen."); 7407 HandleCustomVecRegLoc(); 7408 HandleCustomVecRegLoc(); 7409 } 7410 7411 continue; 7412 } 7413 7414 if (VA.isMemLoc()) { 7415 SDValue PtrOff = 7416 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7417 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7418 MemOpChains.push_back( 7419 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7420 7421 continue; 7422 } 7423 7424 if (!ValVT.isFloatingPoint()) 7425 report_fatal_error( 7426 "Unexpected register handling for calling convention."); 7427 7428 // Custom handling is used for GPR initializations for vararg float 7429 // arguments. 7430 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7431 LocVT.isInteger() && 7432 "Custom register handling only expected for VarArg."); 7433 7434 SDValue ArgAsInt = 7435 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7436 7437 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7438 // f32 in 32-bit GPR 7439 // f64 in 64-bit GPR 7440 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7441 else if (Arg.getValueType().getFixedSizeInBits() < 7442 LocVT.getFixedSizeInBits()) 7443 // f32 in 64-bit GPR. 7444 RegsToPass.push_back(std::make_pair( 7445 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7446 else { 7447 // f64 in two 32-bit GPRs 7448 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7449 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7450 "Unexpected custom register for argument!"); 7451 CCValAssign &GPR1 = VA; 7452 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7453 DAG.getConstant(32, dl, MVT::i8)); 7454 RegsToPass.push_back(std::make_pair( 7455 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7456 7457 if (I != E) { 7458 // If only 1 GPR was available, there will only be one custom GPR and 7459 // the argument will also pass in memory. 7460 CCValAssign &PeekArg = ArgLocs[I]; 7461 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7462 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7463 CCValAssign &GPR2 = ArgLocs[I++]; 7464 RegsToPass.push_back(std::make_pair( 7465 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7466 } 7467 } 7468 } 7469 } 7470 7471 if (!MemOpChains.empty()) 7472 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7473 7474 // For indirect calls, we need to save the TOC base to the stack for 7475 // restoration after the call. 7476 if (CFlags.IsIndirect) { 7477 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7478 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7479 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7480 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7481 const unsigned TOCSaveOffset = 7482 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7483 7484 setUsesTOCBasePtr(DAG); 7485 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7486 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7487 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7488 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7489 Chain = DAG.getStore( 7490 Val.getValue(1), dl, Val, AddPtr, 7491 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7492 } 7493 7494 // Build a sequence of copy-to-reg nodes chained together with token chain 7495 // and flag operands which copy the outgoing args into the appropriate regs. 7496 SDValue InFlag; 7497 for (auto Reg : RegsToPass) { 7498 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7499 InFlag = Chain.getValue(1); 7500 } 7501 7502 const int SPDiff = 0; 7503 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7504 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7505 } 7506 7507 bool 7508 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7509 MachineFunction &MF, bool isVarArg, 7510 const SmallVectorImpl<ISD::OutputArg> &Outs, 7511 LLVMContext &Context) const { 7512 SmallVector<CCValAssign, 16> RVLocs; 7513 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7514 return CCInfo.CheckReturn( 7515 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7516 ? RetCC_PPC_Cold 7517 : RetCC_PPC); 7518 } 7519 7520 SDValue 7521 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7522 bool isVarArg, 7523 const SmallVectorImpl<ISD::OutputArg> &Outs, 7524 const SmallVectorImpl<SDValue> &OutVals, 7525 const SDLoc &dl, SelectionDAG &DAG) const { 7526 SmallVector<CCValAssign, 16> RVLocs; 7527 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7528 *DAG.getContext()); 7529 CCInfo.AnalyzeReturn(Outs, 7530 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7531 ? RetCC_PPC_Cold 7532 : RetCC_PPC); 7533 7534 SDValue Flag; 7535 SmallVector<SDValue, 4> RetOps(1, Chain); 7536 7537 // Copy the result values into the output registers. 7538 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7539 CCValAssign &VA = RVLocs[i]; 7540 assert(VA.isRegLoc() && "Can only return in registers!"); 7541 7542 SDValue Arg = OutVals[RealResIdx]; 7543 7544 switch (VA.getLocInfo()) { 7545 default: llvm_unreachable("Unknown loc info!"); 7546 case CCValAssign::Full: break; 7547 case CCValAssign::AExt: 7548 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7549 break; 7550 case CCValAssign::ZExt: 7551 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7552 break; 7553 case CCValAssign::SExt: 7554 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7555 break; 7556 } 7557 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7558 bool isLittleEndian = Subtarget.isLittleEndian(); 7559 // Legalize ret f64 -> ret 2 x i32. 7560 SDValue SVal = 7561 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7562 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7563 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7564 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7565 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7566 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7567 Flag = Chain.getValue(1); 7568 VA = RVLocs[++i]; // skip ahead to next loc 7569 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7570 } else 7571 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7572 Flag = Chain.getValue(1); 7573 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7574 } 7575 7576 RetOps[0] = Chain; // Update chain. 7577 7578 // Add the flag if we have it. 7579 if (Flag.getNode()) 7580 RetOps.push_back(Flag); 7581 7582 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7583 } 7584 7585 SDValue 7586 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7587 SelectionDAG &DAG) const { 7588 SDLoc dl(Op); 7589 7590 // Get the correct type for integers. 7591 EVT IntVT = Op.getValueType(); 7592 7593 // Get the inputs. 7594 SDValue Chain = Op.getOperand(0); 7595 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7596 // Build a DYNAREAOFFSET node. 7597 SDValue Ops[2] = {Chain, FPSIdx}; 7598 SDVTList VTs = DAG.getVTList(IntVT); 7599 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7600 } 7601 7602 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7603 SelectionDAG &DAG) const { 7604 // When we pop the dynamic allocation we need to restore the SP link. 7605 SDLoc dl(Op); 7606 7607 // Get the correct type for pointers. 7608 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7609 7610 // Construct the stack pointer operand. 7611 bool isPPC64 = Subtarget.isPPC64(); 7612 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7613 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7614 7615 // Get the operands for the STACKRESTORE. 7616 SDValue Chain = Op.getOperand(0); 7617 SDValue SaveSP = Op.getOperand(1); 7618 7619 // Load the old link SP. 7620 SDValue LoadLinkSP = 7621 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7622 7623 // Restore the stack pointer. 7624 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7625 7626 // Store the old link SP. 7627 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7628 } 7629 7630 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7631 MachineFunction &MF = DAG.getMachineFunction(); 7632 bool isPPC64 = Subtarget.isPPC64(); 7633 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7634 7635 // Get current frame pointer save index. The users of this index will be 7636 // primarily DYNALLOC instructions. 7637 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7638 int RASI = FI->getReturnAddrSaveIndex(); 7639 7640 // If the frame pointer save index hasn't been defined yet. 7641 if (!RASI) { 7642 // Find out what the fix offset of the frame pointer save area. 7643 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7644 // Allocate the frame index for frame pointer save area. 7645 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7646 // Save the result. 7647 FI->setReturnAddrSaveIndex(RASI); 7648 } 7649 return DAG.getFrameIndex(RASI, PtrVT); 7650 } 7651 7652 SDValue 7653 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7654 MachineFunction &MF = DAG.getMachineFunction(); 7655 bool isPPC64 = Subtarget.isPPC64(); 7656 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7657 7658 // Get current frame pointer save index. The users of this index will be 7659 // primarily DYNALLOC instructions. 7660 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7661 int FPSI = FI->getFramePointerSaveIndex(); 7662 7663 // If the frame pointer save index hasn't been defined yet. 7664 if (!FPSI) { 7665 // Find out what the fix offset of the frame pointer save area. 7666 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7667 // Allocate the frame index for frame pointer save area. 7668 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7669 // Save the result. 7670 FI->setFramePointerSaveIndex(FPSI); 7671 } 7672 return DAG.getFrameIndex(FPSI, PtrVT); 7673 } 7674 7675 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7676 SelectionDAG &DAG) const { 7677 MachineFunction &MF = DAG.getMachineFunction(); 7678 // Get the inputs. 7679 SDValue Chain = Op.getOperand(0); 7680 SDValue Size = Op.getOperand(1); 7681 SDLoc dl(Op); 7682 7683 // Get the correct type for pointers. 7684 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7685 // Negate the size. 7686 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7687 DAG.getConstant(0, dl, PtrVT), Size); 7688 // Construct a node for the frame pointer save index. 7689 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7690 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7691 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7692 if (hasInlineStackProbe(MF)) 7693 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7694 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7695 } 7696 7697 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7698 SelectionDAG &DAG) const { 7699 MachineFunction &MF = DAG.getMachineFunction(); 7700 7701 bool isPPC64 = Subtarget.isPPC64(); 7702 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7703 7704 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7705 return DAG.getFrameIndex(FI, PtrVT); 7706 } 7707 7708 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7709 SelectionDAG &DAG) const { 7710 SDLoc DL(Op); 7711 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7712 DAG.getVTList(MVT::i32, MVT::Other), 7713 Op.getOperand(0), Op.getOperand(1)); 7714 } 7715 7716 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7717 SelectionDAG &DAG) const { 7718 SDLoc DL(Op); 7719 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7720 Op.getOperand(0), Op.getOperand(1)); 7721 } 7722 7723 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7724 if (Op.getValueType().isVector()) 7725 return LowerVectorLoad(Op, DAG); 7726 7727 assert(Op.getValueType() == MVT::i1 && 7728 "Custom lowering only for i1 loads"); 7729 7730 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7731 7732 SDLoc dl(Op); 7733 LoadSDNode *LD = cast<LoadSDNode>(Op); 7734 7735 SDValue Chain = LD->getChain(); 7736 SDValue BasePtr = LD->getBasePtr(); 7737 MachineMemOperand *MMO = LD->getMemOperand(); 7738 7739 SDValue NewLD = 7740 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7741 BasePtr, MVT::i8, MMO); 7742 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7743 7744 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7745 return DAG.getMergeValues(Ops, dl); 7746 } 7747 7748 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7749 if (Op.getOperand(1).getValueType().isVector()) 7750 return LowerVectorStore(Op, DAG); 7751 7752 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7753 "Custom lowering only for i1 stores"); 7754 7755 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7756 7757 SDLoc dl(Op); 7758 StoreSDNode *ST = cast<StoreSDNode>(Op); 7759 7760 SDValue Chain = ST->getChain(); 7761 SDValue BasePtr = ST->getBasePtr(); 7762 SDValue Value = ST->getValue(); 7763 MachineMemOperand *MMO = ST->getMemOperand(); 7764 7765 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7766 Value); 7767 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7768 } 7769 7770 // FIXME: Remove this once the ANDI glue bug is fixed: 7771 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7772 assert(Op.getValueType() == MVT::i1 && 7773 "Custom lowering only for i1 results"); 7774 7775 SDLoc DL(Op); 7776 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7777 } 7778 7779 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7780 SelectionDAG &DAG) const { 7781 7782 // Implements a vector truncate that fits in a vector register as a shuffle. 7783 // We want to legalize vector truncates down to where the source fits in 7784 // a vector register (and target is therefore smaller than vector register 7785 // size). At that point legalization will try to custom lower the sub-legal 7786 // result and get here - where we can contain the truncate as a single target 7787 // operation. 7788 7789 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7790 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7791 // 7792 // We will implement it for big-endian ordering as this (where x denotes 7793 // undefined): 7794 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7795 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7796 // 7797 // The same operation in little-endian ordering will be: 7798 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7799 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7800 7801 EVT TrgVT = Op.getValueType(); 7802 assert(TrgVT.isVector() && "Vector type expected."); 7803 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7804 EVT EltVT = TrgVT.getVectorElementType(); 7805 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7806 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7807 !isPowerOf2_32(EltVT.getSizeInBits())) 7808 return SDValue(); 7809 7810 SDValue N1 = Op.getOperand(0); 7811 EVT SrcVT = N1.getValueType(); 7812 unsigned SrcSize = SrcVT.getSizeInBits(); 7813 if (SrcSize > 256 || 7814 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7815 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7816 return SDValue(); 7817 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7818 return SDValue(); 7819 7820 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7821 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7822 7823 SDLoc DL(Op); 7824 SDValue Op1, Op2; 7825 if (SrcSize == 256) { 7826 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7827 EVT SplitVT = 7828 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7829 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7830 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7831 DAG.getConstant(0, DL, VecIdxTy)); 7832 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7833 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7834 } 7835 else { 7836 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7837 Op2 = DAG.getUNDEF(WideVT); 7838 } 7839 7840 // First list the elements we want to keep. 7841 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7842 SmallVector<int, 16> ShuffV; 7843 if (Subtarget.isLittleEndian()) 7844 for (unsigned i = 0; i < TrgNumElts; ++i) 7845 ShuffV.push_back(i * SizeMult); 7846 else 7847 for (unsigned i = 1; i <= TrgNumElts; ++i) 7848 ShuffV.push_back(i * SizeMult - 1); 7849 7850 // Populate the remaining elements with undefs. 7851 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7852 // ShuffV.push_back(i + WideNumElts); 7853 ShuffV.push_back(WideNumElts + 1); 7854 7855 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7856 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7857 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7858 } 7859 7860 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7861 /// possible. 7862 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7863 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7864 EVT ResVT = Op.getValueType(); 7865 EVT CmpVT = Op.getOperand(0).getValueType(); 7866 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7867 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7868 SDLoc dl(Op); 7869 7870 // Without power9-vector, we don't have native instruction for f128 comparison. 7871 // Following transformation to libcall is needed for setcc: 7872 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7873 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7874 SDValue Z = DAG.getSetCC( 7875 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7876 LHS, RHS, CC); 7877 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7878 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7879 } 7880 7881 // Not FP, or using SPE? Not a fsel. 7882 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7883 Subtarget.hasSPE()) 7884 return Op; 7885 7886 SDNodeFlags Flags = Op.getNode()->getFlags(); 7887 7888 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7889 // presence of infinities. 7890 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7891 switch (CC) { 7892 default: 7893 break; 7894 case ISD::SETOGT: 7895 case ISD::SETGT: 7896 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7897 case ISD::SETOLT: 7898 case ISD::SETLT: 7899 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7900 } 7901 } 7902 7903 // We might be able to do better than this under some circumstances, but in 7904 // general, fsel-based lowering of select is a finite-math-only optimization. 7905 // For more information, see section F.3 of the 2.06 ISA specification. 7906 // With ISA 3.0 7907 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7908 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7909 return Op; 7910 7911 // If the RHS of the comparison is a 0.0, we don't need to do the 7912 // subtraction at all. 7913 SDValue Sel1; 7914 if (isFloatingPointZero(RHS)) 7915 switch (CC) { 7916 default: break; // SETUO etc aren't handled by fsel. 7917 case ISD::SETNE: 7918 std::swap(TV, FV); 7919 LLVM_FALLTHROUGH; 7920 case ISD::SETEQ: 7921 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7922 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7923 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7924 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7925 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7926 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7927 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7928 case ISD::SETULT: 7929 case ISD::SETLT: 7930 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7931 LLVM_FALLTHROUGH; 7932 case ISD::SETOGE: 7933 case ISD::SETGE: 7934 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7935 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7936 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7937 case ISD::SETUGT: 7938 case ISD::SETGT: 7939 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7940 LLVM_FALLTHROUGH; 7941 case ISD::SETOLE: 7942 case ISD::SETLE: 7943 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7944 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7945 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7946 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7947 } 7948 7949 SDValue Cmp; 7950 switch (CC) { 7951 default: break; // SETUO etc aren't handled by fsel. 7952 case ISD::SETNE: 7953 std::swap(TV, FV); 7954 LLVM_FALLTHROUGH; 7955 case ISD::SETEQ: 7956 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7957 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7958 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7959 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7960 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7961 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7962 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7963 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7964 case ISD::SETULT: 7965 case ISD::SETLT: 7966 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7967 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7968 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7969 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7970 case ISD::SETOGE: 7971 case ISD::SETGE: 7972 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7973 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7974 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7975 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7976 case ISD::SETUGT: 7977 case ISD::SETGT: 7978 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7979 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7980 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7981 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7982 case ISD::SETOLE: 7983 case ISD::SETLE: 7984 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7985 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7986 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7987 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7988 } 7989 return Op; 7990 } 7991 7992 static unsigned getPPCStrictOpcode(unsigned Opc) { 7993 switch (Opc) { 7994 default: 7995 llvm_unreachable("No strict version of this opcode!"); 7996 case PPCISD::FCTIDZ: 7997 return PPCISD::STRICT_FCTIDZ; 7998 case PPCISD::FCTIWZ: 7999 return PPCISD::STRICT_FCTIWZ; 8000 case PPCISD::FCTIDUZ: 8001 return PPCISD::STRICT_FCTIDUZ; 8002 case PPCISD::FCTIWUZ: 8003 return PPCISD::STRICT_FCTIWUZ; 8004 case PPCISD::FCFID: 8005 return PPCISD::STRICT_FCFID; 8006 case PPCISD::FCFIDU: 8007 return PPCISD::STRICT_FCFIDU; 8008 case PPCISD::FCFIDS: 8009 return PPCISD::STRICT_FCFIDS; 8010 case PPCISD::FCFIDUS: 8011 return PPCISD::STRICT_FCFIDUS; 8012 } 8013 } 8014 8015 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8016 const PPCSubtarget &Subtarget) { 8017 SDLoc dl(Op); 8018 bool IsStrict = Op->isStrictFPOpcode(); 8019 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8020 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8021 8022 // TODO: Any other flags to propagate? 8023 SDNodeFlags Flags; 8024 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8025 8026 // For strict nodes, source is the second operand. 8027 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8028 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8029 assert(Src.getValueType().isFloatingPoint()); 8030 if (Src.getValueType() == MVT::f32) { 8031 if (IsStrict) { 8032 Src = 8033 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8034 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8035 Chain = Src.getValue(1); 8036 } else 8037 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8038 } 8039 SDValue Conv; 8040 unsigned Opc = ISD::DELETED_NODE; 8041 switch (Op.getSimpleValueType().SimpleTy) { 8042 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8043 case MVT::i32: 8044 Opc = IsSigned ? PPCISD::FCTIWZ 8045 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8046 break; 8047 case MVT::i64: 8048 assert((IsSigned || Subtarget.hasFPCVT()) && 8049 "i64 FP_TO_UINT is supported only with FPCVT"); 8050 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8051 } 8052 if (IsStrict) { 8053 Opc = getPPCStrictOpcode(Opc); 8054 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8055 {Chain, Src}, Flags); 8056 } else { 8057 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8058 } 8059 return Conv; 8060 } 8061 8062 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8063 SelectionDAG &DAG, 8064 const SDLoc &dl) const { 8065 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8066 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8067 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8068 bool IsStrict = Op->isStrictFPOpcode(); 8069 8070 // Convert the FP value to an int value through memory. 8071 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8072 (IsSigned || Subtarget.hasFPCVT()); 8073 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8074 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8075 MachinePointerInfo MPI = 8076 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8077 8078 // Emit a store to the stack slot. 8079 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8080 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8081 if (i32Stack) { 8082 MachineFunction &MF = DAG.getMachineFunction(); 8083 Alignment = Align(4); 8084 MachineMemOperand *MMO = 8085 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8086 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8087 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8088 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8089 } else 8090 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8091 8092 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8093 // add in a bias on big endian. 8094 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8095 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8096 DAG.getConstant(4, dl, FIPtr.getValueType())); 8097 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8098 } 8099 8100 RLI.Chain = Chain; 8101 RLI.Ptr = FIPtr; 8102 RLI.MPI = MPI; 8103 RLI.Alignment = Alignment; 8104 } 8105 8106 /// Custom lowers floating point to integer conversions to use 8107 /// the direct move instructions available in ISA 2.07 to avoid the 8108 /// need for load/store combinations. 8109 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8110 SelectionDAG &DAG, 8111 const SDLoc &dl) const { 8112 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8113 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8114 if (Op->isStrictFPOpcode()) 8115 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8116 else 8117 return Mov; 8118 } 8119 8120 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8121 const SDLoc &dl) const { 8122 bool IsStrict = Op->isStrictFPOpcode(); 8123 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8124 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8125 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8126 EVT SrcVT = Src.getValueType(); 8127 EVT DstVT = Op.getValueType(); 8128 8129 // FP to INT conversions are legal for f128. 8130 if (SrcVT == MVT::f128) 8131 return Subtarget.hasP9Vector() ? Op : SDValue(); 8132 8133 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8134 // PPC (the libcall is not available). 8135 if (SrcVT == MVT::ppcf128) { 8136 if (DstVT == MVT::i32) { 8137 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8138 // set other fast-math flags to FP operations in both strict and 8139 // non-strict cases. (FP_TO_SINT, FSUB) 8140 SDNodeFlags Flags; 8141 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8142 8143 if (IsSigned) { 8144 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8145 DAG.getIntPtrConstant(0, dl)); 8146 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8147 DAG.getIntPtrConstant(1, dl)); 8148 8149 // Add the two halves of the long double in round-to-zero mode, and use 8150 // a smaller FP_TO_SINT. 8151 if (IsStrict) { 8152 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8153 DAG.getVTList(MVT::f64, MVT::Other), 8154 {Op.getOperand(0), Lo, Hi}, Flags); 8155 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8156 DAG.getVTList(MVT::i32, MVT::Other), 8157 {Res.getValue(1), Res}, Flags); 8158 } else { 8159 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8160 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8161 } 8162 } else { 8163 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8164 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8165 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8166 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8167 if (IsStrict) { 8168 // Sel = Src < 0x80000000 8169 // FltOfs = select Sel, 0.0, 0x80000000 8170 // IntOfs = select Sel, 0, 0x80000000 8171 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8172 SDValue Chain = Op.getOperand(0); 8173 EVT SetCCVT = 8174 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8175 EVT DstSetCCVT = 8176 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8177 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8178 Chain, true); 8179 Chain = Sel.getValue(1); 8180 8181 SDValue FltOfs = DAG.getSelect( 8182 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8183 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8184 8185 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8186 DAG.getVTList(SrcVT, MVT::Other), 8187 {Chain, Src, FltOfs}, Flags); 8188 Chain = Val.getValue(1); 8189 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8190 DAG.getVTList(DstVT, MVT::Other), 8191 {Chain, Val}, Flags); 8192 Chain = SInt.getValue(1); 8193 SDValue IntOfs = DAG.getSelect( 8194 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8195 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8196 return DAG.getMergeValues({Result, Chain}, dl); 8197 } else { 8198 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8199 // FIXME: generated code sucks. 8200 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8201 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8202 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8203 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8204 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8205 } 8206 } 8207 } 8208 8209 return SDValue(); 8210 } 8211 8212 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8213 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8214 8215 ReuseLoadInfo RLI; 8216 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8217 8218 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8219 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8220 } 8221 8222 // We're trying to insert a regular store, S, and then a load, L. If the 8223 // incoming value, O, is a load, we might just be able to have our load use the 8224 // address used by O. However, we don't know if anything else will store to 8225 // that address before we can load from it. To prevent this situation, we need 8226 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8227 // the same chain operand as O, we create a token factor from the chain results 8228 // of O and L, and we replace all uses of O's chain result with that token 8229 // factor (see spliceIntoChain below for this last part). 8230 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8231 ReuseLoadInfo &RLI, 8232 SelectionDAG &DAG, 8233 ISD::LoadExtType ET) const { 8234 // Conservatively skip reusing for constrained FP nodes. 8235 if (Op->isStrictFPOpcode()) 8236 return false; 8237 8238 SDLoc dl(Op); 8239 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8240 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8241 if (ET == ISD::NON_EXTLOAD && 8242 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8243 isOperationLegalOrCustom(Op.getOpcode(), 8244 Op.getOperand(0).getValueType())) { 8245 8246 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8247 return true; 8248 } 8249 8250 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8251 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8252 LD->isNonTemporal()) 8253 return false; 8254 if (LD->getMemoryVT() != MemVT) 8255 return false; 8256 8257 // If the result of the load is an illegal type, then we can't build a 8258 // valid chain for reuse since the legalised loads and token factor node that 8259 // ties the legalised loads together uses a different output chain then the 8260 // illegal load. 8261 if (!isTypeLegal(LD->getValueType(0))) 8262 return false; 8263 8264 RLI.Ptr = LD->getBasePtr(); 8265 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8266 assert(LD->getAddressingMode() == ISD::PRE_INC && 8267 "Non-pre-inc AM on PPC?"); 8268 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8269 LD->getOffset()); 8270 } 8271 8272 RLI.Chain = LD->getChain(); 8273 RLI.MPI = LD->getPointerInfo(); 8274 RLI.IsDereferenceable = LD->isDereferenceable(); 8275 RLI.IsInvariant = LD->isInvariant(); 8276 RLI.Alignment = LD->getAlign(); 8277 RLI.AAInfo = LD->getAAInfo(); 8278 RLI.Ranges = LD->getRanges(); 8279 8280 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8281 return true; 8282 } 8283 8284 // Given the head of the old chain, ResChain, insert a token factor containing 8285 // it and NewResChain, and make users of ResChain now be users of that token 8286 // factor. 8287 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8288 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8289 SDValue NewResChain, 8290 SelectionDAG &DAG) const { 8291 if (!ResChain) 8292 return; 8293 8294 SDLoc dl(NewResChain); 8295 8296 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8297 NewResChain, DAG.getUNDEF(MVT::Other)); 8298 assert(TF.getNode() != NewResChain.getNode() && 8299 "A new TF really is required here"); 8300 8301 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8302 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8303 } 8304 8305 /// Analyze profitability of direct move 8306 /// prefer float load to int load plus direct move 8307 /// when there is no integer use of int load 8308 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8309 SDNode *Origin = Op.getOperand(0).getNode(); 8310 if (Origin->getOpcode() != ISD::LOAD) 8311 return true; 8312 8313 // If there is no LXSIBZX/LXSIHZX, like Power8, 8314 // prefer direct move if the memory size is 1 or 2 bytes. 8315 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8316 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8317 return true; 8318 8319 for (SDNode::use_iterator UI = Origin->use_begin(), 8320 UE = Origin->use_end(); 8321 UI != UE; ++UI) { 8322 8323 // Only look at the users of the loaded value. 8324 if (UI.getUse().get().getResNo() != 0) 8325 continue; 8326 8327 if (UI->getOpcode() != ISD::SINT_TO_FP && 8328 UI->getOpcode() != ISD::UINT_TO_FP && 8329 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8330 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8331 return true; 8332 } 8333 8334 return false; 8335 } 8336 8337 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8338 const PPCSubtarget &Subtarget, 8339 SDValue Chain = SDValue()) { 8340 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8341 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8342 SDLoc dl(Op); 8343 8344 // TODO: Any other flags to propagate? 8345 SDNodeFlags Flags; 8346 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8347 8348 // If we have FCFIDS, then use it when converting to single-precision. 8349 // Otherwise, convert to double-precision and then round. 8350 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8351 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8352 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8353 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8354 if (Op->isStrictFPOpcode()) { 8355 if (!Chain) 8356 Chain = Op.getOperand(0); 8357 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8358 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8359 } else 8360 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8361 } 8362 8363 /// Custom lowers integer to floating point conversions to use 8364 /// the direct move instructions available in ISA 2.07 to avoid the 8365 /// need for load/store combinations. 8366 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8367 SelectionDAG &DAG, 8368 const SDLoc &dl) const { 8369 assert((Op.getValueType() == MVT::f32 || 8370 Op.getValueType() == MVT::f64) && 8371 "Invalid floating point type as target of conversion"); 8372 assert(Subtarget.hasFPCVT() && 8373 "Int to FP conversions with direct moves require FPCVT"); 8374 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8375 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8376 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8377 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8378 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8379 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8380 return convertIntToFP(Op, Mov, DAG, Subtarget); 8381 } 8382 8383 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8384 8385 EVT VecVT = Vec.getValueType(); 8386 assert(VecVT.isVector() && "Expected a vector type."); 8387 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8388 8389 EVT EltVT = VecVT.getVectorElementType(); 8390 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8391 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8392 8393 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8394 SmallVector<SDValue, 16> Ops(NumConcat); 8395 Ops[0] = Vec; 8396 SDValue UndefVec = DAG.getUNDEF(VecVT); 8397 for (unsigned i = 1; i < NumConcat; ++i) 8398 Ops[i] = UndefVec; 8399 8400 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8401 } 8402 8403 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8404 const SDLoc &dl) const { 8405 bool IsStrict = Op->isStrictFPOpcode(); 8406 unsigned Opc = Op.getOpcode(); 8407 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8408 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8409 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8410 "Unexpected conversion type"); 8411 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8412 "Supports conversions to v2f64/v4f32 only."); 8413 8414 // TODO: Any other flags to propagate? 8415 SDNodeFlags Flags; 8416 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8417 8418 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8419 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8420 8421 SDValue Wide = widenVec(DAG, Src, dl); 8422 EVT WideVT = Wide.getValueType(); 8423 unsigned WideNumElts = WideVT.getVectorNumElements(); 8424 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8425 8426 SmallVector<int, 16> ShuffV; 8427 for (unsigned i = 0; i < WideNumElts; ++i) 8428 ShuffV.push_back(i + WideNumElts); 8429 8430 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8431 int SaveElts = FourEltRes ? 4 : 2; 8432 if (Subtarget.isLittleEndian()) 8433 for (int i = 0; i < SaveElts; i++) 8434 ShuffV[i * Stride] = i; 8435 else 8436 for (int i = 1; i <= SaveElts; i++) 8437 ShuffV[i * Stride - 1] = i - 1; 8438 8439 SDValue ShuffleSrc2 = 8440 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8441 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8442 8443 SDValue Extend; 8444 if (SignedConv) { 8445 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8446 EVT ExtVT = Src.getValueType(); 8447 if (Subtarget.hasP9Altivec()) 8448 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8449 IntermediateVT.getVectorNumElements()); 8450 8451 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8452 DAG.getValueType(ExtVT)); 8453 } else 8454 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8455 8456 if (IsStrict) 8457 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8458 {Op.getOperand(0), Extend}, Flags); 8459 8460 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8461 } 8462 8463 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8464 SelectionDAG &DAG) const { 8465 SDLoc dl(Op); 8466 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8467 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8468 bool IsStrict = Op->isStrictFPOpcode(); 8469 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8470 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8471 8472 // TODO: Any other flags to propagate? 8473 SDNodeFlags Flags; 8474 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8475 8476 EVT InVT = Src.getValueType(); 8477 EVT OutVT = Op.getValueType(); 8478 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8479 isOperationCustom(Op.getOpcode(), InVT)) 8480 return LowerINT_TO_FPVector(Op, DAG, dl); 8481 8482 // Conversions to f128 are legal. 8483 if (Op.getValueType() == MVT::f128) 8484 return Subtarget.hasP9Vector() ? Op : SDValue(); 8485 8486 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8487 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8488 return SDValue(); 8489 8490 if (Src.getValueType() == MVT::i1) { 8491 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8492 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8493 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8494 if (IsStrict) 8495 return DAG.getMergeValues({Sel, Chain}, dl); 8496 else 8497 return Sel; 8498 } 8499 8500 // If we have direct moves, we can do all the conversion, skip the store/load 8501 // however, without FPCVT we can't do most conversions. 8502 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8503 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8504 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8505 8506 assert((IsSigned || Subtarget.hasFPCVT()) && 8507 "UINT_TO_FP is supported only with FPCVT"); 8508 8509 if (Src.getValueType() == MVT::i64) { 8510 SDValue SINT = Src; 8511 // When converting to single-precision, we actually need to convert 8512 // to double-precision first and then round to single-precision. 8513 // To avoid double-rounding effects during that operation, we have 8514 // to prepare the input operand. Bits that might be truncated when 8515 // converting to double-precision are replaced by a bit that won't 8516 // be lost at this stage, but is below the single-precision rounding 8517 // position. 8518 // 8519 // However, if -enable-unsafe-fp-math is in effect, accept double 8520 // rounding to avoid the extra overhead. 8521 if (Op.getValueType() == MVT::f32 && 8522 !Subtarget.hasFPCVT() && 8523 !DAG.getTarget().Options.UnsafeFPMath) { 8524 8525 // Twiddle input to make sure the low 11 bits are zero. (If this 8526 // is the case, we are guaranteed the value will fit into the 53 bit 8527 // mantissa of an IEEE double-precision value without rounding.) 8528 // If any of those low 11 bits were not zero originally, make sure 8529 // bit 12 (value 2048) is set instead, so that the final rounding 8530 // to single-precision gets the correct result. 8531 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8532 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8533 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8534 Round, DAG.getConstant(2047, dl, MVT::i64)); 8535 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8536 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8537 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8538 8539 // However, we cannot use that value unconditionally: if the magnitude 8540 // of the input value is small, the bit-twiddling we did above might 8541 // end up visibly changing the output. Fortunately, in that case, we 8542 // don't need to twiddle bits since the original input will convert 8543 // exactly to double-precision floating-point already. Therefore, 8544 // construct a conditional to use the original value if the top 11 8545 // bits are all sign-bit copies, and use the rounded value computed 8546 // above otherwise. 8547 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8548 SINT, DAG.getConstant(53, dl, MVT::i32)); 8549 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8550 Cond, DAG.getConstant(1, dl, MVT::i64)); 8551 Cond = DAG.getSetCC( 8552 dl, 8553 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8554 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8555 8556 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8557 } 8558 8559 ReuseLoadInfo RLI; 8560 SDValue Bits; 8561 8562 MachineFunction &MF = DAG.getMachineFunction(); 8563 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8564 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8565 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8566 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8567 } else if (Subtarget.hasLFIWAX() && 8568 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8569 MachineMemOperand *MMO = 8570 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8571 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8572 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8573 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8574 DAG.getVTList(MVT::f64, MVT::Other), 8575 Ops, MVT::i32, MMO); 8576 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8577 } else if (Subtarget.hasFPCVT() && 8578 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8579 MachineMemOperand *MMO = 8580 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8581 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8582 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8583 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8584 DAG.getVTList(MVT::f64, MVT::Other), 8585 Ops, MVT::i32, MMO); 8586 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8587 } else if (((Subtarget.hasLFIWAX() && 8588 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8589 (Subtarget.hasFPCVT() && 8590 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8591 SINT.getOperand(0).getValueType() == MVT::i32) { 8592 MachineFrameInfo &MFI = MF.getFrameInfo(); 8593 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8594 8595 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8596 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8597 8598 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8599 MachinePointerInfo::getFixedStack( 8600 DAG.getMachineFunction(), FrameIdx)); 8601 Chain = Store; 8602 8603 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8604 "Expected an i32 store"); 8605 8606 RLI.Ptr = FIdx; 8607 RLI.Chain = Chain; 8608 RLI.MPI = 8609 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8610 RLI.Alignment = Align(4); 8611 8612 MachineMemOperand *MMO = 8613 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8614 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8615 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8616 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8617 PPCISD::LFIWZX : PPCISD::LFIWAX, 8618 dl, DAG.getVTList(MVT::f64, MVT::Other), 8619 Ops, MVT::i32, MMO); 8620 Chain = Bits.getValue(1); 8621 } else 8622 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8623 8624 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8625 if (IsStrict) 8626 Chain = FP.getValue(1); 8627 8628 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8629 if (IsStrict) 8630 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8631 DAG.getVTList(MVT::f32, MVT::Other), 8632 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8633 else 8634 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8635 DAG.getIntPtrConstant(0, dl)); 8636 } 8637 return FP; 8638 } 8639 8640 assert(Src.getValueType() == MVT::i32 && 8641 "Unhandled INT_TO_FP type in custom expander!"); 8642 // Since we only generate this in 64-bit mode, we can take advantage of 8643 // 64-bit registers. In particular, sign extend the input value into the 8644 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8645 // then lfd it and fcfid it. 8646 MachineFunction &MF = DAG.getMachineFunction(); 8647 MachineFrameInfo &MFI = MF.getFrameInfo(); 8648 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8649 8650 SDValue Ld; 8651 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8652 ReuseLoadInfo RLI; 8653 bool ReusingLoad; 8654 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8655 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8656 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8657 8658 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8659 MachinePointerInfo::getFixedStack( 8660 DAG.getMachineFunction(), FrameIdx)); 8661 Chain = Store; 8662 8663 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8664 "Expected an i32 store"); 8665 8666 RLI.Ptr = FIdx; 8667 RLI.Chain = Chain; 8668 RLI.MPI = 8669 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8670 RLI.Alignment = Align(4); 8671 } 8672 8673 MachineMemOperand *MMO = 8674 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8675 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8676 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8677 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8678 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8679 MVT::i32, MMO); 8680 Chain = Ld.getValue(1); 8681 if (ReusingLoad) 8682 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8683 } else { 8684 assert(Subtarget.isPPC64() && 8685 "i32->FP without LFIWAX supported only on PPC64"); 8686 8687 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8688 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8689 8690 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8691 8692 // STD the extended value into the stack slot. 8693 SDValue Store = DAG.getStore( 8694 Chain, dl, Ext64, FIdx, 8695 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8696 Chain = Store; 8697 8698 // Load the value as a double. 8699 Ld = DAG.getLoad( 8700 MVT::f64, dl, Chain, FIdx, 8701 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8702 Chain = Ld.getValue(1); 8703 } 8704 8705 // FCFID it and return it. 8706 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8707 if (IsStrict) 8708 Chain = FP.getValue(1); 8709 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8710 if (IsStrict) 8711 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8712 DAG.getVTList(MVT::f32, MVT::Other), 8713 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8714 else 8715 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8716 DAG.getIntPtrConstant(0, dl)); 8717 } 8718 return FP; 8719 } 8720 8721 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8722 SelectionDAG &DAG) const { 8723 SDLoc dl(Op); 8724 /* 8725 The rounding mode is in bits 30:31 of FPSR, and has the following 8726 settings: 8727 00 Round to nearest 8728 01 Round to 0 8729 10 Round to +inf 8730 11 Round to -inf 8731 8732 FLT_ROUNDS, on the other hand, expects the following: 8733 -1 Undefined 8734 0 Round to 0 8735 1 Round to nearest 8736 2 Round to +inf 8737 3 Round to -inf 8738 8739 To perform the conversion, we do: 8740 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8741 */ 8742 8743 MachineFunction &MF = DAG.getMachineFunction(); 8744 EVT VT = Op.getValueType(); 8745 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8746 8747 // Save FP Control Word to register 8748 SDValue Chain = Op.getOperand(0); 8749 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8750 Chain = MFFS.getValue(1); 8751 8752 SDValue CWD; 8753 if (isTypeLegal(MVT::i64)) { 8754 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8755 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8756 } else { 8757 // Save FP register to stack slot 8758 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8759 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8760 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8761 8762 // Load FP Control Word from low 32 bits of stack slot. 8763 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8764 "Stack slot adjustment is valid only on big endian subtargets!"); 8765 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8766 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8767 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8768 Chain = CWD.getValue(1); 8769 } 8770 8771 // Transform as necessary 8772 SDValue CWD1 = 8773 DAG.getNode(ISD::AND, dl, MVT::i32, 8774 CWD, DAG.getConstant(3, dl, MVT::i32)); 8775 SDValue CWD2 = 8776 DAG.getNode(ISD::SRL, dl, MVT::i32, 8777 DAG.getNode(ISD::AND, dl, MVT::i32, 8778 DAG.getNode(ISD::XOR, dl, MVT::i32, 8779 CWD, DAG.getConstant(3, dl, MVT::i32)), 8780 DAG.getConstant(3, dl, MVT::i32)), 8781 DAG.getConstant(1, dl, MVT::i32)); 8782 8783 SDValue RetVal = 8784 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8785 8786 RetVal = 8787 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8788 dl, VT, RetVal); 8789 8790 return DAG.getMergeValues({RetVal, Chain}, dl); 8791 } 8792 8793 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8794 EVT VT = Op.getValueType(); 8795 unsigned BitWidth = VT.getSizeInBits(); 8796 SDLoc dl(Op); 8797 assert(Op.getNumOperands() == 3 && 8798 VT == Op.getOperand(1).getValueType() && 8799 "Unexpected SHL!"); 8800 8801 // Expand into a bunch of logical ops. Note that these ops 8802 // depend on the PPC behavior for oversized shift amounts. 8803 SDValue Lo = Op.getOperand(0); 8804 SDValue Hi = Op.getOperand(1); 8805 SDValue Amt = Op.getOperand(2); 8806 EVT AmtVT = Amt.getValueType(); 8807 8808 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8809 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8810 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8811 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8812 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8813 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8814 DAG.getConstant(-BitWidth, dl, AmtVT)); 8815 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8816 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8817 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8818 SDValue OutOps[] = { OutLo, OutHi }; 8819 return DAG.getMergeValues(OutOps, dl); 8820 } 8821 8822 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8823 EVT VT = Op.getValueType(); 8824 SDLoc dl(Op); 8825 unsigned BitWidth = VT.getSizeInBits(); 8826 assert(Op.getNumOperands() == 3 && 8827 VT == Op.getOperand(1).getValueType() && 8828 "Unexpected SRL!"); 8829 8830 // Expand into a bunch of logical ops. Note that these ops 8831 // depend on the PPC behavior for oversized shift amounts. 8832 SDValue Lo = Op.getOperand(0); 8833 SDValue Hi = Op.getOperand(1); 8834 SDValue Amt = Op.getOperand(2); 8835 EVT AmtVT = Amt.getValueType(); 8836 8837 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8838 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8839 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8840 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8841 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8842 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8843 DAG.getConstant(-BitWidth, dl, AmtVT)); 8844 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8845 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8846 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8847 SDValue OutOps[] = { OutLo, OutHi }; 8848 return DAG.getMergeValues(OutOps, dl); 8849 } 8850 8851 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8852 SDLoc dl(Op); 8853 EVT VT = Op.getValueType(); 8854 unsigned BitWidth = VT.getSizeInBits(); 8855 assert(Op.getNumOperands() == 3 && 8856 VT == Op.getOperand(1).getValueType() && 8857 "Unexpected SRA!"); 8858 8859 // Expand into a bunch of logical ops, followed by a select_cc. 8860 SDValue Lo = Op.getOperand(0); 8861 SDValue Hi = Op.getOperand(1); 8862 SDValue Amt = Op.getOperand(2); 8863 EVT AmtVT = Amt.getValueType(); 8864 8865 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8866 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8867 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8868 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8869 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8870 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8871 DAG.getConstant(-BitWidth, dl, AmtVT)); 8872 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8873 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8874 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8875 Tmp4, Tmp6, ISD::SETLE); 8876 SDValue OutOps[] = { OutLo, OutHi }; 8877 return DAG.getMergeValues(OutOps, dl); 8878 } 8879 8880 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8881 SelectionDAG &DAG) const { 8882 SDLoc dl(Op); 8883 EVT VT = Op.getValueType(); 8884 unsigned BitWidth = VT.getSizeInBits(); 8885 8886 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8887 SDValue X = Op.getOperand(0); 8888 SDValue Y = Op.getOperand(1); 8889 SDValue Z = Op.getOperand(2); 8890 EVT AmtVT = Z.getValueType(); 8891 8892 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8893 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8894 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8895 // on PowerPC shift by BW being well defined. 8896 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8897 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8898 SDValue SubZ = 8899 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8900 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8901 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8902 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8903 } 8904 8905 //===----------------------------------------------------------------------===// 8906 // Vector related lowering. 8907 // 8908 8909 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8910 /// element size of SplatSize. Cast the result to VT. 8911 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8912 SelectionDAG &DAG, const SDLoc &dl) { 8913 static const MVT VTys[] = { // canonical VT to use for each size. 8914 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8915 }; 8916 8917 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8918 8919 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8920 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8921 SplatSize = 1; 8922 Val = 0xFF; 8923 } 8924 8925 EVT CanonicalVT = VTys[SplatSize-1]; 8926 8927 // Build a canonical splat for this value. 8928 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8929 } 8930 8931 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8932 /// specified intrinsic ID. 8933 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8934 const SDLoc &dl, EVT DestVT = MVT::Other) { 8935 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8936 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8937 DAG.getConstant(IID, dl, MVT::i32), Op); 8938 } 8939 8940 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8941 /// specified intrinsic ID. 8942 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8943 SelectionDAG &DAG, const SDLoc &dl, 8944 EVT DestVT = MVT::Other) { 8945 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8946 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8947 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8948 } 8949 8950 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8951 /// specified intrinsic ID. 8952 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8953 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8954 EVT DestVT = MVT::Other) { 8955 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8956 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8957 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8958 } 8959 8960 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8961 /// amount. The result has the specified value type. 8962 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8963 SelectionDAG &DAG, const SDLoc &dl) { 8964 // Force LHS/RHS to be the right type. 8965 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8966 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8967 8968 int Ops[16]; 8969 for (unsigned i = 0; i != 16; ++i) 8970 Ops[i] = i + Amt; 8971 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8972 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8973 } 8974 8975 /// Do we have an efficient pattern in a .td file for this node? 8976 /// 8977 /// \param V - pointer to the BuildVectorSDNode being matched 8978 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8979 /// 8980 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8981 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8982 /// the opposite is true (expansion is beneficial) are: 8983 /// - The node builds a vector out of integers that are not 32 or 64-bits 8984 /// - The node builds a vector out of constants 8985 /// - The node is a "load-and-splat" 8986 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8987 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8988 bool HasDirectMove, 8989 bool HasP8Vector) { 8990 EVT VecVT = V->getValueType(0); 8991 bool RightType = VecVT == MVT::v2f64 || 8992 (HasP8Vector && VecVT == MVT::v4f32) || 8993 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8994 if (!RightType) 8995 return false; 8996 8997 bool IsSplat = true; 8998 bool IsLoad = false; 8999 SDValue Op0 = V->getOperand(0); 9000 9001 // This function is called in a block that confirms the node is not a constant 9002 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9003 // different constants. 9004 if (V->isConstant()) 9005 return false; 9006 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9007 if (V->getOperand(i).isUndef()) 9008 return false; 9009 // We want to expand nodes that represent load-and-splat even if the 9010 // loaded value is a floating point truncation or conversion to int. 9011 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9012 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9013 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9014 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9015 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9016 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9017 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9018 IsLoad = true; 9019 // If the operands are different or the input is not a load and has more 9020 // uses than just this BV node, then it isn't a splat. 9021 if (V->getOperand(i) != Op0 || 9022 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9023 IsSplat = false; 9024 } 9025 return !(IsSplat && IsLoad); 9026 } 9027 9028 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9029 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9030 9031 SDLoc dl(Op); 9032 SDValue Op0 = Op->getOperand(0); 9033 9034 if ((Op.getValueType() != MVT::f128) || 9035 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9036 (Op0.getOperand(0).getValueType() != MVT::i64) || 9037 (Op0.getOperand(1).getValueType() != MVT::i64)) 9038 return SDValue(); 9039 9040 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9041 Op0.getOperand(1)); 9042 } 9043 9044 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9045 const SDValue *InputLoad = &Op; 9046 if (InputLoad->getOpcode() == ISD::BITCAST) 9047 InputLoad = &InputLoad->getOperand(0); 9048 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9049 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9050 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9051 InputLoad = &InputLoad->getOperand(0); 9052 } 9053 if (InputLoad->getOpcode() != ISD::LOAD) 9054 return nullptr; 9055 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9056 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9057 } 9058 9059 // Convert the argument APFloat to a single precision APFloat if there is no 9060 // loss in information during the conversion to single precision APFloat and the 9061 // resulting number is not a denormal number. Return true if successful. 9062 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9063 APFloat APFloatToConvert = ArgAPFloat; 9064 bool LosesInfo = true; 9065 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9066 &LosesInfo); 9067 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9068 if (Success) 9069 ArgAPFloat = APFloatToConvert; 9070 return Success; 9071 } 9072 9073 // Bitcast the argument APInt to a double and convert it to a single precision 9074 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9075 // argument if there is no loss in information during the conversion from 9076 // double to single precision APFloat and the resulting number is not a denormal 9077 // number. Return true if successful. 9078 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9079 double DpValue = ArgAPInt.bitsToDouble(); 9080 APFloat APFloatDp(DpValue); 9081 bool Success = convertToNonDenormSingle(APFloatDp); 9082 if (Success) 9083 ArgAPInt = APFloatDp.bitcastToAPInt(); 9084 return Success; 9085 } 9086 9087 // Nondestructive check for convertTonNonDenormSingle. 9088 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9089 // Only convert if it loses info, since XXSPLTIDP should 9090 // handle the other case. 9091 APFloat APFloatToConvert = ArgAPFloat; 9092 bool LosesInfo = true; 9093 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9094 &LosesInfo); 9095 9096 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9097 } 9098 9099 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, 9100 unsigned &Opcode) { 9101 const SDNode *InputNode = Op.getOperand(0).getNode(); 9102 if (!InputNode || !ISD::isUNINDEXEDLoad(InputNode)) 9103 return false; 9104 9105 if (!Subtarget.hasVSX()) 9106 return false; 9107 9108 EVT Ty = Op->getValueType(0); 9109 if (Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32 || 9110 Ty == MVT::v8i16 || Ty == MVT::v16i8) 9111 return true; 9112 9113 if (Ty == MVT::v2i64) { 9114 // Check the extend type, when the input type is i32, and the output vector 9115 // type is v2i64. 9116 if (cast<LoadSDNode>(Op.getOperand(0))->getMemoryVT() == MVT::i32) { 9117 if (ISD::isZEXTLoad(InputNode)) 9118 Opcode = PPCISD::ZEXT_LD_SPLAT; 9119 if (ISD::isSEXTLoad(InputNode)) 9120 Opcode = PPCISD::SEXT_LD_SPLAT; 9121 } 9122 return true; 9123 } 9124 return false; 9125 } 9126 9127 // If this is a case we can't handle, return null and let the default 9128 // expansion code take care of it. If we CAN select this case, and if it 9129 // selects to a single instruction, return Op. Otherwise, if we can codegen 9130 // this case more efficiently than a constant pool load, lower it to the 9131 // sequence of ops that should be used. 9132 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9133 SelectionDAG &DAG) const { 9134 SDLoc dl(Op); 9135 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9136 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9137 9138 // Check if this is a splat of a constant value. 9139 APInt APSplatBits, APSplatUndef; 9140 unsigned SplatBitSize; 9141 bool HasAnyUndefs; 9142 bool BVNIsConstantSplat = 9143 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9144 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9145 9146 // If it is a splat of a double, check if we can shrink it to a 32 bit 9147 // non-denormal float which when converted back to double gives us the same 9148 // double. This is to exploit the XXSPLTIDP instruction. 9149 // If we lose precision, we use XXSPLTI32DX. 9150 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9151 Subtarget.hasPrefixInstrs()) { 9152 // Check the type first to short-circuit so we don't modify APSplatBits if 9153 // this block isn't executed. 9154 if ((Op->getValueType(0) == MVT::v2f64) && 9155 convertToNonDenormSingle(APSplatBits)) { 9156 SDValue SplatNode = DAG.getNode( 9157 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9158 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9159 return DAG.getBitcast(Op.getValueType(), SplatNode); 9160 } else { 9161 // We may lose precision, so we have to use XXSPLTI32DX. 9162 9163 uint32_t Hi = 9164 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9165 uint32_t Lo = 9166 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9167 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9168 9169 if (!Hi || !Lo) 9170 // If either load is 0, then we should generate XXLXOR to set to 0. 9171 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9172 9173 if (Hi) 9174 SplatNode = DAG.getNode( 9175 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9176 DAG.getTargetConstant(0, dl, MVT::i32), 9177 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9178 9179 if (Lo) 9180 SplatNode = 9181 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9182 DAG.getTargetConstant(1, dl, MVT::i32), 9183 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9184 9185 return DAG.getBitcast(Op.getValueType(), SplatNode); 9186 } 9187 } 9188 9189 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9190 unsigned NewOpcode = PPCISD::LD_SPLAT; 9191 9192 // Handle load-and-splat patterns as we have instructions that will do this 9193 // in one go. 9194 if (DAG.isSplatValue(Op, true) && 9195 isValidSplatLoad(Subtarget, Op, NewOpcode)) { 9196 const SDValue *InputLoad = &Op.getOperand(0); 9197 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9198 9199 // If the input load is an extending load, it will be an i32 -> i64 9200 // extending load and isValidSplatLoad() will update NewOpcode. 9201 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits(); 9202 unsigned ElementSize = 9203 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2); 9204 9205 assert(((ElementSize == 2 * MemorySize) 9206 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || 9207 NewOpcode == PPCISD::SEXT_LD_SPLAT) 9208 : (NewOpcode == PPCISD::LD_SPLAT)) && 9209 "Unmatched element size and opcode!\n"); 9210 9211 // Checking for a single use of this load, we have to check for vector 9212 // width (128 bits) / ElementSize uses (since each operand of the 9213 // BUILD_VECTOR is a separate use of the value. 9214 unsigned NumUsesOfInputLD = 128 / ElementSize; 9215 for (SDValue BVInOp : Op->ops()) 9216 if (BVInOp.isUndef()) 9217 NumUsesOfInputLD--; 9218 9219 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector: 9220 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index 9221 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index 9222 // 15", but funciton IsValidSplatLoad() now will only return true when 9223 // the data at index 0 is not nullptr. So we will not get into trouble for 9224 // these cases. 9225 // 9226 // case 1 - lfiwzx/lfiwax 9227 // 1.1: load result is i32 and is sign/zero extend to i64; 9228 // 1.2: build a v2i64 vector type with above loaded value; 9229 // 1.3: the vector has only one value at index 0, others are all undef; 9230 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute. 9231 if (NumUsesOfInputLD == 1 && 9232 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT && 9233 !Subtarget.isLittleEndian() && Subtarget.hasVSX() && 9234 Subtarget.hasLFIWAX())) 9235 return SDValue(); 9236 9237 // case 2 - lxvr[hb]x 9238 // 2.1: load result is at most i16; 9239 // 2.2: build a vector with above loaded value; 9240 // 2.3: the vector has only one value at index 0, others are all undef; 9241 // 2.4: on LE target, so that lxvr[hb]x does not need any permute. 9242 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() && 9243 Subtarget.isISA3_1() && ElementSize <= 16) 9244 return SDValue(); 9245 9246 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9247 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9248 Subtarget.hasVSX()) { 9249 SDValue Ops[] = { 9250 LD->getChain(), // Chain 9251 LD->getBasePtr(), // Ptr 9252 DAG.getValueType(Op.getValueType()) // VT 9253 }; 9254 SDValue LdSplt = DAG.getMemIntrinsicNode( 9255 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops, 9256 LD->getMemoryVT(), LD->getMemOperand()); 9257 // Replace all uses of the output chain of the original load with the 9258 // output chain of the new load. 9259 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9260 LdSplt.getValue(1)); 9261 return LdSplt; 9262 } 9263 } 9264 9265 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9266 // 32-bits can be lowered to VSX instructions under certain conditions. 9267 // Without VSX, there is no pattern more efficient than expanding the node. 9268 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9269 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9270 Subtarget.hasP8Vector())) 9271 return Op; 9272 return SDValue(); 9273 } 9274 9275 uint64_t SplatBits = APSplatBits.getZExtValue(); 9276 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9277 unsigned SplatSize = SplatBitSize / 8; 9278 9279 // First, handle single instruction cases. 9280 9281 // All zeros? 9282 if (SplatBits == 0) { 9283 // Canonicalize all zero vectors to be v4i32. 9284 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9285 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9286 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9287 } 9288 return Op; 9289 } 9290 9291 // We have XXSPLTIW for constant splats four bytes wide. 9292 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9293 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9294 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9295 // turned into a 4-byte splat of 0xABABABAB. 9296 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9297 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9298 Op.getValueType(), DAG, dl); 9299 9300 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9301 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9302 dl); 9303 9304 // We have XXSPLTIB for constant splats one byte wide. 9305 if (Subtarget.hasP9Vector() && SplatSize == 1) 9306 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9307 dl); 9308 9309 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9310 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9311 (32-SplatBitSize)); 9312 if (SextVal >= -16 && SextVal <= 15) 9313 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9314 dl); 9315 9316 // Two instruction sequences. 9317 9318 // If this value is in the range [-32,30] and is even, use: 9319 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9320 // If this value is in the range [17,31] and is odd, use: 9321 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9322 // If this value is in the range [-31,-17] and is odd, use: 9323 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9324 // Note the last two are three-instruction sequences. 9325 if (SextVal >= -32 && SextVal <= 31) { 9326 // To avoid having these optimizations undone by constant folding, 9327 // we convert to a pseudo that will be expanded later into one of 9328 // the above forms. 9329 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9330 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9331 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9332 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9333 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9334 if (VT == Op.getValueType()) 9335 return RetVal; 9336 else 9337 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9338 } 9339 9340 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9341 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9342 // for fneg/fabs. 9343 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9344 // Make -1 and vspltisw -1: 9345 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9346 9347 // Make the VSLW intrinsic, computing 0x8000_0000. 9348 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9349 OnesV, DAG, dl); 9350 9351 // xor by OnesV to invert it. 9352 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9353 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9354 } 9355 9356 // Check to see if this is a wide variety of vsplti*, binop self cases. 9357 static const signed char SplatCsts[] = { 9358 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9359 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9360 }; 9361 9362 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9363 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9364 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9365 int i = SplatCsts[idx]; 9366 9367 // Figure out what shift amount will be used by altivec if shifted by i in 9368 // this splat size. 9369 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9370 9371 // vsplti + shl self. 9372 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9373 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9374 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9375 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9376 Intrinsic::ppc_altivec_vslw 9377 }; 9378 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9379 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9380 } 9381 9382 // vsplti + srl self. 9383 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9384 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9385 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9386 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9387 Intrinsic::ppc_altivec_vsrw 9388 }; 9389 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9390 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9391 } 9392 9393 // vsplti + rol self. 9394 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9395 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9396 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9397 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9398 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9399 Intrinsic::ppc_altivec_vrlw 9400 }; 9401 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9402 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9403 } 9404 9405 // t = vsplti c, result = vsldoi t, t, 1 9406 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9407 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9408 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9409 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9410 } 9411 // t = vsplti c, result = vsldoi t, t, 2 9412 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9413 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9414 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9415 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9416 } 9417 // t = vsplti c, result = vsldoi t, t, 3 9418 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9419 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9420 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9421 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9422 } 9423 } 9424 9425 return SDValue(); 9426 } 9427 9428 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9429 /// the specified operations to build the shuffle. 9430 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9431 SDValue RHS, SelectionDAG &DAG, 9432 const SDLoc &dl) { 9433 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9434 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9435 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9436 9437 enum { 9438 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9439 OP_VMRGHW, 9440 OP_VMRGLW, 9441 OP_VSPLTISW0, 9442 OP_VSPLTISW1, 9443 OP_VSPLTISW2, 9444 OP_VSPLTISW3, 9445 OP_VSLDOI4, 9446 OP_VSLDOI8, 9447 OP_VSLDOI12 9448 }; 9449 9450 if (OpNum == OP_COPY) { 9451 if (LHSID == (1*9+2)*9+3) return LHS; 9452 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9453 return RHS; 9454 } 9455 9456 SDValue OpLHS, OpRHS; 9457 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9458 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9459 9460 int ShufIdxs[16]; 9461 switch (OpNum) { 9462 default: llvm_unreachable("Unknown i32 permute!"); 9463 case OP_VMRGHW: 9464 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9465 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9466 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9467 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9468 break; 9469 case OP_VMRGLW: 9470 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9471 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9472 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9473 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9474 break; 9475 case OP_VSPLTISW0: 9476 for (unsigned i = 0; i != 16; ++i) 9477 ShufIdxs[i] = (i&3)+0; 9478 break; 9479 case OP_VSPLTISW1: 9480 for (unsigned i = 0; i != 16; ++i) 9481 ShufIdxs[i] = (i&3)+4; 9482 break; 9483 case OP_VSPLTISW2: 9484 for (unsigned i = 0; i != 16; ++i) 9485 ShufIdxs[i] = (i&3)+8; 9486 break; 9487 case OP_VSPLTISW3: 9488 for (unsigned i = 0; i != 16; ++i) 9489 ShufIdxs[i] = (i&3)+12; 9490 break; 9491 case OP_VSLDOI4: 9492 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9493 case OP_VSLDOI8: 9494 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9495 case OP_VSLDOI12: 9496 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9497 } 9498 EVT VT = OpLHS.getValueType(); 9499 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9500 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9501 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9502 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9503 } 9504 9505 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9506 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9507 /// SDValue. 9508 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9509 SelectionDAG &DAG) const { 9510 const unsigned BytesInVector = 16; 9511 bool IsLE = Subtarget.isLittleEndian(); 9512 SDLoc dl(N); 9513 SDValue V1 = N->getOperand(0); 9514 SDValue V2 = N->getOperand(1); 9515 unsigned ShiftElts = 0, InsertAtByte = 0; 9516 bool Swap = false; 9517 9518 // Shifts required to get the byte we want at element 7. 9519 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9520 0, 15, 14, 13, 12, 11, 10, 9}; 9521 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9522 1, 2, 3, 4, 5, 6, 7, 8}; 9523 9524 ArrayRef<int> Mask = N->getMask(); 9525 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9526 9527 // For each mask element, find out if we're just inserting something 9528 // from V2 into V1 or vice versa. 9529 // Possible permutations inserting an element from V2 into V1: 9530 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9531 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9532 // ... 9533 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9534 // Inserting from V1 into V2 will be similar, except mask range will be 9535 // [16,31]. 9536 9537 bool FoundCandidate = false; 9538 // If both vector operands for the shuffle are the same vector, the mask 9539 // will contain only elements from the first one and the second one will be 9540 // undef. 9541 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9542 // Go through the mask of half-words to find an element that's being moved 9543 // from one vector to the other. 9544 for (unsigned i = 0; i < BytesInVector; ++i) { 9545 unsigned CurrentElement = Mask[i]; 9546 // If 2nd operand is undefined, we should only look for element 7 in the 9547 // Mask. 9548 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9549 continue; 9550 9551 bool OtherElementsInOrder = true; 9552 // Examine the other elements in the Mask to see if they're in original 9553 // order. 9554 for (unsigned j = 0; j < BytesInVector; ++j) { 9555 if (j == i) 9556 continue; 9557 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9558 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9559 // in which we always assume we're always picking from the 1st operand. 9560 int MaskOffset = 9561 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9562 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9563 OtherElementsInOrder = false; 9564 break; 9565 } 9566 } 9567 // If other elements are in original order, we record the number of shifts 9568 // we need to get the element we want into element 7. Also record which byte 9569 // in the vector we should insert into. 9570 if (OtherElementsInOrder) { 9571 // If 2nd operand is undefined, we assume no shifts and no swapping. 9572 if (V2.isUndef()) { 9573 ShiftElts = 0; 9574 Swap = false; 9575 } else { 9576 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9577 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9578 : BigEndianShifts[CurrentElement & 0xF]; 9579 Swap = CurrentElement < BytesInVector; 9580 } 9581 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9582 FoundCandidate = true; 9583 break; 9584 } 9585 } 9586 9587 if (!FoundCandidate) 9588 return SDValue(); 9589 9590 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9591 // optionally with VECSHL if shift is required. 9592 if (Swap) 9593 std::swap(V1, V2); 9594 if (V2.isUndef()) 9595 V2 = V1; 9596 if (ShiftElts) { 9597 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9598 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9599 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9600 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9601 } 9602 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9603 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9604 } 9605 9606 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9607 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9608 /// SDValue. 9609 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9610 SelectionDAG &DAG) const { 9611 const unsigned NumHalfWords = 8; 9612 const unsigned BytesInVector = NumHalfWords * 2; 9613 // Check that the shuffle is on half-words. 9614 if (!isNByteElemShuffleMask(N, 2, 1)) 9615 return SDValue(); 9616 9617 bool IsLE = Subtarget.isLittleEndian(); 9618 SDLoc dl(N); 9619 SDValue V1 = N->getOperand(0); 9620 SDValue V2 = N->getOperand(1); 9621 unsigned ShiftElts = 0, InsertAtByte = 0; 9622 bool Swap = false; 9623 9624 // Shifts required to get the half-word we want at element 3. 9625 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9626 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9627 9628 uint32_t Mask = 0; 9629 uint32_t OriginalOrderLow = 0x1234567; 9630 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9631 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9632 // 32-bit space, only need 4-bit nibbles per element. 9633 for (unsigned i = 0; i < NumHalfWords; ++i) { 9634 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9635 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9636 } 9637 9638 // For each mask element, find out if we're just inserting something 9639 // from V2 into V1 or vice versa. Possible permutations inserting an element 9640 // from V2 into V1: 9641 // X, 1, 2, 3, 4, 5, 6, 7 9642 // 0, X, 2, 3, 4, 5, 6, 7 9643 // 0, 1, X, 3, 4, 5, 6, 7 9644 // 0, 1, 2, X, 4, 5, 6, 7 9645 // 0, 1, 2, 3, X, 5, 6, 7 9646 // 0, 1, 2, 3, 4, X, 6, 7 9647 // 0, 1, 2, 3, 4, 5, X, 7 9648 // 0, 1, 2, 3, 4, 5, 6, X 9649 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9650 9651 bool FoundCandidate = false; 9652 // Go through the mask of half-words to find an element that's being moved 9653 // from one vector to the other. 9654 for (unsigned i = 0; i < NumHalfWords; ++i) { 9655 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9656 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9657 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9658 uint32_t TargetOrder = 0x0; 9659 9660 // If both vector operands for the shuffle are the same vector, the mask 9661 // will contain only elements from the first one and the second one will be 9662 // undef. 9663 if (V2.isUndef()) { 9664 ShiftElts = 0; 9665 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9666 TargetOrder = OriginalOrderLow; 9667 Swap = false; 9668 // Skip if not the correct element or mask of other elements don't equal 9669 // to our expected order. 9670 if (MaskOneElt == VINSERTHSrcElem && 9671 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9672 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9673 FoundCandidate = true; 9674 break; 9675 } 9676 } else { // If both operands are defined. 9677 // Target order is [8,15] if the current mask is between [0,7]. 9678 TargetOrder = 9679 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9680 // Skip if mask of other elements don't equal our expected order. 9681 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9682 // We only need the last 3 bits for the number of shifts. 9683 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9684 : BigEndianShifts[MaskOneElt & 0x7]; 9685 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9686 Swap = MaskOneElt < NumHalfWords; 9687 FoundCandidate = true; 9688 break; 9689 } 9690 } 9691 } 9692 9693 if (!FoundCandidate) 9694 return SDValue(); 9695 9696 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9697 // optionally with VECSHL if shift is required. 9698 if (Swap) 9699 std::swap(V1, V2); 9700 if (V2.isUndef()) 9701 V2 = V1; 9702 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9703 if (ShiftElts) { 9704 // Double ShiftElts because we're left shifting on v16i8 type. 9705 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9706 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9707 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9708 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9709 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9710 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9711 } 9712 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9713 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9714 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9715 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9716 } 9717 9718 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9719 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9720 /// return the default SDValue. 9721 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9722 SelectionDAG &DAG) const { 9723 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9724 // to v16i8. Peek through the bitcasts to get the actual operands. 9725 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9726 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9727 9728 auto ShuffleMask = SVN->getMask(); 9729 SDValue VecShuffle(SVN, 0); 9730 SDLoc DL(SVN); 9731 9732 // Check that we have a four byte shuffle. 9733 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9734 return SDValue(); 9735 9736 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9737 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9738 std::swap(LHS, RHS); 9739 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9740 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9741 } 9742 9743 // Ensure that the RHS is a vector of constants. 9744 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9745 if (!BVN) 9746 return SDValue(); 9747 9748 // Check if RHS is a splat of 4-bytes (or smaller). 9749 APInt APSplatValue, APSplatUndef; 9750 unsigned SplatBitSize; 9751 bool HasAnyUndefs; 9752 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9753 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9754 SplatBitSize > 32) 9755 return SDValue(); 9756 9757 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9758 // The instruction splats a constant C into two words of the source vector 9759 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9760 // Thus we check that the shuffle mask is the equivalent of 9761 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9762 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9763 // within each word are consecutive, so we only need to check the first byte. 9764 SDValue Index; 9765 bool IsLE = Subtarget.isLittleEndian(); 9766 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9767 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9768 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9769 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9770 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9771 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9772 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9773 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9774 else 9775 return SDValue(); 9776 9777 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9778 // for XXSPLTI32DX. 9779 unsigned SplatVal = APSplatValue.getZExtValue(); 9780 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9781 SplatVal |= (SplatVal << SplatBitSize); 9782 9783 SDValue SplatNode = DAG.getNode( 9784 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9785 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9786 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9787 } 9788 9789 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9790 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9791 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9792 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9793 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9794 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9795 assert(Op.getValueType() == MVT::v1i128 && 9796 "Only set v1i128 as custom, other type shouldn't reach here!"); 9797 SDLoc dl(Op); 9798 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9799 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9800 unsigned SHLAmt = N1.getConstantOperandVal(0); 9801 if (SHLAmt % 8 == 0) { 9802 SmallVector<int, 16> Mask(16, 0); 9803 std::iota(Mask.begin(), Mask.end(), 0); 9804 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9805 if (SDValue Shuffle = 9806 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9807 DAG.getUNDEF(MVT::v16i8), Mask)) 9808 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9809 } 9810 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9811 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9812 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9813 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9814 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9815 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9816 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9817 } 9818 9819 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9820 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9821 /// return the code it can be lowered into. Worst case, it can always be 9822 /// lowered into a vperm. 9823 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9824 SelectionDAG &DAG) const { 9825 SDLoc dl(Op); 9826 SDValue V1 = Op.getOperand(0); 9827 SDValue V2 = Op.getOperand(1); 9828 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9829 9830 // Any nodes that were combined in the target-independent combiner prior 9831 // to vector legalization will not be sent to the target combine. Try to 9832 // combine it here. 9833 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9834 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9835 return NewShuffle; 9836 Op = NewShuffle; 9837 SVOp = cast<ShuffleVectorSDNode>(Op); 9838 V1 = Op.getOperand(0); 9839 V2 = Op.getOperand(1); 9840 } 9841 EVT VT = Op.getValueType(); 9842 bool isLittleEndian = Subtarget.isLittleEndian(); 9843 9844 unsigned ShiftElts, InsertAtByte; 9845 bool Swap = false; 9846 9847 // If this is a load-and-splat, we can do that with a single instruction 9848 // in some cases. However if the load has multiple uses, we don't want to 9849 // combine it because that will just produce multiple loads. 9850 bool IsPermutedLoad = false; 9851 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9852 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9853 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9854 InputLoad->hasOneUse()) { 9855 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9856 int SplatIdx = 9857 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9858 9859 // The splat index for permuted loads will be in the left half of the vector 9860 // which is strictly wider than the loaded value by 8 bytes. So we need to 9861 // adjust the splat index to point to the correct address in memory. 9862 if (IsPermutedLoad) { 9863 assert((isLittleEndian || IsFourByte) && 9864 "Unexpected size for permuted load on big endian target"); 9865 SplatIdx += IsFourByte ? 2 : 1; 9866 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9867 "Splat of a value outside of the loaded memory"); 9868 } 9869 9870 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9871 // For 4-byte load-and-splat, we need Power9. 9872 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9873 uint64_t Offset = 0; 9874 if (IsFourByte) 9875 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9876 else 9877 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9878 9879 // If the width of the load is the same as the width of the splat, 9880 // loading with an offset would load the wrong memory. 9881 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9882 Offset = 0; 9883 9884 SDValue BasePtr = LD->getBasePtr(); 9885 if (Offset != 0) 9886 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9887 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9888 SDValue Ops[] = { 9889 LD->getChain(), // Chain 9890 BasePtr, // BasePtr 9891 DAG.getValueType(Op.getValueType()) // VT 9892 }; 9893 SDVTList VTL = 9894 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9895 SDValue LdSplt = 9896 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9897 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9898 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9899 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9900 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9901 return LdSplt; 9902 } 9903 } 9904 if (Subtarget.hasP9Vector() && 9905 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9906 isLittleEndian)) { 9907 if (Swap) 9908 std::swap(V1, V2); 9909 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9910 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9911 if (ShiftElts) { 9912 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9913 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9914 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9915 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9916 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9917 } 9918 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9919 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9920 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9921 } 9922 9923 if (Subtarget.hasPrefixInstrs()) { 9924 SDValue SplatInsertNode; 9925 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9926 return SplatInsertNode; 9927 } 9928 9929 if (Subtarget.hasP9Altivec()) { 9930 SDValue NewISDNode; 9931 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9932 return NewISDNode; 9933 9934 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9935 return NewISDNode; 9936 } 9937 9938 if (Subtarget.hasVSX() && 9939 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9940 if (Swap) 9941 std::swap(V1, V2); 9942 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9943 SDValue Conv2 = 9944 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9945 9946 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9947 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9948 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9949 } 9950 9951 if (Subtarget.hasVSX() && 9952 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9953 if (Swap) 9954 std::swap(V1, V2); 9955 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9956 SDValue Conv2 = 9957 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9958 9959 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9960 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9961 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9962 } 9963 9964 if (Subtarget.hasP9Vector()) { 9965 if (PPC::isXXBRHShuffleMask(SVOp)) { 9966 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9967 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9968 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9969 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9970 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9971 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9972 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9973 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9974 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9975 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9976 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9977 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9978 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9979 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9980 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9981 } 9982 } 9983 9984 if (Subtarget.hasVSX()) { 9985 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9986 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9987 9988 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9989 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9990 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9991 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9992 } 9993 9994 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9995 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9996 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9997 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9998 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9999 } 10000 } 10001 10002 // Cases that are handled by instructions that take permute immediates 10003 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10004 // selected by the instruction selector. 10005 if (V2.isUndef()) { 10006 if (PPC::isSplatShuffleMask(SVOp, 1) || 10007 PPC::isSplatShuffleMask(SVOp, 2) || 10008 PPC::isSplatShuffleMask(SVOp, 4) || 10009 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10010 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10011 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10012 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10013 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10014 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10015 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10016 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10017 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10018 (Subtarget.hasP8Altivec() && ( 10019 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10020 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10021 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10022 return Op; 10023 } 10024 } 10025 10026 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10027 // and produce a fixed permutation. If any of these match, do not lower to 10028 // VPERM. 10029 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10030 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10031 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10032 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10033 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10034 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10035 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10036 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10037 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10038 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10039 (Subtarget.hasP8Altivec() && ( 10040 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10041 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10042 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10043 return Op; 10044 10045 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10046 // perfect shuffle table to emit an optimal matching sequence. 10047 ArrayRef<int> PermMask = SVOp->getMask(); 10048 10049 unsigned PFIndexes[4]; 10050 bool isFourElementShuffle = true; 10051 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 10052 unsigned EltNo = 8; // Start out undef. 10053 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10054 if (PermMask[i*4+j] < 0) 10055 continue; // Undef, ignore it. 10056 10057 unsigned ByteSource = PermMask[i*4+j]; 10058 if ((ByteSource & 3) != j) { 10059 isFourElementShuffle = false; 10060 break; 10061 } 10062 10063 if (EltNo == 8) { 10064 EltNo = ByteSource/4; 10065 } else if (EltNo != ByteSource/4) { 10066 isFourElementShuffle = false; 10067 break; 10068 } 10069 } 10070 PFIndexes[i] = EltNo; 10071 } 10072 10073 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10074 // perfect shuffle vector to determine if it is cost effective to do this as 10075 // discrete instructions, or whether we should use a vperm. 10076 // For now, we skip this for little endian until such time as we have a 10077 // little-endian perfect shuffle table. 10078 if (isFourElementShuffle && !isLittleEndian) { 10079 // Compute the index in the perfect shuffle table. 10080 unsigned PFTableIndex = 10081 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10082 10083 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10084 unsigned Cost = (PFEntry >> 30); 10085 10086 // Determining when to avoid vperm is tricky. Many things affect the cost 10087 // of vperm, particularly how many times the perm mask needs to be computed. 10088 // For example, if the perm mask can be hoisted out of a loop or is already 10089 // used (perhaps because there are multiple permutes with the same shuffle 10090 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10091 // the loop requires an extra register. 10092 // 10093 // As a compromise, we only emit discrete instructions if the shuffle can be 10094 // generated in 3 or fewer operations. When we have loop information 10095 // available, if this block is within a loop, we should avoid using vperm 10096 // for 3-operation perms and use a constant pool load instead. 10097 if (Cost < 3) 10098 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10099 } 10100 10101 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10102 // vector that will get spilled to the constant pool. 10103 if (V2.isUndef()) V2 = V1; 10104 10105 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10106 // that it is in input element units, not in bytes. Convert now. 10107 10108 // For little endian, the order of the input vectors is reversed, and 10109 // the permutation mask is complemented with respect to 31. This is 10110 // necessary to produce proper semantics with the big-endian-biased vperm 10111 // instruction. 10112 EVT EltVT = V1.getValueType().getVectorElementType(); 10113 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10114 10115 SmallVector<SDValue, 16> ResultMask; 10116 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10117 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10118 10119 for (unsigned j = 0; j != BytesPerElement; ++j) 10120 if (isLittleEndian) 10121 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10122 dl, MVT::i32)); 10123 else 10124 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10125 MVT::i32)); 10126 } 10127 10128 ShufflesHandledWithVPERM++; 10129 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10130 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10131 LLVM_DEBUG(SVOp->dump()); 10132 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10133 LLVM_DEBUG(VPermMask.dump()); 10134 10135 if (isLittleEndian) 10136 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10137 V2, V1, VPermMask); 10138 else 10139 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10140 V1, V2, VPermMask); 10141 } 10142 10143 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10144 /// vector comparison. If it is, return true and fill in Opc/isDot with 10145 /// information about the intrinsic. 10146 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10147 bool &isDot, const PPCSubtarget &Subtarget) { 10148 unsigned IntrinsicID = 10149 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10150 CompareOpc = -1; 10151 isDot = false; 10152 switch (IntrinsicID) { 10153 default: 10154 return false; 10155 // Comparison predicates. 10156 case Intrinsic::ppc_altivec_vcmpbfp_p: 10157 CompareOpc = 966; 10158 isDot = true; 10159 break; 10160 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10161 CompareOpc = 198; 10162 isDot = true; 10163 break; 10164 case Intrinsic::ppc_altivec_vcmpequb_p: 10165 CompareOpc = 6; 10166 isDot = true; 10167 break; 10168 case Intrinsic::ppc_altivec_vcmpequh_p: 10169 CompareOpc = 70; 10170 isDot = true; 10171 break; 10172 case Intrinsic::ppc_altivec_vcmpequw_p: 10173 CompareOpc = 134; 10174 isDot = true; 10175 break; 10176 case Intrinsic::ppc_altivec_vcmpequd_p: 10177 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10178 CompareOpc = 199; 10179 isDot = true; 10180 } else 10181 return false; 10182 break; 10183 case Intrinsic::ppc_altivec_vcmpneb_p: 10184 case Intrinsic::ppc_altivec_vcmpneh_p: 10185 case Intrinsic::ppc_altivec_vcmpnew_p: 10186 case Intrinsic::ppc_altivec_vcmpnezb_p: 10187 case Intrinsic::ppc_altivec_vcmpnezh_p: 10188 case Intrinsic::ppc_altivec_vcmpnezw_p: 10189 if (Subtarget.hasP9Altivec()) { 10190 switch (IntrinsicID) { 10191 default: 10192 llvm_unreachable("Unknown comparison intrinsic."); 10193 case Intrinsic::ppc_altivec_vcmpneb_p: 10194 CompareOpc = 7; 10195 break; 10196 case Intrinsic::ppc_altivec_vcmpneh_p: 10197 CompareOpc = 71; 10198 break; 10199 case Intrinsic::ppc_altivec_vcmpnew_p: 10200 CompareOpc = 135; 10201 break; 10202 case Intrinsic::ppc_altivec_vcmpnezb_p: 10203 CompareOpc = 263; 10204 break; 10205 case Intrinsic::ppc_altivec_vcmpnezh_p: 10206 CompareOpc = 327; 10207 break; 10208 case Intrinsic::ppc_altivec_vcmpnezw_p: 10209 CompareOpc = 391; 10210 break; 10211 } 10212 isDot = true; 10213 } else 10214 return false; 10215 break; 10216 case Intrinsic::ppc_altivec_vcmpgefp_p: 10217 CompareOpc = 454; 10218 isDot = true; 10219 break; 10220 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10221 CompareOpc = 710; 10222 isDot = true; 10223 break; 10224 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10225 CompareOpc = 774; 10226 isDot = true; 10227 break; 10228 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10229 CompareOpc = 838; 10230 isDot = true; 10231 break; 10232 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10233 CompareOpc = 902; 10234 isDot = true; 10235 break; 10236 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10237 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10238 CompareOpc = 967; 10239 isDot = true; 10240 } else 10241 return false; 10242 break; 10243 case Intrinsic::ppc_altivec_vcmpgtub_p: 10244 CompareOpc = 518; 10245 isDot = true; 10246 break; 10247 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10248 CompareOpc = 582; 10249 isDot = true; 10250 break; 10251 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10252 CompareOpc = 646; 10253 isDot = true; 10254 break; 10255 case Intrinsic::ppc_altivec_vcmpgtud_p: 10256 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10257 CompareOpc = 711; 10258 isDot = true; 10259 } else 10260 return false; 10261 break; 10262 10263 case Intrinsic::ppc_altivec_vcmpequq: 10264 case Intrinsic::ppc_altivec_vcmpgtsq: 10265 case Intrinsic::ppc_altivec_vcmpgtuq: 10266 if (!Subtarget.isISA3_1()) 10267 return false; 10268 switch (IntrinsicID) { 10269 default: 10270 llvm_unreachable("Unknown comparison intrinsic."); 10271 case Intrinsic::ppc_altivec_vcmpequq: 10272 CompareOpc = 455; 10273 break; 10274 case Intrinsic::ppc_altivec_vcmpgtsq: 10275 CompareOpc = 903; 10276 break; 10277 case Intrinsic::ppc_altivec_vcmpgtuq: 10278 CompareOpc = 647; 10279 break; 10280 } 10281 break; 10282 10283 // VSX predicate comparisons use the same infrastructure 10284 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10285 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10286 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10287 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10288 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10289 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10290 if (Subtarget.hasVSX()) { 10291 switch (IntrinsicID) { 10292 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10293 CompareOpc = 99; 10294 break; 10295 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10296 CompareOpc = 115; 10297 break; 10298 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10299 CompareOpc = 107; 10300 break; 10301 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10302 CompareOpc = 67; 10303 break; 10304 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10305 CompareOpc = 83; 10306 break; 10307 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10308 CompareOpc = 75; 10309 break; 10310 } 10311 isDot = true; 10312 } else 10313 return false; 10314 break; 10315 10316 // Normal Comparisons. 10317 case Intrinsic::ppc_altivec_vcmpbfp: 10318 CompareOpc = 966; 10319 break; 10320 case Intrinsic::ppc_altivec_vcmpeqfp: 10321 CompareOpc = 198; 10322 break; 10323 case Intrinsic::ppc_altivec_vcmpequb: 10324 CompareOpc = 6; 10325 break; 10326 case Intrinsic::ppc_altivec_vcmpequh: 10327 CompareOpc = 70; 10328 break; 10329 case Intrinsic::ppc_altivec_vcmpequw: 10330 CompareOpc = 134; 10331 break; 10332 case Intrinsic::ppc_altivec_vcmpequd: 10333 if (Subtarget.hasP8Altivec()) 10334 CompareOpc = 199; 10335 else 10336 return false; 10337 break; 10338 case Intrinsic::ppc_altivec_vcmpneb: 10339 case Intrinsic::ppc_altivec_vcmpneh: 10340 case Intrinsic::ppc_altivec_vcmpnew: 10341 case Intrinsic::ppc_altivec_vcmpnezb: 10342 case Intrinsic::ppc_altivec_vcmpnezh: 10343 case Intrinsic::ppc_altivec_vcmpnezw: 10344 if (Subtarget.hasP9Altivec()) 10345 switch (IntrinsicID) { 10346 default: 10347 llvm_unreachable("Unknown comparison intrinsic."); 10348 case Intrinsic::ppc_altivec_vcmpneb: 10349 CompareOpc = 7; 10350 break; 10351 case Intrinsic::ppc_altivec_vcmpneh: 10352 CompareOpc = 71; 10353 break; 10354 case Intrinsic::ppc_altivec_vcmpnew: 10355 CompareOpc = 135; 10356 break; 10357 case Intrinsic::ppc_altivec_vcmpnezb: 10358 CompareOpc = 263; 10359 break; 10360 case Intrinsic::ppc_altivec_vcmpnezh: 10361 CompareOpc = 327; 10362 break; 10363 case Intrinsic::ppc_altivec_vcmpnezw: 10364 CompareOpc = 391; 10365 break; 10366 } 10367 else 10368 return false; 10369 break; 10370 case Intrinsic::ppc_altivec_vcmpgefp: 10371 CompareOpc = 454; 10372 break; 10373 case Intrinsic::ppc_altivec_vcmpgtfp: 10374 CompareOpc = 710; 10375 break; 10376 case Intrinsic::ppc_altivec_vcmpgtsb: 10377 CompareOpc = 774; 10378 break; 10379 case Intrinsic::ppc_altivec_vcmpgtsh: 10380 CompareOpc = 838; 10381 break; 10382 case Intrinsic::ppc_altivec_vcmpgtsw: 10383 CompareOpc = 902; 10384 break; 10385 case Intrinsic::ppc_altivec_vcmpgtsd: 10386 if (Subtarget.hasP8Altivec()) 10387 CompareOpc = 967; 10388 else 10389 return false; 10390 break; 10391 case Intrinsic::ppc_altivec_vcmpgtub: 10392 CompareOpc = 518; 10393 break; 10394 case Intrinsic::ppc_altivec_vcmpgtuh: 10395 CompareOpc = 582; 10396 break; 10397 case Intrinsic::ppc_altivec_vcmpgtuw: 10398 CompareOpc = 646; 10399 break; 10400 case Intrinsic::ppc_altivec_vcmpgtud: 10401 if (Subtarget.hasP8Altivec()) 10402 CompareOpc = 711; 10403 else 10404 return false; 10405 break; 10406 case Intrinsic::ppc_altivec_vcmpequq_p: 10407 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10408 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10409 if (!Subtarget.isISA3_1()) 10410 return false; 10411 switch (IntrinsicID) { 10412 default: 10413 llvm_unreachable("Unknown comparison intrinsic."); 10414 case Intrinsic::ppc_altivec_vcmpequq_p: 10415 CompareOpc = 455; 10416 break; 10417 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10418 CompareOpc = 903; 10419 break; 10420 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10421 CompareOpc = 647; 10422 break; 10423 } 10424 isDot = true; 10425 break; 10426 } 10427 return true; 10428 } 10429 10430 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10431 /// lower, do it, otherwise return null. 10432 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10433 SelectionDAG &DAG) const { 10434 unsigned IntrinsicID = 10435 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10436 10437 SDLoc dl(Op); 10438 10439 switch (IntrinsicID) { 10440 case Intrinsic::thread_pointer: 10441 // Reads the thread pointer register, used for __builtin_thread_pointer. 10442 if (Subtarget.isPPC64()) 10443 return DAG.getRegister(PPC::X13, MVT::i64); 10444 return DAG.getRegister(PPC::R2, MVT::i32); 10445 10446 case Intrinsic::ppc_mma_disassemble_acc: 10447 case Intrinsic::ppc_vsx_disassemble_pair: { 10448 int NumVecs = 2; 10449 SDValue WideVec = Op.getOperand(1); 10450 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10451 NumVecs = 4; 10452 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10453 } 10454 SmallVector<SDValue, 4> RetOps; 10455 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10456 SDValue Extract = DAG.getNode( 10457 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10458 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10459 : VecNo, 10460 dl, getPointerTy(DAG.getDataLayout()))); 10461 RetOps.push_back(Extract); 10462 } 10463 return DAG.getMergeValues(RetOps, dl); 10464 } 10465 10466 case Intrinsic::ppc_unpack_longdouble: { 10467 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10468 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && 10469 "Argument of long double unpack must be 0 or 1!"); 10470 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1), 10471 DAG.getConstant(!!(Idx->getSExtValue()), dl, 10472 Idx->getValueType(0))); 10473 } 10474 10475 case Intrinsic::ppc_compare_exp_lt: 10476 case Intrinsic::ppc_compare_exp_gt: 10477 case Intrinsic::ppc_compare_exp_eq: 10478 case Intrinsic::ppc_compare_exp_uo: { 10479 unsigned Pred; 10480 switch (IntrinsicID) { 10481 case Intrinsic::ppc_compare_exp_lt: 10482 Pred = PPC::PRED_LT; 10483 break; 10484 case Intrinsic::ppc_compare_exp_gt: 10485 Pred = PPC::PRED_GT; 10486 break; 10487 case Intrinsic::ppc_compare_exp_eq: 10488 Pred = PPC::PRED_EQ; 10489 break; 10490 case Intrinsic::ppc_compare_exp_uo: 10491 Pred = PPC::PRED_UN; 10492 break; 10493 } 10494 return SDValue( 10495 DAG.getMachineNode( 10496 PPC::SELECT_CC_I4, dl, MVT::i32, 10497 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32, 10498 Op.getOperand(1), Op.getOperand(2)), 10499 0), 10500 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10501 DAG.getTargetConstant(Pred, dl, MVT::i32)}), 10502 0); 10503 } 10504 case Intrinsic::ppc_test_data_class_d: 10505 case Intrinsic::ppc_test_data_class_f: { 10506 unsigned CmprOpc = PPC::XSTSTDCDP; 10507 if (IntrinsicID == Intrinsic::ppc_test_data_class_f) 10508 CmprOpc = PPC::XSTSTDCSP; 10509 return SDValue( 10510 DAG.getMachineNode( 10511 PPC::SELECT_CC_I4, dl, MVT::i32, 10512 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2), 10513 Op.getOperand(1)), 10514 0), 10515 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10516 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}), 10517 0); 10518 } 10519 case Intrinsic::ppc_convert_f128_to_ppcf128: 10520 case Intrinsic::ppc_convert_ppcf128_to_f128: { 10521 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128 10522 ? RTLIB::CONVERT_PPCF128_F128 10523 : RTLIB::CONVERT_F128_PPCF128; 10524 MakeLibCallOptions CallOptions; 10525 std::pair<SDValue, SDValue> Result = 10526 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions, 10527 dl, SDValue()); 10528 return Result.first; 10529 } 10530 } 10531 10532 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10533 // opcode number of the comparison. 10534 int CompareOpc; 10535 bool isDot; 10536 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10537 return SDValue(); // Don't custom lower most intrinsics. 10538 10539 // If this is a non-dot comparison, make the VCMP node and we are done. 10540 if (!isDot) { 10541 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10542 Op.getOperand(1), Op.getOperand(2), 10543 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10544 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10545 } 10546 10547 // Create the PPCISD altivec 'dot' comparison node. 10548 SDValue Ops[] = { 10549 Op.getOperand(2), // LHS 10550 Op.getOperand(3), // RHS 10551 DAG.getConstant(CompareOpc, dl, MVT::i32) 10552 }; 10553 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10554 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10555 10556 // Now that we have the comparison, emit a copy from the CR to a GPR. 10557 // This is flagged to the above dot comparison. 10558 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10559 DAG.getRegister(PPC::CR6, MVT::i32), 10560 CompNode.getValue(1)); 10561 10562 // Unpack the result based on how the target uses it. 10563 unsigned BitNo; // Bit # of CR6. 10564 bool InvertBit; // Invert result? 10565 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10566 default: // Can't happen, don't crash on invalid number though. 10567 case 0: // Return the value of the EQ bit of CR6. 10568 BitNo = 0; InvertBit = false; 10569 break; 10570 case 1: // Return the inverted value of the EQ bit of CR6. 10571 BitNo = 0; InvertBit = true; 10572 break; 10573 case 2: // Return the value of the LT bit of CR6. 10574 BitNo = 2; InvertBit = false; 10575 break; 10576 case 3: // Return the inverted value of the LT bit of CR6. 10577 BitNo = 2; InvertBit = true; 10578 break; 10579 } 10580 10581 // Shift the bit into the low position. 10582 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10583 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10584 // Isolate the bit. 10585 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10586 DAG.getConstant(1, dl, MVT::i32)); 10587 10588 // If we are supposed to, toggle the bit. 10589 if (InvertBit) 10590 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10591 DAG.getConstant(1, dl, MVT::i32)); 10592 return Flags; 10593 } 10594 10595 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10596 SelectionDAG &DAG) const { 10597 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10598 // the beginning of the argument list. 10599 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10600 SDLoc DL(Op); 10601 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10602 case Intrinsic::ppc_cfence: { 10603 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10604 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10605 SDValue Val = Op.getOperand(ArgStart + 1); 10606 EVT Ty = Val.getValueType(); 10607 if (Ty == MVT::i128) { 10608 // FIXME: Testing one of two paired registers is sufficient to guarantee 10609 // ordering? 10610 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val); 10611 } 10612 return SDValue( 10613 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10614 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val), 10615 Op.getOperand(0)), 10616 0); 10617 } 10618 default: 10619 break; 10620 } 10621 return SDValue(); 10622 } 10623 10624 // Lower scalar BSWAP64 to xxbrd. 10625 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10626 SDLoc dl(Op); 10627 if (!Subtarget.isPPC64()) 10628 return Op; 10629 // MTVSRDD 10630 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10631 Op.getOperand(0)); 10632 // XXBRD 10633 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10634 // MFVSRD 10635 int VectorIndex = 0; 10636 if (Subtarget.isLittleEndian()) 10637 VectorIndex = 1; 10638 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10639 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10640 return Op; 10641 } 10642 10643 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10644 // compared to a value that is atomically loaded (atomic loads zero-extend). 10645 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10646 SelectionDAG &DAG) const { 10647 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10648 "Expecting an atomic compare-and-swap here."); 10649 SDLoc dl(Op); 10650 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10651 EVT MemVT = AtomicNode->getMemoryVT(); 10652 if (MemVT.getSizeInBits() >= 32) 10653 return Op; 10654 10655 SDValue CmpOp = Op.getOperand(2); 10656 // If this is already correctly zero-extended, leave it alone. 10657 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10658 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10659 return Op; 10660 10661 // Clear the high bits of the compare operand. 10662 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10663 SDValue NewCmpOp = 10664 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10665 DAG.getConstant(MaskVal, dl, MVT::i32)); 10666 10667 // Replace the existing compare operand with the properly zero-extended one. 10668 SmallVector<SDValue, 4> Ops; 10669 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10670 Ops.push_back(AtomicNode->getOperand(i)); 10671 Ops[2] = NewCmpOp; 10672 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10673 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10674 auto NodeTy = 10675 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10676 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10677 } 10678 10679 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op, 10680 SelectionDAG &DAG) const { 10681 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode()); 10682 EVT MemVT = N->getMemoryVT(); 10683 assert(MemVT.getSimpleVT() == MVT::i128 && 10684 "Expect quadword atomic operations"); 10685 SDLoc dl(N); 10686 unsigned Opc = N->getOpcode(); 10687 switch (Opc) { 10688 case ISD::ATOMIC_LOAD: { 10689 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be 10690 // lowered to ppc instructions by pattern matching instruction selector. 10691 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other); 10692 SmallVector<SDValue, 4> Ops{ 10693 N->getOperand(0), 10694 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)}; 10695 for (int I = 1, E = N->getNumOperands(); I < E; ++I) 10696 Ops.push_back(N->getOperand(I)); 10697 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys, 10698 Ops, MemVT, N->getMemOperand()); 10699 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal); 10700 SDValue ValHi = 10701 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1)); 10702 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi, 10703 DAG.getConstant(64, dl, MVT::i32)); 10704 SDValue Val = 10705 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi}); 10706 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other}, 10707 {Val, LoadedVal.getValue(2)}); 10708 } 10709 case ISD::ATOMIC_STORE: { 10710 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be 10711 // lowered to ppc instructions by pattern matching instruction selector. 10712 SDVTList Tys = DAG.getVTList(MVT::Other); 10713 SmallVector<SDValue, 4> Ops{ 10714 N->getOperand(0), 10715 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)}; 10716 SDValue Val = N->getOperand(2); 10717 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val); 10718 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val, 10719 DAG.getConstant(64, dl, MVT::i32)); 10720 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi); 10721 Ops.push_back(ValLo); 10722 Ops.push_back(ValHi); 10723 Ops.push_back(N->getOperand(1)); 10724 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT, 10725 N->getMemOperand()); 10726 } 10727 default: 10728 llvm_unreachable("Unexpected atomic opcode"); 10729 } 10730 } 10731 10732 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10733 SelectionDAG &DAG) const { 10734 SDLoc dl(Op); 10735 // Create a stack slot that is 16-byte aligned. 10736 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10737 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10738 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10739 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10740 10741 // Store the input value into Value#0 of the stack slot. 10742 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10743 MachinePointerInfo()); 10744 // Load it out. 10745 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10746 } 10747 10748 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10749 SelectionDAG &DAG) const { 10750 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10751 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10752 10753 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10754 10755 EVT VT = Op.getValueType(); 10756 SDLoc dl(Op); 10757 SDValue V1 = Op.getOperand(0); 10758 SDValue V2 = Op.getOperand(1); 10759 10760 if (VT == MVT::v2f64 && C) 10761 return Op; 10762 10763 if (Subtarget.isISA3_1()) { 10764 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 10765 return SDValue(); 10766 // On P10, we have legal lowering for constant and variable indices for 10767 // all vectors. 10768 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10769 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64) 10770 return Op; 10771 } 10772 10773 // Before P10, we have legal lowering for constant indices but not for 10774 // variable ones. 10775 if (!C) 10776 return SDValue(); 10777 10778 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10779 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10780 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10781 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10782 unsigned InsertAtElement = C->getZExtValue(); 10783 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10784 if (Subtarget.isLittleEndian()) { 10785 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10786 } 10787 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10788 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10789 } 10790 return Op; 10791 } 10792 10793 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10794 SelectionDAG &DAG) const { 10795 SDLoc dl(Op); 10796 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10797 SDValue LoadChain = LN->getChain(); 10798 SDValue BasePtr = LN->getBasePtr(); 10799 EVT VT = Op.getValueType(); 10800 10801 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10802 return Op; 10803 10804 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10805 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10806 // 2 or 4 vsx registers. 10807 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10808 "Type unsupported without MMA"); 10809 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10810 "Type unsupported without paired vector support"); 10811 Align Alignment = LN->getAlign(); 10812 SmallVector<SDValue, 4> Loads; 10813 SmallVector<SDValue, 4> LoadChains; 10814 unsigned NumVecs = VT.getSizeInBits() / 128; 10815 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10816 SDValue Load = 10817 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10818 LN->getPointerInfo().getWithOffset(Idx * 16), 10819 commonAlignment(Alignment, Idx * 16), 10820 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10821 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10822 DAG.getConstant(16, dl, BasePtr.getValueType())); 10823 Loads.push_back(Load); 10824 LoadChains.push_back(Load.getValue(1)); 10825 } 10826 if (Subtarget.isLittleEndian()) { 10827 std::reverse(Loads.begin(), Loads.end()); 10828 std::reverse(LoadChains.begin(), LoadChains.end()); 10829 } 10830 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10831 SDValue Value = 10832 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10833 dl, VT, Loads); 10834 SDValue RetOps[] = {Value, TF}; 10835 return DAG.getMergeValues(RetOps, dl); 10836 } 10837 10838 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10839 SelectionDAG &DAG) const { 10840 SDLoc dl(Op); 10841 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10842 SDValue StoreChain = SN->getChain(); 10843 SDValue BasePtr = SN->getBasePtr(); 10844 SDValue Value = SN->getValue(); 10845 EVT StoreVT = Value.getValueType(); 10846 10847 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10848 return Op; 10849 10850 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10851 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10852 // underlying registers individually. 10853 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10854 "Type unsupported without MMA"); 10855 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10856 "Type unsupported without paired vector support"); 10857 Align Alignment = SN->getAlign(); 10858 SmallVector<SDValue, 4> Stores; 10859 unsigned NumVecs = 2; 10860 if (StoreVT == MVT::v512i1) { 10861 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10862 NumVecs = 4; 10863 } 10864 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10865 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10866 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10867 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10868 SDValue Store = 10869 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10870 SN->getPointerInfo().getWithOffset(Idx * 16), 10871 commonAlignment(Alignment, Idx * 16), 10872 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10873 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10874 DAG.getConstant(16, dl, BasePtr.getValueType())); 10875 Stores.push_back(Store); 10876 } 10877 SDValue TF = DAG.getTokenFactor(dl, Stores); 10878 return TF; 10879 } 10880 10881 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10882 SDLoc dl(Op); 10883 if (Op.getValueType() == MVT::v4i32) { 10884 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10885 10886 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10887 // +16 as shift amt. 10888 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10889 SDValue RHSSwap = // = vrlw RHS, 16 10890 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10891 10892 // Shrinkify inputs to v8i16. 10893 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10894 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10895 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10896 10897 // Low parts multiplied together, generating 32-bit results (we ignore the 10898 // top parts). 10899 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10900 LHS, RHS, DAG, dl, MVT::v4i32); 10901 10902 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10903 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10904 // Shift the high parts up 16 bits. 10905 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10906 Neg16, DAG, dl); 10907 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10908 } else if (Op.getValueType() == MVT::v16i8) { 10909 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10910 bool isLittleEndian = Subtarget.isLittleEndian(); 10911 10912 // Multiply the even 8-bit parts, producing 16-bit sums. 10913 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10914 LHS, RHS, DAG, dl, MVT::v8i16); 10915 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10916 10917 // Multiply the odd 8-bit parts, producing 16-bit sums. 10918 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10919 LHS, RHS, DAG, dl, MVT::v8i16); 10920 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10921 10922 // Merge the results together. Because vmuleub and vmuloub are 10923 // instructions with a big-endian bias, we must reverse the 10924 // element numbering and reverse the meaning of "odd" and "even" 10925 // when generating little endian code. 10926 int Ops[16]; 10927 for (unsigned i = 0; i != 8; ++i) { 10928 if (isLittleEndian) { 10929 Ops[i*2 ] = 2*i; 10930 Ops[i*2+1] = 2*i+16; 10931 } else { 10932 Ops[i*2 ] = 2*i+1; 10933 Ops[i*2+1] = 2*i+1+16; 10934 } 10935 } 10936 if (isLittleEndian) 10937 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10938 else 10939 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10940 } else { 10941 llvm_unreachable("Unknown mul to lower!"); 10942 } 10943 } 10944 10945 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10946 bool IsStrict = Op->isStrictFPOpcode(); 10947 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10948 !Subtarget.hasP9Vector()) 10949 return SDValue(); 10950 10951 return Op; 10952 } 10953 10954 // Custom lowering for fpext vf32 to v2f64 10955 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10956 10957 assert(Op.getOpcode() == ISD::FP_EXTEND && 10958 "Should only be called for ISD::FP_EXTEND"); 10959 10960 // FIXME: handle extends from half precision float vectors on P9. 10961 // We only want to custom lower an extend from v2f32 to v2f64. 10962 if (Op.getValueType() != MVT::v2f64 || 10963 Op.getOperand(0).getValueType() != MVT::v2f32) 10964 return SDValue(); 10965 10966 SDLoc dl(Op); 10967 SDValue Op0 = Op.getOperand(0); 10968 10969 switch (Op0.getOpcode()) { 10970 default: 10971 return SDValue(); 10972 case ISD::EXTRACT_SUBVECTOR: { 10973 assert(Op0.getNumOperands() == 2 && 10974 isa<ConstantSDNode>(Op0->getOperand(1)) && 10975 "Node should have 2 operands with second one being a constant!"); 10976 10977 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10978 return SDValue(); 10979 10980 // Custom lower is only done for high or low doubleword. 10981 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10982 if (Idx % 2 != 0) 10983 return SDValue(); 10984 10985 // Since input is v4f32, at this point Idx is either 0 or 2. 10986 // Shift to get the doubleword position we want. 10987 int DWord = Idx >> 1; 10988 10989 // High and low word positions are different on little endian. 10990 if (Subtarget.isLittleEndian()) 10991 DWord ^= 0x1; 10992 10993 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10994 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10995 } 10996 case ISD::FADD: 10997 case ISD::FMUL: 10998 case ISD::FSUB: { 10999 SDValue NewLoad[2]; 11000 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11001 // Ensure both input are loads. 11002 SDValue LdOp = Op0.getOperand(i); 11003 if (LdOp.getOpcode() != ISD::LOAD) 11004 return SDValue(); 11005 // Generate new load node. 11006 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11007 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11008 NewLoad[i] = DAG.getMemIntrinsicNode( 11009 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11010 LD->getMemoryVT(), LD->getMemOperand()); 11011 } 11012 SDValue NewOp = 11013 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11014 NewLoad[1], Op0.getNode()->getFlags()); 11015 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11016 DAG.getConstant(0, dl, MVT::i32)); 11017 } 11018 case ISD::LOAD: { 11019 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11020 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11021 SDValue NewLd = DAG.getMemIntrinsicNode( 11022 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11023 LD->getMemoryVT(), LD->getMemOperand()); 11024 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11025 DAG.getConstant(0, dl, MVT::i32)); 11026 } 11027 } 11028 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11029 } 11030 11031 /// LowerOperation - Provide custom lowering hooks for some operations. 11032 /// 11033 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11034 switch (Op.getOpcode()) { 11035 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11036 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11037 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11038 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11039 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11040 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11041 case ISD::STRICT_FSETCC: 11042 case ISD::STRICT_FSETCCS: 11043 case ISD::SETCC: return LowerSETCC(Op, DAG); 11044 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11045 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11046 11047 case ISD::INLINEASM: 11048 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 11049 // Variable argument lowering. 11050 case ISD::VASTART: return LowerVASTART(Op, DAG); 11051 case ISD::VAARG: return LowerVAARG(Op, DAG); 11052 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11053 11054 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11055 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11056 case ISD::GET_DYNAMIC_AREA_OFFSET: 11057 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11058 11059 // Exception handling lowering. 11060 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11061 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11062 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11063 11064 case ISD::LOAD: return LowerLOAD(Op, DAG); 11065 case ISD::STORE: return LowerSTORE(Op, DAG); 11066 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11067 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11068 case ISD::STRICT_FP_TO_UINT: 11069 case ISD::STRICT_FP_TO_SINT: 11070 case ISD::FP_TO_UINT: 11071 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11072 case ISD::STRICT_UINT_TO_FP: 11073 case ISD::STRICT_SINT_TO_FP: 11074 case ISD::UINT_TO_FP: 11075 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11076 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11077 11078 // Lower 64-bit shifts. 11079 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11080 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11081 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11082 11083 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11084 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11085 11086 // Vector-related lowering. 11087 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11088 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11089 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11090 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11091 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11092 case ISD::MUL: return LowerMUL(Op, DAG); 11093 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11094 case ISD::STRICT_FP_ROUND: 11095 case ISD::FP_ROUND: 11096 return LowerFP_ROUND(Op, DAG); 11097 case ISD::ROTL: return LowerROTL(Op, DAG); 11098 11099 // For counter-based loop handling. 11100 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11101 11102 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11103 11104 // Frame & Return address. 11105 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11106 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11107 11108 case ISD::INTRINSIC_VOID: 11109 return LowerINTRINSIC_VOID(Op, DAG); 11110 case ISD::BSWAP: 11111 return LowerBSWAP(Op, DAG); 11112 case ISD::ATOMIC_CMP_SWAP: 11113 return LowerATOMIC_CMP_SWAP(Op, DAG); 11114 case ISD::ATOMIC_STORE: 11115 return LowerATOMIC_LOAD_STORE(Op, DAG); 11116 } 11117 } 11118 11119 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11120 SmallVectorImpl<SDValue>&Results, 11121 SelectionDAG &DAG) const { 11122 SDLoc dl(N); 11123 switch (N->getOpcode()) { 11124 default: 11125 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11126 case ISD::ATOMIC_LOAD: { 11127 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG); 11128 Results.push_back(Res); 11129 Results.push_back(Res.getValue(1)); 11130 break; 11131 } 11132 case ISD::READCYCLECOUNTER: { 11133 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11134 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11135 11136 Results.push_back( 11137 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11138 Results.push_back(RTB.getValue(2)); 11139 break; 11140 } 11141 case ISD::INTRINSIC_W_CHAIN: { 11142 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11143 Intrinsic::loop_decrement) 11144 break; 11145 11146 assert(N->getValueType(0) == MVT::i1 && 11147 "Unexpected result type for CTR decrement intrinsic"); 11148 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11149 N->getValueType(0)); 11150 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11151 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11152 N->getOperand(1)); 11153 11154 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11155 Results.push_back(NewInt.getValue(1)); 11156 break; 11157 } 11158 case ISD::INTRINSIC_WO_CHAIN: { 11159 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) { 11160 case Intrinsic::ppc_pack_longdouble: 11161 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 11162 N->getOperand(2), N->getOperand(1))); 11163 break; 11164 case Intrinsic::ppc_convert_f128_to_ppcf128: 11165 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG)); 11166 break; 11167 } 11168 break; 11169 } 11170 case ISD::VAARG: { 11171 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11172 return; 11173 11174 EVT VT = N->getValueType(0); 11175 11176 if (VT == MVT::i64) { 11177 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11178 11179 Results.push_back(NewNode); 11180 Results.push_back(NewNode.getValue(1)); 11181 } 11182 return; 11183 } 11184 case ISD::STRICT_FP_TO_SINT: 11185 case ISD::STRICT_FP_TO_UINT: 11186 case ISD::FP_TO_SINT: 11187 case ISD::FP_TO_UINT: 11188 // LowerFP_TO_INT() can only handle f32 and f64. 11189 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11190 MVT::ppcf128) 11191 return; 11192 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11193 return; 11194 case ISD::TRUNCATE: { 11195 if (!N->getValueType(0).isVector()) 11196 return; 11197 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11198 if (Lowered) 11199 Results.push_back(Lowered); 11200 return; 11201 } 11202 case ISD::FSHL: 11203 case ISD::FSHR: 11204 // Don't handle funnel shifts here. 11205 return; 11206 case ISD::BITCAST: 11207 // Don't handle bitcast here. 11208 return; 11209 case ISD::FP_EXTEND: 11210 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11211 if (Lowered) 11212 Results.push_back(Lowered); 11213 return; 11214 } 11215 } 11216 11217 //===----------------------------------------------------------------------===// 11218 // Other Lowering Code 11219 //===----------------------------------------------------------------------===// 11220 11221 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 11222 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11223 Function *Func = Intrinsic::getDeclaration(M, Id); 11224 return Builder.CreateCall(Func, {}); 11225 } 11226 11227 // The mappings for emitLeading/TrailingFence is taken from 11228 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11229 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11230 Instruction *Inst, 11231 AtomicOrdering Ord) const { 11232 if (Ord == AtomicOrdering::SequentiallyConsistent) 11233 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11234 if (isReleaseOrStronger(Ord)) 11235 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11236 return nullptr; 11237 } 11238 11239 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11240 Instruction *Inst, 11241 AtomicOrdering Ord) const { 11242 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11243 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11244 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11245 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11246 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11247 return Builder.CreateCall( 11248 Intrinsic::getDeclaration( 11249 Builder.GetInsertBlock()->getParent()->getParent(), 11250 Intrinsic::ppc_cfence, {Inst->getType()}), 11251 {Inst}); 11252 // FIXME: Can use isync for rmw operation. 11253 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11254 } 11255 return nullptr; 11256 } 11257 11258 MachineBasicBlock * 11259 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11260 unsigned AtomicSize, 11261 unsigned BinOpcode, 11262 unsigned CmpOpcode, 11263 unsigned CmpPred) const { 11264 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11265 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11266 11267 auto LoadMnemonic = PPC::LDARX; 11268 auto StoreMnemonic = PPC::STDCX; 11269 switch (AtomicSize) { 11270 default: 11271 llvm_unreachable("Unexpected size of atomic entity"); 11272 case 1: 11273 LoadMnemonic = PPC::LBARX; 11274 StoreMnemonic = PPC::STBCX; 11275 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11276 break; 11277 case 2: 11278 LoadMnemonic = PPC::LHARX; 11279 StoreMnemonic = PPC::STHCX; 11280 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11281 break; 11282 case 4: 11283 LoadMnemonic = PPC::LWARX; 11284 StoreMnemonic = PPC::STWCX; 11285 break; 11286 case 8: 11287 LoadMnemonic = PPC::LDARX; 11288 StoreMnemonic = PPC::STDCX; 11289 break; 11290 } 11291 11292 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11293 MachineFunction *F = BB->getParent(); 11294 MachineFunction::iterator It = ++BB->getIterator(); 11295 11296 Register dest = MI.getOperand(0).getReg(); 11297 Register ptrA = MI.getOperand(1).getReg(); 11298 Register ptrB = MI.getOperand(2).getReg(); 11299 Register incr = MI.getOperand(3).getReg(); 11300 DebugLoc dl = MI.getDebugLoc(); 11301 11302 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11303 MachineBasicBlock *loop2MBB = 11304 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11305 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11306 F->insert(It, loopMBB); 11307 if (CmpOpcode) 11308 F->insert(It, loop2MBB); 11309 F->insert(It, exitMBB); 11310 exitMBB->splice(exitMBB->begin(), BB, 11311 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11312 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11313 11314 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11315 Register TmpReg = (!BinOpcode) ? incr : 11316 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11317 : &PPC::GPRCRegClass); 11318 11319 // thisMBB: 11320 // ... 11321 // fallthrough --> loopMBB 11322 BB->addSuccessor(loopMBB); 11323 11324 // loopMBB: 11325 // l[wd]arx dest, ptr 11326 // add r0, dest, incr 11327 // st[wd]cx. r0, ptr 11328 // bne- loopMBB 11329 // fallthrough --> exitMBB 11330 11331 // For max/min... 11332 // loopMBB: 11333 // l[wd]arx dest, ptr 11334 // cmpl?[wd] incr, dest 11335 // bgt exitMBB 11336 // loop2MBB: 11337 // st[wd]cx. dest, ptr 11338 // bne- loopMBB 11339 // fallthrough --> exitMBB 11340 11341 BB = loopMBB; 11342 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11343 .addReg(ptrA).addReg(ptrB); 11344 if (BinOpcode) 11345 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11346 if (CmpOpcode) { 11347 // Signed comparisons of byte or halfword values must be sign-extended. 11348 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11349 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11350 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11351 ExtReg).addReg(dest); 11352 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11353 .addReg(incr).addReg(ExtReg); 11354 } else 11355 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11356 .addReg(incr).addReg(dest); 11357 11358 BuildMI(BB, dl, TII->get(PPC::BCC)) 11359 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11360 BB->addSuccessor(loop2MBB); 11361 BB->addSuccessor(exitMBB); 11362 BB = loop2MBB; 11363 } 11364 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11365 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11366 BuildMI(BB, dl, TII->get(PPC::BCC)) 11367 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11368 BB->addSuccessor(loopMBB); 11369 BB->addSuccessor(exitMBB); 11370 11371 // exitMBB: 11372 // ... 11373 BB = exitMBB; 11374 return BB; 11375 } 11376 11377 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11378 switch(MI.getOpcode()) { 11379 default: 11380 return false; 11381 case PPC::COPY: 11382 return TII->isSignExtended(MI); 11383 case PPC::LHA: 11384 case PPC::LHA8: 11385 case PPC::LHAU: 11386 case PPC::LHAU8: 11387 case PPC::LHAUX: 11388 case PPC::LHAUX8: 11389 case PPC::LHAX: 11390 case PPC::LHAX8: 11391 case PPC::LWA: 11392 case PPC::LWAUX: 11393 case PPC::LWAX: 11394 case PPC::LWAX_32: 11395 case PPC::LWA_32: 11396 case PPC::PLHA: 11397 case PPC::PLHA8: 11398 case PPC::PLHA8pc: 11399 case PPC::PLHApc: 11400 case PPC::PLWA: 11401 case PPC::PLWA8: 11402 case PPC::PLWA8pc: 11403 case PPC::PLWApc: 11404 case PPC::EXTSB: 11405 case PPC::EXTSB8: 11406 case PPC::EXTSB8_32_64: 11407 case PPC::EXTSB8_rec: 11408 case PPC::EXTSB_rec: 11409 case PPC::EXTSH: 11410 case PPC::EXTSH8: 11411 case PPC::EXTSH8_32_64: 11412 case PPC::EXTSH8_rec: 11413 case PPC::EXTSH_rec: 11414 case PPC::EXTSW: 11415 case PPC::EXTSWSLI: 11416 case PPC::EXTSWSLI_32_64: 11417 case PPC::EXTSWSLI_32_64_rec: 11418 case PPC::EXTSWSLI_rec: 11419 case PPC::EXTSW_32: 11420 case PPC::EXTSW_32_64: 11421 case PPC::EXTSW_32_64_rec: 11422 case PPC::EXTSW_rec: 11423 case PPC::SRAW: 11424 case PPC::SRAWI: 11425 case PPC::SRAWI_rec: 11426 case PPC::SRAW_rec: 11427 return true; 11428 } 11429 return false; 11430 } 11431 11432 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11433 MachineInstr &MI, MachineBasicBlock *BB, 11434 bool is8bit, // operation 11435 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11436 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11437 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11438 11439 // If this is a signed comparison and the value being compared is not known 11440 // to be sign extended, sign extend it here. 11441 DebugLoc dl = MI.getDebugLoc(); 11442 MachineFunction *F = BB->getParent(); 11443 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11444 Register incr = MI.getOperand(3).getReg(); 11445 bool IsSignExtended = Register::isVirtualRegister(incr) && 11446 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11447 11448 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11449 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11450 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11451 .addReg(MI.getOperand(3).getReg()); 11452 MI.getOperand(3).setReg(ValueReg); 11453 } 11454 // If we support part-word atomic mnemonics, just use them 11455 if (Subtarget.hasPartwordAtomics()) 11456 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11457 CmpPred); 11458 11459 // In 64 bit mode we have to use 64 bits for addresses, even though the 11460 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11461 // registers without caring whether they're 32 or 64, but here we're 11462 // doing actual arithmetic on the addresses. 11463 bool is64bit = Subtarget.isPPC64(); 11464 bool isLittleEndian = Subtarget.isLittleEndian(); 11465 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11466 11467 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11468 MachineFunction::iterator It = ++BB->getIterator(); 11469 11470 Register dest = MI.getOperand(0).getReg(); 11471 Register ptrA = MI.getOperand(1).getReg(); 11472 Register ptrB = MI.getOperand(2).getReg(); 11473 11474 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11475 MachineBasicBlock *loop2MBB = 11476 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11477 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11478 F->insert(It, loopMBB); 11479 if (CmpOpcode) 11480 F->insert(It, loop2MBB); 11481 F->insert(It, exitMBB); 11482 exitMBB->splice(exitMBB->begin(), BB, 11483 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11484 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11485 11486 const TargetRegisterClass *RC = 11487 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11488 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11489 11490 Register PtrReg = RegInfo.createVirtualRegister(RC); 11491 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11492 Register ShiftReg = 11493 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11494 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11495 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11496 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11497 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11498 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11499 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11500 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11501 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11502 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11503 Register Ptr1Reg; 11504 Register TmpReg = 11505 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11506 11507 // thisMBB: 11508 // ... 11509 // fallthrough --> loopMBB 11510 BB->addSuccessor(loopMBB); 11511 11512 // The 4-byte load must be aligned, while a char or short may be 11513 // anywhere in the word. Hence all this nasty bookkeeping code. 11514 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11515 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11516 // xori shift, shift1, 24 [16] 11517 // rlwinm ptr, ptr1, 0, 0, 29 11518 // slw incr2, incr, shift 11519 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11520 // slw mask, mask2, shift 11521 // loopMBB: 11522 // lwarx tmpDest, ptr 11523 // add tmp, tmpDest, incr2 11524 // andc tmp2, tmpDest, mask 11525 // and tmp3, tmp, mask 11526 // or tmp4, tmp3, tmp2 11527 // stwcx. tmp4, ptr 11528 // bne- loopMBB 11529 // fallthrough --> exitMBB 11530 // srw SrwDest, tmpDest, shift 11531 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11532 if (ptrA != ZeroReg) { 11533 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11534 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11535 .addReg(ptrA) 11536 .addReg(ptrB); 11537 } else { 11538 Ptr1Reg = ptrB; 11539 } 11540 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11541 // mode. 11542 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11543 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11544 .addImm(3) 11545 .addImm(27) 11546 .addImm(is8bit ? 28 : 27); 11547 if (!isLittleEndian) 11548 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11549 .addReg(Shift1Reg) 11550 .addImm(is8bit ? 24 : 16); 11551 if (is64bit) 11552 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11553 .addReg(Ptr1Reg) 11554 .addImm(0) 11555 .addImm(61); 11556 else 11557 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11558 .addReg(Ptr1Reg) 11559 .addImm(0) 11560 .addImm(0) 11561 .addImm(29); 11562 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11563 if (is8bit) 11564 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11565 else { 11566 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11567 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11568 .addReg(Mask3Reg) 11569 .addImm(65535); 11570 } 11571 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11572 .addReg(Mask2Reg) 11573 .addReg(ShiftReg); 11574 11575 BB = loopMBB; 11576 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11577 .addReg(ZeroReg) 11578 .addReg(PtrReg); 11579 if (BinOpcode) 11580 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11581 .addReg(Incr2Reg) 11582 .addReg(TmpDestReg); 11583 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11584 .addReg(TmpDestReg) 11585 .addReg(MaskReg); 11586 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11587 if (CmpOpcode) { 11588 // For unsigned comparisons, we can directly compare the shifted values. 11589 // For signed comparisons we shift and sign extend. 11590 Register SReg = RegInfo.createVirtualRegister(GPRC); 11591 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11592 .addReg(TmpDestReg) 11593 .addReg(MaskReg); 11594 unsigned ValueReg = SReg; 11595 unsigned CmpReg = Incr2Reg; 11596 if (CmpOpcode == PPC::CMPW) { 11597 ValueReg = RegInfo.createVirtualRegister(GPRC); 11598 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11599 .addReg(SReg) 11600 .addReg(ShiftReg); 11601 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11602 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11603 .addReg(ValueReg); 11604 ValueReg = ValueSReg; 11605 CmpReg = incr; 11606 } 11607 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11608 .addReg(CmpReg) 11609 .addReg(ValueReg); 11610 BuildMI(BB, dl, TII->get(PPC::BCC)) 11611 .addImm(CmpPred) 11612 .addReg(PPC::CR0) 11613 .addMBB(exitMBB); 11614 BB->addSuccessor(loop2MBB); 11615 BB->addSuccessor(exitMBB); 11616 BB = loop2MBB; 11617 } 11618 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11619 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11620 .addReg(Tmp4Reg) 11621 .addReg(ZeroReg) 11622 .addReg(PtrReg); 11623 BuildMI(BB, dl, TII->get(PPC::BCC)) 11624 .addImm(PPC::PRED_NE) 11625 .addReg(PPC::CR0) 11626 .addMBB(loopMBB); 11627 BB->addSuccessor(loopMBB); 11628 BB->addSuccessor(exitMBB); 11629 11630 // exitMBB: 11631 // ... 11632 BB = exitMBB; 11633 // Since the shift amount is not a constant, we need to clear 11634 // the upper bits with a separate RLWINM. 11635 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11636 .addReg(SrwDestReg) 11637 .addImm(0) 11638 .addImm(is8bit ? 24 : 16) 11639 .addImm(31); 11640 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11641 .addReg(TmpDestReg) 11642 .addReg(ShiftReg); 11643 return BB; 11644 } 11645 11646 llvm::MachineBasicBlock * 11647 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11648 MachineBasicBlock *MBB) const { 11649 DebugLoc DL = MI.getDebugLoc(); 11650 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11651 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11652 11653 MachineFunction *MF = MBB->getParent(); 11654 MachineRegisterInfo &MRI = MF->getRegInfo(); 11655 11656 const BasicBlock *BB = MBB->getBasicBlock(); 11657 MachineFunction::iterator I = ++MBB->getIterator(); 11658 11659 Register DstReg = MI.getOperand(0).getReg(); 11660 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11661 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11662 Register mainDstReg = MRI.createVirtualRegister(RC); 11663 Register restoreDstReg = MRI.createVirtualRegister(RC); 11664 11665 MVT PVT = getPointerTy(MF->getDataLayout()); 11666 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11667 "Invalid Pointer Size!"); 11668 // For v = setjmp(buf), we generate 11669 // 11670 // thisMBB: 11671 // SjLjSetup mainMBB 11672 // bl mainMBB 11673 // v_restore = 1 11674 // b sinkMBB 11675 // 11676 // mainMBB: 11677 // buf[LabelOffset] = LR 11678 // v_main = 0 11679 // 11680 // sinkMBB: 11681 // v = phi(main, restore) 11682 // 11683 11684 MachineBasicBlock *thisMBB = MBB; 11685 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11686 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11687 MF->insert(I, mainMBB); 11688 MF->insert(I, sinkMBB); 11689 11690 MachineInstrBuilder MIB; 11691 11692 // Transfer the remainder of BB and its successor edges to sinkMBB. 11693 sinkMBB->splice(sinkMBB->begin(), MBB, 11694 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11695 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11696 11697 // Note that the structure of the jmp_buf used here is not compatible 11698 // with that used by libc, and is not designed to be. Specifically, it 11699 // stores only those 'reserved' registers that LLVM does not otherwise 11700 // understand how to spill. Also, by convention, by the time this 11701 // intrinsic is called, Clang has already stored the frame address in the 11702 // first slot of the buffer and stack address in the third. Following the 11703 // X86 target code, we'll store the jump address in the second slot. We also 11704 // need to save the TOC pointer (R2) to handle jumps between shared 11705 // libraries, and that will be stored in the fourth slot. The thread 11706 // identifier (R13) is not affected. 11707 11708 // thisMBB: 11709 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11710 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11711 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11712 11713 // Prepare IP either in reg. 11714 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11715 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11716 Register BufReg = MI.getOperand(1).getReg(); 11717 11718 if (Subtarget.is64BitELFABI()) { 11719 setUsesTOCBasePtr(*MBB->getParent()); 11720 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11721 .addReg(PPC::X2) 11722 .addImm(TOCOffset) 11723 .addReg(BufReg) 11724 .cloneMemRefs(MI); 11725 } 11726 11727 // Naked functions never have a base pointer, and so we use r1. For all 11728 // other functions, this decision must be delayed until during PEI. 11729 unsigned BaseReg; 11730 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11731 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11732 else 11733 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11734 11735 MIB = BuildMI(*thisMBB, MI, DL, 11736 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11737 .addReg(BaseReg) 11738 .addImm(BPOffset) 11739 .addReg(BufReg) 11740 .cloneMemRefs(MI); 11741 11742 // Setup 11743 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11744 MIB.addRegMask(TRI->getNoPreservedMask()); 11745 11746 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11747 11748 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11749 .addMBB(mainMBB); 11750 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11751 11752 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11753 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11754 11755 // mainMBB: 11756 // mainDstReg = 0 11757 MIB = 11758 BuildMI(mainMBB, DL, 11759 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11760 11761 // Store IP 11762 if (Subtarget.isPPC64()) { 11763 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11764 .addReg(LabelReg) 11765 .addImm(LabelOffset) 11766 .addReg(BufReg); 11767 } else { 11768 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11769 .addReg(LabelReg) 11770 .addImm(LabelOffset) 11771 .addReg(BufReg); 11772 } 11773 MIB.cloneMemRefs(MI); 11774 11775 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11776 mainMBB->addSuccessor(sinkMBB); 11777 11778 // sinkMBB: 11779 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11780 TII->get(PPC::PHI), DstReg) 11781 .addReg(mainDstReg).addMBB(mainMBB) 11782 .addReg(restoreDstReg).addMBB(thisMBB); 11783 11784 MI.eraseFromParent(); 11785 return sinkMBB; 11786 } 11787 11788 MachineBasicBlock * 11789 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11790 MachineBasicBlock *MBB) const { 11791 DebugLoc DL = MI.getDebugLoc(); 11792 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11793 11794 MachineFunction *MF = MBB->getParent(); 11795 MachineRegisterInfo &MRI = MF->getRegInfo(); 11796 11797 MVT PVT = getPointerTy(MF->getDataLayout()); 11798 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11799 "Invalid Pointer Size!"); 11800 11801 const TargetRegisterClass *RC = 11802 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11803 Register Tmp = MRI.createVirtualRegister(RC); 11804 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11805 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11806 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11807 unsigned BP = 11808 (PVT == MVT::i64) 11809 ? PPC::X30 11810 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11811 : PPC::R30); 11812 11813 MachineInstrBuilder MIB; 11814 11815 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11816 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11817 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11818 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11819 11820 Register BufReg = MI.getOperand(0).getReg(); 11821 11822 // Reload FP (the jumped-to function may not have had a 11823 // frame pointer, and if so, then its r31 will be restored 11824 // as necessary). 11825 if (PVT == MVT::i64) { 11826 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11827 .addImm(0) 11828 .addReg(BufReg); 11829 } else { 11830 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11831 .addImm(0) 11832 .addReg(BufReg); 11833 } 11834 MIB.cloneMemRefs(MI); 11835 11836 // Reload IP 11837 if (PVT == MVT::i64) { 11838 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11839 .addImm(LabelOffset) 11840 .addReg(BufReg); 11841 } else { 11842 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11843 .addImm(LabelOffset) 11844 .addReg(BufReg); 11845 } 11846 MIB.cloneMemRefs(MI); 11847 11848 // Reload SP 11849 if (PVT == MVT::i64) { 11850 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11851 .addImm(SPOffset) 11852 .addReg(BufReg); 11853 } else { 11854 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11855 .addImm(SPOffset) 11856 .addReg(BufReg); 11857 } 11858 MIB.cloneMemRefs(MI); 11859 11860 // Reload BP 11861 if (PVT == MVT::i64) { 11862 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11863 .addImm(BPOffset) 11864 .addReg(BufReg); 11865 } else { 11866 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11867 .addImm(BPOffset) 11868 .addReg(BufReg); 11869 } 11870 MIB.cloneMemRefs(MI); 11871 11872 // Reload TOC 11873 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11874 setUsesTOCBasePtr(*MBB->getParent()); 11875 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11876 .addImm(TOCOffset) 11877 .addReg(BufReg) 11878 .cloneMemRefs(MI); 11879 } 11880 11881 // Jump 11882 BuildMI(*MBB, MI, DL, 11883 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11884 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11885 11886 MI.eraseFromParent(); 11887 return MBB; 11888 } 11889 11890 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11891 // If the function specifically requests inline stack probes, emit them. 11892 if (MF.getFunction().hasFnAttribute("probe-stack")) 11893 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11894 "inline-asm"; 11895 return false; 11896 } 11897 11898 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11899 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11900 unsigned StackAlign = TFI->getStackAlignment(); 11901 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11902 "Unexpected stack alignment"); 11903 // The default stack probe size is 4096 if the function has no 11904 // stack-probe-size attribute. 11905 unsigned StackProbeSize = 4096; 11906 const Function &Fn = MF.getFunction(); 11907 if (Fn.hasFnAttribute("stack-probe-size")) 11908 Fn.getFnAttribute("stack-probe-size") 11909 .getValueAsString() 11910 .getAsInteger(0, StackProbeSize); 11911 // Round down to the stack alignment. 11912 StackProbeSize &= ~(StackAlign - 1); 11913 return StackProbeSize ? StackProbeSize : StackAlign; 11914 } 11915 11916 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11917 // into three phases. In the first phase, it uses pseudo instruction 11918 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11919 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11920 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11921 // MaxCallFrameSize so that it can calculate correct data area pointer. 11922 MachineBasicBlock * 11923 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11924 MachineBasicBlock *MBB) const { 11925 const bool isPPC64 = Subtarget.isPPC64(); 11926 MachineFunction *MF = MBB->getParent(); 11927 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11928 DebugLoc DL = MI.getDebugLoc(); 11929 const unsigned ProbeSize = getStackProbeSize(*MF); 11930 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11931 MachineRegisterInfo &MRI = MF->getRegInfo(); 11932 // The CFG of probing stack looks as 11933 // +-----+ 11934 // | MBB | 11935 // +--+--+ 11936 // | 11937 // +----v----+ 11938 // +--->+ TestMBB +---+ 11939 // | +----+----+ | 11940 // | | | 11941 // | +-----v----+ | 11942 // +---+ BlockMBB | | 11943 // +----------+ | 11944 // | 11945 // +---------+ | 11946 // | TailMBB +<--+ 11947 // +---------+ 11948 // In MBB, calculate previous frame pointer and final stack pointer. 11949 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11950 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11951 // TailMBB is spliced via \p MI. 11952 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11953 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11954 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11955 11956 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11957 MF->insert(MBBIter, TestMBB); 11958 MF->insert(MBBIter, BlockMBB); 11959 MF->insert(MBBIter, TailMBB); 11960 11961 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11962 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11963 11964 Register DstReg = MI.getOperand(0).getReg(); 11965 Register NegSizeReg = MI.getOperand(1).getReg(); 11966 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11967 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11968 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11969 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11970 11971 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11972 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11973 // NegSize. 11974 unsigned ProbeOpc; 11975 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11976 ProbeOpc = 11977 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11978 else 11979 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11980 // and NegSizeReg will be allocated in the same phyreg to avoid 11981 // redundant copy when NegSizeReg has only one use which is current MI and 11982 // will be replaced by PREPARE_PROBED_ALLOCA then. 11983 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11984 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11985 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11986 .addDef(ActualNegSizeReg) 11987 .addReg(NegSizeReg) 11988 .add(MI.getOperand(2)) 11989 .add(MI.getOperand(3)); 11990 11991 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11992 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11993 FinalStackPtr) 11994 .addReg(SPReg) 11995 .addReg(ActualNegSizeReg); 11996 11997 // Materialize a scratch register for update. 11998 int64_t NegProbeSize = -(int64_t)ProbeSize; 11999 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 12000 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12001 if (!isInt<16>(NegProbeSize)) { 12002 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12003 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 12004 .addImm(NegProbeSize >> 16); 12005 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 12006 ScratchReg) 12007 .addReg(TempReg) 12008 .addImm(NegProbeSize & 0xFFFF); 12009 } else 12010 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 12011 .addImm(NegProbeSize); 12012 12013 { 12014 // Probing leading residual part. 12015 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12016 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 12017 .addReg(ActualNegSizeReg) 12018 .addReg(ScratchReg); 12019 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12020 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 12021 .addReg(Div) 12022 .addReg(ScratchReg); 12023 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12024 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 12025 .addReg(Mul) 12026 .addReg(ActualNegSizeReg); 12027 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12028 .addReg(FramePointer) 12029 .addReg(SPReg) 12030 .addReg(NegMod); 12031 } 12032 12033 { 12034 // Remaining part should be multiple of ProbeSize. 12035 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 12036 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 12037 .addReg(SPReg) 12038 .addReg(FinalStackPtr); 12039 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 12040 .addImm(PPC::PRED_EQ) 12041 .addReg(CmpResult) 12042 .addMBB(TailMBB); 12043 TestMBB->addSuccessor(BlockMBB); 12044 TestMBB->addSuccessor(TailMBB); 12045 } 12046 12047 { 12048 // Touch the block. 12049 // |P...|P...|P... 12050 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12051 .addReg(FramePointer) 12052 .addReg(SPReg) 12053 .addReg(ScratchReg); 12054 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 12055 BlockMBB->addSuccessor(TestMBB); 12056 } 12057 12058 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 12059 // DYNAREAOFFSET pseudo instruction to get the future result. 12060 Register MaxCallFrameSizeReg = 12061 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12062 BuildMI(TailMBB, DL, 12063 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 12064 MaxCallFrameSizeReg) 12065 .add(MI.getOperand(2)) 12066 .add(MI.getOperand(3)); 12067 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 12068 .addReg(SPReg) 12069 .addReg(MaxCallFrameSizeReg); 12070 12071 // Splice instructions after MI to TailMBB. 12072 TailMBB->splice(TailMBB->end(), MBB, 12073 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12074 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 12075 MBB->addSuccessor(TestMBB); 12076 12077 // Delete the pseudo instruction. 12078 MI.eraseFromParent(); 12079 12080 ++NumDynamicAllocaProbed; 12081 return TailMBB; 12082 } 12083 12084 MachineBasicBlock * 12085 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12086 MachineBasicBlock *BB) const { 12087 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12088 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12089 if (Subtarget.is64BitELFABI() && 12090 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12091 !Subtarget.isUsingPCRelativeCalls()) { 12092 // Call lowering should have added an r2 operand to indicate a dependence 12093 // on the TOC base pointer value. It can't however, because there is no 12094 // way to mark the dependence as implicit there, and so the stackmap code 12095 // will confuse it with a regular operand. Instead, add the dependence 12096 // here. 12097 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12098 } 12099 12100 return emitPatchPoint(MI, BB); 12101 } 12102 12103 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12104 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12105 return emitEHSjLjSetJmp(MI, BB); 12106 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12107 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12108 return emitEHSjLjLongJmp(MI, BB); 12109 } 12110 12111 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12112 12113 // To "insert" these instructions we actually have to insert their 12114 // control-flow patterns. 12115 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12116 MachineFunction::iterator It = ++BB->getIterator(); 12117 12118 MachineFunction *F = BB->getParent(); 12119 12120 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12121 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12122 MI.getOpcode() == PPC::SELECT_I8) { 12123 SmallVector<MachineOperand, 2> Cond; 12124 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12125 MI.getOpcode() == PPC::SELECT_CC_I8) 12126 Cond.push_back(MI.getOperand(4)); 12127 else 12128 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12129 Cond.push_back(MI.getOperand(1)); 12130 12131 DebugLoc dl = MI.getDebugLoc(); 12132 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12133 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12134 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12135 MI.getOpcode() == PPC::SELECT_CC_F8 || 12136 MI.getOpcode() == PPC::SELECT_CC_F16 || 12137 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12138 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12139 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12140 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12141 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12142 MI.getOpcode() == PPC::SELECT_CC_SPE || 12143 MI.getOpcode() == PPC::SELECT_F4 || 12144 MI.getOpcode() == PPC::SELECT_F8 || 12145 MI.getOpcode() == PPC::SELECT_F16 || 12146 MI.getOpcode() == PPC::SELECT_SPE || 12147 MI.getOpcode() == PPC::SELECT_SPE4 || 12148 MI.getOpcode() == PPC::SELECT_VRRC || 12149 MI.getOpcode() == PPC::SELECT_VSFRC || 12150 MI.getOpcode() == PPC::SELECT_VSSRC || 12151 MI.getOpcode() == PPC::SELECT_VSRC) { 12152 // The incoming instruction knows the destination vreg to set, the 12153 // condition code register to branch on, the true/false values to 12154 // select between, and a branch opcode to use. 12155 12156 // thisMBB: 12157 // ... 12158 // TrueVal = ... 12159 // cmpTY ccX, r1, r2 12160 // bCC copy1MBB 12161 // fallthrough --> copy0MBB 12162 MachineBasicBlock *thisMBB = BB; 12163 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12164 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12165 DebugLoc dl = MI.getDebugLoc(); 12166 F->insert(It, copy0MBB); 12167 F->insert(It, sinkMBB); 12168 12169 // Transfer the remainder of BB and its successor edges to sinkMBB. 12170 sinkMBB->splice(sinkMBB->begin(), BB, 12171 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12172 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12173 12174 // Next, add the true and fallthrough blocks as its successors. 12175 BB->addSuccessor(copy0MBB); 12176 BB->addSuccessor(sinkMBB); 12177 12178 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12179 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12180 MI.getOpcode() == PPC::SELECT_F16 || 12181 MI.getOpcode() == PPC::SELECT_SPE4 || 12182 MI.getOpcode() == PPC::SELECT_SPE || 12183 MI.getOpcode() == PPC::SELECT_VRRC || 12184 MI.getOpcode() == PPC::SELECT_VSFRC || 12185 MI.getOpcode() == PPC::SELECT_VSSRC || 12186 MI.getOpcode() == PPC::SELECT_VSRC) { 12187 BuildMI(BB, dl, TII->get(PPC::BC)) 12188 .addReg(MI.getOperand(1).getReg()) 12189 .addMBB(sinkMBB); 12190 } else { 12191 unsigned SelectPred = MI.getOperand(4).getImm(); 12192 BuildMI(BB, dl, TII->get(PPC::BCC)) 12193 .addImm(SelectPred) 12194 .addReg(MI.getOperand(1).getReg()) 12195 .addMBB(sinkMBB); 12196 } 12197 12198 // copy0MBB: 12199 // %FalseValue = ... 12200 // # fallthrough to sinkMBB 12201 BB = copy0MBB; 12202 12203 // Update machine-CFG edges 12204 BB->addSuccessor(sinkMBB); 12205 12206 // sinkMBB: 12207 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12208 // ... 12209 BB = sinkMBB; 12210 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12211 .addReg(MI.getOperand(3).getReg()) 12212 .addMBB(copy0MBB) 12213 .addReg(MI.getOperand(2).getReg()) 12214 .addMBB(thisMBB); 12215 } else if (MI.getOpcode() == PPC::ReadTB) { 12216 // To read the 64-bit time-base register on a 32-bit target, we read the 12217 // two halves. Should the counter have wrapped while it was being read, we 12218 // need to try again. 12219 // ... 12220 // readLoop: 12221 // mfspr Rx,TBU # load from TBU 12222 // mfspr Ry,TB # load from TB 12223 // mfspr Rz,TBU # load from TBU 12224 // cmpw crX,Rx,Rz # check if 'old'='new' 12225 // bne readLoop # branch if they're not equal 12226 // ... 12227 12228 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12229 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12230 DebugLoc dl = MI.getDebugLoc(); 12231 F->insert(It, readMBB); 12232 F->insert(It, sinkMBB); 12233 12234 // Transfer the remainder of BB and its successor edges to sinkMBB. 12235 sinkMBB->splice(sinkMBB->begin(), BB, 12236 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12237 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12238 12239 BB->addSuccessor(readMBB); 12240 BB = readMBB; 12241 12242 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12243 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12244 Register LoReg = MI.getOperand(0).getReg(); 12245 Register HiReg = MI.getOperand(1).getReg(); 12246 12247 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12248 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12249 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12250 12251 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12252 12253 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12254 .addReg(HiReg) 12255 .addReg(ReadAgainReg); 12256 BuildMI(BB, dl, TII->get(PPC::BCC)) 12257 .addImm(PPC::PRED_NE) 12258 .addReg(CmpReg) 12259 .addMBB(readMBB); 12260 12261 BB->addSuccessor(readMBB); 12262 BB->addSuccessor(sinkMBB); 12263 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12264 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12265 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12266 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12267 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12268 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12269 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12270 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12271 12272 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12273 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12274 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12275 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12276 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12277 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12278 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12279 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12280 12281 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12282 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12283 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12284 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12285 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12286 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12287 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12288 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12289 12290 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12291 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12292 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12293 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12294 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12295 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12296 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12297 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12298 12299 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12300 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12301 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12302 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12303 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12304 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12305 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12306 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12307 12308 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12309 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12310 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12311 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12312 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12313 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12314 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12315 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12316 12317 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12318 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12319 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12320 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12321 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12322 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12323 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12324 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12325 12326 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12327 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12328 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12329 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12330 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12331 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12332 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12333 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12334 12335 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12336 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12337 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12338 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12339 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12340 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12341 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12342 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12343 12344 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12345 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12346 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12347 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12348 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12349 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12350 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12351 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12352 12353 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12354 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12355 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12356 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12357 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12358 BB = EmitAtomicBinary(MI, BB, 4, 0); 12359 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12360 BB = EmitAtomicBinary(MI, BB, 8, 0); 12361 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12362 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12363 (Subtarget.hasPartwordAtomics() && 12364 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12365 (Subtarget.hasPartwordAtomics() && 12366 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12367 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12368 12369 auto LoadMnemonic = PPC::LDARX; 12370 auto StoreMnemonic = PPC::STDCX; 12371 switch (MI.getOpcode()) { 12372 default: 12373 llvm_unreachable("Compare and swap of unknown size"); 12374 case PPC::ATOMIC_CMP_SWAP_I8: 12375 LoadMnemonic = PPC::LBARX; 12376 StoreMnemonic = PPC::STBCX; 12377 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12378 break; 12379 case PPC::ATOMIC_CMP_SWAP_I16: 12380 LoadMnemonic = PPC::LHARX; 12381 StoreMnemonic = PPC::STHCX; 12382 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12383 break; 12384 case PPC::ATOMIC_CMP_SWAP_I32: 12385 LoadMnemonic = PPC::LWARX; 12386 StoreMnemonic = PPC::STWCX; 12387 break; 12388 case PPC::ATOMIC_CMP_SWAP_I64: 12389 LoadMnemonic = PPC::LDARX; 12390 StoreMnemonic = PPC::STDCX; 12391 break; 12392 } 12393 Register dest = MI.getOperand(0).getReg(); 12394 Register ptrA = MI.getOperand(1).getReg(); 12395 Register ptrB = MI.getOperand(2).getReg(); 12396 Register oldval = MI.getOperand(3).getReg(); 12397 Register newval = MI.getOperand(4).getReg(); 12398 DebugLoc dl = MI.getDebugLoc(); 12399 12400 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12401 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12402 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12403 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12404 F->insert(It, loop1MBB); 12405 F->insert(It, loop2MBB); 12406 F->insert(It, midMBB); 12407 F->insert(It, exitMBB); 12408 exitMBB->splice(exitMBB->begin(), BB, 12409 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12410 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12411 12412 // thisMBB: 12413 // ... 12414 // fallthrough --> loopMBB 12415 BB->addSuccessor(loop1MBB); 12416 12417 // loop1MBB: 12418 // l[bhwd]arx dest, ptr 12419 // cmp[wd] dest, oldval 12420 // bne- midMBB 12421 // loop2MBB: 12422 // st[bhwd]cx. newval, ptr 12423 // bne- loopMBB 12424 // b exitBB 12425 // midMBB: 12426 // st[bhwd]cx. dest, ptr 12427 // exitBB: 12428 BB = loop1MBB; 12429 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12430 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12431 .addReg(oldval) 12432 .addReg(dest); 12433 BuildMI(BB, dl, TII->get(PPC::BCC)) 12434 .addImm(PPC::PRED_NE) 12435 .addReg(PPC::CR0) 12436 .addMBB(midMBB); 12437 BB->addSuccessor(loop2MBB); 12438 BB->addSuccessor(midMBB); 12439 12440 BB = loop2MBB; 12441 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12442 .addReg(newval) 12443 .addReg(ptrA) 12444 .addReg(ptrB); 12445 BuildMI(BB, dl, TII->get(PPC::BCC)) 12446 .addImm(PPC::PRED_NE) 12447 .addReg(PPC::CR0) 12448 .addMBB(loop1MBB); 12449 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12450 BB->addSuccessor(loop1MBB); 12451 BB->addSuccessor(exitMBB); 12452 12453 BB = midMBB; 12454 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12455 .addReg(dest) 12456 .addReg(ptrA) 12457 .addReg(ptrB); 12458 BB->addSuccessor(exitMBB); 12459 12460 // exitMBB: 12461 // ... 12462 BB = exitMBB; 12463 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12464 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12465 // We must use 64-bit registers for addresses when targeting 64-bit, 12466 // since we're actually doing arithmetic on them. Other registers 12467 // can be 32-bit. 12468 bool is64bit = Subtarget.isPPC64(); 12469 bool isLittleEndian = Subtarget.isLittleEndian(); 12470 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12471 12472 Register dest = MI.getOperand(0).getReg(); 12473 Register ptrA = MI.getOperand(1).getReg(); 12474 Register ptrB = MI.getOperand(2).getReg(); 12475 Register oldval = MI.getOperand(3).getReg(); 12476 Register newval = MI.getOperand(4).getReg(); 12477 DebugLoc dl = MI.getDebugLoc(); 12478 12479 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12480 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12481 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12482 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12483 F->insert(It, loop1MBB); 12484 F->insert(It, loop2MBB); 12485 F->insert(It, midMBB); 12486 F->insert(It, exitMBB); 12487 exitMBB->splice(exitMBB->begin(), BB, 12488 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12489 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12490 12491 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12492 const TargetRegisterClass *RC = 12493 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12494 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12495 12496 Register PtrReg = RegInfo.createVirtualRegister(RC); 12497 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12498 Register ShiftReg = 12499 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12500 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12501 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12502 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12503 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12504 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12505 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12506 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12507 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12508 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12509 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12510 Register Ptr1Reg; 12511 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12512 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12513 // thisMBB: 12514 // ... 12515 // fallthrough --> loopMBB 12516 BB->addSuccessor(loop1MBB); 12517 12518 // The 4-byte load must be aligned, while a char or short may be 12519 // anywhere in the word. Hence all this nasty bookkeeping code. 12520 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12521 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12522 // xori shift, shift1, 24 [16] 12523 // rlwinm ptr, ptr1, 0, 0, 29 12524 // slw newval2, newval, shift 12525 // slw oldval2, oldval,shift 12526 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12527 // slw mask, mask2, shift 12528 // and newval3, newval2, mask 12529 // and oldval3, oldval2, mask 12530 // loop1MBB: 12531 // lwarx tmpDest, ptr 12532 // and tmp, tmpDest, mask 12533 // cmpw tmp, oldval3 12534 // bne- midMBB 12535 // loop2MBB: 12536 // andc tmp2, tmpDest, mask 12537 // or tmp4, tmp2, newval3 12538 // stwcx. tmp4, ptr 12539 // bne- loop1MBB 12540 // b exitBB 12541 // midMBB: 12542 // stwcx. tmpDest, ptr 12543 // exitBB: 12544 // srw dest, tmpDest, shift 12545 if (ptrA != ZeroReg) { 12546 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12547 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12548 .addReg(ptrA) 12549 .addReg(ptrB); 12550 } else { 12551 Ptr1Reg = ptrB; 12552 } 12553 12554 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12555 // mode. 12556 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12557 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12558 .addImm(3) 12559 .addImm(27) 12560 .addImm(is8bit ? 28 : 27); 12561 if (!isLittleEndian) 12562 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12563 .addReg(Shift1Reg) 12564 .addImm(is8bit ? 24 : 16); 12565 if (is64bit) 12566 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12567 .addReg(Ptr1Reg) 12568 .addImm(0) 12569 .addImm(61); 12570 else 12571 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12572 .addReg(Ptr1Reg) 12573 .addImm(0) 12574 .addImm(0) 12575 .addImm(29); 12576 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12577 .addReg(newval) 12578 .addReg(ShiftReg); 12579 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12580 .addReg(oldval) 12581 .addReg(ShiftReg); 12582 if (is8bit) 12583 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12584 else { 12585 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12586 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12587 .addReg(Mask3Reg) 12588 .addImm(65535); 12589 } 12590 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12591 .addReg(Mask2Reg) 12592 .addReg(ShiftReg); 12593 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12594 .addReg(NewVal2Reg) 12595 .addReg(MaskReg); 12596 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12597 .addReg(OldVal2Reg) 12598 .addReg(MaskReg); 12599 12600 BB = loop1MBB; 12601 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12602 .addReg(ZeroReg) 12603 .addReg(PtrReg); 12604 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12605 .addReg(TmpDestReg) 12606 .addReg(MaskReg); 12607 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12608 .addReg(TmpReg) 12609 .addReg(OldVal3Reg); 12610 BuildMI(BB, dl, TII->get(PPC::BCC)) 12611 .addImm(PPC::PRED_NE) 12612 .addReg(PPC::CR0) 12613 .addMBB(midMBB); 12614 BB->addSuccessor(loop2MBB); 12615 BB->addSuccessor(midMBB); 12616 12617 BB = loop2MBB; 12618 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12619 .addReg(TmpDestReg) 12620 .addReg(MaskReg); 12621 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12622 .addReg(Tmp2Reg) 12623 .addReg(NewVal3Reg); 12624 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12625 .addReg(Tmp4Reg) 12626 .addReg(ZeroReg) 12627 .addReg(PtrReg); 12628 BuildMI(BB, dl, TII->get(PPC::BCC)) 12629 .addImm(PPC::PRED_NE) 12630 .addReg(PPC::CR0) 12631 .addMBB(loop1MBB); 12632 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12633 BB->addSuccessor(loop1MBB); 12634 BB->addSuccessor(exitMBB); 12635 12636 BB = midMBB; 12637 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12638 .addReg(TmpDestReg) 12639 .addReg(ZeroReg) 12640 .addReg(PtrReg); 12641 BB->addSuccessor(exitMBB); 12642 12643 // exitMBB: 12644 // ... 12645 BB = exitMBB; 12646 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12647 .addReg(TmpReg) 12648 .addReg(ShiftReg); 12649 } else if (MI.getOpcode() == PPC::FADDrtz) { 12650 // This pseudo performs an FADD with rounding mode temporarily forced 12651 // to round-to-zero. We emit this via custom inserter since the FPSCR 12652 // is not modeled at the SelectionDAG level. 12653 Register Dest = MI.getOperand(0).getReg(); 12654 Register Src1 = MI.getOperand(1).getReg(); 12655 Register Src2 = MI.getOperand(2).getReg(); 12656 DebugLoc dl = MI.getDebugLoc(); 12657 12658 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12659 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12660 12661 // Save FPSCR value. 12662 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12663 12664 // Set rounding mode to round-to-zero. 12665 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12666 .addImm(31) 12667 .addReg(PPC::RM, RegState::ImplicitDefine); 12668 12669 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12670 .addImm(30) 12671 .addReg(PPC::RM, RegState::ImplicitDefine); 12672 12673 // Perform addition. 12674 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12675 .addReg(Src1) 12676 .addReg(Src2); 12677 if (MI.getFlag(MachineInstr::NoFPExcept)) 12678 MIB.setMIFlag(MachineInstr::NoFPExcept); 12679 12680 // Restore FPSCR value. 12681 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12682 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12683 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12684 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12685 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12686 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12687 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12688 ? PPC::ANDI8_rec 12689 : PPC::ANDI_rec; 12690 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12691 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12692 12693 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12694 Register Dest = RegInfo.createVirtualRegister( 12695 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12696 12697 DebugLoc Dl = MI.getDebugLoc(); 12698 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12699 .addReg(MI.getOperand(1).getReg()) 12700 .addImm(1); 12701 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12702 MI.getOperand(0).getReg()) 12703 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12704 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12705 DebugLoc Dl = MI.getDebugLoc(); 12706 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12707 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12708 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12709 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12710 MI.getOperand(0).getReg()) 12711 .addReg(CRReg); 12712 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12713 DebugLoc Dl = MI.getDebugLoc(); 12714 unsigned Imm = MI.getOperand(1).getImm(); 12715 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12716 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12717 MI.getOperand(0).getReg()) 12718 .addReg(PPC::CR0EQ); 12719 } else if (MI.getOpcode() == PPC::SETRNDi) { 12720 DebugLoc dl = MI.getDebugLoc(); 12721 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12722 12723 // Save FPSCR value. 12724 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12725 12726 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12727 // the following settings: 12728 // 00 Round to nearest 12729 // 01 Round to 0 12730 // 10 Round to +inf 12731 // 11 Round to -inf 12732 12733 // When the operand is immediate, using the two least significant bits of 12734 // the immediate to set the bits 62:63 of FPSCR. 12735 unsigned Mode = MI.getOperand(1).getImm(); 12736 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12737 .addImm(31) 12738 .addReg(PPC::RM, RegState::ImplicitDefine); 12739 12740 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12741 .addImm(30) 12742 .addReg(PPC::RM, RegState::ImplicitDefine); 12743 } else if (MI.getOpcode() == PPC::SETRND) { 12744 DebugLoc dl = MI.getDebugLoc(); 12745 12746 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12747 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12748 // If the target doesn't have DirectMove, we should use stack to do the 12749 // conversion, because the target doesn't have the instructions like mtvsrd 12750 // or mfvsrd to do this conversion directly. 12751 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12752 if (Subtarget.hasDirectMove()) { 12753 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12754 .addReg(SrcReg); 12755 } else { 12756 // Use stack to do the register copy. 12757 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12758 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12759 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12760 if (RC == &PPC::F8RCRegClass) { 12761 // Copy register from F8RCRegClass to G8RCRegclass. 12762 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12763 "Unsupported RegClass."); 12764 12765 StoreOp = PPC::STFD; 12766 LoadOp = PPC::LD; 12767 } else { 12768 // Copy register from G8RCRegClass to F8RCRegclass. 12769 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12770 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12771 "Unsupported RegClass."); 12772 } 12773 12774 MachineFrameInfo &MFI = F->getFrameInfo(); 12775 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12776 12777 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12778 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12779 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12780 MFI.getObjectAlign(FrameIdx)); 12781 12782 // Store the SrcReg into the stack. 12783 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12784 .addReg(SrcReg) 12785 .addImm(0) 12786 .addFrameIndex(FrameIdx) 12787 .addMemOperand(MMOStore); 12788 12789 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12790 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12791 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12792 MFI.getObjectAlign(FrameIdx)); 12793 12794 // Load from the stack where SrcReg is stored, and save to DestReg, 12795 // so we have done the RegClass conversion from RegClass::SrcReg to 12796 // RegClass::DestReg. 12797 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12798 .addImm(0) 12799 .addFrameIndex(FrameIdx) 12800 .addMemOperand(MMOLoad); 12801 } 12802 }; 12803 12804 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12805 12806 // Save FPSCR value. 12807 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12808 12809 // When the operand is gprc register, use two least significant bits of the 12810 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12811 // 12812 // copy OldFPSCRTmpReg, OldFPSCRReg 12813 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12814 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12815 // copy NewFPSCRReg, NewFPSCRTmpReg 12816 // mtfsf 255, NewFPSCRReg 12817 MachineOperand SrcOp = MI.getOperand(1); 12818 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12819 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12820 12821 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12822 12823 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12824 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12825 12826 // The first operand of INSERT_SUBREG should be a register which has 12827 // subregisters, we only care about its RegClass, so we should use an 12828 // IMPLICIT_DEF register. 12829 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12830 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12831 .addReg(ImDefReg) 12832 .add(SrcOp) 12833 .addImm(1); 12834 12835 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12836 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12837 .addReg(OldFPSCRTmpReg) 12838 .addReg(ExtSrcReg) 12839 .addImm(0) 12840 .addImm(62); 12841 12842 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12843 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12844 12845 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12846 // bits of FPSCR. 12847 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12848 .addImm(255) 12849 .addReg(NewFPSCRReg) 12850 .addImm(0) 12851 .addImm(0); 12852 } else if (MI.getOpcode() == PPC::SETFLM) { 12853 DebugLoc Dl = MI.getDebugLoc(); 12854 12855 // Result of setflm is previous FPSCR content, so we need to save it first. 12856 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12857 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12858 12859 // Put bits in 32:63 to FPSCR. 12860 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12861 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12862 .addImm(255) 12863 .addReg(NewFPSCRReg) 12864 .addImm(0) 12865 .addImm(0); 12866 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12867 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12868 return emitProbedAlloca(MI, BB); 12869 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) { 12870 DebugLoc DL = MI.getDebugLoc(); 12871 Register Src = MI.getOperand(2).getReg(); 12872 Register Lo = MI.getOperand(0).getReg(); 12873 Register Hi = MI.getOperand(1).getReg(); 12874 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12875 .addDef(Lo) 12876 .addUse(Src, 0, PPC::sub_gp8_x1); 12877 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12878 .addDef(Hi) 12879 .addUse(Src, 0, PPC::sub_gp8_x0); 12880 } else if (MI.getOpcode() == PPC::LQX_PSEUDO || 12881 MI.getOpcode() == PPC::STQX_PSEUDO) { 12882 DebugLoc DL = MI.getDebugLoc(); 12883 // Ptr is used as the ptr_rc_no_r0 part 12884 // of LQ/STQ's memory operand and adding result of RA and RB, 12885 // so it has to be g8rc_and_g8rc_nox0. 12886 Register Ptr = 12887 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 12888 Register Val = MI.getOperand(0).getReg(); 12889 Register RA = MI.getOperand(1).getReg(); 12890 Register RB = MI.getOperand(2).getReg(); 12891 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB); 12892 BuildMI(*BB, MI, DL, 12893 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ) 12894 : TII->get(PPC::STQ)) 12895 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0) 12896 .addImm(0) 12897 .addReg(Ptr); 12898 } else { 12899 llvm_unreachable("Unexpected instr type to insert"); 12900 } 12901 12902 MI.eraseFromParent(); // The pseudo instruction is gone now. 12903 return BB; 12904 } 12905 12906 //===----------------------------------------------------------------------===// 12907 // Target Optimization Hooks 12908 //===----------------------------------------------------------------------===// 12909 12910 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12911 // For the estimates, convergence is quadratic, so we essentially double the 12912 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12913 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12914 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12915 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12916 if (VT.getScalarType() == MVT::f64) 12917 RefinementSteps++; 12918 return RefinementSteps; 12919 } 12920 12921 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12922 const DenormalMode &Mode) const { 12923 // We only have VSX Vector Test for software Square Root. 12924 EVT VT = Op.getValueType(); 12925 if (!isTypeLegal(MVT::i1) || 12926 (VT != MVT::f64 && 12927 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12928 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12929 12930 SDLoc DL(Op); 12931 // The output register of FTSQRT is CR field. 12932 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12933 // ftsqrt BF,FRB 12934 // Let e_b be the unbiased exponent of the double-precision 12935 // floating-point operand in register FRB. 12936 // fe_flag is set to 1 if either of the following conditions occurs. 12937 // - The double-precision floating-point operand in register FRB is a zero, 12938 // a NaN, or an infinity, or a negative value. 12939 // - e_b is less than or equal to -970. 12940 // Otherwise fe_flag is set to 0. 12941 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12942 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12943 // exponent is less than -970) 12944 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12945 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12946 FTSQRT, SRIdxVal), 12947 0); 12948 } 12949 12950 SDValue 12951 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12952 SelectionDAG &DAG) const { 12953 // We only have VSX Vector Square Root. 12954 EVT VT = Op.getValueType(); 12955 if (VT != MVT::f64 && 12956 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12957 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12958 12959 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12960 } 12961 12962 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12963 int Enabled, int &RefinementSteps, 12964 bool &UseOneConstNR, 12965 bool Reciprocal) const { 12966 EVT VT = Operand.getValueType(); 12967 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12968 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12969 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12970 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12971 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12972 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12973 12974 // The Newton-Raphson computation with a single constant does not provide 12975 // enough accuracy on some CPUs. 12976 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12977 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12978 } 12979 return SDValue(); 12980 } 12981 12982 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12983 int Enabled, 12984 int &RefinementSteps) const { 12985 EVT VT = Operand.getValueType(); 12986 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12987 (VT == MVT::f64 && Subtarget.hasFRE()) || 12988 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12989 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12990 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12991 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12992 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12993 } 12994 return SDValue(); 12995 } 12996 12997 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12998 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12999 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 13000 // enabled for division), this functionality is redundant with the default 13001 // combiner logic (once the division -> reciprocal/multiply transformation 13002 // has taken place). As a result, this matters more for older cores than for 13003 // newer ones. 13004 13005 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13006 // reciprocal if there are two or more FDIVs (for embedded cores with only 13007 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 13008 switch (Subtarget.getCPUDirective()) { 13009 default: 13010 return 3; 13011 case PPC::DIR_440: 13012 case PPC::DIR_A2: 13013 case PPC::DIR_E500: 13014 case PPC::DIR_E500mc: 13015 case PPC::DIR_E5500: 13016 return 2; 13017 } 13018 } 13019 13020 // isConsecutiveLSLoc needs to work even if all adds have not yet been 13021 // collapsed, and so we need to look through chains of them. 13022 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 13023 int64_t& Offset, SelectionDAG &DAG) { 13024 if (DAG.isBaseWithConstantOffset(Loc)) { 13025 Base = Loc.getOperand(0); 13026 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 13027 13028 // The base might itself be a base plus an offset, and if so, accumulate 13029 // that as well. 13030 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 13031 } 13032 } 13033 13034 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 13035 unsigned Bytes, int Dist, 13036 SelectionDAG &DAG) { 13037 if (VT.getSizeInBits() / 8 != Bytes) 13038 return false; 13039 13040 SDValue BaseLoc = Base->getBasePtr(); 13041 if (Loc.getOpcode() == ISD::FrameIndex) { 13042 if (BaseLoc.getOpcode() != ISD::FrameIndex) 13043 return false; 13044 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 13045 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 13046 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 13047 int FS = MFI.getObjectSize(FI); 13048 int BFS = MFI.getObjectSize(BFI); 13049 if (FS != BFS || FS != (int)Bytes) return false; 13050 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 13051 } 13052 13053 SDValue Base1 = Loc, Base2 = BaseLoc; 13054 int64_t Offset1 = 0, Offset2 = 0; 13055 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 13056 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 13057 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 13058 return true; 13059 13060 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13061 const GlobalValue *GV1 = nullptr; 13062 const GlobalValue *GV2 = nullptr; 13063 Offset1 = 0; 13064 Offset2 = 0; 13065 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 13066 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 13067 if (isGA1 && isGA2 && GV1 == GV2) 13068 return Offset1 == (Offset2 + Dist*Bytes); 13069 return false; 13070 } 13071 13072 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 13073 // not enforce equality of the chain operands. 13074 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 13075 unsigned Bytes, int Dist, 13076 SelectionDAG &DAG) { 13077 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 13078 EVT VT = LS->getMemoryVT(); 13079 SDValue Loc = LS->getBasePtr(); 13080 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 13081 } 13082 13083 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 13084 EVT VT; 13085 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13086 default: return false; 13087 case Intrinsic::ppc_altivec_lvx: 13088 case Intrinsic::ppc_altivec_lvxl: 13089 case Intrinsic::ppc_vsx_lxvw4x: 13090 case Intrinsic::ppc_vsx_lxvw4x_be: 13091 VT = MVT::v4i32; 13092 break; 13093 case Intrinsic::ppc_vsx_lxvd2x: 13094 case Intrinsic::ppc_vsx_lxvd2x_be: 13095 VT = MVT::v2f64; 13096 break; 13097 case Intrinsic::ppc_altivec_lvebx: 13098 VT = MVT::i8; 13099 break; 13100 case Intrinsic::ppc_altivec_lvehx: 13101 VT = MVT::i16; 13102 break; 13103 case Intrinsic::ppc_altivec_lvewx: 13104 VT = MVT::i32; 13105 break; 13106 } 13107 13108 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 13109 } 13110 13111 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 13112 EVT VT; 13113 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13114 default: return false; 13115 case Intrinsic::ppc_altivec_stvx: 13116 case Intrinsic::ppc_altivec_stvxl: 13117 case Intrinsic::ppc_vsx_stxvw4x: 13118 VT = MVT::v4i32; 13119 break; 13120 case Intrinsic::ppc_vsx_stxvd2x: 13121 VT = MVT::v2f64; 13122 break; 13123 case Intrinsic::ppc_vsx_stxvw4x_be: 13124 VT = MVT::v4i32; 13125 break; 13126 case Intrinsic::ppc_vsx_stxvd2x_be: 13127 VT = MVT::v2f64; 13128 break; 13129 case Intrinsic::ppc_altivec_stvebx: 13130 VT = MVT::i8; 13131 break; 13132 case Intrinsic::ppc_altivec_stvehx: 13133 VT = MVT::i16; 13134 break; 13135 case Intrinsic::ppc_altivec_stvewx: 13136 VT = MVT::i32; 13137 break; 13138 } 13139 13140 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13141 } 13142 13143 return false; 13144 } 13145 13146 // Return true is there is a nearyby consecutive load to the one provided 13147 // (regardless of alignment). We search up and down the chain, looking though 13148 // token factors and other loads (but nothing else). As a result, a true result 13149 // indicates that it is safe to create a new consecutive load adjacent to the 13150 // load provided. 13151 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13152 SDValue Chain = LD->getChain(); 13153 EVT VT = LD->getMemoryVT(); 13154 13155 SmallSet<SDNode *, 16> LoadRoots; 13156 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13157 SmallSet<SDNode *, 16> Visited; 13158 13159 // First, search up the chain, branching to follow all token-factor operands. 13160 // If we find a consecutive load, then we're done, otherwise, record all 13161 // nodes just above the top-level loads and token factors. 13162 while (!Queue.empty()) { 13163 SDNode *ChainNext = Queue.pop_back_val(); 13164 if (!Visited.insert(ChainNext).second) 13165 continue; 13166 13167 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13168 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13169 return true; 13170 13171 if (!Visited.count(ChainLD->getChain().getNode())) 13172 Queue.push_back(ChainLD->getChain().getNode()); 13173 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13174 for (const SDUse &O : ChainNext->ops()) 13175 if (!Visited.count(O.getNode())) 13176 Queue.push_back(O.getNode()); 13177 } else 13178 LoadRoots.insert(ChainNext); 13179 } 13180 13181 // Second, search down the chain, starting from the top-level nodes recorded 13182 // in the first phase. These top-level nodes are the nodes just above all 13183 // loads and token factors. Starting with their uses, recursively look though 13184 // all loads (just the chain uses) and token factors to find a consecutive 13185 // load. 13186 Visited.clear(); 13187 Queue.clear(); 13188 13189 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 13190 IE = LoadRoots.end(); I != IE; ++I) { 13191 Queue.push_back(*I); 13192 13193 while (!Queue.empty()) { 13194 SDNode *LoadRoot = Queue.pop_back_val(); 13195 if (!Visited.insert(LoadRoot).second) 13196 continue; 13197 13198 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13199 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13200 return true; 13201 13202 for (SDNode *U : LoadRoot->uses()) 13203 if (((isa<MemSDNode>(U) && 13204 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) || 13205 U->getOpcode() == ISD::TokenFactor) && 13206 !Visited.count(U)) 13207 Queue.push_back(U); 13208 } 13209 } 13210 13211 return false; 13212 } 13213 13214 /// This function is called when we have proved that a SETCC node can be replaced 13215 /// by subtraction (and other supporting instructions) so that the result of 13216 /// comparison is kept in a GPR instead of CR. This function is purely for 13217 /// codegen purposes and has some flags to guide the codegen process. 13218 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13219 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13220 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13221 13222 // Zero extend the operands to the largest legal integer. Originally, they 13223 // must be of a strictly smaller size. 13224 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13225 DAG.getConstant(Size, DL, MVT::i32)); 13226 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13227 DAG.getConstant(Size, DL, MVT::i32)); 13228 13229 // Swap if needed. Depends on the condition code. 13230 if (Swap) 13231 std::swap(Op0, Op1); 13232 13233 // Subtract extended integers. 13234 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13235 13236 // Move the sign bit to the least significant position and zero out the rest. 13237 // Now the least significant bit carries the result of original comparison. 13238 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13239 DAG.getConstant(Size - 1, DL, MVT::i32)); 13240 auto Final = Shifted; 13241 13242 // Complement the result if needed. Based on the condition code. 13243 if (Complement) 13244 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13245 DAG.getConstant(1, DL, MVT::i64)); 13246 13247 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13248 } 13249 13250 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13251 DAGCombinerInfo &DCI) const { 13252 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13253 13254 SelectionDAG &DAG = DCI.DAG; 13255 SDLoc DL(N); 13256 13257 // Size of integers being compared has a critical role in the following 13258 // analysis, so we prefer to do this when all types are legal. 13259 if (!DCI.isAfterLegalizeDAG()) 13260 return SDValue(); 13261 13262 // If all users of SETCC extend its value to a legal integer type 13263 // then we replace SETCC with a subtraction 13264 for (const SDNode *U : N->uses()) 13265 if (U->getOpcode() != ISD::ZERO_EXTEND) 13266 return SDValue(); 13267 13268 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13269 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13270 13271 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13272 13273 if (OpSize < Size) { 13274 switch (CC) { 13275 default: break; 13276 case ISD::SETULT: 13277 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13278 case ISD::SETULE: 13279 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13280 case ISD::SETUGT: 13281 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13282 case ISD::SETUGE: 13283 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13284 } 13285 } 13286 13287 return SDValue(); 13288 } 13289 13290 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13291 DAGCombinerInfo &DCI) const { 13292 SelectionDAG &DAG = DCI.DAG; 13293 SDLoc dl(N); 13294 13295 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13296 // If we're tracking CR bits, we need to be careful that we don't have: 13297 // trunc(binary-ops(zext(x), zext(y))) 13298 // or 13299 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13300 // such that we're unnecessarily moving things into GPRs when it would be 13301 // better to keep them in CR bits. 13302 13303 // Note that trunc here can be an actual i1 trunc, or can be the effective 13304 // truncation that comes from a setcc or select_cc. 13305 if (N->getOpcode() == ISD::TRUNCATE && 13306 N->getValueType(0) != MVT::i1) 13307 return SDValue(); 13308 13309 if (N->getOperand(0).getValueType() != MVT::i32 && 13310 N->getOperand(0).getValueType() != MVT::i64) 13311 return SDValue(); 13312 13313 if (N->getOpcode() == ISD::SETCC || 13314 N->getOpcode() == ISD::SELECT_CC) { 13315 // If we're looking at a comparison, then we need to make sure that the 13316 // high bits (all except for the first) don't matter the result. 13317 ISD::CondCode CC = 13318 cast<CondCodeSDNode>(N->getOperand( 13319 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13320 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13321 13322 if (ISD::isSignedIntSetCC(CC)) { 13323 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13324 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13325 return SDValue(); 13326 } else if (ISD::isUnsignedIntSetCC(CC)) { 13327 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13328 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13329 !DAG.MaskedValueIsZero(N->getOperand(1), 13330 APInt::getHighBitsSet(OpBits, OpBits-1))) 13331 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13332 : SDValue()); 13333 } else { 13334 // This is neither a signed nor an unsigned comparison, just make sure 13335 // that the high bits are equal. 13336 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13337 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13338 13339 // We don't really care about what is known about the first bit (if 13340 // anything), so pretend that it is known zero for both to ensure they can 13341 // be compared as constants. 13342 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13343 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13344 13345 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13346 Op1Known.getConstant() != Op2Known.getConstant()) 13347 return SDValue(); 13348 } 13349 } 13350 13351 // We now know that the higher-order bits are irrelevant, we just need to 13352 // make sure that all of the intermediate operations are bit operations, and 13353 // all inputs are extensions. 13354 if (N->getOperand(0).getOpcode() != ISD::AND && 13355 N->getOperand(0).getOpcode() != ISD::OR && 13356 N->getOperand(0).getOpcode() != ISD::XOR && 13357 N->getOperand(0).getOpcode() != ISD::SELECT && 13358 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13359 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13360 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13361 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13362 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13363 return SDValue(); 13364 13365 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13366 N->getOperand(1).getOpcode() != ISD::AND && 13367 N->getOperand(1).getOpcode() != ISD::OR && 13368 N->getOperand(1).getOpcode() != ISD::XOR && 13369 N->getOperand(1).getOpcode() != ISD::SELECT && 13370 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13371 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13372 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13373 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13374 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13375 return SDValue(); 13376 13377 SmallVector<SDValue, 4> Inputs; 13378 SmallVector<SDValue, 8> BinOps, PromOps; 13379 SmallPtrSet<SDNode *, 16> Visited; 13380 13381 for (unsigned i = 0; i < 2; ++i) { 13382 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13383 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13384 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13385 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13386 isa<ConstantSDNode>(N->getOperand(i))) 13387 Inputs.push_back(N->getOperand(i)); 13388 else 13389 BinOps.push_back(N->getOperand(i)); 13390 13391 if (N->getOpcode() == ISD::TRUNCATE) 13392 break; 13393 } 13394 13395 // Visit all inputs, collect all binary operations (and, or, xor and 13396 // select) that are all fed by extensions. 13397 while (!BinOps.empty()) { 13398 SDValue BinOp = BinOps.pop_back_val(); 13399 13400 if (!Visited.insert(BinOp.getNode()).second) 13401 continue; 13402 13403 PromOps.push_back(BinOp); 13404 13405 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13406 // The condition of the select is not promoted. 13407 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13408 continue; 13409 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13410 continue; 13411 13412 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13413 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13414 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13415 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13416 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13417 Inputs.push_back(BinOp.getOperand(i)); 13418 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13419 BinOp.getOperand(i).getOpcode() == ISD::OR || 13420 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13421 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13422 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13423 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13424 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13425 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13426 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13427 BinOps.push_back(BinOp.getOperand(i)); 13428 } else { 13429 // We have an input that is not an extension or another binary 13430 // operation; we'll abort this transformation. 13431 return SDValue(); 13432 } 13433 } 13434 } 13435 13436 // Make sure that this is a self-contained cluster of operations (which 13437 // is not quite the same thing as saying that everything has only one 13438 // use). 13439 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13440 if (isa<ConstantSDNode>(Inputs[i])) 13441 continue; 13442 13443 for (const SDNode *User : Inputs[i].getNode()->uses()) { 13444 if (User != N && !Visited.count(User)) 13445 return SDValue(); 13446 13447 // Make sure that we're not going to promote the non-output-value 13448 // operand(s) or SELECT or SELECT_CC. 13449 // FIXME: Although we could sometimes handle this, and it does occur in 13450 // practice that one of the condition inputs to the select is also one of 13451 // the outputs, we currently can't deal with this. 13452 if (User->getOpcode() == ISD::SELECT) { 13453 if (User->getOperand(0) == Inputs[i]) 13454 return SDValue(); 13455 } else if (User->getOpcode() == ISD::SELECT_CC) { 13456 if (User->getOperand(0) == Inputs[i] || 13457 User->getOperand(1) == Inputs[i]) 13458 return SDValue(); 13459 } 13460 } 13461 } 13462 13463 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13464 for (const SDNode *User : PromOps[i].getNode()->uses()) { 13465 if (User != N && !Visited.count(User)) 13466 return SDValue(); 13467 13468 // Make sure that we're not going to promote the non-output-value 13469 // operand(s) or SELECT or SELECT_CC. 13470 // FIXME: Although we could sometimes handle this, and it does occur in 13471 // practice that one of the condition inputs to the select is also one of 13472 // the outputs, we currently can't deal with this. 13473 if (User->getOpcode() == ISD::SELECT) { 13474 if (User->getOperand(0) == PromOps[i]) 13475 return SDValue(); 13476 } else if (User->getOpcode() == ISD::SELECT_CC) { 13477 if (User->getOperand(0) == PromOps[i] || 13478 User->getOperand(1) == PromOps[i]) 13479 return SDValue(); 13480 } 13481 } 13482 } 13483 13484 // Replace all inputs with the extension operand. 13485 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13486 // Constants may have users outside the cluster of to-be-promoted nodes, 13487 // and so we need to replace those as we do the promotions. 13488 if (isa<ConstantSDNode>(Inputs[i])) 13489 continue; 13490 else 13491 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13492 } 13493 13494 std::list<HandleSDNode> PromOpHandles; 13495 for (auto &PromOp : PromOps) 13496 PromOpHandles.emplace_back(PromOp); 13497 13498 // Replace all operations (these are all the same, but have a different 13499 // (i1) return type). DAG.getNode will validate that the types of 13500 // a binary operator match, so go through the list in reverse so that 13501 // we've likely promoted both operands first. Any intermediate truncations or 13502 // extensions disappear. 13503 while (!PromOpHandles.empty()) { 13504 SDValue PromOp = PromOpHandles.back().getValue(); 13505 PromOpHandles.pop_back(); 13506 13507 if (PromOp.getOpcode() == ISD::TRUNCATE || 13508 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13509 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13510 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13511 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13512 PromOp.getOperand(0).getValueType() != MVT::i1) { 13513 // The operand is not yet ready (see comment below). 13514 PromOpHandles.emplace_front(PromOp); 13515 continue; 13516 } 13517 13518 SDValue RepValue = PromOp.getOperand(0); 13519 if (isa<ConstantSDNode>(RepValue)) 13520 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13521 13522 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13523 continue; 13524 } 13525 13526 unsigned C; 13527 switch (PromOp.getOpcode()) { 13528 default: C = 0; break; 13529 case ISD::SELECT: C = 1; break; 13530 case ISD::SELECT_CC: C = 2; break; 13531 } 13532 13533 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13534 PromOp.getOperand(C).getValueType() != MVT::i1) || 13535 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13536 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13537 // The to-be-promoted operands of this node have not yet been 13538 // promoted (this should be rare because we're going through the 13539 // list backward, but if one of the operands has several users in 13540 // this cluster of to-be-promoted nodes, it is possible). 13541 PromOpHandles.emplace_front(PromOp); 13542 continue; 13543 } 13544 13545 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13546 PromOp.getNode()->op_end()); 13547 13548 // If there are any constant inputs, make sure they're replaced now. 13549 for (unsigned i = 0; i < 2; ++i) 13550 if (isa<ConstantSDNode>(Ops[C+i])) 13551 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13552 13553 DAG.ReplaceAllUsesOfValueWith(PromOp, 13554 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13555 } 13556 13557 // Now we're left with the initial truncation itself. 13558 if (N->getOpcode() == ISD::TRUNCATE) 13559 return N->getOperand(0); 13560 13561 // Otherwise, this is a comparison. The operands to be compared have just 13562 // changed type (to i1), but everything else is the same. 13563 return SDValue(N, 0); 13564 } 13565 13566 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13567 DAGCombinerInfo &DCI) const { 13568 SelectionDAG &DAG = DCI.DAG; 13569 SDLoc dl(N); 13570 13571 // If we're tracking CR bits, we need to be careful that we don't have: 13572 // zext(binary-ops(trunc(x), trunc(y))) 13573 // or 13574 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13575 // such that we're unnecessarily moving things into CR bits that can more 13576 // efficiently stay in GPRs. Note that if we're not certain that the high 13577 // bits are set as required by the final extension, we still may need to do 13578 // some masking to get the proper behavior. 13579 13580 // This same functionality is important on PPC64 when dealing with 13581 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13582 // the return values of functions. Because it is so similar, it is handled 13583 // here as well. 13584 13585 if (N->getValueType(0) != MVT::i32 && 13586 N->getValueType(0) != MVT::i64) 13587 return SDValue(); 13588 13589 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13590 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13591 return SDValue(); 13592 13593 if (N->getOperand(0).getOpcode() != ISD::AND && 13594 N->getOperand(0).getOpcode() != ISD::OR && 13595 N->getOperand(0).getOpcode() != ISD::XOR && 13596 N->getOperand(0).getOpcode() != ISD::SELECT && 13597 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13598 return SDValue(); 13599 13600 SmallVector<SDValue, 4> Inputs; 13601 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13602 SmallPtrSet<SDNode *, 16> Visited; 13603 13604 // Visit all inputs, collect all binary operations (and, or, xor and 13605 // select) that are all fed by truncations. 13606 while (!BinOps.empty()) { 13607 SDValue BinOp = BinOps.pop_back_val(); 13608 13609 if (!Visited.insert(BinOp.getNode()).second) 13610 continue; 13611 13612 PromOps.push_back(BinOp); 13613 13614 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13615 // The condition of the select is not promoted. 13616 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13617 continue; 13618 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13619 continue; 13620 13621 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13622 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13623 Inputs.push_back(BinOp.getOperand(i)); 13624 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13625 BinOp.getOperand(i).getOpcode() == ISD::OR || 13626 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13627 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13628 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13629 BinOps.push_back(BinOp.getOperand(i)); 13630 } else { 13631 // We have an input that is not a truncation or another binary 13632 // operation; we'll abort this transformation. 13633 return SDValue(); 13634 } 13635 } 13636 } 13637 13638 // The operands of a select that must be truncated when the select is 13639 // promoted because the operand is actually part of the to-be-promoted set. 13640 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13641 13642 // Make sure that this is a self-contained cluster of operations (which 13643 // is not quite the same thing as saying that everything has only one 13644 // use). 13645 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13646 if (isa<ConstantSDNode>(Inputs[i])) 13647 continue; 13648 13649 for (SDNode *User : Inputs[i].getNode()->uses()) { 13650 if (User != N && !Visited.count(User)) 13651 return SDValue(); 13652 13653 // If we're going to promote the non-output-value operand(s) or SELECT or 13654 // SELECT_CC, record them for truncation. 13655 if (User->getOpcode() == ISD::SELECT) { 13656 if (User->getOperand(0) == Inputs[i]) 13657 SelectTruncOp[0].insert(std::make_pair(User, 13658 User->getOperand(0).getValueType())); 13659 } else if (User->getOpcode() == ISD::SELECT_CC) { 13660 if (User->getOperand(0) == Inputs[i]) 13661 SelectTruncOp[0].insert(std::make_pair(User, 13662 User->getOperand(0).getValueType())); 13663 if (User->getOperand(1) == Inputs[i]) 13664 SelectTruncOp[1].insert(std::make_pair(User, 13665 User->getOperand(1).getValueType())); 13666 } 13667 } 13668 } 13669 13670 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13671 for (SDNode *User : PromOps[i].getNode()->uses()) { 13672 if (User != N && !Visited.count(User)) 13673 return SDValue(); 13674 13675 // If we're going to promote the non-output-value operand(s) or SELECT or 13676 // SELECT_CC, record them for truncation. 13677 if (User->getOpcode() == ISD::SELECT) { 13678 if (User->getOperand(0) == PromOps[i]) 13679 SelectTruncOp[0].insert(std::make_pair(User, 13680 User->getOperand(0).getValueType())); 13681 } else if (User->getOpcode() == ISD::SELECT_CC) { 13682 if (User->getOperand(0) == PromOps[i]) 13683 SelectTruncOp[0].insert(std::make_pair(User, 13684 User->getOperand(0).getValueType())); 13685 if (User->getOperand(1) == PromOps[i]) 13686 SelectTruncOp[1].insert(std::make_pair(User, 13687 User->getOperand(1).getValueType())); 13688 } 13689 } 13690 } 13691 13692 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13693 bool ReallyNeedsExt = false; 13694 if (N->getOpcode() != ISD::ANY_EXTEND) { 13695 // If all of the inputs are not already sign/zero extended, then 13696 // we'll still need to do that at the end. 13697 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13698 if (isa<ConstantSDNode>(Inputs[i])) 13699 continue; 13700 13701 unsigned OpBits = 13702 Inputs[i].getOperand(0).getValueSizeInBits(); 13703 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13704 13705 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13706 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13707 APInt::getHighBitsSet(OpBits, 13708 OpBits-PromBits))) || 13709 (N->getOpcode() == ISD::SIGN_EXTEND && 13710 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13711 (OpBits-(PromBits-1)))) { 13712 ReallyNeedsExt = true; 13713 break; 13714 } 13715 } 13716 } 13717 13718 // Replace all inputs, either with the truncation operand, or a 13719 // truncation or extension to the final output type. 13720 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13721 // Constant inputs need to be replaced with the to-be-promoted nodes that 13722 // use them because they might have users outside of the cluster of 13723 // promoted nodes. 13724 if (isa<ConstantSDNode>(Inputs[i])) 13725 continue; 13726 13727 SDValue InSrc = Inputs[i].getOperand(0); 13728 if (Inputs[i].getValueType() == N->getValueType(0)) 13729 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13730 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13731 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13732 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13733 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13734 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13735 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13736 else 13737 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13738 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13739 } 13740 13741 std::list<HandleSDNode> PromOpHandles; 13742 for (auto &PromOp : PromOps) 13743 PromOpHandles.emplace_back(PromOp); 13744 13745 // Replace all operations (these are all the same, but have a different 13746 // (promoted) return type). DAG.getNode will validate that the types of 13747 // a binary operator match, so go through the list in reverse so that 13748 // we've likely promoted both operands first. 13749 while (!PromOpHandles.empty()) { 13750 SDValue PromOp = PromOpHandles.back().getValue(); 13751 PromOpHandles.pop_back(); 13752 13753 unsigned C; 13754 switch (PromOp.getOpcode()) { 13755 default: C = 0; break; 13756 case ISD::SELECT: C = 1; break; 13757 case ISD::SELECT_CC: C = 2; break; 13758 } 13759 13760 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13761 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13762 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13763 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13764 // The to-be-promoted operands of this node have not yet been 13765 // promoted (this should be rare because we're going through the 13766 // list backward, but if one of the operands has several users in 13767 // this cluster of to-be-promoted nodes, it is possible). 13768 PromOpHandles.emplace_front(PromOp); 13769 continue; 13770 } 13771 13772 // For SELECT and SELECT_CC nodes, we do a similar check for any 13773 // to-be-promoted comparison inputs. 13774 if (PromOp.getOpcode() == ISD::SELECT || 13775 PromOp.getOpcode() == ISD::SELECT_CC) { 13776 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13777 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13778 (SelectTruncOp[1].count(PromOp.getNode()) && 13779 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13780 PromOpHandles.emplace_front(PromOp); 13781 continue; 13782 } 13783 } 13784 13785 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13786 PromOp.getNode()->op_end()); 13787 13788 // If this node has constant inputs, then they'll need to be promoted here. 13789 for (unsigned i = 0; i < 2; ++i) { 13790 if (!isa<ConstantSDNode>(Ops[C+i])) 13791 continue; 13792 if (Ops[C+i].getValueType() == N->getValueType(0)) 13793 continue; 13794 13795 if (N->getOpcode() == ISD::SIGN_EXTEND) 13796 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13797 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13798 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13799 else 13800 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13801 } 13802 13803 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13804 // truncate them again to the original value type. 13805 if (PromOp.getOpcode() == ISD::SELECT || 13806 PromOp.getOpcode() == ISD::SELECT_CC) { 13807 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13808 if (SI0 != SelectTruncOp[0].end()) 13809 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13810 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13811 if (SI1 != SelectTruncOp[1].end()) 13812 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13813 } 13814 13815 DAG.ReplaceAllUsesOfValueWith(PromOp, 13816 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13817 } 13818 13819 // Now we're left with the initial extension itself. 13820 if (!ReallyNeedsExt) 13821 return N->getOperand(0); 13822 13823 // To zero extend, just mask off everything except for the first bit (in the 13824 // i1 case). 13825 if (N->getOpcode() == ISD::ZERO_EXTEND) 13826 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13827 DAG.getConstant(APInt::getLowBitsSet( 13828 N->getValueSizeInBits(0), PromBits), 13829 dl, N->getValueType(0))); 13830 13831 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13832 "Invalid extension type"); 13833 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13834 SDValue ShiftCst = 13835 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13836 return DAG.getNode( 13837 ISD::SRA, dl, N->getValueType(0), 13838 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13839 ShiftCst); 13840 } 13841 13842 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13843 DAGCombinerInfo &DCI) const { 13844 assert(N->getOpcode() == ISD::SETCC && 13845 "Should be called with a SETCC node"); 13846 13847 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13848 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13849 SDValue LHS = N->getOperand(0); 13850 SDValue RHS = N->getOperand(1); 13851 13852 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13853 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13854 LHS.hasOneUse()) 13855 std::swap(LHS, RHS); 13856 13857 // x == 0-y --> x+y == 0 13858 // x != 0-y --> x+y != 0 13859 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13860 RHS.hasOneUse()) { 13861 SDLoc DL(N); 13862 SelectionDAG &DAG = DCI.DAG; 13863 EVT VT = N->getValueType(0); 13864 EVT OpVT = LHS.getValueType(); 13865 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13866 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13867 } 13868 } 13869 13870 return DAGCombineTruncBoolExt(N, DCI); 13871 } 13872 13873 // Is this an extending load from an f32 to an f64? 13874 static bool isFPExtLoad(SDValue Op) { 13875 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13876 return LD->getExtensionType() == ISD::EXTLOAD && 13877 Op.getValueType() == MVT::f64; 13878 return false; 13879 } 13880 13881 /// Reduces the number of fp-to-int conversion when building a vector. 13882 /// 13883 /// If this vector is built out of floating to integer conversions, 13884 /// transform it to a vector built out of floating point values followed by a 13885 /// single floating to integer conversion of the vector. 13886 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13887 /// becomes (fptosi (build_vector ($A, $B, ...))) 13888 SDValue PPCTargetLowering:: 13889 combineElementTruncationToVectorTruncation(SDNode *N, 13890 DAGCombinerInfo &DCI) const { 13891 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13892 "Should be called with a BUILD_VECTOR node"); 13893 13894 SelectionDAG &DAG = DCI.DAG; 13895 SDLoc dl(N); 13896 13897 SDValue FirstInput = N->getOperand(0); 13898 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13899 "The input operand must be an fp-to-int conversion."); 13900 13901 // This combine happens after legalization so the fp_to_[su]i nodes are 13902 // already converted to PPCSISD nodes. 13903 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13904 if (FirstConversion == PPCISD::FCTIDZ || 13905 FirstConversion == PPCISD::FCTIDUZ || 13906 FirstConversion == PPCISD::FCTIWZ || 13907 FirstConversion == PPCISD::FCTIWUZ) { 13908 bool IsSplat = true; 13909 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13910 FirstConversion == PPCISD::FCTIWUZ; 13911 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13912 SmallVector<SDValue, 4> Ops; 13913 EVT TargetVT = N->getValueType(0); 13914 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13915 SDValue NextOp = N->getOperand(i); 13916 if (NextOp.getOpcode() != PPCISD::MFVSR) 13917 return SDValue(); 13918 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13919 if (NextConversion != FirstConversion) 13920 return SDValue(); 13921 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13922 // This is not valid if the input was originally double precision. It is 13923 // also not profitable to do unless this is an extending load in which 13924 // case doing this combine will allow us to combine consecutive loads. 13925 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13926 return SDValue(); 13927 if (N->getOperand(i) != FirstInput) 13928 IsSplat = false; 13929 } 13930 13931 // If this is a splat, we leave it as-is since there will be only a single 13932 // fp-to-int conversion followed by a splat of the integer. This is better 13933 // for 32-bit and smaller ints and neutral for 64-bit ints. 13934 if (IsSplat) 13935 return SDValue(); 13936 13937 // Now that we know we have the right type of node, get its operands 13938 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13939 SDValue In = N->getOperand(i).getOperand(0); 13940 if (Is32Bit) { 13941 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13942 // here, we know that all inputs are extending loads so this is safe). 13943 if (In.isUndef()) 13944 Ops.push_back(DAG.getUNDEF(SrcVT)); 13945 else { 13946 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13947 MVT::f32, In.getOperand(0), 13948 DAG.getIntPtrConstant(1, dl)); 13949 Ops.push_back(Trunc); 13950 } 13951 } else 13952 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13953 } 13954 13955 unsigned Opcode; 13956 if (FirstConversion == PPCISD::FCTIDZ || 13957 FirstConversion == PPCISD::FCTIWZ) 13958 Opcode = ISD::FP_TO_SINT; 13959 else 13960 Opcode = ISD::FP_TO_UINT; 13961 13962 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13963 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13964 return DAG.getNode(Opcode, dl, TargetVT, BV); 13965 } 13966 return SDValue(); 13967 } 13968 13969 /// Reduce the number of loads when building a vector. 13970 /// 13971 /// Building a vector out of multiple loads can be converted to a load 13972 /// of the vector type if the loads are consecutive. If the loads are 13973 /// consecutive but in descending order, a shuffle is added at the end 13974 /// to reorder the vector. 13975 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13976 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13977 "Should be called with a BUILD_VECTOR node"); 13978 13979 SDLoc dl(N); 13980 13981 // Return early for non byte-sized type, as they can't be consecutive. 13982 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13983 return SDValue(); 13984 13985 bool InputsAreConsecutiveLoads = true; 13986 bool InputsAreReverseConsecutive = true; 13987 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13988 SDValue FirstInput = N->getOperand(0); 13989 bool IsRoundOfExtLoad = false; 13990 13991 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13992 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13993 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13994 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13995 } 13996 // Not a build vector of (possibly fp_rounded) loads. 13997 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13998 N->getNumOperands() == 1) 13999 return SDValue(); 14000 14001 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 14002 // If any inputs are fp_round(extload), they all must be. 14003 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 14004 return SDValue(); 14005 14006 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 14007 N->getOperand(i); 14008 if (NextInput.getOpcode() != ISD::LOAD) 14009 return SDValue(); 14010 14011 SDValue PreviousInput = 14012 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 14013 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 14014 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 14015 14016 // If any inputs are fp_round(extload), they all must be. 14017 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 14018 return SDValue(); 14019 14020 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 14021 InputsAreConsecutiveLoads = false; 14022 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 14023 InputsAreReverseConsecutive = false; 14024 14025 // Exit early if the loads are neither consecutive nor reverse consecutive. 14026 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 14027 return SDValue(); 14028 } 14029 14030 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 14031 "The loads cannot be both consecutive and reverse consecutive."); 14032 14033 SDValue FirstLoadOp = 14034 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 14035 SDValue LastLoadOp = 14036 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 14037 N->getOperand(N->getNumOperands()-1); 14038 14039 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 14040 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 14041 if (InputsAreConsecutiveLoads) { 14042 assert(LD1 && "Input needs to be a LoadSDNode."); 14043 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 14044 LD1->getBasePtr(), LD1->getPointerInfo(), 14045 LD1->getAlignment()); 14046 } 14047 if (InputsAreReverseConsecutive) { 14048 assert(LDL && "Input needs to be a LoadSDNode."); 14049 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 14050 LDL->getBasePtr(), LDL->getPointerInfo(), 14051 LDL->getAlignment()); 14052 SmallVector<int, 16> Ops; 14053 for (int i = N->getNumOperands() - 1; i >= 0; i--) 14054 Ops.push_back(i); 14055 14056 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 14057 DAG.getUNDEF(N->getValueType(0)), Ops); 14058 } 14059 return SDValue(); 14060 } 14061 14062 // This function adds the required vector_shuffle needed to get 14063 // the elements of the vector extract in the correct position 14064 // as specified by the CorrectElems encoding. 14065 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 14066 SDValue Input, uint64_t Elems, 14067 uint64_t CorrectElems) { 14068 SDLoc dl(N); 14069 14070 unsigned NumElems = Input.getValueType().getVectorNumElements(); 14071 SmallVector<int, 16> ShuffleMask(NumElems, -1); 14072 14073 // Knowing the element indices being extracted from the original 14074 // vector and the order in which they're being inserted, just put 14075 // them at element indices required for the instruction. 14076 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14077 if (DAG.getDataLayout().isLittleEndian()) 14078 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 14079 else 14080 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 14081 CorrectElems = CorrectElems >> 8; 14082 Elems = Elems >> 8; 14083 } 14084 14085 SDValue Shuffle = 14086 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 14087 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 14088 14089 EVT VT = N->getValueType(0); 14090 SDValue Conv = DAG.getBitcast(VT, Shuffle); 14091 14092 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 14093 Input.getValueType().getVectorElementType(), 14094 VT.getVectorNumElements()); 14095 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 14096 DAG.getValueType(ExtVT)); 14097 } 14098 14099 // Look for build vector patterns where input operands come from sign 14100 // extended vector_extract elements of specific indices. If the correct indices 14101 // aren't used, add a vector shuffle to fix up the indices and create 14102 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14103 // during instruction selection. 14104 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14105 // This array encodes the indices that the vector sign extend instructions 14106 // extract from when extending from one type to another for both BE and LE. 14107 // The right nibble of each byte corresponds to the LE incides. 14108 // and the left nibble of each byte corresponds to the BE incides. 14109 // For example: 0x3074B8FC byte->word 14110 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14111 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14112 // For example: 0x000070F8 byte->double word 14113 // For LE: the allowed indices are: 0x0,0x8 14114 // For BE: the allowed indices are: 0x7,0xF 14115 uint64_t TargetElems[] = { 14116 0x3074B8FC, // b->w 14117 0x000070F8, // b->d 14118 0x10325476, // h->w 14119 0x00003074, // h->d 14120 0x00001032, // w->d 14121 }; 14122 14123 uint64_t Elems = 0; 14124 int Index; 14125 SDValue Input; 14126 14127 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14128 if (!Op) 14129 return false; 14130 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14131 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14132 return false; 14133 14134 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14135 // of the right width. 14136 SDValue Extract = Op.getOperand(0); 14137 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14138 Extract = Extract.getOperand(0); 14139 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14140 return false; 14141 14142 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14143 if (!ExtOp) 14144 return false; 14145 14146 Index = ExtOp->getZExtValue(); 14147 if (Input && Input != Extract.getOperand(0)) 14148 return false; 14149 14150 if (!Input) 14151 Input = Extract.getOperand(0); 14152 14153 Elems = Elems << 8; 14154 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14155 Elems |= Index; 14156 14157 return true; 14158 }; 14159 14160 // If the build vector operands aren't sign extended vector extracts, 14161 // of the same input vector, then return. 14162 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14163 if (!isSExtOfVecExtract(N->getOperand(i))) { 14164 return SDValue(); 14165 } 14166 } 14167 14168 // If the vector extract indicies are not correct, add the appropriate 14169 // vector_shuffle. 14170 int TgtElemArrayIdx; 14171 int InputSize = Input.getValueType().getScalarSizeInBits(); 14172 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14173 if (InputSize + OutputSize == 40) 14174 TgtElemArrayIdx = 0; 14175 else if (InputSize + OutputSize == 72) 14176 TgtElemArrayIdx = 1; 14177 else if (InputSize + OutputSize == 48) 14178 TgtElemArrayIdx = 2; 14179 else if (InputSize + OutputSize == 80) 14180 TgtElemArrayIdx = 3; 14181 else if (InputSize + OutputSize == 96) 14182 TgtElemArrayIdx = 4; 14183 else 14184 return SDValue(); 14185 14186 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14187 CorrectElems = DAG.getDataLayout().isLittleEndian() 14188 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14189 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14190 if (Elems != CorrectElems) { 14191 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14192 } 14193 14194 // Regular lowering will catch cases where a shuffle is not needed. 14195 return SDValue(); 14196 } 14197 14198 // Look for the pattern of a load from a narrow width to i128, feeding 14199 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14200 // (LXVRZX). This node represents a zero extending load that will be matched 14201 // to the Load VSX Vector Rightmost instructions. 14202 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14203 SDLoc DL(N); 14204 14205 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14206 if (N->getValueType(0) != MVT::v1i128) 14207 return SDValue(); 14208 14209 SDValue Operand = N->getOperand(0); 14210 // Proceed with the transformation if the operand to the BUILD_VECTOR 14211 // is a load instruction. 14212 if (Operand.getOpcode() != ISD::LOAD) 14213 return SDValue(); 14214 14215 auto *LD = cast<LoadSDNode>(Operand); 14216 EVT MemoryType = LD->getMemoryVT(); 14217 14218 // This transformation is only valid if the we are loading either a byte, 14219 // halfword, word, or doubleword. 14220 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14221 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14222 14223 // Ensure that the load from the narrow width is being zero extended to i128. 14224 if (!ValidLDType || 14225 (LD->getExtensionType() != ISD::ZEXTLOAD && 14226 LD->getExtensionType() != ISD::EXTLOAD)) 14227 return SDValue(); 14228 14229 SDValue LoadOps[] = { 14230 LD->getChain(), LD->getBasePtr(), 14231 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14232 14233 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14234 DAG.getVTList(MVT::v1i128, MVT::Other), 14235 LoadOps, MemoryType, LD->getMemOperand()); 14236 } 14237 14238 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14239 DAGCombinerInfo &DCI) const { 14240 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14241 "Should be called with a BUILD_VECTOR node"); 14242 14243 SelectionDAG &DAG = DCI.DAG; 14244 SDLoc dl(N); 14245 14246 if (!Subtarget.hasVSX()) 14247 return SDValue(); 14248 14249 // The target independent DAG combiner will leave a build_vector of 14250 // float-to-int conversions intact. We can generate MUCH better code for 14251 // a float-to-int conversion of a vector of floats. 14252 SDValue FirstInput = N->getOperand(0); 14253 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14254 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14255 if (Reduced) 14256 return Reduced; 14257 } 14258 14259 // If we're building a vector out of consecutive loads, just load that 14260 // vector type. 14261 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14262 if (Reduced) 14263 return Reduced; 14264 14265 // If we're building a vector out of extended elements from another vector 14266 // we have P9 vector integer extend instructions. The code assumes legal 14267 // input types (i.e. it can't handle things like v4i16) so do not run before 14268 // legalization. 14269 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14270 Reduced = combineBVOfVecSExt(N, DAG); 14271 if (Reduced) 14272 return Reduced; 14273 } 14274 14275 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14276 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14277 // is a load from <valid narrow width> to i128. 14278 if (Subtarget.isISA3_1()) { 14279 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14280 if (BVOfZLoad) 14281 return BVOfZLoad; 14282 } 14283 14284 if (N->getValueType(0) != MVT::v2f64) 14285 return SDValue(); 14286 14287 // Looking for: 14288 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14289 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14290 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14291 return SDValue(); 14292 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14293 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14294 return SDValue(); 14295 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14296 return SDValue(); 14297 14298 SDValue Ext1 = FirstInput.getOperand(0); 14299 SDValue Ext2 = N->getOperand(1).getOperand(0); 14300 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14301 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14302 return SDValue(); 14303 14304 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14305 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14306 if (!Ext1Op || !Ext2Op) 14307 return SDValue(); 14308 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14309 Ext1.getOperand(0) != Ext2.getOperand(0)) 14310 return SDValue(); 14311 14312 int FirstElem = Ext1Op->getZExtValue(); 14313 int SecondElem = Ext2Op->getZExtValue(); 14314 int SubvecIdx; 14315 if (FirstElem == 0 && SecondElem == 1) 14316 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14317 else if (FirstElem == 2 && SecondElem == 3) 14318 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14319 else 14320 return SDValue(); 14321 14322 SDValue SrcVec = Ext1.getOperand(0); 14323 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14324 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14325 return DAG.getNode(NodeType, dl, MVT::v2f64, 14326 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14327 } 14328 14329 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14330 DAGCombinerInfo &DCI) const { 14331 assert((N->getOpcode() == ISD::SINT_TO_FP || 14332 N->getOpcode() == ISD::UINT_TO_FP) && 14333 "Need an int -> FP conversion node here"); 14334 14335 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14336 return SDValue(); 14337 14338 SelectionDAG &DAG = DCI.DAG; 14339 SDLoc dl(N); 14340 SDValue Op(N, 0); 14341 14342 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14343 // from the hardware. 14344 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14345 return SDValue(); 14346 if (!Op.getOperand(0).getValueType().isSimple()) 14347 return SDValue(); 14348 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14349 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14350 return SDValue(); 14351 14352 SDValue FirstOperand(Op.getOperand(0)); 14353 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14354 (FirstOperand.getValueType() == MVT::i8 || 14355 FirstOperand.getValueType() == MVT::i16); 14356 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14357 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14358 bool DstDouble = Op.getValueType() == MVT::f64; 14359 unsigned ConvOp = Signed ? 14360 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14361 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14362 SDValue WidthConst = 14363 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14364 dl, false); 14365 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14366 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14367 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14368 DAG.getVTList(MVT::f64, MVT::Other), 14369 Ops, MVT::i8, LDN->getMemOperand()); 14370 14371 // For signed conversion, we need to sign-extend the value in the VSR 14372 if (Signed) { 14373 SDValue ExtOps[] = { Ld, WidthConst }; 14374 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14375 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14376 } else 14377 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14378 } 14379 14380 14381 // For i32 intermediate values, unfortunately, the conversion functions 14382 // leave the upper 32 bits of the value are undefined. Within the set of 14383 // scalar instructions, we have no method for zero- or sign-extending the 14384 // value. Thus, we cannot handle i32 intermediate values here. 14385 if (Op.getOperand(0).getValueType() == MVT::i32) 14386 return SDValue(); 14387 14388 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14389 "UINT_TO_FP is supported only with FPCVT"); 14390 14391 // If we have FCFIDS, then use it when converting to single-precision. 14392 // Otherwise, convert to double-precision and then round. 14393 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14394 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14395 : PPCISD::FCFIDS) 14396 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14397 : PPCISD::FCFID); 14398 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14399 ? MVT::f32 14400 : MVT::f64; 14401 14402 // If we're converting from a float, to an int, and back to a float again, 14403 // then we don't need the store/load pair at all. 14404 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14405 Subtarget.hasFPCVT()) || 14406 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14407 SDValue Src = Op.getOperand(0).getOperand(0); 14408 if (Src.getValueType() == MVT::f32) { 14409 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14410 DCI.AddToWorklist(Src.getNode()); 14411 } else if (Src.getValueType() != MVT::f64) { 14412 // Make sure that we don't pick up a ppc_fp128 source value. 14413 return SDValue(); 14414 } 14415 14416 unsigned FCTOp = 14417 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14418 PPCISD::FCTIDUZ; 14419 14420 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14421 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14422 14423 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14424 FP = DAG.getNode(ISD::FP_ROUND, dl, 14425 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14426 DCI.AddToWorklist(FP.getNode()); 14427 } 14428 14429 return FP; 14430 } 14431 14432 return SDValue(); 14433 } 14434 14435 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14436 // builtins) into loads with swaps. 14437 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14438 DAGCombinerInfo &DCI) const { 14439 SelectionDAG &DAG = DCI.DAG; 14440 SDLoc dl(N); 14441 SDValue Chain; 14442 SDValue Base; 14443 MachineMemOperand *MMO; 14444 14445 switch (N->getOpcode()) { 14446 default: 14447 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14448 case ISD::LOAD: { 14449 LoadSDNode *LD = cast<LoadSDNode>(N); 14450 Chain = LD->getChain(); 14451 Base = LD->getBasePtr(); 14452 MMO = LD->getMemOperand(); 14453 // If the MMO suggests this isn't a load of a full vector, leave 14454 // things alone. For a built-in, we have to make the change for 14455 // correctness, so if there is a size problem that will be a bug. 14456 if (MMO->getSize() < 16) 14457 return SDValue(); 14458 break; 14459 } 14460 case ISD::INTRINSIC_W_CHAIN: { 14461 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14462 Chain = Intrin->getChain(); 14463 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14464 // us what we want. Get operand 2 instead. 14465 Base = Intrin->getOperand(2); 14466 MMO = Intrin->getMemOperand(); 14467 break; 14468 } 14469 } 14470 14471 MVT VecTy = N->getValueType(0).getSimpleVT(); 14472 14473 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14474 // aligned and the type is a vector with elements up to 4 bytes 14475 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14476 VecTy.getScalarSizeInBits() <= 32) { 14477 return SDValue(); 14478 } 14479 14480 SDValue LoadOps[] = { Chain, Base }; 14481 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14482 DAG.getVTList(MVT::v2f64, MVT::Other), 14483 LoadOps, MVT::v2f64, MMO); 14484 14485 DCI.AddToWorklist(Load.getNode()); 14486 Chain = Load.getValue(1); 14487 SDValue Swap = DAG.getNode( 14488 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14489 DCI.AddToWorklist(Swap.getNode()); 14490 14491 // Add a bitcast if the resulting load type doesn't match v2f64. 14492 if (VecTy != MVT::v2f64) { 14493 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14494 DCI.AddToWorklist(N.getNode()); 14495 // Package {bitcast value, swap's chain} to match Load's shape. 14496 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14497 N, Swap.getValue(1)); 14498 } 14499 14500 return Swap; 14501 } 14502 14503 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14504 // builtins) into stores with swaps. 14505 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14506 DAGCombinerInfo &DCI) const { 14507 SelectionDAG &DAG = DCI.DAG; 14508 SDLoc dl(N); 14509 SDValue Chain; 14510 SDValue Base; 14511 unsigned SrcOpnd; 14512 MachineMemOperand *MMO; 14513 14514 switch (N->getOpcode()) { 14515 default: 14516 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14517 case ISD::STORE: { 14518 StoreSDNode *ST = cast<StoreSDNode>(N); 14519 Chain = ST->getChain(); 14520 Base = ST->getBasePtr(); 14521 MMO = ST->getMemOperand(); 14522 SrcOpnd = 1; 14523 // If the MMO suggests this isn't a store of a full vector, leave 14524 // things alone. For a built-in, we have to make the change for 14525 // correctness, so if there is a size problem that will be a bug. 14526 if (MMO->getSize() < 16) 14527 return SDValue(); 14528 break; 14529 } 14530 case ISD::INTRINSIC_VOID: { 14531 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14532 Chain = Intrin->getChain(); 14533 // Intrin->getBasePtr() oddly does not get what we want. 14534 Base = Intrin->getOperand(3); 14535 MMO = Intrin->getMemOperand(); 14536 SrcOpnd = 2; 14537 break; 14538 } 14539 } 14540 14541 SDValue Src = N->getOperand(SrcOpnd); 14542 MVT VecTy = Src.getValueType().getSimpleVT(); 14543 14544 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14545 // aligned and the type is a vector with elements up to 4 bytes 14546 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14547 VecTy.getScalarSizeInBits() <= 32) { 14548 return SDValue(); 14549 } 14550 14551 // All stores are done as v2f64 and possible bit cast. 14552 if (VecTy != MVT::v2f64) { 14553 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14554 DCI.AddToWorklist(Src.getNode()); 14555 } 14556 14557 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14558 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14559 DCI.AddToWorklist(Swap.getNode()); 14560 Chain = Swap.getValue(1); 14561 SDValue StoreOps[] = { Chain, Swap, Base }; 14562 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14563 DAG.getVTList(MVT::Other), 14564 StoreOps, VecTy, MMO); 14565 DCI.AddToWorklist(Store.getNode()); 14566 return Store; 14567 } 14568 14569 // Handle DAG combine for STORE (FP_TO_INT F). 14570 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14571 DAGCombinerInfo &DCI) const { 14572 14573 SelectionDAG &DAG = DCI.DAG; 14574 SDLoc dl(N); 14575 unsigned Opcode = N->getOperand(1).getOpcode(); 14576 14577 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14578 && "Not a FP_TO_INT Instruction!"); 14579 14580 SDValue Val = N->getOperand(1).getOperand(0); 14581 EVT Op1VT = N->getOperand(1).getValueType(); 14582 EVT ResVT = Val.getValueType(); 14583 14584 if (!isTypeLegal(ResVT)) 14585 return SDValue(); 14586 14587 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14588 bool ValidTypeForStoreFltAsInt = 14589 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14590 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14591 14592 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14593 return SDValue(); 14594 14595 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14596 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14597 return SDValue(); 14598 14599 // Extend f32 values to f64 14600 if (ResVT.getScalarSizeInBits() == 32) { 14601 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14602 DCI.AddToWorklist(Val.getNode()); 14603 } 14604 14605 // Set signed or unsigned conversion opcode. 14606 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14607 PPCISD::FP_TO_SINT_IN_VSR : 14608 PPCISD::FP_TO_UINT_IN_VSR; 14609 14610 Val = DAG.getNode(ConvOpcode, 14611 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14612 DCI.AddToWorklist(Val.getNode()); 14613 14614 // Set number of bytes being converted. 14615 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14616 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14617 DAG.getIntPtrConstant(ByteSize, dl, false), 14618 DAG.getValueType(Op1VT) }; 14619 14620 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14621 DAG.getVTList(MVT::Other), Ops, 14622 cast<StoreSDNode>(N)->getMemoryVT(), 14623 cast<StoreSDNode>(N)->getMemOperand()); 14624 14625 DCI.AddToWorklist(Val.getNode()); 14626 return Val; 14627 } 14628 14629 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14630 // Check that the source of the element keeps flipping 14631 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14632 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14633 for (int i = 1, e = Mask.size(); i < e; i++) { 14634 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14635 return false; 14636 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14637 return false; 14638 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14639 } 14640 return true; 14641 } 14642 14643 static bool isSplatBV(SDValue Op) { 14644 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14645 return false; 14646 SDValue FirstOp; 14647 14648 // Find first non-undef input. 14649 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14650 FirstOp = Op.getOperand(i); 14651 if (!FirstOp.isUndef()) 14652 break; 14653 } 14654 14655 // All inputs are undef or the same as the first non-undef input. 14656 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14657 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14658 return false; 14659 return true; 14660 } 14661 14662 static SDValue isScalarToVec(SDValue Op) { 14663 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14664 return Op; 14665 if (Op.getOpcode() != ISD::BITCAST) 14666 return SDValue(); 14667 Op = Op.getOperand(0); 14668 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14669 return Op; 14670 return SDValue(); 14671 } 14672 14673 // Fix up the shuffle mask to account for the fact that the result of 14674 // scalar_to_vector is not in lane zero. This just takes all values in 14675 // the ranges specified by the min/max indices and adds the number of 14676 // elements required to ensure each element comes from the respective 14677 // position in the valid lane. 14678 // On little endian, that's just the corresponding element in the other 14679 // half of the vector. On big endian, it is in the same half but right 14680 // justified rather than left justified in that half. 14681 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14682 int LHSMaxIdx, int RHSMinIdx, 14683 int RHSMaxIdx, int HalfVec, 14684 unsigned ValidLaneWidth, 14685 const PPCSubtarget &Subtarget) { 14686 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14687 int Idx = ShuffV[i]; 14688 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14689 ShuffV[i] += 14690 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14691 } 14692 } 14693 14694 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14695 // the original is: 14696 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14697 // In such a case, just change the shuffle mask to extract the element 14698 // from the permuted index. 14699 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14700 const PPCSubtarget &Subtarget) { 14701 SDLoc dl(OrigSToV); 14702 EVT VT = OrigSToV.getValueType(); 14703 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14704 "Expecting a SCALAR_TO_VECTOR here"); 14705 SDValue Input = OrigSToV.getOperand(0); 14706 14707 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14708 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14709 SDValue OrigVector = Input.getOperand(0); 14710 14711 // Can't handle non-const element indices or different vector types 14712 // for the input to the extract and the output of the scalar_to_vector. 14713 if (Idx && VT == OrigVector.getValueType()) { 14714 unsigned NumElts = VT.getVectorNumElements(); 14715 assert( 14716 NumElts > 1 && 14717 "Cannot produce a permuted scalar_to_vector for one element vector"); 14718 SmallVector<int, 16> NewMask(NumElts, -1); 14719 unsigned ResultInElt = NumElts / 2; 14720 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14721 NewMask[ResultInElt] = Idx->getZExtValue(); 14722 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14723 } 14724 } 14725 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14726 OrigSToV.getOperand(0)); 14727 } 14728 14729 // On little endian subtargets, combine shuffles such as: 14730 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14731 // into: 14732 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14733 // because the latter can be matched to a single instruction merge. 14734 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14735 // to put the value into element zero. Adjust the shuffle mask so that the 14736 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14737 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14738 // nodes with elements smaller than doubleword because all the ways 14739 // of getting scalar data into a vector register put the value in the 14740 // rightmost element of the left half of the vector. 14741 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14742 SelectionDAG &DAG) const { 14743 SDValue LHS = SVN->getOperand(0); 14744 SDValue RHS = SVN->getOperand(1); 14745 auto Mask = SVN->getMask(); 14746 int NumElts = LHS.getValueType().getVectorNumElements(); 14747 SDValue Res(SVN, 0); 14748 SDLoc dl(SVN); 14749 bool IsLittleEndian = Subtarget.isLittleEndian(); 14750 14751 // On big endian targets this is only useful for subtargets with direct moves. 14752 // On little endian targets it would be useful for all subtargets with VSX. 14753 // However adding special handling for LE subtargets without direct moves 14754 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8) 14755 // which includes direct moves. 14756 if (!Subtarget.hasDirectMove()) 14757 return Res; 14758 14759 // If this is not a shuffle of a shuffle and the first element comes from 14760 // the second vector, canonicalize to the commuted form. This will make it 14761 // more likely to match one of the single instruction patterns. 14762 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14763 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14764 std::swap(LHS, RHS); 14765 Res = DAG.getCommutedVectorShuffle(*SVN); 14766 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14767 } 14768 14769 // Adjust the shuffle mask if either input vector comes from a 14770 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14771 // form (to prevent the need for a swap). 14772 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14773 SDValue SToVLHS = isScalarToVec(LHS); 14774 SDValue SToVRHS = isScalarToVec(RHS); 14775 if (SToVLHS || SToVRHS) { 14776 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14777 : SToVRHS.getValueType().getVectorNumElements(); 14778 int NumEltsOut = ShuffV.size(); 14779 // The width of the "valid lane" (i.e. the lane that contains the value that 14780 // is vectorized) needs to be expressed in terms of the number of elements 14781 // of the shuffle. It is thereby the ratio of the values before and after 14782 // any bitcast. 14783 unsigned ValidLaneWidth = 14784 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() / 14785 LHS.getValueType().getScalarSizeInBits() 14786 : SToVRHS.getValueType().getScalarSizeInBits() / 14787 RHS.getValueType().getScalarSizeInBits(); 14788 14789 // Initially assume that neither input is permuted. These will be adjusted 14790 // accordingly if either input is. 14791 int LHSMaxIdx = -1; 14792 int RHSMinIdx = -1; 14793 int RHSMaxIdx = -1; 14794 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14795 14796 // Get the permuted scalar to vector nodes for the source(s) that come from 14797 // ISD::SCALAR_TO_VECTOR. 14798 // On big endian systems, this only makes sense for element sizes smaller 14799 // than 64 bits since for 64-bit elements, all instructions already put 14800 // the value into element zero. Since scalar size of LHS and RHS may differ 14801 // after isScalarToVec, this should be checked using their own sizes. 14802 if (SToVLHS) { 14803 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64) 14804 return Res; 14805 // Set up the values for the shuffle vector fixup. 14806 LHSMaxIdx = NumEltsOut / NumEltsIn; 14807 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14808 if (SToVLHS.getValueType() != LHS.getValueType()) 14809 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14810 LHS = SToVLHS; 14811 } 14812 if (SToVRHS) { 14813 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64) 14814 return Res; 14815 RHSMinIdx = NumEltsOut; 14816 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14817 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14818 if (SToVRHS.getValueType() != RHS.getValueType()) 14819 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14820 RHS = SToVRHS; 14821 } 14822 14823 // Fix up the shuffle mask to reflect where the desired element actually is. 14824 // The minimum and maximum indices that correspond to element zero for both 14825 // the LHS and RHS are computed and will control which shuffle mask entries 14826 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14827 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14828 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14829 HalfVec, ValidLaneWidth, Subtarget); 14830 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14831 14832 // We may have simplified away the shuffle. We won't be able to do anything 14833 // further with it here. 14834 if (!isa<ShuffleVectorSDNode>(Res)) 14835 return Res; 14836 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14837 } 14838 14839 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14840 // The common case after we commuted the shuffle is that the RHS is a splat 14841 // and we have elements coming in from the splat at indices that are not 14842 // conducive to using a merge. 14843 // Example: 14844 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14845 if (!isSplatBV(TheSplat)) 14846 return Res; 14847 14848 // We are looking for a mask such that all even elements are from 14849 // one vector and all odd elements from the other. 14850 if (!isAlternatingShuffMask(Mask, NumElts)) 14851 return Res; 14852 14853 // Adjust the mask so we are pulling in the same index from the splat 14854 // as the index from the interesting vector in consecutive elements. 14855 if (IsLittleEndian) { 14856 // Example (even elements from first vector): 14857 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14858 if (Mask[0] < NumElts) 14859 for (int i = 1, e = Mask.size(); i < e; i += 2) 14860 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14861 // Example (odd elements from first vector): 14862 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14863 else 14864 for (int i = 0, e = Mask.size(); i < e; i += 2) 14865 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14866 } else { 14867 // Example (even elements from first vector): 14868 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14869 if (Mask[0] < NumElts) 14870 for (int i = 0, e = Mask.size(); i < e; i += 2) 14871 ShuffV[i] = ShuffV[i + 1] - NumElts; 14872 // Example (odd elements from first vector): 14873 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14874 else 14875 for (int i = 1, e = Mask.size(); i < e; i += 2) 14876 ShuffV[i] = ShuffV[i - 1] - NumElts; 14877 } 14878 14879 // If the RHS has undefs, we need to remove them since we may have created 14880 // a shuffle that adds those instead of the splat value. 14881 SDValue SplatVal = 14882 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14883 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 14884 14885 if (IsLittleEndian) 14886 RHS = TheSplat; 14887 else 14888 LHS = TheSplat; 14889 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14890 } 14891 14892 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14893 LSBaseSDNode *LSBase, 14894 DAGCombinerInfo &DCI) const { 14895 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14896 "Not a reverse memop pattern!"); 14897 14898 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14899 auto Mask = SVN->getMask(); 14900 int i = 0; 14901 auto I = Mask.rbegin(); 14902 auto E = Mask.rend(); 14903 14904 for (; I != E; ++I) { 14905 if (*I != i) 14906 return false; 14907 i++; 14908 } 14909 return true; 14910 }; 14911 14912 SelectionDAG &DAG = DCI.DAG; 14913 EVT VT = SVN->getValueType(0); 14914 14915 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14916 return SDValue(); 14917 14918 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14919 // See comment in PPCVSXSwapRemoval.cpp. 14920 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14921 if (!Subtarget.hasP9Vector()) 14922 return SDValue(); 14923 14924 if(!IsElementReverse(SVN)) 14925 return SDValue(); 14926 14927 if (LSBase->getOpcode() == ISD::LOAD) { 14928 // If the load return value 0 has more than one user except the 14929 // shufflevector instruction, it is not profitable to replace the 14930 // shufflevector with a reverse load. 14931 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 14932 UI != UE; ++UI) 14933 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 14934 return SDValue(); 14935 14936 SDLoc dl(LSBase); 14937 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14938 return DAG.getMemIntrinsicNode( 14939 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14940 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14941 } 14942 14943 if (LSBase->getOpcode() == ISD::STORE) { 14944 // If there are other uses of the shuffle, the swap cannot be avoided. 14945 // Forcing the use of an X-Form (since swapped stores only have 14946 // X-Forms) without removing the swap is unprofitable. 14947 if (!SVN->hasOneUse()) 14948 return SDValue(); 14949 14950 SDLoc dl(LSBase); 14951 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14952 LSBase->getBasePtr()}; 14953 return DAG.getMemIntrinsicNode( 14954 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14955 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14956 } 14957 14958 llvm_unreachable("Expected a load or store node here"); 14959 } 14960 14961 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14962 DAGCombinerInfo &DCI) const { 14963 SelectionDAG &DAG = DCI.DAG; 14964 SDLoc dl(N); 14965 switch (N->getOpcode()) { 14966 default: break; 14967 case ISD::ADD: 14968 return combineADD(N, DCI); 14969 case ISD::SHL: 14970 return combineSHL(N, DCI); 14971 case ISD::SRA: 14972 return combineSRA(N, DCI); 14973 case ISD::SRL: 14974 return combineSRL(N, DCI); 14975 case ISD::MUL: 14976 return combineMUL(N, DCI); 14977 case ISD::FMA: 14978 case PPCISD::FNMSUB: 14979 return combineFMALike(N, DCI); 14980 case PPCISD::SHL: 14981 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14982 return N->getOperand(0); 14983 break; 14984 case PPCISD::SRL: 14985 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14986 return N->getOperand(0); 14987 break; 14988 case PPCISD::SRA: 14989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14990 if (C->isZero() || // 0 >>s V -> 0. 14991 C->isAllOnes()) // -1 >>s V -> -1. 14992 return N->getOperand(0); 14993 } 14994 break; 14995 case ISD::SIGN_EXTEND: 14996 case ISD::ZERO_EXTEND: 14997 case ISD::ANY_EXTEND: 14998 return DAGCombineExtBoolTrunc(N, DCI); 14999 case ISD::TRUNCATE: 15000 return combineTRUNCATE(N, DCI); 15001 case ISD::SETCC: 15002 if (SDValue CSCC = combineSetCC(N, DCI)) 15003 return CSCC; 15004 LLVM_FALLTHROUGH; 15005 case ISD::SELECT_CC: 15006 return DAGCombineTruncBoolExt(N, DCI); 15007 case ISD::SINT_TO_FP: 15008 case ISD::UINT_TO_FP: 15009 return combineFPToIntToFP(N, DCI); 15010 case ISD::VECTOR_SHUFFLE: 15011 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 15012 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 15013 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 15014 } 15015 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 15016 case ISD::STORE: { 15017 15018 EVT Op1VT = N->getOperand(1).getValueType(); 15019 unsigned Opcode = N->getOperand(1).getOpcode(); 15020 15021 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 15022 SDValue Val= combineStoreFPToInt(N, DCI); 15023 if (Val) 15024 return Val; 15025 } 15026 15027 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 15028 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 15029 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 15030 if (Val) 15031 return Val; 15032 } 15033 15034 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 15035 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 15036 N->getOperand(1).getNode()->hasOneUse() && 15037 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 15038 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 15039 15040 // STBRX can only handle simple types and it makes no sense to store less 15041 // two bytes in byte-reversed order. 15042 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 15043 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 15044 break; 15045 15046 SDValue BSwapOp = N->getOperand(1).getOperand(0); 15047 // Do an any-extend to 32-bits if this is a half-word input. 15048 if (BSwapOp.getValueType() == MVT::i16) 15049 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 15050 15051 // If the type of BSWAP operand is wider than stored memory width 15052 // it need to be shifted to the right side before STBRX. 15053 if (Op1VT.bitsGT(mVT)) { 15054 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 15055 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 15056 DAG.getConstant(Shift, dl, MVT::i32)); 15057 // Need to truncate if this is a bswap of i64 stored as i32/i16. 15058 if (Op1VT == MVT::i64) 15059 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 15060 } 15061 15062 SDValue Ops[] = { 15063 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 15064 }; 15065 return 15066 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 15067 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 15068 cast<StoreSDNode>(N)->getMemOperand()); 15069 } 15070 15071 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 15072 // So it can increase the chance of CSE constant construction. 15073 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 15074 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 15075 // Need to sign-extended to 64-bits to handle negative values. 15076 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 15077 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 15078 MemVT.getSizeInBits()); 15079 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 15080 15081 // DAG.getTruncStore() can't be used here because it doesn't accept 15082 // the general (base + offset) addressing mode. 15083 // So we use UpdateNodeOperands and setTruncatingStore instead. 15084 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 15085 N->getOperand(3)); 15086 cast<StoreSDNode>(N)->setTruncatingStore(true); 15087 return SDValue(N, 0); 15088 } 15089 15090 // For little endian, VSX stores require generating xxswapd/lxvd2x. 15091 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15092 if (Op1VT.isSimple()) { 15093 MVT StoreVT = Op1VT.getSimpleVT(); 15094 if (Subtarget.needsSwapsForVSXMemOps() && 15095 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 15096 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 15097 return expandVSXStoreForLE(N, DCI); 15098 } 15099 break; 15100 } 15101 case ISD::LOAD: { 15102 LoadSDNode *LD = cast<LoadSDNode>(N); 15103 EVT VT = LD->getValueType(0); 15104 15105 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15106 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15107 if (VT.isSimple()) { 15108 MVT LoadVT = VT.getSimpleVT(); 15109 if (Subtarget.needsSwapsForVSXMemOps() && 15110 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 15111 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 15112 return expandVSXLoadForLE(N, DCI); 15113 } 15114 15115 // We sometimes end up with a 64-bit integer load, from which we extract 15116 // two single-precision floating-point numbers. This happens with 15117 // std::complex<float>, and other similar structures, because of the way we 15118 // canonicalize structure copies. However, if we lack direct moves, 15119 // then the final bitcasts from the extracted integer values to the 15120 // floating-point numbers turn into store/load pairs. Even with direct moves, 15121 // just loading the two floating-point numbers is likely better. 15122 auto ReplaceTwoFloatLoad = [&]() { 15123 if (VT != MVT::i64) 15124 return false; 15125 15126 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 15127 LD->isVolatile()) 15128 return false; 15129 15130 // We're looking for a sequence like this: 15131 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 15132 // t16: i64 = srl t13, Constant:i32<32> 15133 // t17: i32 = truncate t16 15134 // t18: f32 = bitcast t17 15135 // t19: i32 = truncate t13 15136 // t20: f32 = bitcast t19 15137 15138 if (!LD->hasNUsesOfValue(2, 0)) 15139 return false; 15140 15141 auto UI = LD->use_begin(); 15142 while (UI.getUse().getResNo() != 0) ++UI; 15143 SDNode *Trunc = *UI++; 15144 while (UI.getUse().getResNo() != 0) ++UI; 15145 SDNode *RightShift = *UI; 15146 if (Trunc->getOpcode() != ISD::TRUNCATE) 15147 std::swap(Trunc, RightShift); 15148 15149 if (Trunc->getOpcode() != ISD::TRUNCATE || 15150 Trunc->getValueType(0) != MVT::i32 || 15151 !Trunc->hasOneUse()) 15152 return false; 15153 if (RightShift->getOpcode() != ISD::SRL || 15154 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 15155 RightShift->getConstantOperandVal(1) != 32 || 15156 !RightShift->hasOneUse()) 15157 return false; 15158 15159 SDNode *Trunc2 = *RightShift->use_begin(); 15160 if (Trunc2->getOpcode() != ISD::TRUNCATE || 15161 Trunc2->getValueType(0) != MVT::i32 || 15162 !Trunc2->hasOneUse()) 15163 return false; 15164 15165 SDNode *Bitcast = *Trunc->use_begin(); 15166 SDNode *Bitcast2 = *Trunc2->use_begin(); 15167 15168 if (Bitcast->getOpcode() != ISD::BITCAST || 15169 Bitcast->getValueType(0) != MVT::f32) 15170 return false; 15171 if (Bitcast2->getOpcode() != ISD::BITCAST || 15172 Bitcast2->getValueType(0) != MVT::f32) 15173 return false; 15174 15175 if (Subtarget.isLittleEndian()) 15176 std::swap(Bitcast, Bitcast2); 15177 15178 // Bitcast has the second float (in memory-layout order) and Bitcast2 15179 // has the first one. 15180 15181 SDValue BasePtr = LD->getBasePtr(); 15182 if (LD->isIndexed()) { 15183 assert(LD->getAddressingMode() == ISD::PRE_INC && 15184 "Non-pre-inc AM on PPC?"); 15185 BasePtr = 15186 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15187 LD->getOffset()); 15188 } 15189 15190 auto MMOFlags = 15191 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15192 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15193 LD->getPointerInfo(), LD->getAlignment(), 15194 MMOFlags, LD->getAAInfo()); 15195 SDValue AddPtr = 15196 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15197 BasePtr, DAG.getIntPtrConstant(4, dl)); 15198 SDValue FloatLoad2 = DAG.getLoad( 15199 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15200 LD->getPointerInfo().getWithOffset(4), 15201 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 15202 15203 if (LD->isIndexed()) { 15204 // Note that DAGCombine should re-form any pre-increment load(s) from 15205 // what is produced here if that makes sense. 15206 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15207 } 15208 15209 DCI.CombineTo(Bitcast2, FloatLoad); 15210 DCI.CombineTo(Bitcast, FloatLoad2); 15211 15212 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15213 SDValue(FloatLoad2.getNode(), 1)); 15214 return true; 15215 }; 15216 15217 if (ReplaceTwoFloatLoad()) 15218 return SDValue(N, 0); 15219 15220 EVT MemVT = LD->getMemoryVT(); 15221 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15222 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15223 if (LD->isUnindexed() && VT.isVector() && 15224 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15225 // P8 and later hardware should just use LOAD. 15226 !Subtarget.hasP8Vector() && 15227 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15228 VT == MVT::v4f32))) && 15229 LD->getAlign() < ABIAlignment) { 15230 // This is a type-legal unaligned Altivec load. 15231 SDValue Chain = LD->getChain(); 15232 SDValue Ptr = LD->getBasePtr(); 15233 bool isLittleEndian = Subtarget.isLittleEndian(); 15234 15235 // This implements the loading of unaligned vectors as described in 15236 // the venerable Apple Velocity Engine overview. Specifically: 15237 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15238 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15239 // 15240 // The general idea is to expand a sequence of one or more unaligned 15241 // loads into an alignment-based permutation-control instruction (lvsl 15242 // or lvsr), a series of regular vector loads (which always truncate 15243 // their input address to an aligned address), and a series of 15244 // permutations. The results of these permutations are the requested 15245 // loaded values. The trick is that the last "extra" load is not taken 15246 // from the address you might suspect (sizeof(vector) bytes after the 15247 // last requested load), but rather sizeof(vector) - 1 bytes after the 15248 // last requested vector. The point of this is to avoid a page fault if 15249 // the base address happened to be aligned. This works because if the 15250 // base address is aligned, then adding less than a full vector length 15251 // will cause the last vector in the sequence to be (re)loaded. 15252 // Otherwise, the next vector will be fetched as you might suspect was 15253 // necessary. 15254 15255 // We might be able to reuse the permutation generation from 15256 // a different base address offset from this one by an aligned amount. 15257 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15258 // optimization later. 15259 Intrinsic::ID Intr, IntrLD, IntrPerm; 15260 MVT PermCntlTy, PermTy, LDTy; 15261 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15262 : Intrinsic::ppc_altivec_lvsl; 15263 IntrLD = Intrinsic::ppc_altivec_lvx; 15264 IntrPerm = Intrinsic::ppc_altivec_vperm; 15265 PermCntlTy = MVT::v16i8; 15266 PermTy = MVT::v4i32; 15267 LDTy = MVT::v4i32; 15268 15269 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15270 15271 // Create the new MMO for the new base load. It is like the original MMO, 15272 // but represents an area in memory almost twice the vector size centered 15273 // on the original address. If the address is unaligned, we might start 15274 // reading up to (sizeof(vector)-1) bytes below the address of the 15275 // original unaligned load. 15276 MachineFunction &MF = DAG.getMachineFunction(); 15277 MachineMemOperand *BaseMMO = 15278 MF.getMachineMemOperand(LD->getMemOperand(), 15279 -(long)MemVT.getStoreSize()+1, 15280 2*MemVT.getStoreSize()-1); 15281 15282 // Create the new base load. 15283 SDValue LDXIntID = 15284 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15285 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15286 SDValue BaseLoad = 15287 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15288 DAG.getVTList(PermTy, MVT::Other), 15289 BaseLoadOps, LDTy, BaseMMO); 15290 15291 // Note that the value of IncOffset (which is provided to the next 15292 // load's pointer info offset value, and thus used to calculate the 15293 // alignment), and the value of IncValue (which is actually used to 15294 // increment the pointer value) are different! This is because we 15295 // require the next load to appear to be aligned, even though it 15296 // is actually offset from the base pointer by a lesser amount. 15297 int IncOffset = VT.getSizeInBits() / 8; 15298 int IncValue = IncOffset; 15299 15300 // Walk (both up and down) the chain looking for another load at the real 15301 // (aligned) offset (the alignment of the other load does not matter in 15302 // this case). If found, then do not use the offset reduction trick, as 15303 // that will prevent the loads from being later combined (as they would 15304 // otherwise be duplicates). 15305 if (!findConsecutiveLoad(LD, DAG)) 15306 --IncValue; 15307 15308 SDValue Increment = 15309 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15310 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15311 15312 MachineMemOperand *ExtraMMO = 15313 MF.getMachineMemOperand(LD->getMemOperand(), 15314 1, 2*MemVT.getStoreSize()-1); 15315 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15316 SDValue ExtraLoad = 15317 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15318 DAG.getVTList(PermTy, MVT::Other), 15319 ExtraLoadOps, LDTy, ExtraMMO); 15320 15321 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15322 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15323 15324 // Because vperm has a big-endian bias, we must reverse the order 15325 // of the input vectors and complement the permute control vector 15326 // when generating little endian code. We have already handled the 15327 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15328 // and ExtraLoad here. 15329 SDValue Perm; 15330 if (isLittleEndian) 15331 Perm = BuildIntrinsicOp(IntrPerm, 15332 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15333 else 15334 Perm = BuildIntrinsicOp(IntrPerm, 15335 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15336 15337 if (VT != PermTy) 15338 Perm = Subtarget.hasAltivec() 15339 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15340 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15341 DAG.getTargetConstant(1, dl, MVT::i64)); 15342 // second argument is 1 because this rounding 15343 // is always exact. 15344 15345 // The output of the permutation is our loaded result, the TokenFactor is 15346 // our new chain. 15347 DCI.CombineTo(N, Perm, TF); 15348 return SDValue(N, 0); 15349 } 15350 } 15351 break; 15352 case ISD::INTRINSIC_WO_CHAIN: { 15353 bool isLittleEndian = Subtarget.isLittleEndian(); 15354 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15355 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15356 : Intrinsic::ppc_altivec_lvsl); 15357 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15358 SDValue Add = N->getOperand(1); 15359 15360 int Bits = 4 /* 16 byte alignment */; 15361 15362 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15363 APInt::getAllOnes(Bits /* alignment */) 15364 .zext(Add.getScalarValueSizeInBits()))) { 15365 SDNode *BasePtr = Add->getOperand(0).getNode(); 15366 for (SDNode *U : BasePtr->uses()) { 15367 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15368 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) { 15369 // We've found another LVSL/LVSR, and this address is an aligned 15370 // multiple of that one. The results will be the same, so use the 15371 // one we've just found instead. 15372 15373 return SDValue(U, 0); 15374 } 15375 } 15376 } 15377 15378 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15379 SDNode *BasePtr = Add->getOperand(0).getNode(); 15380 for (SDNode *U : BasePtr->uses()) { 15381 if (U->getOpcode() == ISD::ADD && 15382 isa<ConstantSDNode>(U->getOperand(1)) && 15383 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15384 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) % 15385 (1ULL << Bits) == 15386 0) { 15387 SDNode *OtherAdd = U; 15388 for (SDNode *V : OtherAdd->uses()) { 15389 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15390 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() == 15391 IID) { 15392 return SDValue(V, 0); 15393 } 15394 } 15395 } 15396 } 15397 } 15398 } 15399 15400 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15401 // Expose the vabsduw/h/b opportunity for down stream 15402 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15403 (IID == Intrinsic::ppc_altivec_vmaxsw || 15404 IID == Intrinsic::ppc_altivec_vmaxsh || 15405 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15406 SDValue V1 = N->getOperand(1); 15407 SDValue V2 = N->getOperand(2); 15408 if ((V1.getSimpleValueType() == MVT::v4i32 || 15409 V1.getSimpleValueType() == MVT::v8i16 || 15410 V1.getSimpleValueType() == MVT::v16i8) && 15411 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15412 // (0-a, a) 15413 if (V1.getOpcode() == ISD::SUB && 15414 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15415 V1.getOperand(1) == V2) { 15416 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15417 } 15418 // (a, 0-a) 15419 if (V2.getOpcode() == ISD::SUB && 15420 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15421 V2.getOperand(1) == V1) { 15422 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15423 } 15424 // (x-y, y-x) 15425 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15426 V1.getOperand(0) == V2.getOperand(1) && 15427 V1.getOperand(1) == V2.getOperand(0)) { 15428 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15429 } 15430 } 15431 } 15432 } 15433 15434 break; 15435 case ISD::INTRINSIC_W_CHAIN: 15436 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15437 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15438 if (Subtarget.needsSwapsForVSXMemOps()) { 15439 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15440 default: 15441 break; 15442 case Intrinsic::ppc_vsx_lxvw4x: 15443 case Intrinsic::ppc_vsx_lxvd2x: 15444 return expandVSXLoadForLE(N, DCI); 15445 } 15446 } 15447 break; 15448 case ISD::INTRINSIC_VOID: 15449 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15450 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15451 if (Subtarget.needsSwapsForVSXMemOps()) { 15452 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15453 default: 15454 break; 15455 case Intrinsic::ppc_vsx_stxvw4x: 15456 case Intrinsic::ppc_vsx_stxvd2x: 15457 return expandVSXStoreForLE(N, DCI); 15458 } 15459 } 15460 break; 15461 case ISD::BSWAP: { 15462 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15463 // For subtargets without LDBRX, we can still do better than the default 15464 // expansion even for 64-bit BSWAP (LOAD). 15465 bool Is64BitBswapOn64BitTgt = 15466 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64; 15467 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) && 15468 N->getOperand(0).hasOneUse(); 15469 if (IsSingleUseNormalLd && 15470 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15471 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) { 15472 SDValue Load = N->getOperand(0); 15473 LoadSDNode *LD = cast<LoadSDNode>(Load); 15474 // Create the byte-swapping load. 15475 SDValue Ops[] = { 15476 LD->getChain(), // Chain 15477 LD->getBasePtr(), // Ptr 15478 DAG.getValueType(N->getValueType(0)) // VT 15479 }; 15480 SDValue BSLoad = 15481 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15482 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15483 MVT::i64 : MVT::i32, MVT::Other), 15484 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15485 15486 // If this is an i16 load, insert the truncate. 15487 SDValue ResVal = BSLoad; 15488 if (N->getValueType(0) == MVT::i16) 15489 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15490 15491 // First, combine the bswap away. This makes the value produced by the 15492 // load dead. 15493 DCI.CombineTo(N, ResVal); 15494 15495 // Next, combine the load away, we give it a bogus result value but a real 15496 // chain result. The result value is dead because the bswap is dead. 15497 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15498 15499 // Return N so it doesn't get rechecked! 15500 return SDValue(N, 0); 15501 } 15502 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only 15503 // before legalization so that the BUILD_PAIR is handled correctly. 15504 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt || 15505 !IsSingleUseNormalLd) 15506 return SDValue(); 15507 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0)); 15508 15509 // Can't split volatile or atomic loads. 15510 if (!LD->isSimple()) 15511 return SDValue(); 15512 SDValue BasePtr = LD->getBasePtr(); 15513 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, 15514 LD->getPointerInfo(), LD->getAlignment()); 15515 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo); 15516 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15517 DAG.getIntPtrConstant(4, dl)); 15518 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand( 15519 LD->getMemOperand(), 4, 4); 15520 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO); 15521 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi); 15522 SDValue Res; 15523 if (Subtarget.isLittleEndian()) 15524 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo); 15525 else 15526 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 15527 SDValue TF = 15528 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15529 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1)); 15530 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF); 15531 return Res; 15532 } 15533 case PPCISD::VCMP: 15534 // If a VCMP_rec node already exists with exactly the same operands as this 15535 // node, use its result instead of this node (VCMP_rec computes both a CR6 15536 // and a normal output). 15537 // 15538 if (!N->getOperand(0).hasOneUse() && 15539 !N->getOperand(1).hasOneUse() && 15540 !N->getOperand(2).hasOneUse()) { 15541 15542 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15543 SDNode *VCMPrecNode = nullptr; 15544 15545 SDNode *LHSN = N->getOperand(0).getNode(); 15546 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15547 UI != E; ++UI) 15548 if (UI->getOpcode() == PPCISD::VCMP_rec && 15549 UI->getOperand(1) == N->getOperand(1) && 15550 UI->getOperand(2) == N->getOperand(2) && 15551 UI->getOperand(0) == N->getOperand(0)) { 15552 VCMPrecNode = *UI; 15553 break; 15554 } 15555 15556 // If there is no VCMP_rec node, or if the flag value has a single use, 15557 // don't transform this. 15558 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15559 break; 15560 15561 // Look at the (necessarily single) use of the flag value. If it has a 15562 // chain, this transformation is more complex. Note that multiple things 15563 // could use the value result, which we should ignore. 15564 SDNode *FlagUser = nullptr; 15565 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15566 FlagUser == nullptr; ++UI) { 15567 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15568 SDNode *User = *UI; 15569 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15570 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15571 FlagUser = User; 15572 break; 15573 } 15574 } 15575 } 15576 15577 // If the user is a MFOCRF instruction, we know this is safe. 15578 // Otherwise we give up for right now. 15579 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15580 return SDValue(VCMPrecNode, 0); 15581 } 15582 break; 15583 case ISD::BRCOND: { 15584 SDValue Cond = N->getOperand(1); 15585 SDValue Target = N->getOperand(2); 15586 15587 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15588 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15589 Intrinsic::loop_decrement) { 15590 15591 // We now need to make the intrinsic dead (it cannot be instruction 15592 // selected). 15593 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15594 assert(Cond.getNode()->hasOneUse() && 15595 "Counter decrement has more than one use"); 15596 15597 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15598 N->getOperand(0), Target); 15599 } 15600 } 15601 break; 15602 case ISD::BR_CC: { 15603 // If this is a branch on an altivec predicate comparison, lower this so 15604 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15605 // lowering is done pre-legalize, because the legalizer lowers the predicate 15606 // compare down to code that is difficult to reassemble. 15607 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15608 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15609 15610 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15611 // value. If so, pass-through the AND to get to the intrinsic. 15612 if (LHS.getOpcode() == ISD::AND && 15613 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15614 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15615 Intrinsic::loop_decrement && 15616 isa<ConstantSDNode>(LHS.getOperand(1)) && 15617 !isNullConstant(LHS.getOperand(1))) 15618 LHS = LHS.getOperand(0); 15619 15620 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15621 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15622 Intrinsic::loop_decrement && 15623 isa<ConstantSDNode>(RHS)) { 15624 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15625 "Counter decrement comparison is not EQ or NE"); 15626 15627 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15628 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15629 (CC == ISD::SETNE && !Val); 15630 15631 // We now need to make the intrinsic dead (it cannot be instruction 15632 // selected). 15633 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15634 assert(LHS.getNode()->hasOneUse() && 15635 "Counter decrement has more than one use"); 15636 15637 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15638 N->getOperand(0), N->getOperand(4)); 15639 } 15640 15641 int CompareOpc; 15642 bool isDot; 15643 15644 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15645 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15646 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15647 assert(isDot && "Can't compare against a vector result!"); 15648 15649 // If this is a comparison against something other than 0/1, then we know 15650 // that the condition is never/always true. 15651 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15652 if (Val != 0 && Val != 1) { 15653 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15654 return N->getOperand(0); 15655 // Always !=, turn it into an unconditional branch. 15656 return DAG.getNode(ISD::BR, dl, MVT::Other, 15657 N->getOperand(0), N->getOperand(4)); 15658 } 15659 15660 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15661 15662 // Create the PPCISD altivec 'dot' comparison node. 15663 SDValue Ops[] = { 15664 LHS.getOperand(2), // LHS of compare 15665 LHS.getOperand(3), // RHS of compare 15666 DAG.getConstant(CompareOpc, dl, MVT::i32) 15667 }; 15668 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15669 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15670 15671 // Unpack the result based on how the target uses it. 15672 PPC::Predicate CompOpc; 15673 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15674 default: // Can't happen, don't crash on invalid number though. 15675 case 0: // Branch on the value of the EQ bit of CR6. 15676 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15677 break; 15678 case 1: // Branch on the inverted value of the EQ bit of CR6. 15679 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15680 break; 15681 case 2: // Branch on the value of the LT bit of CR6. 15682 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15683 break; 15684 case 3: // Branch on the inverted value of the LT bit of CR6. 15685 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15686 break; 15687 } 15688 15689 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15690 DAG.getConstant(CompOpc, dl, MVT::i32), 15691 DAG.getRegister(PPC::CR6, MVT::i32), 15692 N->getOperand(4), CompNode.getValue(1)); 15693 } 15694 break; 15695 } 15696 case ISD::BUILD_VECTOR: 15697 return DAGCombineBuildVector(N, DCI); 15698 case ISD::ABS: 15699 return combineABS(N, DCI); 15700 case ISD::VSELECT: 15701 return combineVSelect(N, DCI); 15702 } 15703 15704 return SDValue(); 15705 } 15706 15707 SDValue 15708 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15709 SelectionDAG &DAG, 15710 SmallVectorImpl<SDNode *> &Created) const { 15711 // fold (sdiv X, pow2) 15712 EVT VT = N->getValueType(0); 15713 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15714 return SDValue(); 15715 if ((VT != MVT::i32 && VT != MVT::i64) || 15716 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2())) 15717 return SDValue(); 15718 15719 SDLoc DL(N); 15720 SDValue N0 = N->getOperand(0); 15721 15722 bool IsNegPow2 = Divisor.isNegatedPowerOf2(); 15723 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15724 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15725 15726 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15727 Created.push_back(Op.getNode()); 15728 15729 if (IsNegPow2) { 15730 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15731 Created.push_back(Op.getNode()); 15732 } 15733 15734 return Op; 15735 } 15736 15737 //===----------------------------------------------------------------------===// 15738 // Inline Assembly Support 15739 //===----------------------------------------------------------------------===// 15740 15741 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15742 KnownBits &Known, 15743 const APInt &DemandedElts, 15744 const SelectionDAG &DAG, 15745 unsigned Depth) const { 15746 Known.resetAll(); 15747 switch (Op.getOpcode()) { 15748 default: break; 15749 case PPCISD::LBRX: { 15750 // lhbrx is known to have the top bits cleared out. 15751 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15752 Known.Zero = 0xFFFF0000; 15753 break; 15754 } 15755 case ISD::INTRINSIC_WO_CHAIN: { 15756 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15757 default: break; 15758 case Intrinsic::ppc_altivec_vcmpbfp_p: 15759 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15760 case Intrinsic::ppc_altivec_vcmpequb_p: 15761 case Intrinsic::ppc_altivec_vcmpequh_p: 15762 case Intrinsic::ppc_altivec_vcmpequw_p: 15763 case Intrinsic::ppc_altivec_vcmpequd_p: 15764 case Intrinsic::ppc_altivec_vcmpequq_p: 15765 case Intrinsic::ppc_altivec_vcmpgefp_p: 15766 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15767 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15768 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15769 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15770 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15771 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15772 case Intrinsic::ppc_altivec_vcmpgtub_p: 15773 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15774 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15775 case Intrinsic::ppc_altivec_vcmpgtud_p: 15776 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15777 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15778 break; 15779 } 15780 break; 15781 } 15782 case ISD::INTRINSIC_W_CHAIN: { 15783 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 15784 default: 15785 break; 15786 case Intrinsic::ppc_load2r: 15787 // Top bits are cleared for load2r (which is the same as lhbrx). 15788 Known.Zero = 0xFFFF0000; 15789 break; 15790 } 15791 break; 15792 } 15793 } 15794 } 15795 15796 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15797 switch (Subtarget.getCPUDirective()) { 15798 default: break; 15799 case PPC::DIR_970: 15800 case PPC::DIR_PWR4: 15801 case PPC::DIR_PWR5: 15802 case PPC::DIR_PWR5X: 15803 case PPC::DIR_PWR6: 15804 case PPC::DIR_PWR6X: 15805 case PPC::DIR_PWR7: 15806 case PPC::DIR_PWR8: 15807 case PPC::DIR_PWR9: 15808 case PPC::DIR_PWR10: 15809 case PPC::DIR_PWR_FUTURE: { 15810 if (!ML) 15811 break; 15812 15813 if (!DisableInnermostLoopAlign32) { 15814 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15815 // so that we can decrease cache misses and branch-prediction misses. 15816 // Actual alignment of the loop will depend on the hotness check and other 15817 // logic in alignBlocks. 15818 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15819 return Align(32); 15820 } 15821 15822 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15823 15824 // For small loops (between 5 and 8 instructions), align to a 32-byte 15825 // boundary so that the entire loop fits in one instruction-cache line. 15826 uint64_t LoopSize = 0; 15827 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15828 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15829 LoopSize += TII->getInstSizeInBytes(*J); 15830 if (LoopSize > 32) 15831 break; 15832 } 15833 15834 if (LoopSize > 16 && LoopSize <= 32) 15835 return Align(32); 15836 15837 break; 15838 } 15839 } 15840 15841 return TargetLowering::getPrefLoopAlignment(ML); 15842 } 15843 15844 /// getConstraintType - Given a constraint, return the type of 15845 /// constraint it is for this target. 15846 PPCTargetLowering::ConstraintType 15847 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15848 if (Constraint.size() == 1) { 15849 switch (Constraint[0]) { 15850 default: break; 15851 case 'b': 15852 case 'r': 15853 case 'f': 15854 case 'd': 15855 case 'v': 15856 case 'y': 15857 return C_RegisterClass; 15858 case 'Z': 15859 // FIXME: While Z does indicate a memory constraint, it specifically 15860 // indicates an r+r address (used in conjunction with the 'y' modifier 15861 // in the replacement string). Currently, we're forcing the base 15862 // register to be r0 in the asm printer (which is interpreted as zero) 15863 // and forming the complete address in the second register. This is 15864 // suboptimal. 15865 return C_Memory; 15866 } 15867 } else if (Constraint == "wc") { // individual CR bits. 15868 return C_RegisterClass; 15869 } else if (Constraint == "wa" || Constraint == "wd" || 15870 Constraint == "wf" || Constraint == "ws" || 15871 Constraint == "wi" || Constraint == "ww") { 15872 return C_RegisterClass; // VSX registers. 15873 } 15874 return TargetLowering::getConstraintType(Constraint); 15875 } 15876 15877 /// Examine constraint type and operand type and determine a weight value. 15878 /// This object must already have been set up with the operand type 15879 /// and the current alternative constraint selected. 15880 TargetLowering::ConstraintWeight 15881 PPCTargetLowering::getSingleConstraintMatchWeight( 15882 AsmOperandInfo &info, const char *constraint) const { 15883 ConstraintWeight weight = CW_Invalid; 15884 Value *CallOperandVal = info.CallOperandVal; 15885 // If we don't have a value, we can't do a match, 15886 // but allow it at the lowest weight. 15887 if (!CallOperandVal) 15888 return CW_Default; 15889 Type *type = CallOperandVal->getType(); 15890 15891 // Look at the constraint type. 15892 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15893 return CW_Register; // an individual CR bit. 15894 else if ((StringRef(constraint) == "wa" || 15895 StringRef(constraint) == "wd" || 15896 StringRef(constraint) == "wf") && 15897 type->isVectorTy()) 15898 return CW_Register; 15899 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15900 return CW_Register; // just hold 64-bit integers data. 15901 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15902 return CW_Register; 15903 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15904 return CW_Register; 15905 15906 switch (*constraint) { 15907 default: 15908 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15909 break; 15910 case 'b': 15911 if (type->isIntegerTy()) 15912 weight = CW_Register; 15913 break; 15914 case 'f': 15915 if (type->isFloatTy()) 15916 weight = CW_Register; 15917 break; 15918 case 'd': 15919 if (type->isDoubleTy()) 15920 weight = CW_Register; 15921 break; 15922 case 'v': 15923 if (type->isVectorTy()) 15924 weight = CW_Register; 15925 break; 15926 case 'y': 15927 weight = CW_Register; 15928 break; 15929 case 'Z': 15930 weight = CW_Memory; 15931 break; 15932 } 15933 return weight; 15934 } 15935 15936 std::pair<unsigned, const TargetRegisterClass *> 15937 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15938 StringRef Constraint, 15939 MVT VT) const { 15940 if (Constraint.size() == 1) { 15941 // GCC RS6000 Constraint Letters 15942 switch (Constraint[0]) { 15943 case 'b': // R1-R31 15944 if (VT == MVT::i64 && Subtarget.isPPC64()) 15945 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15946 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15947 case 'r': // R0-R31 15948 if (VT == MVT::i64 && Subtarget.isPPC64()) 15949 return std::make_pair(0U, &PPC::G8RCRegClass); 15950 return std::make_pair(0U, &PPC::GPRCRegClass); 15951 // 'd' and 'f' constraints are both defined to be "the floating point 15952 // registers", where one is for 32-bit and the other for 64-bit. We don't 15953 // really care overly much here so just give them all the same reg classes. 15954 case 'd': 15955 case 'f': 15956 if (Subtarget.hasSPE()) { 15957 if (VT == MVT::f32 || VT == MVT::i32) 15958 return std::make_pair(0U, &PPC::GPRCRegClass); 15959 if (VT == MVT::f64 || VT == MVT::i64) 15960 return std::make_pair(0U, &PPC::SPERCRegClass); 15961 } else { 15962 if (VT == MVT::f32 || VT == MVT::i32) 15963 return std::make_pair(0U, &PPC::F4RCRegClass); 15964 if (VT == MVT::f64 || VT == MVT::i64) 15965 return std::make_pair(0U, &PPC::F8RCRegClass); 15966 } 15967 break; 15968 case 'v': 15969 if (Subtarget.hasAltivec()) 15970 return std::make_pair(0U, &PPC::VRRCRegClass); 15971 break; 15972 case 'y': // crrc 15973 return std::make_pair(0U, &PPC::CRRCRegClass); 15974 } 15975 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15976 // An individual CR bit. 15977 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15978 } else if ((Constraint == "wa" || Constraint == "wd" || 15979 Constraint == "wf" || Constraint == "wi") && 15980 Subtarget.hasVSX()) { 15981 // A VSX register for either a scalar (FP) or vector. There is no 15982 // support for single precision scalars on subtargets prior to Power8. 15983 if (VT.isVector()) 15984 return std::make_pair(0U, &PPC::VSRCRegClass); 15985 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15986 return std::make_pair(0U, &PPC::VSSRCRegClass); 15987 return std::make_pair(0U, &PPC::VSFRCRegClass); 15988 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15989 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15990 return std::make_pair(0U, &PPC::VSSRCRegClass); 15991 else 15992 return std::make_pair(0U, &PPC::VSFRCRegClass); 15993 } else if (Constraint == "lr") { 15994 if (VT == MVT::i64) 15995 return std::make_pair(0U, &PPC::LR8RCRegClass); 15996 else 15997 return std::make_pair(0U, &PPC::LRRCRegClass); 15998 } 15999 16000 // Handle special cases of physical registers that are not properly handled 16001 // by the base class. 16002 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 16003 // If we name a VSX register, we can't defer to the base class because it 16004 // will not recognize the correct register (their names will be VSL{0-31} 16005 // and V{0-31} so they won't match). So we match them here. 16006 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 16007 int VSNum = atoi(Constraint.data() + 3); 16008 assert(VSNum >= 0 && VSNum <= 63 && 16009 "Attempted to access a vsr out of range"); 16010 if (VSNum < 32) 16011 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 16012 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 16013 } 16014 16015 // For float registers, we can't defer to the base class as it will match 16016 // the SPILLTOVSRRC class. 16017 if (Constraint.size() > 3 && Constraint[1] == 'f') { 16018 int RegNum = atoi(Constraint.data() + 2); 16019 if (RegNum > 31 || RegNum < 0) 16020 report_fatal_error("Invalid floating point register number"); 16021 if (VT == MVT::f32 || VT == MVT::i32) 16022 return Subtarget.hasSPE() 16023 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 16024 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 16025 if (VT == MVT::f64 || VT == MVT::i64) 16026 return Subtarget.hasSPE() 16027 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 16028 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 16029 } 16030 } 16031 16032 std::pair<unsigned, const TargetRegisterClass *> R = 16033 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16034 16035 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 16036 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 16037 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 16038 // register. 16039 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 16040 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 16041 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 16042 PPC::GPRCRegClass.contains(R.first)) 16043 return std::make_pair(TRI->getMatchingSuperReg(R.first, 16044 PPC::sub_32, &PPC::G8RCRegClass), 16045 &PPC::G8RCRegClass); 16046 16047 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 16048 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) { 16049 R.first = PPC::CR0; 16050 R.second = &PPC::CRRCRegClass; 16051 } 16052 // FIXME: This warning should ideally be emitted in the front end. 16053 const auto &TM = getTargetMachine(); 16054 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 16055 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 16056 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 16057 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 16058 errs() << "warning: vector registers 20 to 32 are reserved in the " 16059 "default AIX AltiVec ABI and cannot be used\n"; 16060 } 16061 16062 return R; 16063 } 16064 16065 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16066 /// vector. If it is invalid, don't add anything to Ops. 16067 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16068 std::string &Constraint, 16069 std::vector<SDValue>&Ops, 16070 SelectionDAG &DAG) const { 16071 SDValue Result; 16072 16073 // Only support length 1 constraints. 16074 if (Constraint.length() > 1) return; 16075 16076 char Letter = Constraint[0]; 16077 switch (Letter) { 16078 default: break; 16079 case 'I': 16080 case 'J': 16081 case 'K': 16082 case 'L': 16083 case 'M': 16084 case 'N': 16085 case 'O': 16086 case 'P': { 16087 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 16088 if (!CST) return; // Must be an immediate to match. 16089 SDLoc dl(Op); 16090 int64_t Value = CST->getSExtValue(); 16091 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 16092 // numbers are printed as such. 16093 switch (Letter) { 16094 default: llvm_unreachable("Unknown constraint letter!"); 16095 case 'I': // "I" is a signed 16-bit constant. 16096 if (isInt<16>(Value)) 16097 Result = DAG.getTargetConstant(Value, dl, TCVT); 16098 break; 16099 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 16100 if (isShiftedUInt<16, 16>(Value)) 16101 Result = DAG.getTargetConstant(Value, dl, TCVT); 16102 break; 16103 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 16104 if (isShiftedInt<16, 16>(Value)) 16105 Result = DAG.getTargetConstant(Value, dl, TCVT); 16106 break; 16107 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 16108 if (isUInt<16>(Value)) 16109 Result = DAG.getTargetConstant(Value, dl, TCVT); 16110 break; 16111 case 'M': // "M" is a constant that is greater than 31. 16112 if (Value > 31) 16113 Result = DAG.getTargetConstant(Value, dl, TCVT); 16114 break; 16115 case 'N': // "N" is a positive constant that is an exact power of two. 16116 if (Value > 0 && isPowerOf2_64(Value)) 16117 Result = DAG.getTargetConstant(Value, dl, TCVT); 16118 break; 16119 case 'O': // "O" is the constant zero. 16120 if (Value == 0) 16121 Result = DAG.getTargetConstant(Value, dl, TCVT); 16122 break; 16123 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 16124 if (isInt<16>(-Value)) 16125 Result = DAG.getTargetConstant(Value, dl, TCVT); 16126 break; 16127 } 16128 break; 16129 } 16130 } 16131 16132 if (Result.getNode()) { 16133 Ops.push_back(Result); 16134 return; 16135 } 16136 16137 // Handle standard constraint letters. 16138 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16139 } 16140 16141 // isLegalAddressingMode - Return true if the addressing mode represented 16142 // by AM is legal for this target, for a load/store of the specified type. 16143 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16144 const AddrMode &AM, Type *Ty, 16145 unsigned AS, 16146 Instruction *I) const { 16147 // Vector type r+i form is supported since power9 as DQ form. We don't check 16148 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 16149 // imm form is preferred and the offset can be adjusted to use imm form later 16150 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 16151 // max offset to check legal addressing mode, we should be a little aggressive 16152 // to contain other offsets for that LSRUse. 16153 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 16154 return false; 16155 16156 // PPC allows a sign-extended 16-bit immediate field. 16157 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 16158 return false; 16159 16160 // No global is ever allowed as a base. 16161 if (AM.BaseGV) 16162 return false; 16163 16164 // PPC only support r+r, 16165 switch (AM.Scale) { 16166 case 0: // "r+i" or just "i", depending on HasBaseReg. 16167 break; 16168 case 1: 16169 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 16170 return false; 16171 // Otherwise we have r+r or r+i. 16172 break; 16173 case 2: 16174 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 16175 return false; 16176 // Allow 2*r as r+r. 16177 break; 16178 default: 16179 // No other scales are supported. 16180 return false; 16181 } 16182 16183 return true; 16184 } 16185 16186 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 16187 SelectionDAG &DAG) const { 16188 MachineFunction &MF = DAG.getMachineFunction(); 16189 MachineFrameInfo &MFI = MF.getFrameInfo(); 16190 MFI.setReturnAddressIsTaken(true); 16191 16192 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 16193 return SDValue(); 16194 16195 SDLoc dl(Op); 16196 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16197 16198 // Make sure the function does not optimize away the store of the RA to 16199 // the stack. 16200 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 16201 FuncInfo->setLRStoreRequired(); 16202 bool isPPC64 = Subtarget.isPPC64(); 16203 auto PtrVT = getPointerTy(MF.getDataLayout()); 16204 16205 if (Depth > 0) { 16206 // The link register (return address) is saved in the caller's frame 16207 // not the callee's stack frame. So we must get the caller's frame 16208 // address and load the return address at the LR offset from there. 16209 SDValue FrameAddr = 16210 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16211 LowerFRAMEADDR(Op, DAG), MachinePointerInfo()); 16212 SDValue Offset = 16213 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 16214 isPPC64 ? MVT::i64 : MVT::i32); 16215 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 16216 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 16217 MachinePointerInfo()); 16218 } 16219 16220 // Just load the return address off the stack. 16221 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 16222 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 16223 MachinePointerInfo()); 16224 } 16225 16226 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 16227 SelectionDAG &DAG) const { 16228 SDLoc dl(Op); 16229 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16230 16231 MachineFunction &MF = DAG.getMachineFunction(); 16232 MachineFrameInfo &MFI = MF.getFrameInfo(); 16233 MFI.setFrameAddressIsTaken(true); 16234 16235 EVT PtrVT = getPointerTy(MF.getDataLayout()); 16236 bool isPPC64 = PtrVT == MVT::i64; 16237 16238 // Naked functions never have a frame pointer, and so we use r1. For all 16239 // other functions, this decision must be delayed until during PEI. 16240 unsigned FrameReg; 16241 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 16242 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 16243 else 16244 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 16245 16246 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 16247 PtrVT); 16248 while (Depth--) 16249 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16250 FrameAddr, MachinePointerInfo()); 16251 return FrameAddr; 16252 } 16253 16254 // FIXME? Maybe this could be a TableGen attribute on some registers and 16255 // this table could be generated automatically from RegInfo. 16256 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 16257 const MachineFunction &MF) const { 16258 bool isPPC64 = Subtarget.isPPC64(); 16259 16260 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 16261 if (!is64Bit && VT != LLT::scalar(32)) 16262 report_fatal_error("Invalid register global variable type"); 16263 16264 Register Reg = StringSwitch<Register>(RegName) 16265 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16266 .Case("r2", isPPC64 ? Register() : PPC::R2) 16267 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16268 .Default(Register()); 16269 16270 if (Reg) 16271 return Reg; 16272 report_fatal_error("Invalid register name global variable"); 16273 } 16274 16275 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16276 // 32-bit SVR4 ABI access everything as got-indirect. 16277 if (Subtarget.is32BitELFABI()) 16278 return true; 16279 16280 // AIX accesses everything indirectly through the TOC, which is similar to 16281 // the GOT. 16282 if (Subtarget.isAIXABI()) 16283 return true; 16284 16285 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16286 // If it is small or large code model, module locals are accessed 16287 // indirectly by loading their address from .toc/.got. 16288 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16289 return true; 16290 16291 // JumpTable and BlockAddress are accessed as got-indirect. 16292 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16293 return true; 16294 16295 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16296 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16297 16298 return false; 16299 } 16300 16301 bool 16302 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16303 // The PowerPC target isn't yet aware of offsets. 16304 return false; 16305 } 16306 16307 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16308 const CallInst &I, 16309 MachineFunction &MF, 16310 unsigned Intrinsic) const { 16311 switch (Intrinsic) { 16312 case Intrinsic::ppc_atomicrmw_xchg_i128: 16313 case Intrinsic::ppc_atomicrmw_add_i128: 16314 case Intrinsic::ppc_atomicrmw_sub_i128: 16315 case Intrinsic::ppc_atomicrmw_nand_i128: 16316 case Intrinsic::ppc_atomicrmw_and_i128: 16317 case Intrinsic::ppc_atomicrmw_or_i128: 16318 case Intrinsic::ppc_atomicrmw_xor_i128: 16319 case Intrinsic::ppc_cmpxchg_i128: 16320 Info.opc = ISD::INTRINSIC_W_CHAIN; 16321 Info.memVT = MVT::i128; 16322 Info.ptrVal = I.getArgOperand(0); 16323 Info.offset = 0; 16324 Info.align = Align(16); 16325 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 16326 MachineMemOperand::MOVolatile; 16327 return true; 16328 case Intrinsic::ppc_atomic_load_i128: 16329 Info.opc = ISD::INTRINSIC_W_CHAIN; 16330 Info.memVT = MVT::i128; 16331 Info.ptrVal = I.getArgOperand(0); 16332 Info.offset = 0; 16333 Info.align = Align(16); 16334 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16335 return true; 16336 case Intrinsic::ppc_atomic_store_i128: 16337 Info.opc = ISD::INTRINSIC_VOID; 16338 Info.memVT = MVT::i128; 16339 Info.ptrVal = I.getArgOperand(2); 16340 Info.offset = 0; 16341 Info.align = Align(16); 16342 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16343 return true; 16344 case Intrinsic::ppc_altivec_lvx: 16345 case Intrinsic::ppc_altivec_lvxl: 16346 case Intrinsic::ppc_altivec_lvebx: 16347 case Intrinsic::ppc_altivec_lvehx: 16348 case Intrinsic::ppc_altivec_lvewx: 16349 case Intrinsic::ppc_vsx_lxvd2x: 16350 case Intrinsic::ppc_vsx_lxvw4x: 16351 case Intrinsic::ppc_vsx_lxvd2x_be: 16352 case Intrinsic::ppc_vsx_lxvw4x_be: 16353 case Intrinsic::ppc_vsx_lxvl: 16354 case Intrinsic::ppc_vsx_lxvll: { 16355 EVT VT; 16356 switch (Intrinsic) { 16357 case Intrinsic::ppc_altivec_lvebx: 16358 VT = MVT::i8; 16359 break; 16360 case Intrinsic::ppc_altivec_lvehx: 16361 VT = MVT::i16; 16362 break; 16363 case Intrinsic::ppc_altivec_lvewx: 16364 VT = MVT::i32; 16365 break; 16366 case Intrinsic::ppc_vsx_lxvd2x: 16367 case Intrinsic::ppc_vsx_lxvd2x_be: 16368 VT = MVT::v2f64; 16369 break; 16370 default: 16371 VT = MVT::v4i32; 16372 break; 16373 } 16374 16375 Info.opc = ISD::INTRINSIC_W_CHAIN; 16376 Info.memVT = VT; 16377 Info.ptrVal = I.getArgOperand(0); 16378 Info.offset = -VT.getStoreSize()+1; 16379 Info.size = 2*VT.getStoreSize()-1; 16380 Info.align = Align(1); 16381 Info.flags = MachineMemOperand::MOLoad; 16382 return true; 16383 } 16384 case Intrinsic::ppc_altivec_stvx: 16385 case Intrinsic::ppc_altivec_stvxl: 16386 case Intrinsic::ppc_altivec_stvebx: 16387 case Intrinsic::ppc_altivec_stvehx: 16388 case Intrinsic::ppc_altivec_stvewx: 16389 case Intrinsic::ppc_vsx_stxvd2x: 16390 case Intrinsic::ppc_vsx_stxvw4x: 16391 case Intrinsic::ppc_vsx_stxvd2x_be: 16392 case Intrinsic::ppc_vsx_stxvw4x_be: 16393 case Intrinsic::ppc_vsx_stxvl: 16394 case Intrinsic::ppc_vsx_stxvll: { 16395 EVT VT; 16396 switch (Intrinsic) { 16397 case Intrinsic::ppc_altivec_stvebx: 16398 VT = MVT::i8; 16399 break; 16400 case Intrinsic::ppc_altivec_stvehx: 16401 VT = MVT::i16; 16402 break; 16403 case Intrinsic::ppc_altivec_stvewx: 16404 VT = MVT::i32; 16405 break; 16406 case Intrinsic::ppc_vsx_stxvd2x: 16407 case Intrinsic::ppc_vsx_stxvd2x_be: 16408 VT = MVT::v2f64; 16409 break; 16410 default: 16411 VT = MVT::v4i32; 16412 break; 16413 } 16414 16415 Info.opc = ISD::INTRINSIC_VOID; 16416 Info.memVT = VT; 16417 Info.ptrVal = I.getArgOperand(1); 16418 Info.offset = -VT.getStoreSize()+1; 16419 Info.size = 2*VT.getStoreSize()-1; 16420 Info.align = Align(1); 16421 Info.flags = MachineMemOperand::MOStore; 16422 return true; 16423 } 16424 default: 16425 break; 16426 } 16427 16428 return false; 16429 } 16430 16431 /// It returns EVT::Other if the type should be determined using generic 16432 /// target-independent logic. 16433 EVT PPCTargetLowering::getOptimalMemOpType( 16434 const MemOp &Op, const AttributeList &FuncAttributes) const { 16435 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16436 // We should use Altivec/VSX loads and stores when available. For unaligned 16437 // addresses, unaligned VSX loads are only fast starting with the P8. 16438 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16439 (Op.isAligned(Align(16)) || 16440 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16441 return MVT::v4i32; 16442 } 16443 16444 if (Subtarget.isPPC64()) { 16445 return MVT::i64; 16446 } 16447 16448 return MVT::i32; 16449 } 16450 16451 /// Returns true if it is beneficial to convert a load of a constant 16452 /// to just the constant itself. 16453 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16454 Type *Ty) const { 16455 assert(Ty->isIntegerTy()); 16456 16457 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16458 return !(BitSize == 0 || BitSize > 64); 16459 } 16460 16461 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16462 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16463 return false; 16464 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16465 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16466 return NumBits1 == 64 && NumBits2 == 32; 16467 } 16468 16469 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16470 if (!VT1.isInteger() || !VT2.isInteger()) 16471 return false; 16472 unsigned NumBits1 = VT1.getSizeInBits(); 16473 unsigned NumBits2 = VT2.getSizeInBits(); 16474 return NumBits1 == 64 && NumBits2 == 32; 16475 } 16476 16477 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16478 // Generally speaking, zexts are not free, but they are free when they can be 16479 // folded with other operations. 16480 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16481 EVT MemVT = LD->getMemoryVT(); 16482 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16483 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16484 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16485 LD->getExtensionType() == ISD::ZEXTLOAD)) 16486 return true; 16487 } 16488 16489 // FIXME: Add other cases... 16490 // - 32-bit shifts with a zext to i64 16491 // - zext after ctlz, bswap, etc. 16492 // - zext after and by a constant mask 16493 16494 return TargetLowering::isZExtFree(Val, VT2); 16495 } 16496 16497 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16498 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16499 "invalid fpext types"); 16500 // Extending to float128 is not free. 16501 if (DestVT == MVT::f128) 16502 return false; 16503 return true; 16504 } 16505 16506 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16507 return isInt<16>(Imm) || isUInt<16>(Imm); 16508 } 16509 16510 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16511 return isInt<16>(Imm) || isUInt<16>(Imm); 16512 } 16513 16514 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16515 MachineMemOperand::Flags, 16516 bool *Fast) const { 16517 if (DisablePPCUnaligned) 16518 return false; 16519 16520 // PowerPC supports unaligned memory access for simple non-vector types. 16521 // Although accessing unaligned addresses is not as efficient as accessing 16522 // aligned addresses, it is generally more efficient than manual expansion, 16523 // and generally only traps for software emulation when crossing page 16524 // boundaries. 16525 16526 if (!VT.isSimple()) 16527 return false; 16528 16529 if (VT.isFloatingPoint() && !VT.isVector() && 16530 !Subtarget.allowsUnalignedFPAccess()) 16531 return false; 16532 16533 if (VT.getSimpleVT().isVector()) { 16534 if (Subtarget.hasVSX()) { 16535 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16536 VT != MVT::v4f32 && VT != MVT::v4i32) 16537 return false; 16538 } else { 16539 return false; 16540 } 16541 } 16542 16543 if (VT == MVT::ppcf128) 16544 return false; 16545 16546 if (Fast) 16547 *Fast = true; 16548 16549 return true; 16550 } 16551 16552 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16553 SDValue C) const { 16554 // Check integral scalar types. 16555 if (!VT.isScalarInteger()) 16556 return false; 16557 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16558 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16559 return false; 16560 // This transformation will generate >= 2 operations. But the following 16561 // cases will generate <= 2 instructions during ISEL. So exclude them. 16562 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16563 // HW instruction, ie. MULLI 16564 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16565 // instruction is needed than case 1, ie. MULLI and RLDICR 16566 int64_t Imm = ConstNode->getSExtValue(); 16567 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16568 Imm >>= Shift; 16569 if (isInt<16>(Imm)) 16570 return false; 16571 uint64_t UImm = static_cast<uint64_t>(Imm); 16572 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16573 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16574 return true; 16575 } 16576 return false; 16577 } 16578 16579 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16580 EVT VT) const { 16581 return isFMAFasterThanFMulAndFAdd( 16582 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16583 } 16584 16585 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16586 Type *Ty) const { 16587 switch (Ty->getScalarType()->getTypeID()) { 16588 case Type::FloatTyID: 16589 case Type::DoubleTyID: 16590 return true; 16591 case Type::FP128TyID: 16592 return Subtarget.hasP9Vector(); 16593 default: 16594 return false; 16595 } 16596 } 16597 16598 // FIXME: add more patterns which are not profitable to hoist. 16599 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16600 if (!I->hasOneUse()) 16601 return true; 16602 16603 Instruction *User = I->user_back(); 16604 assert(User && "A single use instruction with no uses."); 16605 16606 switch (I->getOpcode()) { 16607 case Instruction::FMul: { 16608 // Don't break FMA, PowerPC prefers FMA. 16609 if (User->getOpcode() != Instruction::FSub && 16610 User->getOpcode() != Instruction::FAdd) 16611 return true; 16612 16613 const TargetOptions &Options = getTargetMachine().Options; 16614 const Function *F = I->getFunction(); 16615 const DataLayout &DL = F->getParent()->getDataLayout(); 16616 Type *Ty = User->getOperand(0)->getType(); 16617 16618 return !( 16619 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16620 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16621 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16622 } 16623 case Instruction::Load: { 16624 // Don't break "store (load float*)" pattern, this pattern will be combined 16625 // to "store (load int32)" in later InstCombine pass. See function 16626 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16627 // cycles than loading a 32 bit integer. 16628 LoadInst *LI = cast<LoadInst>(I); 16629 // For the loads that combineLoadToOperationType does nothing, like 16630 // ordered load, it should be profitable to hoist them. 16631 // For swifterror load, it can only be used for pointer to pointer type, so 16632 // later type check should get rid of this case. 16633 if (!LI->isUnordered()) 16634 return true; 16635 16636 if (User->getOpcode() != Instruction::Store) 16637 return true; 16638 16639 if (I->getType()->getTypeID() != Type::FloatTyID) 16640 return true; 16641 16642 return false; 16643 } 16644 default: 16645 return true; 16646 } 16647 return true; 16648 } 16649 16650 const MCPhysReg * 16651 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16652 // LR is a callee-save register, but we must treat it as clobbered by any call 16653 // site. Hence we include LR in the scratch registers, which are in turn added 16654 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16655 // to CTR, which is used by any indirect call. 16656 static const MCPhysReg ScratchRegs[] = { 16657 PPC::X12, PPC::LR8, PPC::CTR8, 0 16658 }; 16659 16660 return ScratchRegs; 16661 } 16662 16663 Register PPCTargetLowering::getExceptionPointerRegister( 16664 const Constant *PersonalityFn) const { 16665 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16666 } 16667 16668 Register PPCTargetLowering::getExceptionSelectorRegister( 16669 const Constant *PersonalityFn) const { 16670 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16671 } 16672 16673 bool 16674 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16675 EVT VT , unsigned DefinedValues) const { 16676 if (VT == MVT::v2i64) 16677 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16678 16679 if (Subtarget.hasVSX()) 16680 return true; 16681 16682 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16683 } 16684 16685 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16686 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16687 return TargetLowering::getSchedulingPreference(N); 16688 16689 return Sched::ILP; 16690 } 16691 16692 // Create a fast isel object. 16693 FastISel * 16694 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16695 const TargetLibraryInfo *LibInfo) const { 16696 return PPC::createFastISel(FuncInfo, LibInfo); 16697 } 16698 16699 // 'Inverted' means the FMA opcode after negating one multiplicand. 16700 // For example, (fma -a b c) = (fnmsub a b c) 16701 static unsigned invertFMAOpcode(unsigned Opc) { 16702 switch (Opc) { 16703 default: 16704 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16705 case ISD::FMA: 16706 return PPCISD::FNMSUB; 16707 case PPCISD::FNMSUB: 16708 return ISD::FMA; 16709 } 16710 } 16711 16712 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16713 bool LegalOps, bool OptForSize, 16714 NegatibleCost &Cost, 16715 unsigned Depth) const { 16716 if (Depth > SelectionDAG::MaxRecursionDepth) 16717 return SDValue(); 16718 16719 unsigned Opc = Op.getOpcode(); 16720 EVT VT = Op.getValueType(); 16721 SDNodeFlags Flags = Op.getNode()->getFlags(); 16722 16723 switch (Opc) { 16724 case PPCISD::FNMSUB: 16725 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16726 break; 16727 16728 const TargetOptions &Options = getTargetMachine().Options; 16729 SDValue N0 = Op.getOperand(0); 16730 SDValue N1 = Op.getOperand(1); 16731 SDValue N2 = Op.getOperand(2); 16732 SDLoc Loc(Op); 16733 16734 NegatibleCost N2Cost = NegatibleCost::Expensive; 16735 SDValue NegN2 = 16736 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16737 16738 if (!NegN2) 16739 return SDValue(); 16740 16741 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16742 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16743 // These transformations may change sign of zeroes. For example, 16744 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16745 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16746 // Try and choose the cheaper one to negate. 16747 NegatibleCost N0Cost = NegatibleCost::Expensive; 16748 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16749 N0Cost, Depth + 1); 16750 16751 NegatibleCost N1Cost = NegatibleCost::Expensive; 16752 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16753 N1Cost, Depth + 1); 16754 16755 if (NegN0 && N0Cost <= N1Cost) { 16756 Cost = std::min(N0Cost, N2Cost); 16757 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16758 } else if (NegN1) { 16759 Cost = std::min(N1Cost, N2Cost); 16760 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16761 } 16762 } 16763 16764 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16765 if (isOperationLegal(ISD::FMA, VT)) { 16766 Cost = N2Cost; 16767 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16768 } 16769 16770 break; 16771 } 16772 16773 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16774 Cost, Depth); 16775 } 16776 16777 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16778 bool PPCTargetLowering::useLoadStackGuardNode() const { 16779 if (!Subtarget.isTargetLinux()) 16780 return TargetLowering::useLoadStackGuardNode(); 16781 return true; 16782 } 16783 16784 // Override to disable global variable loading on Linux and insert AIX canary 16785 // word declaration. 16786 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16787 if (Subtarget.isAIXABI()) { 16788 M.getOrInsertGlobal(AIXSSPCanaryWordName, 16789 Type::getInt8PtrTy(M.getContext())); 16790 return; 16791 } 16792 if (!Subtarget.isTargetLinux()) 16793 return TargetLowering::insertSSPDeclarations(M); 16794 } 16795 16796 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 16797 if (Subtarget.isAIXABI()) 16798 return M.getGlobalVariable(AIXSSPCanaryWordName); 16799 return TargetLowering::getSDagStackGuard(M); 16800 } 16801 16802 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16803 bool ForCodeSize) const { 16804 if (!VT.isSimple() || !Subtarget.hasVSX()) 16805 return false; 16806 16807 switch(VT.getSimpleVT().SimpleTy) { 16808 default: 16809 // For FP types that are currently not supported by PPC backend, return 16810 // false. Examples: f16, f80. 16811 return false; 16812 case MVT::f32: 16813 case MVT::f64: 16814 if (Subtarget.hasPrefixInstrs()) { 16815 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16816 return true; 16817 } 16818 LLVM_FALLTHROUGH; 16819 case MVT::ppcf128: 16820 return Imm.isPosZero(); 16821 } 16822 } 16823 16824 // For vector shift operation op, fold 16825 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16826 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16827 SelectionDAG &DAG) { 16828 SDValue N0 = N->getOperand(0); 16829 SDValue N1 = N->getOperand(1); 16830 EVT VT = N0.getValueType(); 16831 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16832 unsigned Opcode = N->getOpcode(); 16833 unsigned TargetOpcode; 16834 16835 switch (Opcode) { 16836 default: 16837 llvm_unreachable("Unexpected shift operation"); 16838 case ISD::SHL: 16839 TargetOpcode = PPCISD::SHL; 16840 break; 16841 case ISD::SRL: 16842 TargetOpcode = PPCISD::SRL; 16843 break; 16844 case ISD::SRA: 16845 TargetOpcode = PPCISD::SRA; 16846 break; 16847 } 16848 16849 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16850 N1->getOpcode() == ISD::AND) 16851 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16852 if (Mask->getZExtValue() == OpSizeInBits - 1) 16853 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16854 16855 return SDValue(); 16856 } 16857 16858 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16859 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16860 return Value; 16861 16862 SDValue N0 = N->getOperand(0); 16863 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16864 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16865 N0.getOpcode() != ISD::SIGN_EXTEND || 16866 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16867 N->getValueType(0) != MVT::i64) 16868 return SDValue(); 16869 16870 // We can't save an operation here if the value is already extended, and 16871 // the existing shift is easier to combine. 16872 SDValue ExtsSrc = N0.getOperand(0); 16873 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16874 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16875 return SDValue(); 16876 16877 SDLoc DL(N0); 16878 SDValue ShiftBy = SDValue(CN1, 0); 16879 // We want the shift amount to be i32 on the extswli, but the shift could 16880 // have an i64. 16881 if (ShiftBy.getValueType() == MVT::i64) 16882 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16883 16884 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16885 ShiftBy); 16886 } 16887 16888 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16889 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16890 return Value; 16891 16892 return SDValue(); 16893 } 16894 16895 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16896 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16897 return Value; 16898 16899 return SDValue(); 16900 } 16901 16902 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16903 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16904 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16905 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16906 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16907 const PPCSubtarget &Subtarget) { 16908 if (!Subtarget.isPPC64()) 16909 return SDValue(); 16910 16911 SDValue LHS = N->getOperand(0); 16912 SDValue RHS = N->getOperand(1); 16913 16914 auto isZextOfCompareWithConstant = [](SDValue Op) { 16915 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16916 Op.getValueType() != MVT::i64) 16917 return false; 16918 16919 SDValue Cmp = Op.getOperand(0); 16920 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16921 Cmp.getOperand(0).getValueType() != MVT::i64) 16922 return false; 16923 16924 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16925 int64_t NegConstant = 0 - Constant->getSExtValue(); 16926 // Due to the limitations of the addi instruction, 16927 // -C is required to be [-32768, 32767]. 16928 return isInt<16>(NegConstant); 16929 } 16930 16931 return false; 16932 }; 16933 16934 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16935 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16936 16937 // If there is a pattern, canonicalize a zext operand to the RHS. 16938 if (LHSHasPattern && !RHSHasPattern) 16939 std::swap(LHS, RHS); 16940 else if (!LHSHasPattern && !RHSHasPattern) 16941 return SDValue(); 16942 16943 SDLoc DL(N); 16944 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16945 SDValue Cmp = RHS.getOperand(0); 16946 SDValue Z = Cmp.getOperand(0); 16947 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 16948 int64_t NegConstant = 0 - Constant->getSExtValue(); 16949 16950 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16951 default: break; 16952 case ISD::SETNE: { 16953 // when C == 0 16954 // --> addze X, (addic Z, -1).carry 16955 // / 16956 // add X, (zext(setne Z, C))-- 16957 // \ when -32768 <= -C <= 32767 && C != 0 16958 // --> addze X, (addic (addi Z, -C), -1).carry 16959 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16960 DAG.getConstant(NegConstant, DL, MVT::i64)); 16961 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16962 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16963 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16964 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16965 SDValue(Addc.getNode(), 1)); 16966 } 16967 case ISD::SETEQ: { 16968 // when C == 0 16969 // --> addze X, (subfic Z, 0).carry 16970 // / 16971 // add X, (zext(sete Z, C))-- 16972 // \ when -32768 <= -C <= 32767 && C != 0 16973 // --> addze X, (subfic (addi Z, -C), 0).carry 16974 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16975 DAG.getConstant(NegConstant, DL, MVT::i64)); 16976 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16977 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16978 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16979 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16980 SDValue(Subc.getNode(), 1)); 16981 } 16982 } 16983 16984 return SDValue(); 16985 } 16986 16987 // Transform 16988 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16989 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16990 // In this case both C1 and C2 must be known constants. 16991 // C1+C2 must fit into a 34 bit signed integer. 16992 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16993 const PPCSubtarget &Subtarget) { 16994 if (!Subtarget.isUsingPCRelativeCalls()) 16995 return SDValue(); 16996 16997 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16998 // If we find that node try to cast the Global Address and the Constant. 16999 SDValue LHS = N->getOperand(0); 17000 SDValue RHS = N->getOperand(1); 17001 17002 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17003 std::swap(LHS, RHS); 17004 17005 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17006 return SDValue(); 17007 17008 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 17009 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 17010 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 17011 17012 // Check that both casts succeeded. 17013 if (!GSDN || !ConstNode) 17014 return SDValue(); 17015 17016 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 17017 SDLoc DL(GSDN); 17018 17019 // The signed int offset needs to fit in 34 bits. 17020 if (!isInt<34>(NewOffset)) 17021 return SDValue(); 17022 17023 // The new global address is a copy of the old global address except 17024 // that it has the updated Offset. 17025 SDValue GA = 17026 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 17027 NewOffset, GSDN->getTargetFlags()); 17028 SDValue MatPCRel = 17029 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 17030 return MatPCRel; 17031 } 17032 17033 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 17034 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 17035 return Value; 17036 17037 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 17038 return Value; 17039 17040 return SDValue(); 17041 } 17042 17043 // Detect TRUNCATE operations on bitcasts of float128 values. 17044 // What we are looking for here is the situtation where we extract a subset 17045 // of bits from a 128 bit float. 17046 // This can be of two forms: 17047 // 1) BITCAST of f128 feeding TRUNCATE 17048 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 17049 // The reason this is required is because we do not have a legal i128 type 17050 // and so we want to prevent having to store the f128 and then reload part 17051 // of it. 17052 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 17053 DAGCombinerInfo &DCI) const { 17054 // If we are using CRBits then try that first. 17055 if (Subtarget.useCRBits()) { 17056 // Check if CRBits did anything and return that if it did. 17057 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 17058 return CRTruncValue; 17059 } 17060 17061 SDLoc dl(N); 17062 SDValue Op0 = N->getOperand(0); 17063 17064 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 17065 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 17066 EVT VT = N->getValueType(0); 17067 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17068 return SDValue(); 17069 SDValue Sub = Op0.getOperand(0); 17070 if (Sub.getOpcode() == ISD::SUB) { 17071 SDValue SubOp0 = Sub.getOperand(0); 17072 SDValue SubOp1 = Sub.getOperand(1); 17073 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 17074 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 17075 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 17076 SubOp1.getOperand(0), 17077 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 17078 } 17079 } 17080 } 17081 17082 // Looking for a truncate of i128 to i64. 17083 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 17084 return SDValue(); 17085 17086 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 17087 17088 // SRL feeding TRUNCATE. 17089 if (Op0.getOpcode() == ISD::SRL) { 17090 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 17091 // The right shift has to be by 64 bits. 17092 if (!ConstNode || ConstNode->getZExtValue() != 64) 17093 return SDValue(); 17094 17095 // Switch the element number to extract. 17096 EltToExtract = EltToExtract ? 0 : 1; 17097 // Update Op0 past the SRL. 17098 Op0 = Op0.getOperand(0); 17099 } 17100 17101 // BITCAST feeding a TRUNCATE possibly via SRL. 17102 if (Op0.getOpcode() == ISD::BITCAST && 17103 Op0.getValueType() == MVT::i128 && 17104 Op0.getOperand(0).getValueType() == MVT::f128) { 17105 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 17106 return DCI.DAG.getNode( 17107 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 17108 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 17109 } 17110 return SDValue(); 17111 } 17112 17113 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 17114 SelectionDAG &DAG = DCI.DAG; 17115 17116 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 17117 if (!ConstOpOrElement) 17118 return SDValue(); 17119 17120 // An imul is usually smaller than the alternative sequence for legal type. 17121 if (DAG.getMachineFunction().getFunction().hasMinSize() && 17122 isOperationLegal(ISD::MUL, N->getValueType(0))) 17123 return SDValue(); 17124 17125 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 17126 switch (this->Subtarget.getCPUDirective()) { 17127 default: 17128 // TODO: enhance the condition for subtarget before pwr8 17129 return false; 17130 case PPC::DIR_PWR8: 17131 // type mul add shl 17132 // scalar 4 1 1 17133 // vector 7 2 2 17134 return true; 17135 case PPC::DIR_PWR9: 17136 case PPC::DIR_PWR10: 17137 case PPC::DIR_PWR_FUTURE: 17138 // type mul add shl 17139 // scalar 5 2 2 17140 // vector 7 2 2 17141 17142 // The cycle RATIO of related operations are showed as a table above. 17143 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 17144 // scalar and vector type. For 2 instrs patterns, add/sub + shl 17145 // are 4, it is always profitable; but for 3 instrs patterns 17146 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 17147 // So we should only do it for vector type. 17148 return IsAddOne && IsNeg ? VT.isVector() : true; 17149 } 17150 }; 17151 17152 EVT VT = N->getValueType(0); 17153 SDLoc DL(N); 17154 17155 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 17156 bool IsNeg = MulAmt.isNegative(); 17157 APInt MulAmtAbs = MulAmt.abs(); 17158 17159 if ((MulAmtAbs - 1).isPowerOf2()) { 17160 // (mul x, 2^N + 1) => (add (shl x, N), x) 17161 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 17162 17163 if (!IsProfitable(IsNeg, true, VT)) 17164 return SDValue(); 17165 17166 SDValue Op0 = N->getOperand(0); 17167 SDValue Op1 = 17168 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17169 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 17170 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 17171 17172 if (!IsNeg) 17173 return Res; 17174 17175 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 17176 } else if ((MulAmtAbs + 1).isPowerOf2()) { 17177 // (mul x, 2^N - 1) => (sub (shl x, N), x) 17178 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 17179 17180 if (!IsProfitable(IsNeg, false, VT)) 17181 return SDValue(); 17182 17183 SDValue Op0 = N->getOperand(0); 17184 SDValue Op1 = 17185 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17186 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 17187 17188 if (!IsNeg) 17189 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 17190 else 17191 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 17192 17193 } else { 17194 return SDValue(); 17195 } 17196 } 17197 17198 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 17199 // in combiner since we need to check SD flags and other subtarget features. 17200 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 17201 DAGCombinerInfo &DCI) const { 17202 SDValue N0 = N->getOperand(0); 17203 SDValue N1 = N->getOperand(1); 17204 SDValue N2 = N->getOperand(2); 17205 SDNodeFlags Flags = N->getFlags(); 17206 EVT VT = N->getValueType(0); 17207 SelectionDAG &DAG = DCI.DAG; 17208 const TargetOptions &Options = getTargetMachine().Options; 17209 unsigned Opc = N->getOpcode(); 17210 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 17211 bool LegalOps = !DCI.isBeforeLegalizeOps(); 17212 SDLoc Loc(N); 17213 17214 if (!isOperationLegal(ISD::FMA, VT)) 17215 return SDValue(); 17216 17217 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 17218 // since (fnmsub a b c)=-0 while c-ab=+0. 17219 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 17220 return SDValue(); 17221 17222 // (fma (fneg a) b c) => (fnmsub a b c) 17223 // (fnmsub (fneg a) b c) => (fma a b c) 17224 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 17225 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 17226 17227 // (fma a (fneg b) c) => (fnmsub a b c) 17228 // (fnmsub a (fneg b) c) => (fma a b c) 17229 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 17230 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 17231 17232 return SDValue(); 17233 } 17234 17235 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 17236 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 17237 if (!Subtarget.is64BitELFABI()) 17238 return false; 17239 17240 // If not a tail call then no need to proceed. 17241 if (!CI->isTailCall()) 17242 return false; 17243 17244 // If sibling calls have been disabled and tail-calls aren't guaranteed 17245 // there is no reason to duplicate. 17246 auto &TM = getTargetMachine(); 17247 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 17248 return false; 17249 17250 // Can't tail call a function called indirectly, or if it has variadic args. 17251 const Function *Callee = CI->getCalledFunction(); 17252 if (!Callee || Callee->isVarArg()) 17253 return false; 17254 17255 // Make sure the callee and caller calling conventions are eligible for tco. 17256 const Function *Caller = CI->getParent()->getParent(); 17257 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 17258 CI->getCallingConv())) 17259 return false; 17260 17261 // If the function is local then we have a good chance at tail-calling it 17262 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 17263 } 17264 17265 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 17266 if (!Subtarget.hasVSX()) 17267 return false; 17268 if (Subtarget.hasP9Vector() && VT == MVT::f128) 17269 return true; 17270 return VT == MVT::f32 || VT == MVT::f64 || 17271 VT == MVT::v4f32 || VT == MVT::v2f64; 17272 } 17273 17274 bool PPCTargetLowering:: 17275 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 17276 const Value *Mask = AndI.getOperand(1); 17277 // If the mask is suitable for andi. or andis. we should sink the and. 17278 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 17279 // Can't handle constants wider than 64-bits. 17280 if (CI->getBitWidth() > 64) 17281 return false; 17282 int64_t ConstVal = CI->getZExtValue(); 17283 return isUInt<16>(ConstVal) || 17284 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 17285 } 17286 17287 // For non-constant masks, we can always use the record-form and. 17288 return true; 17289 } 17290 17291 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 17292 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 17293 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 17294 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 17295 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 17296 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 17297 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 17298 assert(Subtarget.hasP9Altivec() && 17299 "Only combine this when P9 altivec supported!"); 17300 EVT VT = N->getValueType(0); 17301 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17302 return SDValue(); 17303 17304 SelectionDAG &DAG = DCI.DAG; 17305 SDLoc dl(N); 17306 if (N->getOperand(0).getOpcode() == ISD::SUB) { 17307 // Even for signed integers, if it's known to be positive (as signed 17308 // integer) due to zero-extended inputs. 17309 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 17310 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 17311 if ((SubOpcd0 == ISD::ZERO_EXTEND || 17312 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 17313 (SubOpcd1 == ISD::ZERO_EXTEND || 17314 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 17315 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17316 N->getOperand(0)->getOperand(0), 17317 N->getOperand(0)->getOperand(1), 17318 DAG.getTargetConstant(0, dl, MVT::i32)); 17319 } 17320 17321 // For type v4i32, it can be optimized with xvnegsp + vabsduw 17322 if (N->getOperand(0).getValueType() == MVT::v4i32 && 17323 N->getOperand(0).hasOneUse()) { 17324 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17325 N->getOperand(0)->getOperand(0), 17326 N->getOperand(0)->getOperand(1), 17327 DAG.getTargetConstant(1, dl, MVT::i32)); 17328 } 17329 } 17330 17331 return SDValue(); 17332 } 17333 17334 // For type v4i32/v8ii16/v16i8, transform 17335 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 17336 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 17337 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 17338 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 17339 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17340 DAGCombinerInfo &DCI) const { 17341 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17342 assert(Subtarget.hasP9Altivec() && 17343 "Only combine this when P9 altivec supported!"); 17344 17345 SelectionDAG &DAG = DCI.DAG; 17346 SDLoc dl(N); 17347 SDValue Cond = N->getOperand(0); 17348 SDValue TrueOpnd = N->getOperand(1); 17349 SDValue FalseOpnd = N->getOperand(2); 17350 EVT VT = N->getOperand(1).getValueType(); 17351 17352 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17353 FalseOpnd.getOpcode() != ISD::SUB) 17354 return SDValue(); 17355 17356 // ABSD only available for type v4i32/v8i16/v16i8 17357 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17358 return SDValue(); 17359 17360 // At least to save one more dependent computation 17361 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17362 return SDValue(); 17363 17364 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17365 17366 // Can only handle unsigned comparison here 17367 switch (CC) { 17368 default: 17369 return SDValue(); 17370 case ISD::SETUGT: 17371 case ISD::SETUGE: 17372 break; 17373 case ISD::SETULT: 17374 case ISD::SETULE: 17375 std::swap(TrueOpnd, FalseOpnd); 17376 break; 17377 } 17378 17379 SDValue CmpOpnd1 = Cond.getOperand(0); 17380 SDValue CmpOpnd2 = Cond.getOperand(1); 17381 17382 // SETCC CmpOpnd1 CmpOpnd2 cond 17383 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17384 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17385 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17386 TrueOpnd.getOperand(1) == CmpOpnd2 && 17387 FalseOpnd.getOperand(0) == CmpOpnd2 && 17388 FalseOpnd.getOperand(1) == CmpOpnd1) { 17389 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17390 CmpOpnd1, CmpOpnd2, 17391 DAG.getTargetConstant(0, dl, MVT::i32)); 17392 } 17393 17394 return SDValue(); 17395 } 17396 17397 /// getAddrModeForFlags - Based on the set of address flags, select the most 17398 /// optimal instruction format to match by. 17399 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17400 // This is not a node we should be handling here. 17401 if (Flags == PPC::MOF_None) 17402 return PPC::AM_None; 17403 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17404 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17405 if ((Flags & FlagSet) == FlagSet) 17406 return PPC::AM_DForm; 17407 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17408 if ((Flags & FlagSet) == FlagSet) 17409 return PPC::AM_DSForm; 17410 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17411 if ((Flags & FlagSet) == FlagSet) 17412 return PPC::AM_DQForm; 17413 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm)) 17414 if ((Flags & FlagSet) == FlagSet) 17415 return PPC::AM_PrefixDForm; 17416 // If no other forms are selected, return an X-Form as it is the most 17417 // general addressing mode. 17418 return PPC::AM_XForm; 17419 } 17420 17421 /// Set alignment flags based on whether or not the Frame Index is aligned. 17422 /// Utilized when computing flags for address computation when selecting 17423 /// load and store instructions. 17424 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17425 SelectionDAG &DAG) { 17426 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17427 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17428 if (!FI) 17429 return; 17430 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17431 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17432 // If this is (add $FI, $S16Imm), the alignment flags are already set 17433 // based on the immediate. We just need to clear the alignment flags 17434 // if the FI alignment is weaker. 17435 if ((FrameIndexAlign % 4) != 0) 17436 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17437 if ((FrameIndexAlign % 16) != 0) 17438 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17439 // If the address is a plain FrameIndex, set alignment flags based on 17440 // FI alignment. 17441 if (!IsAdd) { 17442 if ((FrameIndexAlign % 4) == 0) 17443 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17444 if ((FrameIndexAlign % 16) == 0) 17445 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17446 } 17447 } 17448 17449 /// Given a node, compute flags that are used for address computation when 17450 /// selecting load and store instructions. The flags computed are stored in 17451 /// FlagSet. This function takes into account whether the node is a constant, 17452 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17453 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17454 SelectionDAG &DAG) { 17455 // Set the alignment flags for the node depending on if the node is 17456 // 4-byte or 16-byte aligned. 17457 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17458 if ((Imm & 0x3) == 0) 17459 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17460 if ((Imm & 0xf) == 0) 17461 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17462 }; 17463 17464 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17465 // All 32-bit constants can be computed as LIS + Disp. 17466 const APInt &ConstImm = CN->getAPIntValue(); 17467 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17468 FlagSet |= PPC::MOF_AddrIsSImm32; 17469 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17470 setAlignFlagsForFI(N, FlagSet, DAG); 17471 } 17472 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17473 FlagSet |= PPC::MOF_RPlusSImm34; 17474 else // Let constant materialization handle large constants. 17475 FlagSet |= PPC::MOF_NotAddNorCst; 17476 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17477 // This address can be represented as an addition of: 17478 // - Register + Imm16 (possibly a multiple of 4/16) 17479 // - Register + Imm34 17480 // - Register + PPCISD::Lo 17481 // - Register + Register 17482 // In any case, we won't have to match this as Base + Zero. 17483 SDValue RHS = N.getOperand(1); 17484 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17485 const APInt &ConstImm = CN->getAPIntValue(); 17486 if (ConstImm.isSignedIntN(16)) { 17487 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17488 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17489 setAlignFlagsForFI(N, FlagSet, DAG); 17490 } 17491 if (ConstImm.isSignedIntN(34)) 17492 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17493 else 17494 FlagSet |= PPC::MOF_RPlusR; // Register. 17495 } else if (RHS.getOpcode() == PPCISD::Lo && 17496 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17497 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17498 else 17499 FlagSet |= PPC::MOF_RPlusR; 17500 } else { // The address computation is not a constant or an addition. 17501 setAlignFlagsForFI(N, FlagSet, DAG); 17502 FlagSet |= PPC::MOF_NotAddNorCst; 17503 } 17504 } 17505 17506 static bool isPCRelNode(SDValue N) { 17507 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR || 17508 isValidPCRelNode<ConstantPoolSDNode>(N) || 17509 isValidPCRelNode<GlobalAddressSDNode>(N) || 17510 isValidPCRelNode<JumpTableSDNode>(N) || 17511 isValidPCRelNode<BlockAddressSDNode>(N)); 17512 } 17513 17514 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17515 /// the address flags of the load/store instruction that is to be matched. 17516 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17517 SelectionDAG &DAG) const { 17518 unsigned FlagSet = PPC::MOF_None; 17519 17520 // Compute subtarget flags. 17521 if (!Subtarget.hasP9Vector()) 17522 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17523 else { 17524 FlagSet |= PPC::MOF_SubtargetP9; 17525 if (Subtarget.hasPrefixInstrs()) 17526 FlagSet |= PPC::MOF_SubtargetP10; 17527 } 17528 if (Subtarget.hasSPE()) 17529 FlagSet |= PPC::MOF_SubtargetSPE; 17530 17531 // Check if we have a PCRel node and return early. 17532 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N)) 17533 return FlagSet; 17534 17535 // If the node is the paired load/store intrinsics, compute flags for 17536 // address computation and return early. 17537 unsigned ParentOp = Parent->getOpcode(); 17538 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) || 17539 (ParentOp == ISD::INTRINSIC_VOID))) { 17540 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue(); 17541 assert( 17542 ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) && 17543 "Only the paired load and store (lxvp/stxvp) intrinsics are valid."); 17544 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) ? Parent->getOperand(2) 17545 : Parent->getOperand(3); 17546 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG); 17547 FlagSet |= PPC::MOF_Vector; 17548 return FlagSet; 17549 } 17550 17551 // Mark this as something we don't want to handle here if it is atomic 17552 // or pre-increment instruction. 17553 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17554 if (LSB->isIndexed()) 17555 return PPC::MOF_None; 17556 17557 // Compute in-memory type flags. This is based on if there are scalars, 17558 // floats or vectors. 17559 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17560 assert(MN && "Parent should be a MemSDNode!"); 17561 EVT MemVT = MN->getMemoryVT(); 17562 unsigned Size = MemVT.getSizeInBits(); 17563 if (MemVT.isScalarInteger()) { 17564 assert(Size <= 128 && 17565 "Not expecting scalar integers larger than 16 bytes!"); 17566 if (Size < 32) 17567 FlagSet |= PPC::MOF_SubWordInt; 17568 else if (Size == 32) 17569 FlagSet |= PPC::MOF_WordInt; 17570 else 17571 FlagSet |= PPC::MOF_DoubleWordInt; 17572 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17573 if (Size == 128) 17574 FlagSet |= PPC::MOF_Vector; 17575 else if (Size == 256) { 17576 assert(Subtarget.pairedVectorMemops() && 17577 "256-bit vectors are only available when paired vector memops is " 17578 "enabled!"); 17579 FlagSet |= PPC::MOF_Vector; 17580 } else 17581 llvm_unreachable("Not expecting illegal vectors!"); 17582 } else { // Floating point type: can be scalar, f128 or vector types. 17583 if (Size == 32 || Size == 64) 17584 FlagSet |= PPC::MOF_ScalarFloat; 17585 else if (MemVT == MVT::f128 || MemVT.isVector()) 17586 FlagSet |= PPC::MOF_Vector; 17587 else 17588 llvm_unreachable("Not expecting illegal scalar floats!"); 17589 } 17590 17591 // Compute flags for address computation. 17592 computeFlagsForAddressComputation(N, FlagSet, DAG); 17593 17594 // Compute type extension flags. 17595 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17596 switch (LN->getExtensionType()) { 17597 case ISD::SEXTLOAD: 17598 FlagSet |= PPC::MOF_SExt; 17599 break; 17600 case ISD::EXTLOAD: 17601 case ISD::ZEXTLOAD: 17602 FlagSet |= PPC::MOF_ZExt; 17603 break; 17604 case ISD::NON_EXTLOAD: 17605 FlagSet |= PPC::MOF_NoExt; 17606 break; 17607 } 17608 } else 17609 FlagSet |= PPC::MOF_NoExt; 17610 17611 // For integers, no extension is the same as zero extension. 17612 // We set the extension mode to zero extension so we don't have 17613 // to add separate entries in AddrModesMap for loads and stores. 17614 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17615 FlagSet |= PPC::MOF_ZExt; 17616 FlagSet &= ~PPC::MOF_NoExt; 17617 } 17618 17619 // If we don't have prefixed instructions, 34-bit constants should be 17620 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17621 bool IsNonP1034BitConst = 17622 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17623 FlagSet) == PPC::MOF_RPlusSImm34; 17624 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17625 IsNonP1034BitConst) 17626 FlagSet |= PPC::MOF_NotAddNorCst; 17627 17628 return FlagSet; 17629 } 17630 17631 /// SelectForceXFormMode - Given the specified address, force it to be 17632 /// represented as an indexed [r+r] operation (an XForm instruction). 17633 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17634 SDValue &Base, 17635 SelectionDAG &DAG) const { 17636 17637 PPC::AddrMode Mode = PPC::AM_XForm; 17638 int16_t ForceXFormImm = 0; 17639 if (provablyDisjointOr(DAG, N) && 17640 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17641 Disp = N.getOperand(0); 17642 Base = N.getOperand(1); 17643 return Mode; 17644 } 17645 17646 // If the address is the result of an add, we will utilize the fact that the 17647 // address calculation includes an implicit add. However, we can reduce 17648 // register pressure if we do not materialize a constant just for use as the 17649 // index register. We only get rid of the add if it is not an add of a 17650 // value and a 16-bit signed constant and both have a single use. 17651 if (N.getOpcode() == ISD::ADD && 17652 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17653 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17654 Disp = N.getOperand(0); 17655 Base = N.getOperand(1); 17656 return Mode; 17657 } 17658 17659 // Otherwise, use R0 as the base register. 17660 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17661 N.getValueType()); 17662 Base = N; 17663 17664 return Mode; 17665 } 17666 17667 // If we happen to match to an aligned D-Form, check if the Frame Index is 17668 // adequately aligned. If it is not, reset the mode to match to X-Form. 17669 static void setXFormForUnalignedFI(SDValue N, unsigned Flags, 17670 PPC::AddrMode &Mode) { 17671 if (!isa<FrameIndexSDNode>(N)) 17672 return; 17673 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) || 17674 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16))) 17675 Mode = PPC::AM_XForm; 17676 } 17677 17678 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 17679 /// compute the address flags of the node, get the optimal address mode based 17680 /// on the flags, and set the Base and Disp based on the address mode. 17681 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 17682 SDValue N, SDValue &Disp, 17683 SDValue &Base, 17684 SelectionDAG &DAG, 17685 MaybeAlign Align) const { 17686 SDLoc DL(Parent); 17687 17688 // Compute the address flags. 17689 unsigned Flags = computeMOFlags(Parent, N, DAG); 17690 17691 // Get the optimal address mode based on the Flags. 17692 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 17693 17694 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned. 17695 // Select an X-Form load if it is not. 17696 setXFormForUnalignedFI(N, Flags, Mode); 17697 17698 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node. 17699 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) { 17700 assert(Subtarget.isUsingPCRelativeCalls() && 17701 "Must be using PC-Relative calls when a valid PC-Relative node is " 17702 "present!"); 17703 Mode = PPC::AM_PCRel; 17704 } 17705 17706 // Set Base and Disp accordingly depending on the address mode. 17707 switch (Mode) { 17708 case PPC::AM_DForm: 17709 case PPC::AM_DSForm: 17710 case PPC::AM_DQForm: { 17711 // This is a register plus a 16-bit immediate. The base will be the 17712 // register and the displacement will be the immediate unless it 17713 // isn't sufficiently aligned. 17714 if (Flags & PPC::MOF_RPlusSImm16) { 17715 SDValue Op0 = N.getOperand(0); 17716 SDValue Op1 = N.getOperand(1); 17717 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 17718 if (!Align || isAligned(*Align, Imm)) { 17719 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 17720 Base = Op0; 17721 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 17722 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17723 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17724 } 17725 break; 17726 } 17727 } 17728 // This is a register plus the @lo relocation. The base is the register 17729 // and the displacement is the global address. 17730 else if (Flags & PPC::MOF_RPlusLo) { 17731 Disp = N.getOperand(1).getOperand(0); // The global address. 17732 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 17733 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 17734 Disp.getOpcode() == ISD::TargetConstantPool || 17735 Disp.getOpcode() == ISD::TargetJumpTable); 17736 Base = N.getOperand(0); 17737 break; 17738 } 17739 // This is a constant address at most 32 bits. The base will be 17740 // zero or load-immediate-shifted and the displacement will be 17741 // the low 16 bits of the address. 17742 else if (Flags & PPC::MOF_AddrIsSImm32) { 17743 auto *CN = cast<ConstantSDNode>(N); 17744 EVT CNType = CN->getValueType(0); 17745 uint64_t CNImm = CN->getZExtValue(); 17746 // If this address fits entirely in a 16-bit sext immediate field, codegen 17747 // this as "d, 0". 17748 int16_t Imm; 17749 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 17750 Disp = DAG.getTargetConstant(Imm, DL, CNType); 17751 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17752 CNType); 17753 break; 17754 } 17755 // Handle 32-bit sext immediate with LIS + Addr mode. 17756 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 17757 (!Align || isAligned(*Align, CNImm))) { 17758 int32_t Addr = (int32_t)CNImm; 17759 // Otherwise, break this down into LIS + Disp. 17760 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 17761 Base = 17762 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 17763 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 17764 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 17765 break; 17766 } 17767 } 17768 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 17769 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 17770 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 17771 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17772 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17773 } else 17774 Base = N; 17775 break; 17776 } 17777 case PPC::AM_PrefixDForm: { 17778 int64_t Imm34 = 0; 17779 unsigned Opcode = N.getOpcode(); 17780 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) && 17781 (isIntS34Immediate(N.getOperand(1), Imm34))) { 17782 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate. 17783 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 17784 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 17785 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17786 else 17787 Base = N.getOperand(0); 17788 } else if (isIntS34Immediate(N, Imm34)) { 17789 // The address is a 34-bit signed immediate. 17790 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 17791 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 17792 } 17793 break; 17794 } 17795 case PPC::AM_PCRel: { 17796 // When selecting PC-Relative instructions, "Base" is not utilized as 17797 // we select the address as [PC+imm]. 17798 Disp = N; 17799 break; 17800 } 17801 case PPC::AM_None: 17802 break; 17803 default: { // By default, X-Form is always available to be selected. 17804 // When a frame index is not aligned, we also match by XForm. 17805 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 17806 Base = FI ? N : N.getOperand(1); 17807 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17808 N.getValueType()) 17809 : N.getOperand(0); 17810 break; 17811 } 17812 } 17813 return Mode; 17814 } 17815 17816 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 17817 bool Return, 17818 bool IsVarArg) const { 17819 switch (CC) { 17820 case CallingConv::Cold: 17821 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 17822 default: 17823 return CC_PPC64_ELF_FIS; 17824 } 17825 } 17826 17827 TargetLowering::AtomicExpansionKind 17828 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 17829 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 17830 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128) 17831 return AtomicExpansionKind::MaskedIntrinsic; 17832 return TargetLowering::shouldExpandAtomicRMWInIR(AI); 17833 } 17834 17835 TargetLowering::AtomicExpansionKind 17836 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 17837 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits(); 17838 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128) 17839 return AtomicExpansionKind::MaskedIntrinsic; 17840 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI); 17841 } 17842 17843 static Intrinsic::ID 17844 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) { 17845 switch (BinOp) { 17846 default: 17847 llvm_unreachable("Unexpected AtomicRMW BinOp"); 17848 case AtomicRMWInst::Xchg: 17849 return Intrinsic::ppc_atomicrmw_xchg_i128; 17850 case AtomicRMWInst::Add: 17851 return Intrinsic::ppc_atomicrmw_add_i128; 17852 case AtomicRMWInst::Sub: 17853 return Intrinsic::ppc_atomicrmw_sub_i128; 17854 case AtomicRMWInst::And: 17855 return Intrinsic::ppc_atomicrmw_and_i128; 17856 case AtomicRMWInst::Or: 17857 return Intrinsic::ppc_atomicrmw_or_i128; 17858 case AtomicRMWInst::Xor: 17859 return Intrinsic::ppc_atomicrmw_xor_i128; 17860 case AtomicRMWInst::Nand: 17861 return Intrinsic::ppc_atomicrmw_nand_i128; 17862 } 17863 } 17864 17865 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic( 17866 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 17867 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 17868 assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && 17869 "Only support quadword now"); 17870 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17871 Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType(); 17872 assert(ValTy->getPrimitiveSizeInBits() == 128); 17873 Function *RMW = Intrinsic::getDeclaration( 17874 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation())); 17875 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 17876 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo"); 17877 Value *IncrHi = 17878 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi"); 17879 Value *Addr = 17880 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 17881 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi}); 17882 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 17883 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 17884 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 17885 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 17886 return Builder.CreateOr( 17887 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 17888 } 17889 17890 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 17891 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 17892 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 17893 assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && 17894 "Only support quadword now"); 17895 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 17896 Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType(); 17897 assert(ValTy->getPrimitiveSizeInBits() == 128); 17898 Function *IntCmpXchg = 17899 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128); 17900 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 17901 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo"); 17902 Value *CmpHi = 17903 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi"); 17904 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo"); 17905 Value *NewHi = 17906 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi"); 17907 Value *Addr = 17908 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 17909 emitLeadingFence(Builder, CI, Ord); 17910 Value *LoHi = 17911 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi}); 17912 emitTrailingFence(Builder, CI, Ord); 17913 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 17914 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 17915 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 17916 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 17917 return Builder.CreateOr( 17918 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 17919 } 17920