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/MCSymbolXCOFF.h" 78 #include "llvm/Support/AtomicOrdering.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CodeGen.h" 82 #include "llvm/Support/CommandLine.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/Debug.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/KnownBits.h" 88 #include "llvm/Support/MachineValueType.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Target/TargetMachine.h" 92 #include "llvm/Target/TargetOptions.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <list> 98 #include <utility> 99 #include <vector> 100 101 using namespace llvm; 102 103 #define DEBUG_TYPE "ppc-lowering" 104 105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 113 114 static cl::opt<bool> DisableSCO("disable-ppc-sco", 115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 116 117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 119 120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 121 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 122 123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 124 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 125 126 STATISTIC(NumTailCalls, "Number of tail calls"); 127 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 128 129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 130 131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 132 133 // FIXME: Remove this once the bug has been fixed! 134 extern cl::opt<bool> ANDIGlueBug; 135 136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 137 const PPCSubtarget &STI) 138 : TargetLowering(TM), Subtarget(STI) { 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 if (Subtarget.isISA3_0()) { 170 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 171 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 172 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 174 } else { 175 // No extending loads from f16 or HW conversions back and forth. 176 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 177 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 178 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 179 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 180 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 181 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 182 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 183 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 184 } 185 186 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 187 188 // PowerPC has pre-inc load and store's. 189 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 194 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 199 if (!Subtarget.hasSPE()) { 200 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 204 } 205 206 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 207 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 208 for (MVT VT : ScalarIntVTs) { 209 setOperationAction(ISD::ADDC, VT, Legal); 210 setOperationAction(ISD::ADDE, VT, Legal); 211 setOperationAction(ISD::SUBC, VT, Legal); 212 setOperationAction(ISD::SUBE, VT, Legal); 213 } 214 215 if (Subtarget.useCRBits()) { 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 217 218 if (isPPC64 || Subtarget.hasFPCVT()) { 219 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 220 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 221 isPPC64 ? MVT::i64 : MVT::i32); 222 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 223 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 224 isPPC64 ? MVT::i64 : MVT::i32); 225 } else { 226 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 228 } 229 230 // PowerPC does not support direct load/store of condition registers. 231 setOperationAction(ISD::LOAD, MVT::i1, Custom); 232 setOperationAction(ISD::STORE, MVT::i1, Custom); 233 234 // FIXME: Remove this once the ANDI glue bug is fixed: 235 if (ANDIGlueBug) 236 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 237 238 for (MVT VT : MVT::integer_valuetypes()) { 239 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 241 setTruncStoreAction(VT, MVT::i1, Expand); 242 } 243 244 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 245 } 246 247 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 248 // PPC (the libcall is not available). 249 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 250 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 251 252 // We do not currently implement these libm ops for PowerPC. 253 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 254 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 259 260 // PowerPC has no SREM/UREM instructions unless we are on P9 261 // On P9 we may use a hardware instruction to compute the remainder. 262 // The instructions are not legalized directly because in the cases where the 263 // result of both the remainder and the division is required it is more 264 // efficient to compute the remainder from the result of the division rather 265 // than use the remainder instruction. 266 if (Subtarget.isISA3_0()) { 267 setOperationAction(ISD::SREM, MVT::i32, Custom); 268 setOperationAction(ISD::UREM, MVT::i32, Custom); 269 setOperationAction(ISD::SREM, MVT::i64, Custom); 270 setOperationAction(ISD::UREM, MVT::i64, Custom); 271 } else { 272 setOperationAction(ISD::SREM, MVT::i32, Expand); 273 setOperationAction(ISD::UREM, MVT::i32, Expand); 274 setOperationAction(ISD::SREM, MVT::i64, Expand); 275 setOperationAction(ISD::UREM, MVT::i64, Expand); 276 } 277 278 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 279 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 280 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 282 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 284 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 287 288 // Handle constrained floating-point operations of scalar. 289 // TODO: Handle SPE specific operation. 290 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 291 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 294 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 295 296 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 297 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 300 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 301 302 if (Subtarget.hasFSQRT()) { 303 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 304 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 305 } 306 307 // We don't support sin/cos/sqrt/fmod/pow 308 setOperationAction(ISD::FSIN , MVT::f64, Expand); 309 setOperationAction(ISD::FCOS , MVT::f64, Expand); 310 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 311 setOperationAction(ISD::FREM , MVT::f64, Expand); 312 setOperationAction(ISD::FPOW , MVT::f64, Expand); 313 setOperationAction(ISD::FSIN , MVT::f32, Expand); 314 setOperationAction(ISD::FCOS , MVT::f32, Expand); 315 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 316 setOperationAction(ISD::FREM , MVT::f32, Expand); 317 setOperationAction(ISD::FPOW , MVT::f32, Expand); 318 if (Subtarget.hasSPE()) { 319 setOperationAction(ISD::FMA , MVT::f64, Expand); 320 setOperationAction(ISD::FMA , MVT::f32, Expand); 321 } else { 322 setOperationAction(ISD::FMA , MVT::f64, Legal); 323 setOperationAction(ISD::FMA , MVT::f32, Legal); 324 } 325 326 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 327 328 // If we're enabling GP optimizations, use hardware square root 329 if (!Subtarget.hasFSQRT() && 330 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 331 Subtarget.hasFRE())) 332 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 333 334 if (!Subtarget.hasFSQRT() && 335 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 336 Subtarget.hasFRES())) 337 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 338 339 if (Subtarget.hasFCPSGN()) { 340 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 341 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 342 } else { 343 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 344 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 345 } 346 347 if (Subtarget.hasFPRND()) { 348 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 349 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 350 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 351 setOperationAction(ISD::FROUND, MVT::f64, Legal); 352 353 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 354 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 355 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 356 setOperationAction(ISD::FROUND, MVT::f32, Legal); 357 } 358 359 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 360 // to speed up scalar BSWAP64. 361 // CTPOP or CTTZ were introduced in P8/P9 respectively 362 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 363 if (Subtarget.hasP9Vector()) 364 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 365 else 366 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 367 if (Subtarget.isISA3_0()) { 368 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 369 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 370 } else { 371 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 372 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 373 } 374 375 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 376 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 377 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 378 } else { 379 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 380 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 381 } 382 383 // PowerPC does not have ROTR 384 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 385 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 386 387 if (!Subtarget.useCRBits()) { 388 // PowerPC does not have Select 389 setOperationAction(ISD::SELECT, MVT::i32, Expand); 390 setOperationAction(ISD::SELECT, MVT::i64, Expand); 391 setOperationAction(ISD::SELECT, MVT::f32, Expand); 392 setOperationAction(ISD::SELECT, MVT::f64, Expand); 393 } 394 395 // PowerPC wants to turn select_cc of FP into fsel when possible. 396 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 397 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 398 399 // PowerPC wants to optimize integer setcc a bit 400 if (!Subtarget.useCRBits()) 401 setOperationAction(ISD::SETCC, MVT::i32, Custom); 402 403 // PowerPC does not have BRCOND which requires SetCC 404 if (!Subtarget.useCRBits()) 405 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 406 407 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 408 409 if (Subtarget.hasSPE()) { 410 // SPE has built-in conversions 411 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 412 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 413 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 414 } else { 415 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 416 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 417 418 // PowerPC does not have [U|S]INT_TO_FP 419 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 420 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 421 } 422 423 if (Subtarget.hasDirectMove() && isPPC64) { 424 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 425 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 426 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 427 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 428 if (TM.Options.UnsafeFPMath) { 429 setOperationAction(ISD::LRINT, MVT::f64, Legal); 430 setOperationAction(ISD::LRINT, MVT::f32, Legal); 431 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 432 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 433 setOperationAction(ISD::LROUND, MVT::f64, Legal); 434 setOperationAction(ISD::LROUND, MVT::f32, Legal); 435 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 436 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 437 } 438 } else { 439 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 440 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 441 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 442 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 443 } 444 445 // We cannot sextinreg(i1). Expand to shifts. 446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 447 448 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 449 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 450 // support continuation, user-level threading, and etc.. As a result, no 451 // other SjLj exception interfaces are implemented and please don't build 452 // your own exception handling based on them. 453 // LLVM/Clang supports zero-cost DWARF exception handling. 454 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 455 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 456 457 // We want to legalize GlobalAddress and ConstantPool nodes into the 458 // appropriate instructions to materialize the address. 459 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 460 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 461 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 462 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 463 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 464 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 466 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 467 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 468 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 469 470 // TRAP is legal. 471 setOperationAction(ISD::TRAP, MVT::Other, Legal); 472 473 // TRAMPOLINE is custom lowered. 474 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 475 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 476 477 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 478 setOperationAction(ISD::VASTART , MVT::Other, Custom); 479 480 if (Subtarget.is64BitELFABI()) { 481 // VAARG always uses double-word chunks, so promote anything smaller. 482 setOperationAction(ISD::VAARG, MVT::i1, Promote); 483 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 484 setOperationAction(ISD::VAARG, MVT::i8, Promote); 485 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 486 setOperationAction(ISD::VAARG, MVT::i16, Promote); 487 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 488 setOperationAction(ISD::VAARG, MVT::i32, Promote); 489 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 490 setOperationAction(ISD::VAARG, MVT::Other, Expand); 491 } else if (Subtarget.is32BitELFABI()) { 492 // VAARG is custom lowered with the 32-bit SVR4 ABI. 493 setOperationAction(ISD::VAARG, MVT::Other, Custom); 494 setOperationAction(ISD::VAARG, MVT::i64, Custom); 495 } else 496 setOperationAction(ISD::VAARG, MVT::Other, Expand); 497 498 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 499 if (Subtarget.is32BitELFABI()) 500 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 501 else 502 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 503 504 // Use the default implementation. 505 setOperationAction(ISD::VAEND , MVT::Other, Expand); 506 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 507 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 508 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 509 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 510 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 511 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 512 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 513 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 514 515 // We want to custom lower some of our intrinsics. 516 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 517 518 // To handle counter-based loop conditions. 519 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 520 521 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 522 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 523 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 524 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 525 526 // Comparisons that require checking two conditions. 527 if (Subtarget.hasSPE()) { 528 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 529 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 530 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 531 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 532 } 533 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 534 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 535 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 536 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 537 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 538 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 539 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 540 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 541 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 542 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 543 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 544 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 545 546 if (Subtarget.has64BitSupport()) { 547 // They also have instructions for converting between i64 and fp. 548 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 549 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 550 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 551 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 552 // This is just the low 32 bits of a (signed) fp->i64 conversion. 553 // We cannot do this with Promote because i64 is not a legal type. 554 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 555 556 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 557 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 558 } else { 559 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 560 if (Subtarget.hasSPE()) 561 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 562 else 563 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 564 } 565 566 // With the instructions enabled under FPCVT, we can do everything. 567 if (Subtarget.hasFPCVT()) { 568 if (Subtarget.has64BitSupport()) { 569 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 570 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 571 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 572 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 573 } 574 575 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 576 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 577 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 578 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 579 } 580 581 if (Subtarget.use64BitRegs()) { 582 // 64-bit PowerPC implementations can support i64 types directly 583 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 584 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 585 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 586 // 64-bit PowerPC wants to expand i128 shifts itself. 587 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 588 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 589 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 590 } else { 591 // 32-bit PowerPC wants to expand i64 shifts itself. 592 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 593 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 594 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 595 } 596 597 if (Subtarget.hasVSX()) { 598 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 599 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 600 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 601 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 602 } 603 604 if (Subtarget.hasAltivec()) { 605 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 606 setOperationAction(ISD::SADDSAT, VT, Legal); 607 setOperationAction(ISD::SSUBSAT, VT, Legal); 608 setOperationAction(ISD::UADDSAT, VT, Legal); 609 setOperationAction(ISD::USUBSAT, VT, Legal); 610 } 611 // First set operation action for all vector types to expand. Then we 612 // will selectively turn on ones that can be effectively codegen'd. 613 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 614 // add/sub are legal for all supported vector VT's. 615 setOperationAction(ISD::ADD, VT, Legal); 616 setOperationAction(ISD::SUB, VT, Legal); 617 618 // For v2i64, these are only valid with P8Vector. This is corrected after 619 // the loop. 620 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 621 setOperationAction(ISD::SMAX, VT, Legal); 622 setOperationAction(ISD::SMIN, VT, Legal); 623 setOperationAction(ISD::UMAX, VT, Legal); 624 setOperationAction(ISD::UMIN, VT, Legal); 625 } 626 else { 627 setOperationAction(ISD::SMAX, VT, Expand); 628 setOperationAction(ISD::SMIN, VT, Expand); 629 setOperationAction(ISD::UMAX, VT, Expand); 630 setOperationAction(ISD::UMIN, VT, Expand); 631 } 632 633 if (Subtarget.hasVSX()) { 634 setOperationAction(ISD::FMAXNUM, VT, Legal); 635 setOperationAction(ISD::FMINNUM, VT, Legal); 636 } 637 638 // Vector instructions introduced in P8 639 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 640 setOperationAction(ISD::CTPOP, VT, Legal); 641 setOperationAction(ISD::CTLZ, VT, Legal); 642 } 643 else { 644 setOperationAction(ISD::CTPOP, VT, Expand); 645 setOperationAction(ISD::CTLZ, VT, Expand); 646 } 647 648 // Vector instructions introduced in P9 649 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 650 setOperationAction(ISD::CTTZ, VT, Legal); 651 else 652 setOperationAction(ISD::CTTZ, VT, Expand); 653 654 // We promote all shuffles to v16i8. 655 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 656 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 657 658 // We promote all non-typed operations to v4i32. 659 setOperationAction(ISD::AND , VT, Promote); 660 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 661 setOperationAction(ISD::OR , VT, Promote); 662 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 663 setOperationAction(ISD::XOR , VT, Promote); 664 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 665 setOperationAction(ISD::LOAD , VT, Promote); 666 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 667 setOperationAction(ISD::SELECT, VT, Promote); 668 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 669 setOperationAction(ISD::VSELECT, VT, Legal); 670 setOperationAction(ISD::SELECT_CC, VT, Promote); 671 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 672 setOperationAction(ISD::STORE, VT, Promote); 673 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 674 675 // No other operations are legal. 676 setOperationAction(ISD::MUL , VT, Expand); 677 setOperationAction(ISD::SDIV, VT, Expand); 678 setOperationAction(ISD::SREM, VT, Expand); 679 setOperationAction(ISD::UDIV, VT, Expand); 680 setOperationAction(ISD::UREM, VT, Expand); 681 setOperationAction(ISD::FDIV, VT, Expand); 682 setOperationAction(ISD::FREM, VT, Expand); 683 setOperationAction(ISD::FNEG, VT, Expand); 684 setOperationAction(ISD::FSQRT, VT, Expand); 685 setOperationAction(ISD::FLOG, VT, Expand); 686 setOperationAction(ISD::FLOG10, VT, Expand); 687 setOperationAction(ISD::FLOG2, VT, Expand); 688 setOperationAction(ISD::FEXP, VT, Expand); 689 setOperationAction(ISD::FEXP2, VT, Expand); 690 setOperationAction(ISD::FSIN, VT, Expand); 691 setOperationAction(ISD::FCOS, VT, Expand); 692 setOperationAction(ISD::FABS, VT, Expand); 693 setOperationAction(ISD::FFLOOR, VT, Expand); 694 setOperationAction(ISD::FCEIL, VT, Expand); 695 setOperationAction(ISD::FTRUNC, VT, Expand); 696 setOperationAction(ISD::FRINT, VT, Expand); 697 setOperationAction(ISD::FNEARBYINT, VT, Expand); 698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 699 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 700 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 701 setOperationAction(ISD::MULHU, VT, Expand); 702 setOperationAction(ISD::MULHS, VT, Expand); 703 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 704 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 705 setOperationAction(ISD::UDIVREM, VT, Expand); 706 setOperationAction(ISD::SDIVREM, VT, Expand); 707 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 708 setOperationAction(ISD::FPOW, VT, Expand); 709 setOperationAction(ISD::BSWAP, VT, Expand); 710 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 711 setOperationAction(ISD::ROTL, VT, Expand); 712 setOperationAction(ISD::ROTR, VT, Expand); 713 714 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 715 setTruncStoreAction(VT, InnerVT, Expand); 716 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 717 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 718 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 719 } 720 } 721 if (!Subtarget.hasP8Vector()) { 722 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 723 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 724 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 725 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 726 } 727 728 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 729 setOperationAction(ISD::ABS, VT, Custom); 730 731 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 732 // with merges, splats, etc. 733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 734 735 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 736 // are cheap, so handle them before they get expanded to scalar. 737 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 738 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 739 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 740 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 741 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 742 743 setOperationAction(ISD::AND , MVT::v4i32, Legal); 744 setOperationAction(ISD::OR , MVT::v4i32, Legal); 745 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 746 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 747 setOperationAction(ISD::SELECT, MVT::v4i32, 748 Subtarget.useCRBits() ? Legal : Expand); 749 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 750 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 751 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 752 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 753 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 754 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 755 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 756 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 757 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 758 759 // Without hasP8Altivec set, v2i64 SMAX isn't available. 760 // But ABS custom lowering requires SMAX support. 761 if (!Subtarget.hasP8Altivec()) 762 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 763 764 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 765 if (Subtarget.hasAltivec()) 766 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 767 setOperationAction(ISD::ROTL, VT, Legal); 768 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 769 if (Subtarget.hasP8Altivec()) 770 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 771 772 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 773 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 774 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 775 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 776 777 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 778 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 779 780 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 781 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 782 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 783 } 784 785 if (Subtarget.hasP8Altivec()) 786 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 787 else 788 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 789 790 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 791 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 792 793 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 794 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 795 796 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 797 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 800 801 // Altivec does not contain unordered floating-point compare instructions 802 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 803 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 804 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 805 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 806 807 if (Subtarget.hasVSX()) { 808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 810 if (Subtarget.hasP8Vector()) { 811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 812 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 813 } 814 if (Subtarget.hasDirectMove() && isPPC64) { 815 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 818 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 823 } 824 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 825 826 // The nearbyint variants are not allowed to raise the inexact exception 827 // so we can only code-gen them with unsafe math. 828 if (TM.Options.UnsafeFPMath) { 829 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 830 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 831 } 832 833 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 834 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 835 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 836 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 837 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 838 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 839 setOperationAction(ISD::FROUND, MVT::f64, Legal); 840 setOperationAction(ISD::FRINT, MVT::f64, Legal); 841 842 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 843 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 844 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 845 setOperationAction(ISD::FROUND, MVT::f32, Legal); 846 setOperationAction(ISD::FRINT, MVT::f32, Legal); 847 848 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 849 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 850 851 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 852 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 853 854 // Share the Altivec comparison restrictions. 855 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 856 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 857 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 858 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 859 860 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 861 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 862 863 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 864 865 if (Subtarget.hasP8Vector()) 866 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 867 868 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 869 870 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 871 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 872 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 873 874 if (Subtarget.hasP8Altivec()) { 875 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 876 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 877 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 878 879 // 128 bit shifts can be accomplished via 3 instructions for SHL and 880 // SRL, but not for SRA because of the instructions available: 881 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 882 // doing 883 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 884 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 885 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 886 887 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 888 } 889 else { 890 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 891 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 892 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 893 894 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 895 896 // VSX v2i64 only supports non-arithmetic operations. 897 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 898 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 899 } 900 901 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 902 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 903 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 904 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 905 906 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 907 908 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 909 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 910 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 911 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 912 913 // Custom handling for partial vectors of integers converted to 914 // floating point. We already have optimal handling for v2i32 through 915 // the DAG combine, so those aren't necessary. 916 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 917 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 918 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 919 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 920 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 921 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 922 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 923 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 924 925 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 926 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 927 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 928 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 929 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 930 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 931 932 if (Subtarget.hasDirectMove()) 933 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 934 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 935 936 // Handle constrained floating-point operations of vector. 937 // The predictor is `hasVSX` because altivec instruction has 938 // no exception but VSX vector instruction has. 939 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 940 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 941 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 942 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 943 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 944 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 945 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 946 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 947 948 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 949 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 950 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 951 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 952 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 953 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 954 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 955 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 956 957 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 958 } 959 960 if (Subtarget.hasP8Altivec()) { 961 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 962 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 963 } 964 965 if (Subtarget.hasP9Vector()) { 966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 968 969 // 128 bit shifts can be accomplished via 3 instructions for SHL and 970 // SRL, but not for SRA because of the instructions available: 971 // VS{RL} and VS{RL}O. 972 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 973 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 974 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 975 976 if (EnableQuadPrecision) { 977 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 978 setOperationAction(ISD::FADD, MVT::f128, Legal); 979 setOperationAction(ISD::FSUB, MVT::f128, Legal); 980 setOperationAction(ISD::FDIV, MVT::f128, Legal); 981 setOperationAction(ISD::FMUL, MVT::f128, Legal); 982 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 983 // No extending loads to f128 on PPC. 984 for (MVT FPT : MVT::fp_valuetypes()) 985 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 986 setOperationAction(ISD::FMA, MVT::f128, Legal); 987 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 988 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 989 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 990 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 991 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 992 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 993 994 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 995 setOperationAction(ISD::FRINT, MVT::f128, Legal); 996 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 997 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 998 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 999 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1000 1001 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1002 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1003 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1004 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1005 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1006 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1007 // No implementation for these ops for PowerPC. 1008 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1009 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1010 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1011 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1012 setOperationAction(ISD::FREM, MVT::f128, Expand); 1013 1014 // Handle constrained floating-point operations of fp128 1015 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1016 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1017 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1018 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1019 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1020 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1021 } 1022 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1023 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1024 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1025 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1026 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1027 } 1028 1029 if (Subtarget.hasP9Altivec()) { 1030 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1031 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1032 1033 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1034 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1035 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1036 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1037 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1038 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1039 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1040 } 1041 } 1042 1043 if (Subtarget.hasQPX()) { 1044 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1045 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1046 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1047 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1048 1049 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1050 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1051 1052 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1053 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1054 1055 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1056 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1057 1058 if (!Subtarget.useCRBits()) 1059 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1060 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1061 1062 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1063 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1064 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1065 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1066 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1067 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1068 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1069 1070 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1071 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1072 1073 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1074 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1075 1076 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1077 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1078 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1079 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1080 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1081 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1082 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1083 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1084 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1085 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1086 1087 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1088 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1089 1090 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1091 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1092 1093 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1094 1095 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1096 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1097 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1098 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1099 1100 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1101 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1102 1103 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1104 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1105 1106 if (!Subtarget.useCRBits()) 1107 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1108 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1109 1110 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1111 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1112 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1113 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1114 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1115 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1116 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1117 1118 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1119 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1120 1121 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1122 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1123 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1124 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1125 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1126 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1127 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1128 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1129 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1130 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1131 1132 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1133 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1134 1135 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1136 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1137 1138 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1139 1140 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1141 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1142 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1143 1144 if (!Subtarget.useCRBits()) 1145 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1146 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1147 1148 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1149 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1150 1151 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1152 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1153 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1154 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1155 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1156 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1157 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1158 1159 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1160 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1161 1162 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1163 1164 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1165 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1166 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1167 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1168 1169 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1170 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1172 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1173 1174 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1175 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1176 1177 // These need to set FE_INEXACT, and so cannot be vectorized here. 1178 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1179 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1180 1181 if (TM.Options.UnsafeFPMath) { 1182 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1183 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1184 1185 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1186 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1187 } else { 1188 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1189 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1190 1191 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1192 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1193 } 1194 1195 // TODO: Handle constrained floating-point operations of v4f64 1196 } 1197 1198 if (Subtarget.has64BitSupport()) 1199 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1200 1201 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1202 1203 if (!isPPC64) { 1204 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1205 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1206 } 1207 1208 setBooleanContents(ZeroOrOneBooleanContent); 1209 1210 if (Subtarget.hasAltivec()) { 1211 // Altivec instructions set fields to all zeros or all ones. 1212 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1213 } 1214 1215 if (!isPPC64) { 1216 // These libcalls are not available in 32-bit. 1217 setLibcallName(RTLIB::SHL_I128, nullptr); 1218 setLibcallName(RTLIB::SRL_I128, nullptr); 1219 setLibcallName(RTLIB::SRA_I128, nullptr); 1220 } 1221 1222 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1223 1224 // We have target-specific dag combine patterns for the following nodes: 1225 setTargetDAGCombine(ISD::ADD); 1226 setTargetDAGCombine(ISD::SHL); 1227 setTargetDAGCombine(ISD::SRA); 1228 setTargetDAGCombine(ISD::SRL); 1229 setTargetDAGCombine(ISD::MUL); 1230 setTargetDAGCombine(ISD::SINT_TO_FP); 1231 setTargetDAGCombine(ISD::BUILD_VECTOR); 1232 if (Subtarget.hasFPCVT()) 1233 setTargetDAGCombine(ISD::UINT_TO_FP); 1234 setTargetDAGCombine(ISD::LOAD); 1235 setTargetDAGCombine(ISD::STORE); 1236 setTargetDAGCombine(ISD::BR_CC); 1237 if (Subtarget.useCRBits()) 1238 setTargetDAGCombine(ISD::BRCOND); 1239 setTargetDAGCombine(ISD::BSWAP); 1240 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1241 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1242 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1243 1244 setTargetDAGCombine(ISD::SIGN_EXTEND); 1245 setTargetDAGCombine(ISD::ZERO_EXTEND); 1246 setTargetDAGCombine(ISD::ANY_EXTEND); 1247 1248 setTargetDAGCombine(ISD::TRUNCATE); 1249 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1250 1251 1252 if (Subtarget.useCRBits()) { 1253 setTargetDAGCombine(ISD::TRUNCATE); 1254 setTargetDAGCombine(ISD::SETCC); 1255 setTargetDAGCombine(ISD::SELECT_CC); 1256 } 1257 1258 // Use reciprocal estimates. 1259 if (TM.Options.UnsafeFPMath) { 1260 setTargetDAGCombine(ISD::FDIV); 1261 setTargetDAGCombine(ISD::FSQRT); 1262 } 1263 1264 if (Subtarget.hasP9Altivec()) { 1265 setTargetDAGCombine(ISD::ABS); 1266 setTargetDAGCombine(ISD::VSELECT); 1267 } 1268 1269 if (EnableQuadPrecision) { 1270 setLibcallName(RTLIB::LOG_F128, "logf128"); 1271 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1272 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1273 setLibcallName(RTLIB::EXP_F128, "expf128"); 1274 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1275 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1276 setLibcallName(RTLIB::COS_F128, "cosf128"); 1277 setLibcallName(RTLIB::POW_F128, "powf128"); 1278 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1279 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1280 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1281 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1282 } 1283 1284 // With 32 condition bits, we don't need to sink (and duplicate) compares 1285 // aggressively in CodeGenPrep. 1286 if (Subtarget.useCRBits()) { 1287 setHasMultipleConditionRegisters(); 1288 setJumpIsExpensive(); 1289 } 1290 1291 setMinFunctionAlignment(Align(4)); 1292 1293 switch (Subtarget.getCPUDirective()) { 1294 default: break; 1295 case PPC::DIR_970: 1296 case PPC::DIR_A2: 1297 case PPC::DIR_E500: 1298 case PPC::DIR_E500mc: 1299 case PPC::DIR_E5500: 1300 case PPC::DIR_PWR4: 1301 case PPC::DIR_PWR5: 1302 case PPC::DIR_PWR5X: 1303 case PPC::DIR_PWR6: 1304 case PPC::DIR_PWR6X: 1305 case PPC::DIR_PWR7: 1306 case PPC::DIR_PWR8: 1307 case PPC::DIR_PWR9: 1308 case PPC::DIR_PWR_FUTURE: 1309 setPrefLoopAlignment(Align(16)); 1310 setPrefFunctionAlignment(Align(16)); 1311 break; 1312 } 1313 1314 if (Subtarget.enableMachineScheduler()) 1315 setSchedulingPreference(Sched::Source); 1316 else 1317 setSchedulingPreference(Sched::Hybrid); 1318 1319 computeRegisterProperties(STI.getRegisterInfo()); 1320 1321 // The Freescale cores do better with aggressive inlining of memcpy and 1322 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1323 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1324 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1325 MaxStoresPerMemset = 32; 1326 MaxStoresPerMemsetOptSize = 16; 1327 MaxStoresPerMemcpy = 32; 1328 MaxStoresPerMemcpyOptSize = 8; 1329 MaxStoresPerMemmove = 32; 1330 MaxStoresPerMemmoveOptSize = 8; 1331 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1332 // The A2 also benefits from (very) aggressive inlining of memcpy and 1333 // friends. The overhead of a the function call, even when warm, can be 1334 // over one hundred cycles. 1335 MaxStoresPerMemset = 128; 1336 MaxStoresPerMemcpy = 128; 1337 MaxStoresPerMemmove = 128; 1338 MaxLoadsPerMemcmp = 128; 1339 } else { 1340 MaxLoadsPerMemcmp = 8; 1341 MaxLoadsPerMemcmpOptSize = 4; 1342 } 1343 1344 // Let the subtarget (CPU) decide if a predictable select is more expensive 1345 // than the corresponding branch. This information is used in CGP to decide 1346 // when to convert selects into branches. 1347 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1348 } 1349 1350 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1351 /// the desired ByVal argument alignment. 1352 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1353 unsigned MaxMaxAlign) { 1354 if (MaxAlign == MaxMaxAlign) 1355 return; 1356 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1357 if (MaxMaxAlign >= 32 && 1358 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1359 MaxAlign = 32; 1360 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1361 MaxAlign < 16) 1362 MaxAlign = 16; 1363 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1364 unsigned EltAlign = 0; 1365 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1366 if (EltAlign > MaxAlign) 1367 MaxAlign = EltAlign; 1368 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1369 for (auto *EltTy : STy->elements()) { 1370 unsigned EltAlign = 0; 1371 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1372 if (EltAlign > MaxAlign) 1373 MaxAlign = EltAlign; 1374 if (MaxAlign == MaxMaxAlign) 1375 break; 1376 } 1377 } 1378 } 1379 1380 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1381 /// function arguments in the caller parameter area. 1382 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1383 const DataLayout &DL) const { 1384 // 16byte and wider vectors are passed on 16byte boundary. 1385 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1386 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1387 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1388 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1389 return Align; 1390 } 1391 1392 bool PPCTargetLowering::useSoftFloat() const { 1393 return Subtarget.useSoftFloat(); 1394 } 1395 1396 bool PPCTargetLowering::hasSPE() const { 1397 return Subtarget.hasSPE(); 1398 } 1399 1400 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1401 return VT.isScalarInteger(); 1402 } 1403 1404 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1405 switch ((PPCISD::NodeType)Opcode) { 1406 case PPCISD::FIRST_NUMBER: break; 1407 case PPCISD::FSEL: return "PPCISD::FSEL"; 1408 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1409 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1410 case PPCISD::FCFID: return "PPCISD::FCFID"; 1411 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1412 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1413 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1414 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1415 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1416 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1417 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1418 case PPCISD::FP_TO_UINT_IN_VSR: 1419 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1420 case PPCISD::FP_TO_SINT_IN_VSR: 1421 return "PPCISD::FP_TO_SINT_IN_VSR"; 1422 case PPCISD::FRE: return "PPCISD::FRE"; 1423 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1424 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1425 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1426 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1427 case PPCISD::VPERM: return "PPCISD::VPERM"; 1428 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1429 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1430 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1431 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1432 case PPCISD::CMPB: return "PPCISD::CMPB"; 1433 case PPCISD::Hi: return "PPCISD::Hi"; 1434 case PPCISD::Lo: return "PPCISD::Lo"; 1435 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1436 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1437 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1438 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1439 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1440 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1441 case PPCISD::SRL: return "PPCISD::SRL"; 1442 case PPCISD::SRA: return "PPCISD::SRA"; 1443 case PPCISD::SHL: return "PPCISD::SHL"; 1444 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1445 case PPCISD::CALL: return "PPCISD::CALL"; 1446 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1447 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1448 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1449 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1450 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1451 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1452 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1453 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1454 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1455 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1456 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1457 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1458 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1459 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1460 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1461 case PPCISD::ANDI_rec_1_EQ_BIT: 1462 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1463 case PPCISD::ANDI_rec_1_GT_BIT: 1464 return "PPCISD::ANDI_rec_1_GT_BIT"; 1465 case PPCISD::VCMP: return "PPCISD::VCMP"; 1466 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1467 case PPCISD::LBRX: return "PPCISD::LBRX"; 1468 case PPCISD::STBRX: return "PPCISD::STBRX"; 1469 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1470 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1471 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1472 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1473 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1474 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1475 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1476 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1477 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1478 case PPCISD::ST_VSR_SCAL_INT: 1479 return "PPCISD::ST_VSR_SCAL_INT"; 1480 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1481 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1482 case PPCISD::BDZ: return "PPCISD::BDZ"; 1483 case PPCISD::MFFS: return "PPCISD::MFFS"; 1484 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1485 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1486 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1487 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1488 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1489 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1490 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1491 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1492 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1493 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1494 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1495 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1496 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1497 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1498 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1499 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1500 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1501 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1502 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1503 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1504 case PPCISD::SC: return "PPCISD::SC"; 1505 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1506 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1507 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1508 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1509 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1510 case PPCISD::VABSD: return "PPCISD::VABSD"; 1511 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1512 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1513 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1514 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1515 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1516 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1517 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1518 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1519 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1520 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1521 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1522 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1523 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1524 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1525 } 1526 return nullptr; 1527 } 1528 1529 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1530 EVT VT) const { 1531 if (!VT.isVector()) 1532 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1533 1534 if (Subtarget.hasQPX()) 1535 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1536 1537 return VT.changeVectorElementTypeToInteger(); 1538 } 1539 1540 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1541 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1542 return true; 1543 } 1544 1545 //===----------------------------------------------------------------------===// 1546 // Node matching predicates, for use by the tblgen matching code. 1547 //===----------------------------------------------------------------------===// 1548 1549 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1550 static bool isFloatingPointZero(SDValue Op) { 1551 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1552 return CFP->getValueAPF().isZero(); 1553 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1554 // Maybe this has already been legalized into the constant pool? 1555 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1556 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1557 return CFP->getValueAPF().isZero(); 1558 } 1559 return false; 1560 } 1561 1562 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1563 /// true if Op is undef or if it matches the specified value. 1564 static bool isConstantOrUndef(int Op, int Val) { 1565 return Op < 0 || Op == Val; 1566 } 1567 1568 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1569 /// VPKUHUM instruction. 1570 /// The ShuffleKind distinguishes between big-endian operations with 1571 /// two different inputs (0), either-endian operations with two identical 1572 /// inputs (1), and little-endian operations with two different inputs (2). 1573 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1574 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1575 SelectionDAG &DAG) { 1576 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1577 if (ShuffleKind == 0) { 1578 if (IsLE) 1579 return false; 1580 for (unsigned i = 0; i != 16; ++i) 1581 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1582 return false; 1583 } else if (ShuffleKind == 2) { 1584 if (!IsLE) 1585 return false; 1586 for (unsigned i = 0; i != 16; ++i) 1587 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1588 return false; 1589 } else if (ShuffleKind == 1) { 1590 unsigned j = IsLE ? 0 : 1; 1591 for (unsigned i = 0; i != 8; ++i) 1592 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1593 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1594 return false; 1595 } 1596 return true; 1597 } 1598 1599 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1600 /// VPKUWUM instruction. 1601 /// The ShuffleKind distinguishes between big-endian operations with 1602 /// two different inputs (0), either-endian operations with two identical 1603 /// inputs (1), and little-endian operations with two different inputs (2). 1604 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1605 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1606 SelectionDAG &DAG) { 1607 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1608 if (ShuffleKind == 0) { 1609 if (IsLE) 1610 return false; 1611 for (unsigned i = 0; i != 16; i += 2) 1612 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1613 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1614 return false; 1615 } else if (ShuffleKind == 2) { 1616 if (!IsLE) 1617 return false; 1618 for (unsigned i = 0; i != 16; i += 2) 1619 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1620 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1621 return false; 1622 } else if (ShuffleKind == 1) { 1623 unsigned j = IsLE ? 0 : 2; 1624 for (unsigned i = 0; i != 8; i += 2) 1625 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1626 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1627 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1628 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1629 return false; 1630 } 1631 return true; 1632 } 1633 1634 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1635 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1636 /// current subtarget. 1637 /// 1638 /// The ShuffleKind distinguishes between big-endian operations with 1639 /// two different inputs (0), either-endian operations with two identical 1640 /// inputs (1), and little-endian operations with two different inputs (2). 1641 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1642 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1643 SelectionDAG &DAG) { 1644 const PPCSubtarget& Subtarget = 1645 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1646 if (!Subtarget.hasP8Vector()) 1647 return false; 1648 1649 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1650 if (ShuffleKind == 0) { 1651 if (IsLE) 1652 return false; 1653 for (unsigned i = 0; i != 16; i += 4) 1654 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1655 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1656 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1657 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1658 return false; 1659 } else if (ShuffleKind == 2) { 1660 if (!IsLE) 1661 return false; 1662 for (unsigned i = 0; i != 16; i += 4) 1663 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1664 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1665 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1666 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1667 return false; 1668 } else if (ShuffleKind == 1) { 1669 unsigned j = IsLE ? 0 : 4; 1670 for (unsigned i = 0; i != 8; i += 4) 1671 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1672 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1673 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1674 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1675 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1676 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1678 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1679 return false; 1680 } 1681 return true; 1682 } 1683 1684 /// isVMerge - Common function, used to match vmrg* shuffles. 1685 /// 1686 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1687 unsigned LHSStart, unsigned RHSStart) { 1688 if (N->getValueType(0) != MVT::v16i8) 1689 return false; 1690 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1691 "Unsupported merge size!"); 1692 1693 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1694 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1695 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1696 LHSStart+j+i*UnitSize) || 1697 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1698 RHSStart+j+i*UnitSize)) 1699 return false; 1700 } 1701 return true; 1702 } 1703 1704 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1705 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1706 /// The ShuffleKind distinguishes between big-endian merges with two 1707 /// different inputs (0), either-endian merges with two identical inputs (1), 1708 /// and little-endian merges with two different inputs (2). For the latter, 1709 /// the input operands are swapped (see PPCInstrAltivec.td). 1710 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1711 unsigned ShuffleKind, SelectionDAG &DAG) { 1712 if (DAG.getDataLayout().isLittleEndian()) { 1713 if (ShuffleKind == 1) // unary 1714 return isVMerge(N, UnitSize, 0, 0); 1715 else if (ShuffleKind == 2) // swapped 1716 return isVMerge(N, UnitSize, 0, 16); 1717 else 1718 return false; 1719 } else { 1720 if (ShuffleKind == 1) // unary 1721 return isVMerge(N, UnitSize, 8, 8); 1722 else if (ShuffleKind == 0) // normal 1723 return isVMerge(N, UnitSize, 8, 24); 1724 else 1725 return false; 1726 } 1727 } 1728 1729 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1730 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1731 /// The ShuffleKind distinguishes between big-endian merges with two 1732 /// different inputs (0), either-endian merges with two identical inputs (1), 1733 /// and little-endian merges with two different inputs (2). For the latter, 1734 /// the input operands are swapped (see PPCInstrAltivec.td). 1735 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1736 unsigned ShuffleKind, SelectionDAG &DAG) { 1737 if (DAG.getDataLayout().isLittleEndian()) { 1738 if (ShuffleKind == 1) // unary 1739 return isVMerge(N, UnitSize, 8, 8); 1740 else if (ShuffleKind == 2) // swapped 1741 return isVMerge(N, UnitSize, 8, 24); 1742 else 1743 return false; 1744 } else { 1745 if (ShuffleKind == 1) // unary 1746 return isVMerge(N, UnitSize, 0, 0); 1747 else if (ShuffleKind == 0) // normal 1748 return isVMerge(N, UnitSize, 0, 16); 1749 else 1750 return false; 1751 } 1752 } 1753 1754 /** 1755 * Common function used to match vmrgew and vmrgow shuffles 1756 * 1757 * The indexOffset determines whether to look for even or odd words in 1758 * the shuffle mask. This is based on the of the endianness of the target 1759 * machine. 1760 * - Little Endian: 1761 * - Use offset of 0 to check for odd elements 1762 * - Use offset of 4 to check for even elements 1763 * - Big Endian: 1764 * - Use offset of 0 to check for even elements 1765 * - Use offset of 4 to check for odd elements 1766 * A detailed description of the vector element ordering for little endian and 1767 * big endian can be found at 1768 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1769 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1770 * compiler differences mean to you 1771 * 1772 * The mask to the shuffle vector instruction specifies the indices of the 1773 * elements from the two input vectors to place in the result. The elements are 1774 * numbered in array-access order, starting with the first vector. These vectors 1775 * are always of type v16i8, thus each vector will contain 16 elements of size 1776 * 8. More info on the shuffle vector can be found in the 1777 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1778 * Language Reference. 1779 * 1780 * The RHSStartValue indicates whether the same input vectors are used (unary) 1781 * or two different input vectors are used, based on the following: 1782 * - If the instruction uses the same vector for both inputs, the range of the 1783 * indices will be 0 to 15. In this case, the RHSStart value passed should 1784 * be 0. 1785 * - If the instruction has two different vectors then the range of the 1786 * indices will be 0 to 31. In this case, the RHSStart value passed should 1787 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1788 * to 31 specify elements in the second vector). 1789 * 1790 * \param[in] N The shuffle vector SD Node to analyze 1791 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1792 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1793 * vector to the shuffle_vector instruction 1794 * \return true iff this shuffle vector represents an even or odd word merge 1795 */ 1796 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1797 unsigned RHSStartValue) { 1798 if (N->getValueType(0) != MVT::v16i8) 1799 return false; 1800 1801 for (unsigned i = 0; i < 2; ++i) 1802 for (unsigned j = 0; j < 4; ++j) 1803 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1804 i*RHSStartValue+j+IndexOffset) || 1805 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1806 i*RHSStartValue+j+IndexOffset+8)) 1807 return false; 1808 return true; 1809 } 1810 1811 /** 1812 * Determine if the specified shuffle mask is suitable for the vmrgew or 1813 * vmrgow instructions. 1814 * 1815 * \param[in] N The shuffle vector SD Node to analyze 1816 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1817 * \param[in] ShuffleKind Identify the type of merge: 1818 * - 0 = big-endian merge with two different inputs; 1819 * - 1 = either-endian merge with two identical inputs; 1820 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1821 * little-endian merges). 1822 * \param[in] DAG The current SelectionDAG 1823 * \return true iff this shuffle mask 1824 */ 1825 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1826 unsigned ShuffleKind, SelectionDAG &DAG) { 1827 if (DAG.getDataLayout().isLittleEndian()) { 1828 unsigned indexOffset = CheckEven ? 4 : 0; 1829 if (ShuffleKind == 1) // Unary 1830 return isVMerge(N, indexOffset, 0); 1831 else if (ShuffleKind == 2) // swapped 1832 return isVMerge(N, indexOffset, 16); 1833 else 1834 return false; 1835 } 1836 else { 1837 unsigned indexOffset = CheckEven ? 0 : 4; 1838 if (ShuffleKind == 1) // Unary 1839 return isVMerge(N, indexOffset, 0); 1840 else if (ShuffleKind == 0) // Normal 1841 return isVMerge(N, indexOffset, 16); 1842 else 1843 return false; 1844 } 1845 return false; 1846 } 1847 1848 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1849 /// amount, otherwise return -1. 1850 /// The ShuffleKind distinguishes between big-endian operations with two 1851 /// different inputs (0), either-endian operations with two identical inputs 1852 /// (1), and little-endian operations with two different inputs (2). For the 1853 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1854 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1855 SelectionDAG &DAG) { 1856 if (N->getValueType(0) != MVT::v16i8) 1857 return -1; 1858 1859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1860 1861 // Find the first non-undef value in the shuffle mask. 1862 unsigned i; 1863 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1864 /*search*/; 1865 1866 if (i == 16) return -1; // all undef. 1867 1868 // Otherwise, check to see if the rest of the elements are consecutively 1869 // numbered from this value. 1870 unsigned ShiftAmt = SVOp->getMaskElt(i); 1871 if (ShiftAmt < i) return -1; 1872 1873 ShiftAmt -= i; 1874 bool isLE = DAG.getDataLayout().isLittleEndian(); 1875 1876 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1877 // Check the rest of the elements to see if they are consecutive. 1878 for (++i; i != 16; ++i) 1879 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1880 return -1; 1881 } else if (ShuffleKind == 1) { 1882 // Check the rest of the elements to see if they are consecutive. 1883 for (++i; i != 16; ++i) 1884 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1885 return -1; 1886 } else 1887 return -1; 1888 1889 if (isLE) 1890 ShiftAmt = 16 - ShiftAmt; 1891 1892 return ShiftAmt; 1893 } 1894 1895 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1896 /// specifies a splat of a single element that is suitable for input to 1897 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1898 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1899 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1900 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1901 1902 // The consecutive indices need to specify an element, not part of two 1903 // different elements. So abandon ship early if this isn't the case. 1904 if (N->getMaskElt(0) % EltSize != 0) 1905 return false; 1906 1907 // This is a splat operation if each element of the permute is the same, and 1908 // if the value doesn't reference the second vector. 1909 unsigned ElementBase = N->getMaskElt(0); 1910 1911 // FIXME: Handle UNDEF elements too! 1912 if (ElementBase >= 16) 1913 return false; 1914 1915 // Check that the indices are consecutive, in the case of a multi-byte element 1916 // splatted with a v16i8 mask. 1917 for (unsigned i = 1; i != EltSize; ++i) 1918 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1919 return false; 1920 1921 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1922 if (N->getMaskElt(i) < 0) continue; 1923 for (unsigned j = 0; j != EltSize; ++j) 1924 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1925 return false; 1926 } 1927 return true; 1928 } 1929 1930 /// Check that the mask is shuffling N byte elements. Within each N byte 1931 /// element of the mask, the indices could be either in increasing or 1932 /// decreasing order as long as they are consecutive. 1933 /// \param[in] N the shuffle vector SD Node to analyze 1934 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1935 /// Word/DoubleWord/QuadWord). 1936 /// \param[in] StepLen the delta indices number among the N byte element, if 1937 /// the mask is in increasing/decreasing order then it is 1/-1. 1938 /// \return true iff the mask is shuffling N byte elements. 1939 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1940 int StepLen) { 1941 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1942 "Unexpected element width."); 1943 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1944 1945 unsigned NumOfElem = 16 / Width; 1946 unsigned MaskVal[16]; // Width is never greater than 16 1947 for (unsigned i = 0; i < NumOfElem; ++i) { 1948 MaskVal[0] = N->getMaskElt(i * Width); 1949 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1950 return false; 1951 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1952 return false; 1953 } 1954 1955 for (unsigned int j = 1; j < Width; ++j) { 1956 MaskVal[j] = N->getMaskElt(i * Width + j); 1957 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1958 return false; 1959 } 1960 } 1961 } 1962 1963 return true; 1964 } 1965 1966 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1967 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1968 if (!isNByteElemShuffleMask(N, 4, 1)) 1969 return false; 1970 1971 // Now we look at mask elements 0,4,8,12 1972 unsigned M0 = N->getMaskElt(0) / 4; 1973 unsigned M1 = N->getMaskElt(4) / 4; 1974 unsigned M2 = N->getMaskElt(8) / 4; 1975 unsigned M3 = N->getMaskElt(12) / 4; 1976 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1977 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1978 1979 // Below, let H and L be arbitrary elements of the shuffle mask 1980 // where H is in the range [4,7] and L is in the range [0,3]. 1981 // H, 1, 2, 3 or L, 5, 6, 7 1982 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1983 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1984 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1985 InsertAtByte = IsLE ? 12 : 0; 1986 Swap = M0 < 4; 1987 return true; 1988 } 1989 // 0, H, 2, 3 or 4, L, 6, 7 1990 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1991 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1992 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1993 InsertAtByte = IsLE ? 8 : 4; 1994 Swap = M1 < 4; 1995 return true; 1996 } 1997 // 0, 1, H, 3 or 4, 5, L, 7 1998 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1999 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2000 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2001 InsertAtByte = IsLE ? 4 : 8; 2002 Swap = M2 < 4; 2003 return true; 2004 } 2005 // 0, 1, 2, H or 4, 5, 6, L 2006 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2007 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2008 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2009 InsertAtByte = IsLE ? 0 : 12; 2010 Swap = M3 < 4; 2011 return true; 2012 } 2013 2014 // If both vector operands for the shuffle are the same vector, the mask will 2015 // contain only elements from the first one and the second one will be undef. 2016 if (N->getOperand(1).isUndef()) { 2017 ShiftElts = 0; 2018 Swap = true; 2019 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2020 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2021 InsertAtByte = IsLE ? 12 : 0; 2022 return true; 2023 } 2024 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2025 InsertAtByte = IsLE ? 8 : 4; 2026 return true; 2027 } 2028 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2029 InsertAtByte = IsLE ? 4 : 8; 2030 return true; 2031 } 2032 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2033 InsertAtByte = IsLE ? 0 : 12; 2034 return true; 2035 } 2036 } 2037 2038 return false; 2039 } 2040 2041 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2042 bool &Swap, bool IsLE) { 2043 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2044 // Ensure each byte index of the word is consecutive. 2045 if (!isNByteElemShuffleMask(N, 4, 1)) 2046 return false; 2047 2048 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2049 unsigned M0 = N->getMaskElt(0) / 4; 2050 unsigned M1 = N->getMaskElt(4) / 4; 2051 unsigned M2 = N->getMaskElt(8) / 4; 2052 unsigned M3 = N->getMaskElt(12) / 4; 2053 2054 // If both vector operands for the shuffle are the same vector, the mask will 2055 // contain only elements from the first one and the second one will be undef. 2056 if (N->getOperand(1).isUndef()) { 2057 assert(M0 < 4 && "Indexing into an undef vector?"); 2058 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2059 return false; 2060 2061 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2062 Swap = false; 2063 return true; 2064 } 2065 2066 // Ensure each word index of the ShuffleVector Mask is consecutive. 2067 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2068 return false; 2069 2070 if (IsLE) { 2071 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2072 // Input vectors don't need to be swapped if the leading element 2073 // of the result is one of the 3 left elements of the second vector 2074 // (or if there is no shift to be done at all). 2075 Swap = false; 2076 ShiftElts = (8 - M0) % 8; 2077 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2078 // Input vectors need to be swapped if the leading element 2079 // of the result is one of the 3 left elements of the first vector 2080 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2081 Swap = true; 2082 ShiftElts = (4 - M0) % 4; 2083 } 2084 2085 return true; 2086 } else { // BE 2087 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2088 // Input vectors don't need to be swapped if the leading element 2089 // of the result is one of the 4 elements of the first vector. 2090 Swap = false; 2091 ShiftElts = M0; 2092 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2093 // Input vectors need to be swapped if the leading element 2094 // of the result is one of the 4 elements of the right vector. 2095 Swap = true; 2096 ShiftElts = M0 - 4; 2097 } 2098 2099 return true; 2100 } 2101 } 2102 2103 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2104 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2105 2106 if (!isNByteElemShuffleMask(N, Width, -1)) 2107 return false; 2108 2109 for (int i = 0; i < 16; i += Width) 2110 if (N->getMaskElt(i) != i + Width - 1) 2111 return false; 2112 2113 return true; 2114 } 2115 2116 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2117 return isXXBRShuffleMaskHelper(N, 2); 2118 } 2119 2120 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2121 return isXXBRShuffleMaskHelper(N, 4); 2122 } 2123 2124 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2125 return isXXBRShuffleMaskHelper(N, 8); 2126 } 2127 2128 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2129 return isXXBRShuffleMaskHelper(N, 16); 2130 } 2131 2132 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2133 /// if the inputs to the instruction should be swapped and set \p DM to the 2134 /// value for the immediate. 2135 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2136 /// AND element 0 of the result comes from the first input (LE) or second input 2137 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2138 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2139 /// mask. 2140 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2141 bool &Swap, bool IsLE) { 2142 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2143 2144 // Ensure each byte index of the double word is consecutive. 2145 if (!isNByteElemShuffleMask(N, 8, 1)) 2146 return false; 2147 2148 unsigned M0 = N->getMaskElt(0) / 8; 2149 unsigned M1 = N->getMaskElt(8) / 8; 2150 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2151 2152 // If both vector operands for the shuffle are the same vector, the mask will 2153 // contain only elements from the first one and the second one will be undef. 2154 if (N->getOperand(1).isUndef()) { 2155 if ((M0 | M1) < 2) { 2156 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2157 Swap = false; 2158 return true; 2159 } else 2160 return false; 2161 } 2162 2163 if (IsLE) { 2164 if (M0 > 1 && M1 < 2) { 2165 Swap = false; 2166 } else if (M0 < 2 && M1 > 1) { 2167 M0 = (M0 + 2) % 4; 2168 M1 = (M1 + 2) % 4; 2169 Swap = true; 2170 } else 2171 return false; 2172 2173 // Note: if control flow comes here that means Swap is already set above 2174 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2175 return true; 2176 } else { // BE 2177 if (M0 < 2 && M1 > 1) { 2178 Swap = false; 2179 } else if (M0 > 1 && M1 < 2) { 2180 M0 = (M0 + 2) % 4; 2181 M1 = (M1 + 2) % 4; 2182 Swap = true; 2183 } else 2184 return false; 2185 2186 // Note: if control flow comes here that means Swap is already set above 2187 DM = (M0 << 1) + (M1 & 1); 2188 return true; 2189 } 2190 } 2191 2192 2193 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2194 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2195 /// elements are counted from the left of the vector register). 2196 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2197 SelectionDAG &DAG) { 2198 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2199 assert(isSplatShuffleMask(SVOp, EltSize)); 2200 if (DAG.getDataLayout().isLittleEndian()) 2201 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2202 else 2203 return SVOp->getMaskElt(0) / EltSize; 2204 } 2205 2206 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2207 /// by using a vspltis[bhw] instruction of the specified element size, return 2208 /// the constant being splatted. The ByteSize field indicates the number of 2209 /// bytes of each element [124] -> [bhw]. 2210 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2211 SDValue OpVal(nullptr, 0); 2212 2213 // If ByteSize of the splat is bigger than the element size of the 2214 // build_vector, then we have a case where we are checking for a splat where 2215 // multiple elements of the buildvector are folded together into a single 2216 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2217 unsigned EltSize = 16/N->getNumOperands(); 2218 if (EltSize < ByteSize) { 2219 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2220 SDValue UniquedVals[4]; 2221 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2222 2223 // See if all of the elements in the buildvector agree across. 2224 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2225 if (N->getOperand(i).isUndef()) continue; 2226 // If the element isn't a constant, bail fully out. 2227 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2228 2229 if (!UniquedVals[i&(Multiple-1)].getNode()) 2230 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2231 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2232 return SDValue(); // no match. 2233 } 2234 2235 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2236 // either constant or undef values that are identical for each chunk. See 2237 // if these chunks can form into a larger vspltis*. 2238 2239 // Check to see if all of the leading entries are either 0 or -1. If 2240 // neither, then this won't fit into the immediate field. 2241 bool LeadingZero = true; 2242 bool LeadingOnes = true; 2243 for (unsigned i = 0; i != Multiple-1; ++i) { 2244 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2245 2246 LeadingZero &= isNullConstant(UniquedVals[i]); 2247 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2248 } 2249 // Finally, check the least significant entry. 2250 if (LeadingZero) { 2251 if (!UniquedVals[Multiple-1].getNode()) 2252 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2253 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2254 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2255 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2256 } 2257 if (LeadingOnes) { 2258 if (!UniquedVals[Multiple-1].getNode()) 2259 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2260 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2261 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2262 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2263 } 2264 2265 return SDValue(); 2266 } 2267 2268 // Check to see if this buildvec has a single non-undef value in its elements. 2269 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2270 if (N->getOperand(i).isUndef()) continue; 2271 if (!OpVal.getNode()) 2272 OpVal = N->getOperand(i); 2273 else if (OpVal != N->getOperand(i)) 2274 return SDValue(); 2275 } 2276 2277 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2278 2279 unsigned ValSizeInBytes = EltSize; 2280 uint64_t Value = 0; 2281 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2282 Value = CN->getZExtValue(); 2283 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2284 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2285 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2286 } 2287 2288 // If the splat value is larger than the element value, then we can never do 2289 // this splat. The only case that we could fit the replicated bits into our 2290 // immediate field for would be zero, and we prefer to use vxor for it. 2291 if (ValSizeInBytes < ByteSize) return SDValue(); 2292 2293 // If the element value is larger than the splat value, check if it consists 2294 // of a repeated bit pattern of size ByteSize. 2295 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2296 return SDValue(); 2297 2298 // Properly sign extend the value. 2299 int MaskVal = SignExtend32(Value, ByteSize * 8); 2300 2301 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2302 if (MaskVal == 0) return SDValue(); 2303 2304 // Finally, if this value fits in a 5 bit sext field, return it 2305 if (SignExtend32<5>(MaskVal) == MaskVal) 2306 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2307 return SDValue(); 2308 } 2309 2310 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2311 /// amount, otherwise return -1. 2312 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2313 EVT VT = N->getValueType(0); 2314 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2315 return -1; 2316 2317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2318 2319 // Find the first non-undef value in the shuffle mask. 2320 unsigned i; 2321 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2322 /*search*/; 2323 2324 if (i == 4) return -1; // all undef. 2325 2326 // Otherwise, check to see if the rest of the elements are consecutively 2327 // numbered from this value. 2328 unsigned ShiftAmt = SVOp->getMaskElt(i); 2329 if (ShiftAmt < i) return -1; 2330 ShiftAmt -= i; 2331 2332 // Check the rest of the elements to see if they are consecutive. 2333 for (++i; i != 4; ++i) 2334 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2335 return -1; 2336 2337 return ShiftAmt; 2338 } 2339 2340 //===----------------------------------------------------------------------===// 2341 // Addressing Mode Selection 2342 //===----------------------------------------------------------------------===// 2343 2344 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2345 /// or 64-bit immediate, and if the value can be accurately represented as a 2346 /// sign extension from a 16-bit value. If so, this returns true and the 2347 /// immediate. 2348 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2349 if (!isa<ConstantSDNode>(N)) 2350 return false; 2351 2352 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2353 if (N->getValueType(0) == MVT::i32) 2354 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2355 else 2356 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2357 } 2358 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2359 return isIntS16Immediate(Op.getNode(), Imm); 2360 } 2361 2362 2363 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2364 /// be represented as an indexed [r+r] operation. 2365 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2366 SDValue &Index, 2367 SelectionDAG &DAG) const { 2368 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2369 UI != E; ++UI) { 2370 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2371 if (Memop->getMemoryVT() == MVT::f64) { 2372 Base = N.getOperand(0); 2373 Index = N.getOperand(1); 2374 return true; 2375 } 2376 } 2377 } 2378 return false; 2379 } 2380 2381 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2382 /// can be represented as an indexed [r+r] operation. Returns false if it 2383 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2384 /// non-zero and N can be represented by a base register plus a signed 16-bit 2385 /// displacement, make a more precise judgement by checking (displacement % \p 2386 /// EncodingAlignment). 2387 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2388 SDValue &Index, SelectionDAG &DAG, 2389 unsigned EncodingAlignment) const { 2390 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2391 // a [pc+imm]. 2392 if (SelectAddressPCRel(N, Base)) 2393 return false; 2394 2395 int16_t imm = 0; 2396 if (N.getOpcode() == ISD::ADD) { 2397 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2398 // SPE load/store can only handle 8-bit offsets. 2399 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2400 return true; 2401 if (isIntS16Immediate(N.getOperand(1), imm) && 2402 (!EncodingAlignment || !(imm % EncodingAlignment))) 2403 return false; // r+i 2404 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2405 return false; // r+i 2406 2407 Base = N.getOperand(0); 2408 Index = N.getOperand(1); 2409 return true; 2410 } else if (N.getOpcode() == ISD::OR) { 2411 if (isIntS16Immediate(N.getOperand(1), imm) && 2412 (!EncodingAlignment || !(imm % EncodingAlignment))) 2413 return false; // r+i can fold it if we can. 2414 2415 // If this is an or of disjoint bitfields, we can codegen this as an add 2416 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2417 // disjoint. 2418 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2419 2420 if (LHSKnown.Zero.getBoolValue()) { 2421 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2422 // If all of the bits are known zero on the LHS or RHS, the add won't 2423 // carry. 2424 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2425 Base = N.getOperand(0); 2426 Index = N.getOperand(1); 2427 return true; 2428 } 2429 } 2430 } 2431 2432 return false; 2433 } 2434 2435 // If we happen to be doing an i64 load or store into a stack slot that has 2436 // less than a 4-byte alignment, then the frame-index elimination may need to 2437 // use an indexed load or store instruction (because the offset may not be a 2438 // multiple of 4). The extra register needed to hold the offset comes from the 2439 // register scavenger, and it is possible that the scavenger will need to use 2440 // an emergency spill slot. As a result, we need to make sure that a spill slot 2441 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2442 // stack slot. 2443 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2444 // FIXME: This does not handle the LWA case. 2445 if (VT != MVT::i64) 2446 return; 2447 2448 // NOTE: We'll exclude negative FIs here, which come from argument 2449 // lowering, because there are no known test cases triggering this problem 2450 // using packed structures (or similar). We can remove this exclusion if 2451 // we find such a test case. The reason why this is so test-case driven is 2452 // because this entire 'fixup' is only to prevent crashes (from the 2453 // register scavenger) on not-really-valid inputs. For example, if we have: 2454 // %a = alloca i1 2455 // %b = bitcast i1* %a to i64* 2456 // store i64* a, i64 b 2457 // then the store should really be marked as 'align 1', but is not. If it 2458 // were marked as 'align 1' then the indexed form would have been 2459 // instruction-selected initially, and the problem this 'fixup' is preventing 2460 // won't happen regardless. 2461 if (FrameIdx < 0) 2462 return; 2463 2464 MachineFunction &MF = DAG.getMachineFunction(); 2465 MachineFrameInfo &MFI = MF.getFrameInfo(); 2466 2467 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2468 return; 2469 2470 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2471 FuncInfo->setHasNonRISpills(); 2472 } 2473 2474 /// Returns true if the address N can be represented by a base register plus 2475 /// a signed 16-bit displacement [r+imm], and if it is not better 2476 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2477 /// displacements that are multiples of that value. 2478 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2479 SDValue &Base, 2480 SelectionDAG &DAG, 2481 unsigned EncodingAlignment) const { 2482 // FIXME dl should come from parent load or store, not from address 2483 SDLoc dl(N); 2484 2485 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2486 // a [pc+imm]. 2487 if (SelectAddressPCRel(N, Base)) 2488 return false; 2489 2490 // If this can be more profitably realized as r+r, fail. 2491 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2492 return false; 2493 2494 if (N.getOpcode() == ISD::ADD) { 2495 int16_t imm = 0; 2496 if (isIntS16Immediate(N.getOperand(1), imm) && 2497 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2498 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2499 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2500 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2501 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2502 } else { 2503 Base = N.getOperand(0); 2504 } 2505 return true; // [r+i] 2506 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2507 // Match LOAD (ADD (X, Lo(G))). 2508 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2509 && "Cannot handle constant offsets yet!"); 2510 Disp = N.getOperand(1).getOperand(0); // The global address. 2511 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2512 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2513 Disp.getOpcode() == ISD::TargetConstantPool || 2514 Disp.getOpcode() == ISD::TargetJumpTable); 2515 Base = N.getOperand(0); 2516 return true; // [&g+r] 2517 } 2518 } else if (N.getOpcode() == ISD::OR) { 2519 int16_t imm = 0; 2520 if (isIntS16Immediate(N.getOperand(1), imm) && 2521 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2522 // If this is an or of disjoint bitfields, we can codegen this as an add 2523 // (for better address arithmetic) if the LHS and RHS of the OR are 2524 // provably disjoint. 2525 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2526 2527 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2528 // If all of the bits are known zero on the LHS or RHS, the add won't 2529 // carry. 2530 if (FrameIndexSDNode *FI = 2531 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2532 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2533 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2534 } else { 2535 Base = N.getOperand(0); 2536 } 2537 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2538 return true; 2539 } 2540 } 2541 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2542 // Loading from a constant address. 2543 2544 // If this address fits entirely in a 16-bit sext immediate field, codegen 2545 // this as "d, 0" 2546 int16_t Imm; 2547 if (isIntS16Immediate(CN, Imm) && 2548 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2549 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2550 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2551 CN->getValueType(0)); 2552 return true; 2553 } 2554 2555 // Handle 32-bit sext immediates with LIS + addr mode. 2556 if ((CN->getValueType(0) == MVT::i32 || 2557 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2558 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2559 int Addr = (int)CN->getZExtValue(); 2560 2561 // Otherwise, break this down into an LIS + disp. 2562 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2563 2564 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2565 MVT::i32); 2566 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2567 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2568 return true; 2569 } 2570 } 2571 2572 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2573 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2574 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2575 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2576 } else 2577 Base = N; 2578 return true; // [r+0] 2579 } 2580 2581 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2582 /// represented as an indexed [r+r] operation. 2583 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2584 SDValue &Index, 2585 SelectionDAG &DAG) const { 2586 // Check to see if we can easily represent this as an [r+r] address. This 2587 // will fail if it thinks that the address is more profitably represented as 2588 // reg+imm, e.g. where imm = 0. 2589 if (SelectAddressRegReg(N, Base, Index, DAG)) 2590 return true; 2591 2592 // If the address is the result of an add, we will utilize the fact that the 2593 // address calculation includes an implicit add. However, we can reduce 2594 // register pressure if we do not materialize a constant just for use as the 2595 // index register. We only get rid of the add if it is not an add of a 2596 // value and a 16-bit signed constant and both have a single use. 2597 int16_t imm = 0; 2598 if (N.getOpcode() == ISD::ADD && 2599 (!isIntS16Immediate(N.getOperand(1), imm) || 2600 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2601 Base = N.getOperand(0); 2602 Index = N.getOperand(1); 2603 return true; 2604 } 2605 2606 // Otherwise, do it the hard way, using R0 as the base register. 2607 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2608 N.getValueType()); 2609 Index = N; 2610 return true; 2611 } 2612 2613 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2614 Ty *PCRelCand = dyn_cast<Ty>(N); 2615 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2616 } 2617 2618 /// Returns true if this address is a PC Relative address. 2619 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2620 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2621 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2622 // This is a materialize PC Relative node. Always select this as PC Relative. 2623 Base = N; 2624 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2625 return true; 2626 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2627 isValidPCRelNode<GlobalAddressSDNode>(N) || 2628 isValidPCRelNode<JumpTableSDNode>(N) || 2629 isValidPCRelNode<BlockAddressSDNode>(N)) 2630 return true; 2631 return false; 2632 } 2633 2634 /// Returns true if we should use a direct load into vector instruction 2635 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2636 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2637 2638 // If there are any other uses other than scalar to vector, then we should 2639 // keep it as a scalar load -> direct move pattern to prevent multiple 2640 // loads. 2641 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2642 if (!LD) 2643 return false; 2644 2645 EVT MemVT = LD->getMemoryVT(); 2646 if (!MemVT.isSimple()) 2647 return false; 2648 switch(MemVT.getSimpleVT().SimpleTy) { 2649 case MVT::i64: 2650 break; 2651 case MVT::i32: 2652 if (!ST.hasP8Vector()) 2653 return false; 2654 break; 2655 case MVT::i16: 2656 case MVT::i8: 2657 if (!ST.hasP9Vector()) 2658 return false; 2659 break; 2660 default: 2661 return false; 2662 } 2663 2664 SDValue LoadedVal(N, 0); 2665 if (!LoadedVal.hasOneUse()) 2666 return false; 2667 2668 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2669 UI != UE; ++UI) 2670 if (UI.getUse().get().getResNo() == 0 && 2671 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2672 return false; 2673 2674 return true; 2675 } 2676 2677 /// getPreIndexedAddressParts - returns true by value, base pointer and 2678 /// offset pointer and addressing mode by reference if the node's address 2679 /// can be legally represented as pre-indexed load / store address. 2680 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2681 SDValue &Offset, 2682 ISD::MemIndexedMode &AM, 2683 SelectionDAG &DAG) const { 2684 if (DisablePPCPreinc) return false; 2685 2686 bool isLoad = true; 2687 SDValue Ptr; 2688 EVT VT; 2689 unsigned Alignment; 2690 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2691 Ptr = LD->getBasePtr(); 2692 VT = LD->getMemoryVT(); 2693 Alignment = LD->getAlignment(); 2694 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2695 Ptr = ST->getBasePtr(); 2696 VT = ST->getMemoryVT(); 2697 Alignment = ST->getAlignment(); 2698 isLoad = false; 2699 } else 2700 return false; 2701 2702 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2703 // instructions because we can fold these into a more efficient instruction 2704 // instead, (such as LXSD). 2705 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2706 return false; 2707 } 2708 2709 // PowerPC doesn't have preinc load/store instructions for vectors (except 2710 // for QPX, which does have preinc r+r forms). 2711 if (VT.isVector()) { 2712 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2713 return false; 2714 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2715 AM = ISD::PRE_INC; 2716 return true; 2717 } 2718 } 2719 2720 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2721 // Common code will reject creating a pre-inc form if the base pointer 2722 // is a frame index, or if N is a store and the base pointer is either 2723 // the same as or a predecessor of the value being stored. Check for 2724 // those situations here, and try with swapped Base/Offset instead. 2725 bool Swap = false; 2726 2727 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2728 Swap = true; 2729 else if (!isLoad) { 2730 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2731 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2732 Swap = true; 2733 } 2734 2735 if (Swap) 2736 std::swap(Base, Offset); 2737 2738 AM = ISD::PRE_INC; 2739 return true; 2740 } 2741 2742 // LDU/STU can only handle immediates that are a multiple of 4. 2743 if (VT != MVT::i64) { 2744 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2745 return false; 2746 } else { 2747 // LDU/STU need an address with at least 4-byte alignment. 2748 if (Alignment < 4) 2749 return false; 2750 2751 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2752 return false; 2753 } 2754 2755 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2756 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2757 // sext i32 to i64 when addr mode is r+i. 2758 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2759 LD->getExtensionType() == ISD::SEXTLOAD && 2760 isa<ConstantSDNode>(Offset)) 2761 return false; 2762 } 2763 2764 AM = ISD::PRE_INC; 2765 return true; 2766 } 2767 2768 //===----------------------------------------------------------------------===// 2769 // LowerOperation implementation 2770 //===----------------------------------------------------------------------===// 2771 2772 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2773 /// and LoOpFlags to the target MO flags. 2774 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2775 unsigned &HiOpFlags, unsigned &LoOpFlags, 2776 const GlobalValue *GV = nullptr) { 2777 HiOpFlags = PPCII::MO_HA; 2778 LoOpFlags = PPCII::MO_LO; 2779 2780 // Don't use the pic base if not in PIC relocation model. 2781 if (IsPIC) { 2782 HiOpFlags |= PPCII::MO_PIC_FLAG; 2783 LoOpFlags |= PPCII::MO_PIC_FLAG; 2784 } 2785 } 2786 2787 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2788 SelectionDAG &DAG) { 2789 SDLoc DL(HiPart); 2790 EVT PtrVT = HiPart.getValueType(); 2791 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2792 2793 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2794 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2795 2796 // With PIC, the first instruction is actually "GR+hi(&G)". 2797 if (isPIC) 2798 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2799 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2800 2801 // Generate non-pic code that has direct accesses to the constant pool. 2802 // The address of the global is just (hi(&g)+lo(&g)). 2803 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2804 } 2805 2806 static void setUsesTOCBasePtr(MachineFunction &MF) { 2807 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2808 FuncInfo->setUsesTOCBasePtr(); 2809 } 2810 2811 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2812 setUsesTOCBasePtr(DAG.getMachineFunction()); 2813 } 2814 2815 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2816 SDValue GA) const { 2817 const bool Is64Bit = Subtarget.isPPC64(); 2818 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2819 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2820 : Subtarget.isAIXABI() 2821 ? DAG.getRegister(PPC::R2, VT) 2822 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2823 SDValue Ops[] = { GA, Reg }; 2824 return DAG.getMemIntrinsicNode( 2825 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2826 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2827 MachineMemOperand::MOLoad); 2828 } 2829 2830 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2831 SelectionDAG &DAG) const { 2832 EVT PtrVT = Op.getValueType(); 2833 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2834 const Constant *C = CP->getConstVal(); 2835 2836 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2837 // The actual address of the GlobalValue is stored in the TOC. 2838 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2839 if (Subtarget.isUsingPCRelativeCalls()) { 2840 SDLoc DL(CP); 2841 EVT Ty = getPointerTy(DAG.getDataLayout()); 2842 SDValue ConstPool = DAG.getTargetConstantPool( 2843 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2844 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2845 } 2846 setUsesTOCBasePtr(DAG); 2847 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2848 return getTOCEntry(DAG, SDLoc(CP), GA); 2849 } 2850 2851 unsigned MOHiFlag, MOLoFlag; 2852 bool IsPIC = isPositionIndependent(); 2853 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2854 2855 if (IsPIC && Subtarget.isSVR4ABI()) { 2856 SDValue GA = 2857 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2858 return getTOCEntry(DAG, SDLoc(CP), GA); 2859 } 2860 2861 SDValue CPIHi = 2862 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2863 SDValue CPILo = 2864 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2865 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2866 } 2867 2868 // For 64-bit PowerPC, prefer the more compact relative encodings. 2869 // This trades 32 bits per jump table entry for one or two instructions 2870 // on the jump site. 2871 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2872 if (isJumpTableRelative()) 2873 return MachineJumpTableInfo::EK_LabelDifference32; 2874 2875 return TargetLowering::getJumpTableEncoding(); 2876 } 2877 2878 bool PPCTargetLowering::isJumpTableRelative() const { 2879 if (UseAbsoluteJumpTables) 2880 return false; 2881 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2882 return true; 2883 return TargetLowering::isJumpTableRelative(); 2884 } 2885 2886 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2887 SelectionDAG &DAG) const { 2888 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2889 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2890 2891 switch (getTargetMachine().getCodeModel()) { 2892 case CodeModel::Small: 2893 case CodeModel::Medium: 2894 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2895 default: 2896 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2897 getPointerTy(DAG.getDataLayout())); 2898 } 2899 } 2900 2901 const MCExpr * 2902 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2903 unsigned JTI, 2904 MCContext &Ctx) const { 2905 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2906 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2907 2908 switch (getTargetMachine().getCodeModel()) { 2909 case CodeModel::Small: 2910 case CodeModel::Medium: 2911 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2912 default: 2913 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2914 } 2915 } 2916 2917 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2918 EVT PtrVT = Op.getValueType(); 2919 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2920 2921 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2922 if (Subtarget.isUsingPCRelativeCalls()) { 2923 SDLoc DL(JT); 2924 EVT Ty = getPointerTy(DAG.getDataLayout()); 2925 SDValue GA = 2926 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2927 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2928 return MatAddr; 2929 } 2930 2931 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2932 // The actual address of the GlobalValue is stored in the TOC. 2933 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2934 setUsesTOCBasePtr(DAG); 2935 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2936 return getTOCEntry(DAG, SDLoc(JT), GA); 2937 } 2938 2939 unsigned MOHiFlag, MOLoFlag; 2940 bool IsPIC = isPositionIndependent(); 2941 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2942 2943 if (IsPIC && Subtarget.isSVR4ABI()) { 2944 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2945 PPCII::MO_PIC_FLAG); 2946 return getTOCEntry(DAG, SDLoc(GA), GA); 2947 } 2948 2949 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2950 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2951 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2952 } 2953 2954 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2955 SelectionDAG &DAG) const { 2956 EVT PtrVT = Op.getValueType(); 2957 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2958 const BlockAddress *BA = BASDN->getBlockAddress(); 2959 2960 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2961 if (Subtarget.isUsingPCRelativeCalls()) { 2962 SDLoc DL(BASDN); 2963 EVT Ty = getPointerTy(DAG.getDataLayout()); 2964 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2965 PPCII::MO_PCREL_FLAG); 2966 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2967 return MatAddr; 2968 } 2969 2970 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2971 // The actual BlockAddress is stored in the TOC. 2972 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2973 setUsesTOCBasePtr(DAG); 2974 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2975 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2976 } 2977 2978 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2979 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2980 return getTOCEntry( 2981 DAG, SDLoc(BASDN), 2982 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2983 2984 unsigned MOHiFlag, MOLoFlag; 2985 bool IsPIC = isPositionIndependent(); 2986 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2987 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2988 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2989 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2990 } 2991 2992 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2993 SelectionDAG &DAG) const { 2994 // FIXME: TLS addresses currently use medium model code sequences, 2995 // which is the most useful form. Eventually support for small and 2996 // large models could be added if users need it, at the cost of 2997 // additional complexity. 2998 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2999 if (DAG.getTarget().useEmulatedTLS()) 3000 return LowerToTLSEmulatedModel(GA, DAG); 3001 3002 SDLoc dl(GA); 3003 const GlobalValue *GV = GA->getGlobal(); 3004 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3005 bool is64bit = Subtarget.isPPC64(); 3006 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3007 PICLevel::Level picLevel = M->getPICLevel(); 3008 3009 const TargetMachine &TM = getTargetMachine(); 3010 TLSModel::Model Model = TM.getTLSModel(GV); 3011 3012 if (Model == TLSModel::LocalExec) { 3013 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3014 PPCII::MO_TPREL_HA); 3015 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3016 PPCII::MO_TPREL_LO); 3017 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3018 : DAG.getRegister(PPC::R2, MVT::i32); 3019 3020 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3021 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3022 } 3023 3024 if (Model == TLSModel::InitialExec) { 3025 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3026 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3027 PPCII::MO_TLS); 3028 SDValue GOTPtr; 3029 if (is64bit) { 3030 setUsesTOCBasePtr(DAG); 3031 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3032 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3033 PtrVT, GOTReg, TGA); 3034 } else { 3035 if (!TM.isPositionIndependent()) 3036 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3037 else if (picLevel == PICLevel::SmallPIC) 3038 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3039 else 3040 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3041 } 3042 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3043 PtrVT, TGA, GOTPtr); 3044 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3045 } 3046 3047 if (Model == TLSModel::GeneralDynamic) { 3048 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3049 SDValue GOTPtr; 3050 if (is64bit) { 3051 setUsesTOCBasePtr(DAG); 3052 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3053 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3054 GOTReg, TGA); 3055 } else { 3056 if (picLevel == PICLevel::SmallPIC) 3057 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3058 else 3059 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3060 } 3061 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3062 GOTPtr, TGA, TGA); 3063 } 3064 3065 if (Model == TLSModel::LocalDynamic) { 3066 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3067 SDValue GOTPtr; 3068 if (is64bit) { 3069 setUsesTOCBasePtr(DAG); 3070 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3071 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3072 GOTReg, TGA); 3073 } else { 3074 if (picLevel == PICLevel::SmallPIC) 3075 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3076 else 3077 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3078 } 3079 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3080 PtrVT, GOTPtr, TGA, TGA); 3081 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3082 PtrVT, TLSAddr, TGA); 3083 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3084 } 3085 3086 llvm_unreachable("Unknown TLS model!"); 3087 } 3088 3089 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3090 SelectionDAG &DAG) const { 3091 EVT PtrVT = Op.getValueType(); 3092 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3093 SDLoc DL(GSDN); 3094 const GlobalValue *GV = GSDN->getGlobal(); 3095 3096 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3097 // The actual address of the GlobalValue is stored in the TOC. 3098 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3099 if (Subtarget.isUsingPCRelativeCalls()) { 3100 EVT Ty = getPointerTy(DAG.getDataLayout()); 3101 if (isAccessedAsGotIndirect(Op)) { 3102 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3103 PPCII::MO_PCREL_FLAG | 3104 PPCII::MO_GOT_FLAG); 3105 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3106 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3107 MachinePointerInfo()); 3108 return Load; 3109 } else { 3110 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3111 PPCII::MO_PCREL_FLAG); 3112 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3113 } 3114 } 3115 setUsesTOCBasePtr(DAG); 3116 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3117 return getTOCEntry(DAG, DL, GA); 3118 } 3119 3120 unsigned MOHiFlag, MOLoFlag; 3121 bool IsPIC = isPositionIndependent(); 3122 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3123 3124 if (IsPIC && Subtarget.isSVR4ABI()) { 3125 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3126 GSDN->getOffset(), 3127 PPCII::MO_PIC_FLAG); 3128 return getTOCEntry(DAG, DL, GA); 3129 } 3130 3131 SDValue GAHi = 3132 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3133 SDValue GALo = 3134 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3135 3136 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3137 } 3138 3139 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3140 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3141 SDLoc dl(Op); 3142 3143 if (Op.getValueType() == MVT::v2i64) { 3144 // When the operands themselves are v2i64 values, we need to do something 3145 // special because VSX has no underlying comparison operations for these. 3146 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3147 // Equality can be handled by casting to the legal type for Altivec 3148 // comparisons, everything else needs to be expanded. 3149 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3150 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3151 DAG.getSetCC(dl, MVT::v4i32, 3152 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3153 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3154 CC)); 3155 } 3156 3157 return SDValue(); 3158 } 3159 3160 // We handle most of these in the usual way. 3161 return Op; 3162 } 3163 3164 // If we're comparing for equality to zero, expose the fact that this is 3165 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3166 // fold the new nodes. 3167 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3168 return V; 3169 3170 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3171 // Leave comparisons against 0 and -1 alone for now, since they're usually 3172 // optimized. FIXME: revisit this when we can custom lower all setcc 3173 // optimizations. 3174 if (C->isAllOnesValue() || C->isNullValue()) 3175 return SDValue(); 3176 } 3177 3178 // If we have an integer seteq/setne, turn it into a compare against zero 3179 // by xor'ing the rhs with the lhs, which is faster than setting a 3180 // condition register, reading it back out, and masking the correct bit. The 3181 // normal approach here uses sub to do this instead of xor. Using xor exposes 3182 // the result to other bit-twiddling opportunities. 3183 EVT LHSVT = Op.getOperand(0).getValueType(); 3184 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3185 EVT VT = Op.getValueType(); 3186 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3187 Op.getOperand(1)); 3188 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3189 } 3190 return SDValue(); 3191 } 3192 3193 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3194 SDNode *Node = Op.getNode(); 3195 EVT VT = Node->getValueType(0); 3196 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3197 SDValue InChain = Node->getOperand(0); 3198 SDValue VAListPtr = Node->getOperand(1); 3199 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3200 SDLoc dl(Node); 3201 3202 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3203 3204 // gpr_index 3205 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3206 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3207 InChain = GprIndex.getValue(1); 3208 3209 if (VT == MVT::i64) { 3210 // Check if GprIndex is even 3211 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3212 DAG.getConstant(1, dl, MVT::i32)); 3213 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3214 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3215 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3216 DAG.getConstant(1, dl, MVT::i32)); 3217 // Align GprIndex to be even if it isn't 3218 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3219 GprIndex); 3220 } 3221 3222 // fpr index is 1 byte after gpr 3223 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3224 DAG.getConstant(1, dl, MVT::i32)); 3225 3226 // fpr 3227 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3228 FprPtr, MachinePointerInfo(SV), MVT::i8); 3229 InChain = FprIndex.getValue(1); 3230 3231 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3232 DAG.getConstant(8, dl, MVT::i32)); 3233 3234 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3235 DAG.getConstant(4, dl, MVT::i32)); 3236 3237 // areas 3238 SDValue OverflowArea = 3239 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3240 InChain = OverflowArea.getValue(1); 3241 3242 SDValue RegSaveArea = 3243 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3244 InChain = RegSaveArea.getValue(1); 3245 3246 // select overflow_area if index > 8 3247 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3248 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3249 3250 // adjustment constant gpr_index * 4/8 3251 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3252 VT.isInteger() ? GprIndex : FprIndex, 3253 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3254 MVT::i32)); 3255 3256 // OurReg = RegSaveArea + RegConstant 3257 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3258 RegConstant); 3259 3260 // Floating types are 32 bytes into RegSaveArea 3261 if (VT.isFloatingPoint()) 3262 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3263 DAG.getConstant(32, dl, MVT::i32)); 3264 3265 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3266 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3267 VT.isInteger() ? GprIndex : FprIndex, 3268 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3269 MVT::i32)); 3270 3271 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3272 VT.isInteger() ? VAListPtr : FprPtr, 3273 MachinePointerInfo(SV), MVT::i8); 3274 3275 // determine if we should load from reg_save_area or overflow_area 3276 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3277 3278 // increase overflow_area by 4/8 if gpr/fpr > 8 3279 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3280 DAG.getConstant(VT.isInteger() ? 4 : 8, 3281 dl, MVT::i32)); 3282 3283 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3284 OverflowAreaPlusN); 3285 3286 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3287 MachinePointerInfo(), MVT::i32); 3288 3289 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3290 } 3291 3292 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3293 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3294 3295 // We have to copy the entire va_list struct: 3296 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3297 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3298 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3299 false, true, false, MachinePointerInfo(), 3300 MachinePointerInfo()); 3301 } 3302 3303 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3304 SelectionDAG &DAG) const { 3305 if (Subtarget.isAIXABI()) 3306 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3307 3308 return Op.getOperand(0); 3309 } 3310 3311 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3312 SelectionDAG &DAG) const { 3313 if (Subtarget.isAIXABI()) 3314 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3315 3316 SDValue Chain = Op.getOperand(0); 3317 SDValue Trmp = Op.getOperand(1); // trampoline 3318 SDValue FPtr = Op.getOperand(2); // nested function 3319 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3320 SDLoc dl(Op); 3321 3322 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3323 bool isPPC64 = (PtrVT == MVT::i64); 3324 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3325 3326 TargetLowering::ArgListTy Args; 3327 TargetLowering::ArgListEntry Entry; 3328 3329 Entry.Ty = IntPtrTy; 3330 Entry.Node = Trmp; Args.push_back(Entry); 3331 3332 // TrampSize == (isPPC64 ? 48 : 40); 3333 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3334 isPPC64 ? MVT::i64 : MVT::i32); 3335 Args.push_back(Entry); 3336 3337 Entry.Node = FPtr; Args.push_back(Entry); 3338 Entry.Node = Nest; Args.push_back(Entry); 3339 3340 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3341 TargetLowering::CallLoweringInfo CLI(DAG); 3342 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3343 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3344 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3345 3346 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3347 return CallResult.second; 3348 } 3349 3350 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3351 MachineFunction &MF = DAG.getMachineFunction(); 3352 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3353 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3354 3355 SDLoc dl(Op); 3356 3357 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3358 // vastart just stores the address of the VarArgsFrameIndex slot into the 3359 // memory location argument. 3360 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3361 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3362 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3363 MachinePointerInfo(SV)); 3364 } 3365 3366 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3367 // We suppose the given va_list is already allocated. 3368 // 3369 // typedef struct { 3370 // char gpr; /* index into the array of 8 GPRs 3371 // * stored in the register save area 3372 // * gpr=0 corresponds to r3, 3373 // * gpr=1 to r4, etc. 3374 // */ 3375 // char fpr; /* index into the array of 8 FPRs 3376 // * stored in the register save area 3377 // * fpr=0 corresponds to f1, 3378 // * fpr=1 to f2, etc. 3379 // */ 3380 // char *overflow_arg_area; 3381 // /* location on stack that holds 3382 // * the next overflow argument 3383 // */ 3384 // char *reg_save_area; 3385 // /* where r3:r10 and f1:f8 (if saved) 3386 // * are stored 3387 // */ 3388 // } va_list[1]; 3389 3390 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3391 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3392 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3393 PtrVT); 3394 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3395 PtrVT); 3396 3397 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3398 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3399 3400 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3401 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3402 3403 uint64_t FPROffset = 1; 3404 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3405 3406 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3407 3408 // Store first byte : number of int regs 3409 SDValue firstStore = 3410 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3411 MachinePointerInfo(SV), MVT::i8); 3412 uint64_t nextOffset = FPROffset; 3413 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3414 ConstFPROffset); 3415 3416 // Store second byte : number of float regs 3417 SDValue secondStore = 3418 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3419 MachinePointerInfo(SV, nextOffset), MVT::i8); 3420 nextOffset += StackOffset; 3421 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3422 3423 // Store second word : arguments given on stack 3424 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3425 MachinePointerInfo(SV, nextOffset)); 3426 nextOffset += FrameOffset; 3427 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3428 3429 // Store third word : arguments given in registers 3430 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3431 MachinePointerInfo(SV, nextOffset)); 3432 } 3433 3434 /// FPR - The set of FP registers that should be allocated for arguments 3435 /// on Darwin and AIX. 3436 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3437 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3438 PPC::F11, PPC::F12, PPC::F13}; 3439 3440 /// QFPR - The set of QPX registers that should be allocated for arguments. 3441 static const MCPhysReg QFPR[] = { 3442 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3443 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3444 3445 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3446 /// the stack. 3447 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3448 unsigned PtrByteSize) { 3449 unsigned ArgSize = ArgVT.getStoreSize(); 3450 if (Flags.isByVal()) 3451 ArgSize = Flags.getByValSize(); 3452 3453 // Round up to multiples of the pointer size, except for array members, 3454 // which are always packed. 3455 if (!Flags.isInConsecutiveRegs()) 3456 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3457 3458 return ArgSize; 3459 } 3460 3461 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3462 /// on the stack. 3463 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3464 ISD::ArgFlagsTy Flags, 3465 unsigned PtrByteSize) { 3466 Align Alignment(PtrByteSize); 3467 3468 // Altivec parameters are padded to a 16 byte boundary. 3469 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3470 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3471 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3472 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3473 Alignment = Align(16); 3474 // QPX vector types stored in double-precision are padded to a 32 byte 3475 // boundary. 3476 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3477 Alignment = Align(32); 3478 3479 // ByVal parameters are aligned as requested. 3480 if (Flags.isByVal()) { 3481 auto BVAlign = Flags.getNonZeroByValAlign(); 3482 if (BVAlign > PtrByteSize) { 3483 if (BVAlign.value() % PtrByteSize != 0) 3484 llvm_unreachable( 3485 "ByVal alignment is not a multiple of the pointer size"); 3486 3487 Alignment = BVAlign; 3488 } 3489 } 3490 3491 // Array members are always packed to their original alignment. 3492 if (Flags.isInConsecutiveRegs()) { 3493 // If the array member was split into multiple registers, the first 3494 // needs to be aligned to the size of the full type. (Except for 3495 // ppcf128, which is only aligned as its f64 components.) 3496 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3497 Alignment = Align(OrigVT.getStoreSize()); 3498 else 3499 Alignment = Align(ArgVT.getStoreSize()); 3500 } 3501 3502 return Alignment; 3503 } 3504 3505 /// CalculateStackSlotUsed - Return whether this argument will use its 3506 /// stack slot (instead of being passed in registers). ArgOffset, 3507 /// AvailableFPRs, and AvailableVRs must hold the current argument 3508 /// position, and will be updated to account for this argument. 3509 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3510 ISD::ArgFlagsTy Flags, 3511 unsigned PtrByteSize, 3512 unsigned LinkageSize, 3513 unsigned ParamAreaSize, 3514 unsigned &ArgOffset, 3515 unsigned &AvailableFPRs, 3516 unsigned &AvailableVRs, bool HasQPX) { 3517 bool UseMemory = false; 3518 3519 // Respect alignment of argument on the stack. 3520 Align Alignment = 3521 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3522 ArgOffset = alignTo(ArgOffset, Alignment); 3523 // If there's no space left in the argument save area, we must 3524 // use memory (this check also catches zero-sized arguments). 3525 if (ArgOffset >= LinkageSize + ParamAreaSize) 3526 UseMemory = true; 3527 3528 // Allocate argument on the stack. 3529 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3530 if (Flags.isInConsecutiveRegsLast()) 3531 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3532 // If we overran the argument save area, we must use memory 3533 // (this check catches arguments passed partially in memory) 3534 if (ArgOffset > LinkageSize + ParamAreaSize) 3535 UseMemory = true; 3536 3537 // However, if the argument is actually passed in an FPR or a VR, 3538 // we don't use memory after all. 3539 if (!Flags.isByVal()) { 3540 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3541 // QPX registers overlap with the scalar FP registers. 3542 (HasQPX && (ArgVT == MVT::v4f32 || 3543 ArgVT == MVT::v4f64 || 3544 ArgVT == MVT::v4i1))) 3545 if (AvailableFPRs > 0) { 3546 --AvailableFPRs; 3547 return false; 3548 } 3549 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3550 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3551 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3552 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3553 if (AvailableVRs > 0) { 3554 --AvailableVRs; 3555 return false; 3556 } 3557 } 3558 3559 return UseMemory; 3560 } 3561 3562 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3563 /// ensure minimum alignment required for target. 3564 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3565 unsigned NumBytes) { 3566 return alignTo(NumBytes, Lowering->getStackAlign()); 3567 } 3568 3569 SDValue PPCTargetLowering::LowerFormalArguments( 3570 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3571 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3572 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3573 if (Subtarget.isAIXABI()) 3574 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3575 InVals); 3576 if (Subtarget.is64BitELFABI()) 3577 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3578 InVals); 3579 if (Subtarget.is32BitELFABI()) 3580 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3581 InVals); 3582 3583 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3584 InVals); 3585 } 3586 3587 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3588 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3589 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3590 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3591 3592 // 32-bit SVR4 ABI Stack Frame Layout: 3593 // +-----------------------------------+ 3594 // +--> | Back chain | 3595 // | +-----------------------------------+ 3596 // | | Floating-point register save area | 3597 // | +-----------------------------------+ 3598 // | | General register save area | 3599 // | +-----------------------------------+ 3600 // | | CR save word | 3601 // | +-----------------------------------+ 3602 // | | VRSAVE save word | 3603 // | +-----------------------------------+ 3604 // | | Alignment padding | 3605 // | +-----------------------------------+ 3606 // | | Vector register save area | 3607 // | +-----------------------------------+ 3608 // | | Local variable space | 3609 // | +-----------------------------------+ 3610 // | | Parameter list area | 3611 // | +-----------------------------------+ 3612 // | | LR save word | 3613 // | +-----------------------------------+ 3614 // SP--> +--- | Back chain | 3615 // +-----------------------------------+ 3616 // 3617 // Specifications: 3618 // System V Application Binary Interface PowerPC Processor Supplement 3619 // AltiVec Technology Programming Interface Manual 3620 3621 MachineFunction &MF = DAG.getMachineFunction(); 3622 MachineFrameInfo &MFI = MF.getFrameInfo(); 3623 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3624 3625 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3626 // Potential tail calls could cause overwriting of argument stack slots. 3627 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3628 (CallConv == CallingConv::Fast)); 3629 unsigned PtrByteSize = 4; 3630 3631 // Assign locations to all of the incoming arguments. 3632 SmallVector<CCValAssign, 16> ArgLocs; 3633 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3634 *DAG.getContext()); 3635 3636 // Reserve space for the linkage area on the stack. 3637 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3638 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3639 if (useSoftFloat()) 3640 CCInfo.PreAnalyzeFormalArguments(Ins); 3641 3642 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3643 CCInfo.clearWasPPCF128(); 3644 3645 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3646 CCValAssign &VA = ArgLocs[i]; 3647 3648 // Arguments stored in registers. 3649 if (VA.isRegLoc()) { 3650 const TargetRegisterClass *RC; 3651 EVT ValVT = VA.getValVT(); 3652 3653 switch (ValVT.getSimpleVT().SimpleTy) { 3654 default: 3655 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3656 case MVT::i1: 3657 case MVT::i32: 3658 RC = &PPC::GPRCRegClass; 3659 break; 3660 case MVT::f32: 3661 if (Subtarget.hasP8Vector()) 3662 RC = &PPC::VSSRCRegClass; 3663 else if (Subtarget.hasSPE()) 3664 RC = &PPC::GPRCRegClass; 3665 else 3666 RC = &PPC::F4RCRegClass; 3667 break; 3668 case MVT::f64: 3669 if (Subtarget.hasVSX()) 3670 RC = &PPC::VSFRCRegClass; 3671 else if (Subtarget.hasSPE()) 3672 // SPE passes doubles in GPR pairs. 3673 RC = &PPC::GPRCRegClass; 3674 else 3675 RC = &PPC::F8RCRegClass; 3676 break; 3677 case MVT::v16i8: 3678 case MVT::v8i16: 3679 case MVT::v4i32: 3680 RC = &PPC::VRRCRegClass; 3681 break; 3682 case MVT::v4f32: 3683 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3684 break; 3685 case MVT::v2f64: 3686 case MVT::v2i64: 3687 RC = &PPC::VRRCRegClass; 3688 break; 3689 case MVT::v4f64: 3690 RC = &PPC::QFRCRegClass; 3691 break; 3692 case MVT::v4i1: 3693 RC = &PPC::QBRCRegClass; 3694 break; 3695 } 3696 3697 SDValue ArgValue; 3698 // Transform the arguments stored in physical registers into 3699 // virtual ones. 3700 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3701 assert(i + 1 < e && "No second half of double precision argument"); 3702 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3703 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3704 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3705 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3706 if (!Subtarget.isLittleEndian()) 3707 std::swap (ArgValueLo, ArgValueHi); 3708 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3709 ArgValueHi); 3710 } else { 3711 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3712 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3713 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3714 if (ValVT == MVT::i1) 3715 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3716 } 3717 3718 InVals.push_back(ArgValue); 3719 } else { 3720 // Argument stored in memory. 3721 assert(VA.isMemLoc()); 3722 3723 // Get the extended size of the argument type in stack 3724 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3725 // Get the actual size of the argument type 3726 unsigned ObjSize = VA.getValVT().getStoreSize(); 3727 unsigned ArgOffset = VA.getLocMemOffset(); 3728 // Stack objects in PPC32 are right justified. 3729 ArgOffset += ArgSize - ObjSize; 3730 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3731 3732 // Create load nodes to retrieve arguments from the stack. 3733 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3734 InVals.push_back( 3735 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3736 } 3737 } 3738 3739 // Assign locations to all of the incoming aggregate by value arguments. 3740 // Aggregates passed by value are stored in the local variable space of the 3741 // caller's stack frame, right above the parameter list area. 3742 SmallVector<CCValAssign, 16> ByValArgLocs; 3743 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3744 ByValArgLocs, *DAG.getContext()); 3745 3746 // Reserve stack space for the allocations in CCInfo. 3747 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3748 3749 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3750 3751 // Area that is at least reserved in the caller of this function. 3752 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3753 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3754 3755 // Set the size that is at least reserved in caller of this function. Tail 3756 // call optimized function's reserved stack space needs to be aligned so that 3757 // taking the difference between two stack areas will result in an aligned 3758 // stack. 3759 MinReservedArea = 3760 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3761 FuncInfo->setMinReservedArea(MinReservedArea); 3762 3763 SmallVector<SDValue, 8> MemOps; 3764 3765 // If the function takes variable number of arguments, make a frame index for 3766 // the start of the first vararg value... for expansion of llvm.va_start. 3767 if (isVarArg) { 3768 static const MCPhysReg GPArgRegs[] = { 3769 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3770 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3771 }; 3772 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3773 3774 static const MCPhysReg FPArgRegs[] = { 3775 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3776 PPC::F8 3777 }; 3778 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3779 3780 if (useSoftFloat() || hasSPE()) 3781 NumFPArgRegs = 0; 3782 3783 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3784 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3785 3786 // Make room for NumGPArgRegs and NumFPArgRegs. 3787 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3788 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3789 3790 FuncInfo->setVarArgsStackOffset( 3791 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3792 CCInfo.getNextStackOffset(), true)); 3793 3794 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3795 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3796 3797 // The fixed integer arguments of a variadic function are stored to the 3798 // VarArgsFrameIndex on the stack so that they may be loaded by 3799 // dereferencing the result of va_next. 3800 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3801 // Get an existing live-in vreg, or add a new one. 3802 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3803 if (!VReg) 3804 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3805 3806 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3807 SDValue Store = 3808 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3809 MemOps.push_back(Store); 3810 // Increment the address by four for the next argument to store 3811 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3812 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3813 } 3814 3815 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3816 // is set. 3817 // The double arguments are stored to the VarArgsFrameIndex 3818 // on the stack. 3819 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3820 // Get an existing live-in vreg, or add a new one. 3821 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3822 if (!VReg) 3823 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3824 3825 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3826 SDValue Store = 3827 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3828 MemOps.push_back(Store); 3829 // Increment the address by eight for the next argument to store 3830 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3831 PtrVT); 3832 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3833 } 3834 } 3835 3836 if (!MemOps.empty()) 3837 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3838 3839 return Chain; 3840 } 3841 3842 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3843 // value to MVT::i64 and then truncate to the correct register size. 3844 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3845 EVT ObjectVT, SelectionDAG &DAG, 3846 SDValue ArgVal, 3847 const SDLoc &dl) const { 3848 if (Flags.isSExt()) 3849 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3850 DAG.getValueType(ObjectVT)); 3851 else if (Flags.isZExt()) 3852 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3853 DAG.getValueType(ObjectVT)); 3854 3855 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3856 } 3857 3858 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3859 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3860 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3861 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3862 // TODO: add description of PPC stack frame format, or at least some docs. 3863 // 3864 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3865 bool isLittleEndian = Subtarget.isLittleEndian(); 3866 MachineFunction &MF = DAG.getMachineFunction(); 3867 MachineFrameInfo &MFI = MF.getFrameInfo(); 3868 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3869 3870 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3871 "fastcc not supported on varargs functions"); 3872 3873 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3874 // Potential tail calls could cause overwriting of argument stack slots. 3875 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3876 (CallConv == CallingConv::Fast)); 3877 unsigned PtrByteSize = 8; 3878 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3879 3880 static const MCPhysReg GPR[] = { 3881 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3882 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3883 }; 3884 static const MCPhysReg VR[] = { 3885 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3886 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3887 }; 3888 3889 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3890 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3891 const unsigned Num_VR_Regs = array_lengthof(VR); 3892 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3893 3894 // Do a first pass over the arguments to determine whether the ABI 3895 // guarantees that our caller has allocated the parameter save area 3896 // on its stack frame. In the ELFv1 ABI, this is always the case; 3897 // in the ELFv2 ABI, it is true if this is a vararg function or if 3898 // any parameter is located in a stack slot. 3899 3900 bool HasParameterArea = !isELFv2ABI || isVarArg; 3901 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3902 unsigned NumBytes = LinkageSize; 3903 unsigned AvailableFPRs = Num_FPR_Regs; 3904 unsigned AvailableVRs = Num_VR_Regs; 3905 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3906 if (Ins[i].Flags.isNest()) 3907 continue; 3908 3909 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3910 PtrByteSize, LinkageSize, ParamAreaSize, 3911 NumBytes, AvailableFPRs, AvailableVRs, 3912 Subtarget.hasQPX())) 3913 HasParameterArea = true; 3914 } 3915 3916 // Add DAG nodes to load the arguments or copy them out of registers. On 3917 // entry to a function on PPC, the arguments start after the linkage area, 3918 // although the first ones are often in registers. 3919 3920 unsigned ArgOffset = LinkageSize; 3921 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3922 unsigned &QFPR_idx = FPR_idx; 3923 SmallVector<SDValue, 8> MemOps; 3924 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3925 unsigned CurArgIdx = 0; 3926 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3927 SDValue ArgVal; 3928 bool needsLoad = false; 3929 EVT ObjectVT = Ins[ArgNo].VT; 3930 EVT OrigVT = Ins[ArgNo].ArgVT; 3931 unsigned ObjSize = ObjectVT.getStoreSize(); 3932 unsigned ArgSize = ObjSize; 3933 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3934 if (Ins[ArgNo].isOrigArg()) { 3935 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3936 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3937 } 3938 // We re-align the argument offset for each argument, except when using the 3939 // fast calling convention, when we need to make sure we do that only when 3940 // we'll actually use a stack slot. 3941 unsigned CurArgOffset; 3942 Align Alignment; 3943 auto ComputeArgOffset = [&]() { 3944 /* Respect alignment of argument on the stack. */ 3945 Alignment = 3946 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3947 ArgOffset = alignTo(ArgOffset, Alignment); 3948 CurArgOffset = ArgOffset; 3949 }; 3950 3951 if (CallConv != CallingConv::Fast) { 3952 ComputeArgOffset(); 3953 3954 /* Compute GPR index associated with argument offset. */ 3955 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3956 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3957 } 3958 3959 // FIXME the codegen can be much improved in some cases. 3960 // We do not have to keep everything in memory. 3961 if (Flags.isByVal()) { 3962 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3963 3964 if (CallConv == CallingConv::Fast) 3965 ComputeArgOffset(); 3966 3967 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3968 ObjSize = Flags.getByValSize(); 3969 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3970 // Empty aggregate parameters do not take up registers. Examples: 3971 // struct { } a; 3972 // union { } b; 3973 // int c[0]; 3974 // etc. However, we have to provide a place-holder in InVals, so 3975 // pretend we have an 8-byte item at the current address for that 3976 // purpose. 3977 if (!ObjSize) { 3978 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3979 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3980 InVals.push_back(FIN); 3981 continue; 3982 } 3983 3984 // Create a stack object covering all stack doublewords occupied 3985 // by the argument. If the argument is (fully or partially) on 3986 // the stack, or if the argument is fully in registers but the 3987 // caller has allocated the parameter save anyway, we can refer 3988 // directly to the caller's stack frame. Otherwise, create a 3989 // local copy in our own frame. 3990 int FI; 3991 if (HasParameterArea || 3992 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3993 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3994 else 3995 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3996 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3997 3998 // Handle aggregates smaller than 8 bytes. 3999 if (ObjSize < PtrByteSize) { 4000 // The value of the object is its address, which differs from the 4001 // address of the enclosing doubleword on big-endian systems. 4002 SDValue Arg = FIN; 4003 if (!isLittleEndian) { 4004 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4005 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4006 } 4007 InVals.push_back(Arg); 4008 4009 if (GPR_idx != Num_GPR_Regs) { 4010 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4011 FuncInfo->addLiveInAttr(VReg, Flags); 4012 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4013 SDValue Store; 4014 4015 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4016 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4017 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4018 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4019 MachinePointerInfo(&*FuncArg), ObjType); 4020 } else { 4021 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4022 // store the whole register as-is to the parameter save area 4023 // slot. 4024 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4025 MachinePointerInfo(&*FuncArg)); 4026 } 4027 4028 MemOps.push_back(Store); 4029 } 4030 // Whether we copied from a register or not, advance the offset 4031 // into the parameter save area by a full doubleword. 4032 ArgOffset += PtrByteSize; 4033 continue; 4034 } 4035 4036 // The value of the object is its address, which is the address of 4037 // its first stack doubleword. 4038 InVals.push_back(FIN); 4039 4040 // Store whatever pieces of the object are in registers to memory. 4041 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4042 if (GPR_idx == Num_GPR_Regs) 4043 break; 4044 4045 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4046 FuncInfo->addLiveInAttr(VReg, Flags); 4047 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4048 SDValue Addr = FIN; 4049 if (j) { 4050 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4051 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4052 } 4053 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4054 MachinePointerInfo(&*FuncArg, j)); 4055 MemOps.push_back(Store); 4056 ++GPR_idx; 4057 } 4058 ArgOffset += ArgSize; 4059 continue; 4060 } 4061 4062 switch (ObjectVT.getSimpleVT().SimpleTy) { 4063 default: llvm_unreachable("Unhandled argument type!"); 4064 case MVT::i1: 4065 case MVT::i32: 4066 case MVT::i64: 4067 if (Flags.isNest()) { 4068 // The 'nest' parameter, if any, is passed in R11. 4069 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4070 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4071 4072 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4073 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4074 4075 break; 4076 } 4077 4078 // These can be scalar arguments or elements of an integer array type 4079 // passed directly. Clang may use those instead of "byval" aggregate 4080 // types to avoid forcing arguments to memory unnecessarily. 4081 if (GPR_idx != Num_GPR_Regs) { 4082 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4083 FuncInfo->addLiveInAttr(VReg, Flags); 4084 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4085 4086 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4087 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4088 // value to MVT::i64 and then truncate to the correct register size. 4089 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4090 } else { 4091 if (CallConv == CallingConv::Fast) 4092 ComputeArgOffset(); 4093 4094 needsLoad = true; 4095 ArgSize = PtrByteSize; 4096 } 4097 if (CallConv != CallingConv::Fast || needsLoad) 4098 ArgOffset += 8; 4099 break; 4100 4101 case MVT::f32: 4102 case MVT::f64: 4103 // These can be scalar arguments or elements of a float array type 4104 // passed directly. The latter are used to implement ELFv2 homogenous 4105 // float aggregates. 4106 if (FPR_idx != Num_FPR_Regs) { 4107 unsigned VReg; 4108 4109 if (ObjectVT == MVT::f32) 4110 VReg = MF.addLiveIn(FPR[FPR_idx], 4111 Subtarget.hasP8Vector() 4112 ? &PPC::VSSRCRegClass 4113 : &PPC::F4RCRegClass); 4114 else 4115 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4116 ? &PPC::VSFRCRegClass 4117 : &PPC::F8RCRegClass); 4118 4119 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4120 ++FPR_idx; 4121 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4122 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4123 // once we support fp <-> gpr moves. 4124 4125 // This can only ever happen in the presence of f32 array types, 4126 // since otherwise we never run out of FPRs before running out 4127 // of GPRs. 4128 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4129 FuncInfo->addLiveInAttr(VReg, Flags); 4130 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4131 4132 if (ObjectVT == MVT::f32) { 4133 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4134 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4135 DAG.getConstant(32, dl, MVT::i32)); 4136 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4137 } 4138 4139 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4140 } else { 4141 if (CallConv == CallingConv::Fast) 4142 ComputeArgOffset(); 4143 4144 needsLoad = true; 4145 } 4146 4147 // When passing an array of floats, the array occupies consecutive 4148 // space in the argument area; only round up to the next doubleword 4149 // at the end of the array. Otherwise, each float takes 8 bytes. 4150 if (CallConv != CallingConv::Fast || needsLoad) { 4151 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4152 ArgOffset += ArgSize; 4153 if (Flags.isInConsecutiveRegsLast()) 4154 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4155 } 4156 break; 4157 case MVT::v4f32: 4158 case MVT::v4i32: 4159 case MVT::v8i16: 4160 case MVT::v16i8: 4161 case MVT::v2f64: 4162 case MVT::v2i64: 4163 case MVT::v1i128: 4164 case MVT::f128: 4165 if (!Subtarget.hasQPX()) { 4166 // These can be scalar arguments or elements of a vector array type 4167 // passed directly. The latter are used to implement ELFv2 homogenous 4168 // vector aggregates. 4169 if (VR_idx != Num_VR_Regs) { 4170 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4171 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4172 ++VR_idx; 4173 } else { 4174 if (CallConv == CallingConv::Fast) 4175 ComputeArgOffset(); 4176 needsLoad = true; 4177 } 4178 if (CallConv != CallingConv::Fast || needsLoad) 4179 ArgOffset += 16; 4180 break; 4181 } // not QPX 4182 4183 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4184 "Invalid QPX parameter type"); 4185 LLVM_FALLTHROUGH; 4186 4187 case MVT::v4f64: 4188 case MVT::v4i1: 4189 // QPX vectors are treated like their scalar floating-point subregisters 4190 // (except that they're larger). 4191 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4192 if (QFPR_idx != Num_QFPR_Regs) { 4193 const TargetRegisterClass *RC; 4194 switch (ObjectVT.getSimpleVT().SimpleTy) { 4195 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4196 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4197 default: RC = &PPC::QBRCRegClass; break; 4198 } 4199 4200 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4201 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4202 ++QFPR_idx; 4203 } else { 4204 if (CallConv == CallingConv::Fast) 4205 ComputeArgOffset(); 4206 needsLoad = true; 4207 } 4208 if (CallConv != CallingConv::Fast || needsLoad) 4209 ArgOffset += Sz; 4210 break; 4211 } 4212 4213 // We need to load the argument to a virtual register if we determined 4214 // above that we ran out of physical registers of the appropriate type. 4215 if (needsLoad) { 4216 if (ObjSize < ArgSize && !isLittleEndian) 4217 CurArgOffset += ArgSize - ObjSize; 4218 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4219 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4220 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4221 } 4222 4223 InVals.push_back(ArgVal); 4224 } 4225 4226 // Area that is at least reserved in the caller of this function. 4227 unsigned MinReservedArea; 4228 if (HasParameterArea) 4229 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4230 else 4231 MinReservedArea = LinkageSize; 4232 4233 // Set the size that is at least reserved in caller of this function. Tail 4234 // call optimized functions' reserved stack space needs to be aligned so that 4235 // taking the difference between two stack areas will result in an aligned 4236 // stack. 4237 MinReservedArea = 4238 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4239 FuncInfo->setMinReservedArea(MinReservedArea); 4240 4241 // If the function takes variable number of arguments, make a frame index for 4242 // the start of the first vararg value... for expansion of llvm.va_start. 4243 if (isVarArg) { 4244 int Depth = ArgOffset; 4245 4246 FuncInfo->setVarArgsFrameIndex( 4247 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4248 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4249 4250 // If this function is vararg, store any remaining integer argument regs 4251 // to their spots on the stack so that they may be loaded by dereferencing 4252 // the result of va_next. 4253 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4254 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4255 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4256 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4257 SDValue Store = 4258 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4259 MemOps.push_back(Store); 4260 // Increment the address by four for the next argument to store 4261 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4262 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4263 } 4264 } 4265 4266 if (!MemOps.empty()) 4267 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4268 4269 return Chain; 4270 } 4271 4272 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4273 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4274 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4275 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4276 // TODO: add description of PPC stack frame format, or at least some docs. 4277 // 4278 MachineFunction &MF = DAG.getMachineFunction(); 4279 MachineFrameInfo &MFI = MF.getFrameInfo(); 4280 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4281 4282 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4283 bool isPPC64 = PtrVT == MVT::i64; 4284 // Potential tail calls could cause overwriting of argument stack slots. 4285 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4286 (CallConv == CallingConv::Fast)); 4287 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4288 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4289 unsigned ArgOffset = LinkageSize; 4290 // Area that is at least reserved in caller of this function. 4291 unsigned MinReservedArea = ArgOffset; 4292 4293 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4294 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4295 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4296 }; 4297 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4298 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4299 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4300 }; 4301 static const MCPhysReg VR[] = { 4302 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4303 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4304 }; 4305 4306 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4307 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4308 const unsigned Num_VR_Regs = array_lengthof( VR); 4309 4310 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4311 4312 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4313 4314 // In 32-bit non-varargs functions, the stack space for vectors is after the 4315 // stack space for non-vectors. We do not use this space unless we have 4316 // too many vectors to fit in registers, something that only occurs in 4317 // constructed examples:), but we have to walk the arglist to figure 4318 // that out...for the pathological case, compute VecArgOffset as the 4319 // start of the vector parameter area. Computing VecArgOffset is the 4320 // entire point of the following loop. 4321 unsigned VecArgOffset = ArgOffset; 4322 if (!isVarArg && !isPPC64) { 4323 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4324 ++ArgNo) { 4325 EVT ObjectVT = Ins[ArgNo].VT; 4326 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4327 4328 if (Flags.isByVal()) { 4329 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4330 unsigned ObjSize = Flags.getByValSize(); 4331 unsigned ArgSize = 4332 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4333 VecArgOffset += ArgSize; 4334 continue; 4335 } 4336 4337 switch(ObjectVT.getSimpleVT().SimpleTy) { 4338 default: llvm_unreachable("Unhandled argument type!"); 4339 case MVT::i1: 4340 case MVT::i32: 4341 case MVT::f32: 4342 VecArgOffset += 4; 4343 break; 4344 case MVT::i64: // PPC64 4345 case MVT::f64: 4346 // FIXME: We are guaranteed to be !isPPC64 at this point. 4347 // Does MVT::i64 apply? 4348 VecArgOffset += 8; 4349 break; 4350 case MVT::v4f32: 4351 case MVT::v4i32: 4352 case MVT::v8i16: 4353 case MVT::v16i8: 4354 // Nothing to do, we're only looking at Nonvector args here. 4355 break; 4356 } 4357 } 4358 } 4359 // We've found where the vector parameter area in memory is. Skip the 4360 // first 12 parameters; these don't use that memory. 4361 VecArgOffset = ((VecArgOffset+15)/16)*16; 4362 VecArgOffset += 12*16; 4363 4364 // Add DAG nodes to load the arguments or copy them out of registers. On 4365 // entry to a function on PPC, the arguments start after the linkage area, 4366 // although the first ones are often in registers. 4367 4368 SmallVector<SDValue, 8> MemOps; 4369 unsigned nAltivecParamsAtEnd = 0; 4370 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4371 unsigned CurArgIdx = 0; 4372 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4373 SDValue ArgVal; 4374 bool needsLoad = false; 4375 EVT ObjectVT = Ins[ArgNo].VT; 4376 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4377 unsigned ArgSize = ObjSize; 4378 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4379 if (Ins[ArgNo].isOrigArg()) { 4380 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4381 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4382 } 4383 unsigned CurArgOffset = ArgOffset; 4384 4385 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4386 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4387 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4388 if (isVarArg || isPPC64) { 4389 MinReservedArea = ((MinReservedArea+15)/16)*16; 4390 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4391 Flags, 4392 PtrByteSize); 4393 } else nAltivecParamsAtEnd++; 4394 } else 4395 // Calculate min reserved area. 4396 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4397 Flags, 4398 PtrByteSize); 4399 4400 // FIXME the codegen can be much improved in some cases. 4401 // We do not have to keep everything in memory. 4402 if (Flags.isByVal()) { 4403 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4404 4405 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4406 ObjSize = Flags.getByValSize(); 4407 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4408 // Objects of size 1 and 2 are right justified, everything else is 4409 // left justified. This means the memory address is adjusted forwards. 4410 if (ObjSize==1 || ObjSize==2) { 4411 CurArgOffset = CurArgOffset + (4 - ObjSize); 4412 } 4413 // The value of the object is its address. 4414 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4415 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4416 InVals.push_back(FIN); 4417 if (ObjSize==1 || ObjSize==2) { 4418 if (GPR_idx != Num_GPR_Regs) { 4419 unsigned VReg; 4420 if (isPPC64) 4421 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4422 else 4423 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4424 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4425 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4426 SDValue Store = 4427 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4428 MachinePointerInfo(&*FuncArg), ObjType); 4429 MemOps.push_back(Store); 4430 ++GPR_idx; 4431 } 4432 4433 ArgOffset += PtrByteSize; 4434 4435 continue; 4436 } 4437 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4438 // Store whatever pieces of the object are in registers 4439 // to memory. ArgOffset will be the address of the beginning 4440 // of the object. 4441 if (GPR_idx != Num_GPR_Regs) { 4442 unsigned VReg; 4443 if (isPPC64) 4444 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4445 else 4446 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4447 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4448 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4449 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4450 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4451 MachinePointerInfo(&*FuncArg, j)); 4452 MemOps.push_back(Store); 4453 ++GPR_idx; 4454 ArgOffset += PtrByteSize; 4455 } else { 4456 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4457 break; 4458 } 4459 } 4460 continue; 4461 } 4462 4463 switch (ObjectVT.getSimpleVT().SimpleTy) { 4464 default: llvm_unreachable("Unhandled argument type!"); 4465 case MVT::i1: 4466 case MVT::i32: 4467 if (!isPPC64) { 4468 if (GPR_idx != Num_GPR_Regs) { 4469 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4470 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4471 4472 if (ObjectVT == MVT::i1) 4473 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4474 4475 ++GPR_idx; 4476 } else { 4477 needsLoad = true; 4478 ArgSize = PtrByteSize; 4479 } 4480 // All int arguments reserve stack space in the Darwin ABI. 4481 ArgOffset += PtrByteSize; 4482 break; 4483 } 4484 LLVM_FALLTHROUGH; 4485 case MVT::i64: // PPC64 4486 if (GPR_idx != Num_GPR_Regs) { 4487 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4488 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4489 4490 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4491 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4492 // value to MVT::i64 and then truncate to the correct register size. 4493 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4494 4495 ++GPR_idx; 4496 } else { 4497 needsLoad = true; 4498 ArgSize = PtrByteSize; 4499 } 4500 // All int arguments reserve stack space in the Darwin ABI. 4501 ArgOffset += 8; 4502 break; 4503 4504 case MVT::f32: 4505 case MVT::f64: 4506 // Every 4 bytes of argument space consumes one of the GPRs available for 4507 // argument passing. 4508 if (GPR_idx != Num_GPR_Regs) { 4509 ++GPR_idx; 4510 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4511 ++GPR_idx; 4512 } 4513 if (FPR_idx != Num_FPR_Regs) { 4514 unsigned VReg; 4515 4516 if (ObjectVT == MVT::f32) 4517 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4518 else 4519 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4520 4521 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4522 ++FPR_idx; 4523 } else { 4524 needsLoad = true; 4525 } 4526 4527 // All FP arguments reserve stack space in the Darwin ABI. 4528 ArgOffset += isPPC64 ? 8 : ObjSize; 4529 break; 4530 case MVT::v4f32: 4531 case MVT::v4i32: 4532 case MVT::v8i16: 4533 case MVT::v16i8: 4534 // Note that vector arguments in registers don't reserve stack space, 4535 // except in varargs functions. 4536 if (VR_idx != Num_VR_Regs) { 4537 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4538 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4539 if (isVarArg) { 4540 while ((ArgOffset % 16) != 0) { 4541 ArgOffset += PtrByteSize; 4542 if (GPR_idx != Num_GPR_Regs) 4543 GPR_idx++; 4544 } 4545 ArgOffset += 16; 4546 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4547 } 4548 ++VR_idx; 4549 } else { 4550 if (!isVarArg && !isPPC64) { 4551 // Vectors go after all the nonvectors. 4552 CurArgOffset = VecArgOffset; 4553 VecArgOffset += 16; 4554 } else { 4555 // Vectors are aligned. 4556 ArgOffset = ((ArgOffset+15)/16)*16; 4557 CurArgOffset = ArgOffset; 4558 ArgOffset += 16; 4559 } 4560 needsLoad = true; 4561 } 4562 break; 4563 } 4564 4565 // We need to load the argument to a virtual register if we determined above 4566 // that we ran out of physical registers of the appropriate type. 4567 if (needsLoad) { 4568 int FI = MFI.CreateFixedObject(ObjSize, 4569 CurArgOffset + (ArgSize - ObjSize), 4570 isImmutable); 4571 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4572 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4573 } 4574 4575 InVals.push_back(ArgVal); 4576 } 4577 4578 // Allow for Altivec parameters at the end, if needed. 4579 if (nAltivecParamsAtEnd) { 4580 MinReservedArea = ((MinReservedArea+15)/16)*16; 4581 MinReservedArea += 16*nAltivecParamsAtEnd; 4582 } 4583 4584 // Area that is at least reserved in the caller of this function. 4585 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4586 4587 // Set the size that is at least reserved in caller of this function. Tail 4588 // call optimized functions' reserved stack space needs to be aligned so that 4589 // taking the difference between two stack areas will result in an aligned 4590 // stack. 4591 MinReservedArea = 4592 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4593 FuncInfo->setMinReservedArea(MinReservedArea); 4594 4595 // If the function takes variable number of arguments, make a frame index for 4596 // the start of the first vararg value... for expansion of llvm.va_start. 4597 if (isVarArg) { 4598 int Depth = ArgOffset; 4599 4600 FuncInfo->setVarArgsFrameIndex( 4601 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4602 Depth, true)); 4603 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4604 4605 // If this function is vararg, store any remaining integer argument regs 4606 // to their spots on the stack so that they may be loaded by dereferencing 4607 // the result of va_next. 4608 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4609 unsigned VReg; 4610 4611 if (isPPC64) 4612 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4613 else 4614 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4615 4616 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4617 SDValue Store = 4618 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4619 MemOps.push_back(Store); 4620 // Increment the address by four for the next argument to store 4621 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4622 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4623 } 4624 } 4625 4626 if (!MemOps.empty()) 4627 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4628 4629 return Chain; 4630 } 4631 4632 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4633 /// adjusted to accommodate the arguments for the tailcall. 4634 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4635 unsigned ParamSize) { 4636 4637 if (!isTailCall) return 0; 4638 4639 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4640 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4641 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4642 // Remember only if the new adjustment is bigger. 4643 if (SPDiff < FI->getTailCallSPDelta()) 4644 FI->setTailCallSPDelta(SPDiff); 4645 4646 return SPDiff; 4647 } 4648 4649 static bool isFunctionGlobalAddress(SDValue Callee); 4650 4651 static bool 4652 callsShareTOCBase(const Function *Caller, SDValue Callee, 4653 const TargetMachine &TM) { 4654 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4655 // don't have enough information to determine if the caller and calle share 4656 // the same TOC base, so we have to pessimistically assume they don't for 4657 // correctness. 4658 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4659 if (!G) 4660 return false; 4661 4662 const GlobalValue *GV = G->getGlobal(); 4663 // The medium and large code models are expected to provide a sufficiently 4664 // large TOC to provide all data addressing needs of a module with a 4665 // single TOC. Since each module will be addressed with a single TOC then we 4666 // only need to check that caller and callee don't cross dso boundaries. 4667 if (CodeModel::Medium == TM.getCodeModel() || 4668 CodeModel::Large == TM.getCodeModel()) 4669 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4670 4671 // Otherwise we need to ensure callee and caller are in the same section, 4672 // since the linker may allocate multiple TOCs, and we don't know which 4673 // sections will belong to the same TOC base. 4674 4675 if (!GV->isStrongDefinitionForLinker()) 4676 return false; 4677 4678 // Any explicitly-specified sections and section prefixes must also match. 4679 // Also, if we're using -ffunction-sections, then each function is always in 4680 // a different section (the same is true for COMDAT functions). 4681 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4682 GV->getSection() != Caller->getSection()) 4683 return false; 4684 if (const auto *F = dyn_cast<Function>(GV)) { 4685 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4686 return false; 4687 } 4688 4689 // If the callee might be interposed, then we can't assume the ultimate call 4690 // target will be in the same section. Even in cases where we can assume that 4691 // interposition won't happen, in any case where the linker might insert a 4692 // stub to allow for interposition, we must generate code as though 4693 // interposition might occur. To understand why this matters, consider a 4694 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4695 // in the same section, but a is in a different module (i.e. has a different 4696 // TOC base pointer). If the linker allows for interposition between b and c, 4697 // then it will generate a stub for the call edge between b and c which will 4698 // save the TOC pointer into the designated stack slot allocated by b. If we 4699 // return true here, and therefore allow a tail call between b and c, that 4700 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4701 // pointer into the stack slot allocated by a (where the a -> b stub saved 4702 // a's TOC base pointer). If we're not considering a tail call, but rather, 4703 // whether a nop is needed after the call instruction in b, because the linker 4704 // will insert a stub, it might complain about a missing nop if we omit it 4705 // (although many don't complain in this case). 4706 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4707 return false; 4708 4709 return true; 4710 } 4711 4712 static bool 4713 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4714 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4715 assert(Subtarget.is64BitELFABI()); 4716 4717 const unsigned PtrByteSize = 8; 4718 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4719 4720 static const MCPhysReg GPR[] = { 4721 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4722 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4723 }; 4724 static const MCPhysReg VR[] = { 4725 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4726 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4727 }; 4728 4729 const unsigned NumGPRs = array_lengthof(GPR); 4730 const unsigned NumFPRs = 13; 4731 const unsigned NumVRs = array_lengthof(VR); 4732 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4733 4734 unsigned NumBytes = LinkageSize; 4735 unsigned AvailableFPRs = NumFPRs; 4736 unsigned AvailableVRs = NumVRs; 4737 4738 for (const ISD::OutputArg& Param : Outs) { 4739 if (Param.Flags.isNest()) continue; 4740 4741 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4742 PtrByteSize, LinkageSize, ParamAreaSize, 4743 NumBytes, AvailableFPRs, AvailableVRs, 4744 Subtarget.hasQPX())) 4745 return true; 4746 } 4747 return false; 4748 } 4749 4750 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4751 if (CB.arg_size() != CallerFn->arg_size()) 4752 return false; 4753 4754 auto CalleeArgIter = CB.arg_begin(); 4755 auto CalleeArgEnd = CB.arg_end(); 4756 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4757 4758 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4759 const Value* CalleeArg = *CalleeArgIter; 4760 const Value* CallerArg = &(*CallerArgIter); 4761 if (CalleeArg == CallerArg) 4762 continue; 4763 4764 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4765 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4766 // } 4767 // 1st argument of callee is undef and has the same type as caller. 4768 if (CalleeArg->getType() == CallerArg->getType() && 4769 isa<UndefValue>(CalleeArg)) 4770 continue; 4771 4772 return false; 4773 } 4774 4775 return true; 4776 } 4777 4778 // Returns true if TCO is possible between the callers and callees 4779 // calling conventions. 4780 static bool 4781 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4782 CallingConv::ID CalleeCC) { 4783 // Tail calls are possible with fastcc and ccc. 4784 auto isTailCallableCC = [] (CallingConv::ID CC){ 4785 return CC == CallingConv::C || CC == CallingConv::Fast; 4786 }; 4787 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4788 return false; 4789 4790 // We can safely tail call both fastcc and ccc callees from a c calling 4791 // convention caller. If the caller is fastcc, we may have less stack space 4792 // than a non-fastcc caller with the same signature so disable tail-calls in 4793 // that case. 4794 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4795 } 4796 4797 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4798 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4799 const SmallVectorImpl<ISD::OutputArg> &Outs, 4800 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4801 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4802 4803 if (DisableSCO && !TailCallOpt) return false; 4804 4805 // Variadic argument functions are not supported. 4806 if (isVarArg) return false; 4807 4808 auto &Caller = DAG.getMachineFunction().getFunction(); 4809 // Check that the calling conventions are compatible for tco. 4810 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4811 return false; 4812 4813 // Caller contains any byval parameter is not supported. 4814 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4815 return false; 4816 4817 // Callee contains any byval parameter is not supported, too. 4818 // Note: This is a quick work around, because in some cases, e.g. 4819 // caller's stack size > callee's stack size, we are still able to apply 4820 // sibling call optimization. For example, gcc is able to do SCO for caller1 4821 // in the following example, but not for caller2. 4822 // struct test { 4823 // long int a; 4824 // char ary[56]; 4825 // } gTest; 4826 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4827 // b->a = v.a; 4828 // return 0; 4829 // } 4830 // void caller1(struct test a, struct test c, struct test *b) { 4831 // callee(gTest, b); } 4832 // void caller2(struct test *b) { callee(gTest, b); } 4833 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4834 return false; 4835 4836 // If callee and caller use different calling conventions, we cannot pass 4837 // parameters on stack since offsets for the parameter area may be different. 4838 if (Caller.getCallingConv() != CalleeCC && 4839 needStackSlotPassParameters(Subtarget, Outs)) 4840 return false; 4841 4842 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4843 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4844 // callee potentially have different TOC bases then we cannot tail call since 4845 // we need to restore the TOC pointer after the call. 4846 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4847 // We cannot guarantee this for indirect calls or calls to external functions. 4848 // When PC-Relative addressing is used, the concept of the TOC is no longer 4849 // applicable so this check is not required. 4850 // Check first for indirect calls. 4851 if (!Subtarget.isUsingPCRelativeCalls() && 4852 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4853 return false; 4854 4855 // Check if we share the TOC base. 4856 if (!Subtarget.isUsingPCRelativeCalls() && 4857 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4858 return false; 4859 4860 // TCO allows altering callee ABI, so we don't have to check further. 4861 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4862 return true; 4863 4864 if (DisableSCO) return false; 4865 4866 // If callee use the same argument list that caller is using, then we can 4867 // apply SCO on this case. If it is not, then we need to check if callee needs 4868 // stack for passing arguments. 4869 // PC Relative tail calls may not have a CallBase. 4870 // If there is no CallBase we cannot verify if we have the same argument 4871 // list so assume that we don't have the same argument list. 4872 if (CB && !hasSameArgumentList(&Caller, *CB) && 4873 needStackSlotPassParameters(Subtarget, Outs)) 4874 return false; 4875 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4876 return false; 4877 4878 return true; 4879 } 4880 4881 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4882 /// for tail call optimization. Targets which want to do tail call 4883 /// optimization should implement this function. 4884 bool 4885 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4886 CallingConv::ID CalleeCC, 4887 bool isVarArg, 4888 const SmallVectorImpl<ISD::InputArg> &Ins, 4889 SelectionDAG& DAG) const { 4890 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4891 return false; 4892 4893 // Variable argument functions are not supported. 4894 if (isVarArg) 4895 return false; 4896 4897 MachineFunction &MF = DAG.getMachineFunction(); 4898 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4899 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4900 // Functions containing by val parameters are not supported. 4901 for (unsigned i = 0; i != Ins.size(); i++) { 4902 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4903 if (Flags.isByVal()) return false; 4904 } 4905 4906 // Non-PIC/GOT tail calls are supported. 4907 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4908 return true; 4909 4910 // At the moment we can only do local tail calls (in same module, hidden 4911 // or protected) if we are generating PIC. 4912 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4913 return G->getGlobal()->hasHiddenVisibility() 4914 || G->getGlobal()->hasProtectedVisibility(); 4915 } 4916 4917 return false; 4918 } 4919 4920 /// isCallCompatibleAddress - Return the immediate to use if the specified 4921 /// 32-bit value is representable in the immediate field of a BxA instruction. 4922 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4923 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4924 if (!C) return nullptr; 4925 4926 int Addr = C->getZExtValue(); 4927 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4928 SignExtend32<26>(Addr) != Addr) 4929 return nullptr; // Top 6 bits have to be sext of immediate. 4930 4931 return DAG 4932 .getConstant( 4933 (int)C->getZExtValue() >> 2, SDLoc(Op), 4934 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4935 .getNode(); 4936 } 4937 4938 namespace { 4939 4940 struct TailCallArgumentInfo { 4941 SDValue Arg; 4942 SDValue FrameIdxOp; 4943 int FrameIdx = 0; 4944 4945 TailCallArgumentInfo() = default; 4946 }; 4947 4948 } // end anonymous namespace 4949 4950 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4951 static void StoreTailCallArgumentsToStackSlot( 4952 SelectionDAG &DAG, SDValue Chain, 4953 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4954 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4955 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4956 SDValue Arg = TailCallArgs[i].Arg; 4957 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4958 int FI = TailCallArgs[i].FrameIdx; 4959 // Store relative to framepointer. 4960 MemOpChains.push_back(DAG.getStore( 4961 Chain, dl, Arg, FIN, 4962 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4963 } 4964 } 4965 4966 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4967 /// the appropriate stack slot for the tail call optimized function call. 4968 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4969 SDValue OldRetAddr, SDValue OldFP, 4970 int SPDiff, const SDLoc &dl) { 4971 if (SPDiff) { 4972 // Calculate the new stack slot for the return address. 4973 MachineFunction &MF = DAG.getMachineFunction(); 4974 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4975 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4976 bool isPPC64 = Subtarget.isPPC64(); 4977 int SlotSize = isPPC64 ? 8 : 4; 4978 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4979 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4980 NewRetAddrLoc, true); 4981 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4982 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4983 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4984 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4985 } 4986 return Chain; 4987 } 4988 4989 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4990 /// the position of the argument. 4991 static void 4992 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4993 SDValue Arg, int SPDiff, unsigned ArgOffset, 4994 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4995 int Offset = ArgOffset + SPDiff; 4996 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4997 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4998 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4999 SDValue FIN = DAG.getFrameIndex(FI, VT); 5000 TailCallArgumentInfo Info; 5001 Info.Arg = Arg; 5002 Info.FrameIdxOp = FIN; 5003 Info.FrameIdx = FI; 5004 TailCallArguments.push_back(Info); 5005 } 5006 5007 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5008 /// stack slot. Returns the chain as result and the loaded frame pointers in 5009 /// LROpOut/FPOpout. Used when tail calling. 5010 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5011 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5012 SDValue &FPOpOut, const SDLoc &dl) const { 5013 if (SPDiff) { 5014 // Load the LR and FP stack slot for later adjusting. 5015 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5016 LROpOut = getReturnAddrFrameIndex(DAG); 5017 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5018 Chain = SDValue(LROpOut.getNode(), 1); 5019 } 5020 return Chain; 5021 } 5022 5023 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5024 /// by "Src" to address "Dst" of size "Size". Alignment information is 5025 /// specified by the specific parameter attribute. The copy will be passed as 5026 /// a byval function parameter. 5027 /// Sometimes what we are copying is the end of a larger object, the part that 5028 /// does not fit in registers. 5029 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5030 SDValue Chain, ISD::ArgFlagsTy Flags, 5031 SelectionDAG &DAG, const SDLoc &dl) { 5032 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5033 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5034 Flags.getNonZeroByValAlign(), false, false, false, 5035 MachinePointerInfo(), MachinePointerInfo()); 5036 } 5037 5038 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5039 /// tail calls. 5040 static void LowerMemOpCallTo( 5041 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5042 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5043 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5044 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5045 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5046 if (!isTailCall) { 5047 if (isVector) { 5048 SDValue StackPtr; 5049 if (isPPC64) 5050 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5051 else 5052 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5053 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5054 DAG.getConstant(ArgOffset, dl, PtrVT)); 5055 } 5056 MemOpChains.push_back( 5057 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5058 // Calculate and remember argument location. 5059 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5060 TailCallArguments); 5061 } 5062 5063 static void 5064 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5065 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5066 SDValue FPOp, 5067 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5068 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5069 // might overwrite each other in case of tail call optimization. 5070 SmallVector<SDValue, 8> MemOpChains2; 5071 // Do not flag preceding copytoreg stuff together with the following stuff. 5072 InFlag = SDValue(); 5073 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5074 MemOpChains2, dl); 5075 if (!MemOpChains2.empty()) 5076 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5077 5078 // Store the return address to the appropriate stack slot. 5079 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5080 5081 // Emit callseq_end just before tailcall node. 5082 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5083 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5084 InFlag = Chain.getValue(1); 5085 } 5086 5087 // Is this global address that of a function that can be called by name? (as 5088 // opposed to something that must hold a descriptor for an indirect call). 5089 static bool isFunctionGlobalAddress(SDValue Callee) { 5090 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5091 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5092 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5093 return false; 5094 5095 return G->getGlobal()->getValueType()->isFunctionTy(); 5096 } 5097 5098 return false; 5099 } 5100 5101 SDValue PPCTargetLowering::LowerCallResult( 5102 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5103 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5104 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5105 SmallVector<CCValAssign, 16> RVLocs; 5106 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5107 *DAG.getContext()); 5108 5109 CCRetInfo.AnalyzeCallResult( 5110 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5111 ? RetCC_PPC_Cold 5112 : RetCC_PPC); 5113 5114 // Copy all of the result registers out of their specified physreg. 5115 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5116 CCValAssign &VA = RVLocs[i]; 5117 assert(VA.isRegLoc() && "Can only return in registers!"); 5118 5119 SDValue Val; 5120 5121 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5122 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5123 InFlag); 5124 Chain = Lo.getValue(1); 5125 InFlag = Lo.getValue(2); 5126 VA = RVLocs[++i]; // skip ahead to next loc 5127 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5128 InFlag); 5129 Chain = Hi.getValue(1); 5130 InFlag = Hi.getValue(2); 5131 if (!Subtarget.isLittleEndian()) 5132 std::swap (Lo, Hi); 5133 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5134 } else { 5135 Val = DAG.getCopyFromReg(Chain, dl, 5136 VA.getLocReg(), VA.getLocVT(), InFlag); 5137 Chain = Val.getValue(1); 5138 InFlag = Val.getValue(2); 5139 } 5140 5141 switch (VA.getLocInfo()) { 5142 default: llvm_unreachable("Unknown loc info!"); 5143 case CCValAssign::Full: break; 5144 case CCValAssign::AExt: 5145 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5146 break; 5147 case CCValAssign::ZExt: 5148 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5149 DAG.getValueType(VA.getValVT())); 5150 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5151 break; 5152 case CCValAssign::SExt: 5153 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5154 DAG.getValueType(VA.getValVT())); 5155 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5156 break; 5157 } 5158 5159 InVals.push_back(Val); 5160 } 5161 5162 return Chain; 5163 } 5164 5165 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5166 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5167 // PatchPoint calls are not indirect. 5168 if (isPatchPoint) 5169 return false; 5170 5171 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5172 return false; 5173 5174 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5175 // becuase the immediate function pointer points to a descriptor instead of 5176 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5177 // pointer immediate points to the global entry point, while the BLA would 5178 // need to jump to the local entry point (see rL211174). 5179 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5180 isBLACompatibleAddress(Callee, DAG)) 5181 return false; 5182 5183 return true; 5184 } 5185 5186 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5187 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5188 return Subtarget.isAIXABI() || 5189 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5190 } 5191 5192 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5193 const Function &Caller, 5194 const SDValue &Callee, 5195 const PPCSubtarget &Subtarget, 5196 const TargetMachine &TM) { 5197 if (CFlags.IsTailCall) 5198 return PPCISD::TC_RETURN; 5199 5200 // This is a call through a function pointer. 5201 if (CFlags.IsIndirect) { 5202 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5203 // indirect calls. The save of the caller's TOC pointer to the stack will be 5204 // inserted into the DAG as part of call lowering. The restore of the TOC 5205 // pointer is modeled by using a pseudo instruction for the call opcode that 5206 // represents the 2 instruction sequence of an indirect branch and link, 5207 // immediately followed by a load of the TOC pointer from the the stack save 5208 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5209 // as it is not saved or used. 5210 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5211 : PPCISD::BCTRL; 5212 } 5213 5214 if (Subtarget.isUsingPCRelativeCalls()) { 5215 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5216 return PPCISD::CALL_NOTOC; 5217 } 5218 5219 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5220 // immediately following the call instruction if the caller and callee may 5221 // have different TOC bases. At link time if the linker determines the calls 5222 // may not share a TOC base, the call is redirected to a trampoline inserted 5223 // by the linker. The trampoline will (among other things) save the callers 5224 // TOC pointer at an ABI designated offset in the linkage area and the linker 5225 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5226 // into gpr2. 5227 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5228 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5229 : PPCISD::CALL_NOP; 5230 5231 return PPCISD::CALL; 5232 } 5233 5234 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5235 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5236 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5237 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5238 return SDValue(Dest, 0); 5239 5240 // Returns true if the callee is local, and false otherwise. 5241 auto isLocalCallee = [&]() { 5242 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5243 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5244 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5245 5246 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5247 !dyn_cast_or_null<GlobalIFunc>(GV); 5248 }; 5249 5250 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5251 // a static relocation model causes some versions of GNU LD (2.17.50, at 5252 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5253 // built with secure-PLT. 5254 bool UsePlt = 5255 Subtarget.is32BitELFABI() && !isLocalCallee() && 5256 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5257 5258 // On AIX, direct function calls reference the symbol for the function's 5259 // entry point, which is named by prepending a "." before the function's 5260 // C-linkage name. 5261 const auto getAIXFuncEntryPointSymbolSDNode = 5262 [&](StringRef FuncName, bool IsDeclaration, 5263 const XCOFF::StorageClass &SC) { 5264 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5265 5266 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5267 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5268 5269 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5270 // On AIX, an undefined symbol needs to be associated with a 5271 // MCSectionXCOFF to get the correct storage mapping class. 5272 // In this case, XCOFF::XMC_PR. 5273 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5274 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5275 SectionKind::getMetadata()); 5276 S->setRepresentedCsect(Sec); 5277 } 5278 5279 MVT PtrVT = 5280 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5281 return DAG.getMCSymbol(S, PtrVT); 5282 }; 5283 5284 if (isFunctionGlobalAddress(Callee)) { 5285 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5286 const GlobalValue *GV = G->getGlobal(); 5287 5288 if (!Subtarget.isAIXABI()) 5289 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5290 UsePlt ? PPCII::MO_PLT : 0); 5291 5292 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5293 const GlobalObject *GO = cast<GlobalObject>(GV); 5294 const XCOFF::StorageClass SC = 5295 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5296 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5297 SC); 5298 } 5299 5300 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5301 const char *SymName = S->getSymbol(); 5302 if (!Subtarget.isAIXABI()) 5303 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5304 UsePlt ? PPCII::MO_PLT : 0); 5305 5306 // If there exists a user-declared function whose name is the same as the 5307 // ExternalSymbol's, then we pick up the user-declared version. 5308 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5309 if (const Function *F = 5310 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5311 const XCOFF::StorageClass SC = 5312 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5313 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5314 SC); 5315 } 5316 5317 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5318 } 5319 5320 // No transformation needed. 5321 assert(Callee.getNode() && "What no callee?"); 5322 return Callee; 5323 } 5324 5325 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5326 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5327 "Expected a CALLSEQ_STARTSDNode."); 5328 5329 // The last operand is the chain, except when the node has glue. If the node 5330 // has glue, then the last operand is the glue, and the chain is the second 5331 // last operand. 5332 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5333 if (LastValue.getValueType() != MVT::Glue) 5334 return LastValue; 5335 5336 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5337 } 5338 5339 // Creates the node that moves a functions address into the count register 5340 // to prepare for an indirect call instruction. 5341 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5342 SDValue &Glue, SDValue &Chain, 5343 const SDLoc &dl) { 5344 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5345 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5346 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5347 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5348 // The glue is the second value produced. 5349 Glue = Chain.getValue(1); 5350 } 5351 5352 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5353 SDValue &Glue, SDValue &Chain, 5354 SDValue CallSeqStart, 5355 const CallBase *CB, const SDLoc &dl, 5356 bool hasNest, 5357 const PPCSubtarget &Subtarget) { 5358 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5359 // entry point, but to the function descriptor (the function entry point 5360 // address is part of the function descriptor though). 5361 // The function descriptor is a three doubleword structure with the 5362 // following fields: function entry point, TOC base address and 5363 // environment pointer. 5364 // Thus for a call through a function pointer, the following actions need 5365 // to be performed: 5366 // 1. Save the TOC of the caller in the TOC save area of its stack 5367 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5368 // 2. Load the address of the function entry point from the function 5369 // descriptor. 5370 // 3. Load the TOC of the callee from the function descriptor into r2. 5371 // 4. Load the environment pointer from the function descriptor into 5372 // r11. 5373 // 5. Branch to the function entry point address. 5374 // 6. On return of the callee, the TOC of the caller needs to be 5375 // restored (this is done in FinishCall()). 5376 // 5377 // The loads are scheduled at the beginning of the call sequence, and the 5378 // register copies are flagged together to ensure that no other 5379 // operations can be scheduled in between. E.g. without flagging the 5380 // copies together, a TOC access in the caller could be scheduled between 5381 // the assignment of the callee TOC and the branch to the callee, which leads 5382 // to incorrect code. 5383 5384 // Start by loading the function address from the descriptor. 5385 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5386 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5387 ? (MachineMemOperand::MODereferenceable | 5388 MachineMemOperand::MOInvariant) 5389 : MachineMemOperand::MONone; 5390 5391 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5392 5393 // Registers used in building the DAG. 5394 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5395 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5396 5397 // Offsets of descriptor members. 5398 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5399 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5400 5401 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5402 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5403 5404 // One load for the functions entry point address. 5405 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5406 Alignment, MMOFlags); 5407 5408 // One for loading the TOC anchor for the module that contains the called 5409 // function. 5410 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5411 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5412 SDValue TOCPtr = 5413 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5414 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5415 5416 // One for loading the environment pointer. 5417 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5418 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5419 SDValue LoadEnvPtr = 5420 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5421 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5422 5423 5424 // Then copy the newly loaded TOC anchor to the TOC pointer. 5425 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5426 Chain = TOCVal.getValue(0); 5427 Glue = TOCVal.getValue(1); 5428 5429 // If the function call has an explicit 'nest' parameter, it takes the 5430 // place of the environment pointer. 5431 assert((!hasNest || !Subtarget.isAIXABI()) && 5432 "Nest parameter is not supported on AIX."); 5433 if (!hasNest) { 5434 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5435 Chain = EnvVal.getValue(0); 5436 Glue = EnvVal.getValue(1); 5437 } 5438 5439 // The rest of the indirect call sequence is the same as the non-descriptor 5440 // DAG. 5441 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5442 } 5443 5444 static void 5445 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5446 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5447 SelectionDAG &DAG, 5448 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5449 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5450 const PPCSubtarget &Subtarget) { 5451 const bool IsPPC64 = Subtarget.isPPC64(); 5452 // MVT for a general purpose register. 5453 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5454 5455 // First operand is always the chain. 5456 Ops.push_back(Chain); 5457 5458 // If it's a direct call pass the callee as the second operand. 5459 if (!CFlags.IsIndirect) 5460 Ops.push_back(Callee); 5461 else { 5462 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5463 5464 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5465 // on the stack (this would have been done in `LowerCall_64SVR4` or 5466 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5467 // represents both the indirect branch and a load that restores the TOC 5468 // pointer from the linkage area. The operand for the TOC restore is an add 5469 // of the TOC save offset to the stack pointer. This must be the second 5470 // operand: after the chain input but before any other variadic arguments. 5471 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5472 // saved or used. 5473 if (isTOCSaveRestoreRequired(Subtarget)) { 5474 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5475 5476 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5477 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5478 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5479 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5480 Ops.push_back(AddTOC); 5481 } 5482 5483 // Add the register used for the environment pointer. 5484 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5485 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5486 RegVT)); 5487 5488 5489 // Add CTR register as callee so a bctr can be emitted later. 5490 if (CFlags.IsTailCall) 5491 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5492 } 5493 5494 // If this is a tail call add stack pointer delta. 5495 if (CFlags.IsTailCall) 5496 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5497 5498 // Add argument registers to the end of the list so that they are known live 5499 // into the call. 5500 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5501 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5502 RegsToPass[i].second.getValueType())); 5503 5504 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5505 // no way to mark dependencies as implicit here. 5506 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5507 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5508 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5509 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5510 5511 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5512 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5513 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5514 5515 // Add a register mask operand representing the call-preserved registers. 5516 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5517 const uint32_t *Mask = 5518 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5519 assert(Mask && "Missing call preserved mask for calling convention"); 5520 Ops.push_back(DAG.getRegisterMask(Mask)); 5521 5522 // If the glue is valid, it is the last operand. 5523 if (Glue.getNode()) 5524 Ops.push_back(Glue); 5525 } 5526 5527 SDValue PPCTargetLowering::FinishCall( 5528 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5529 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5530 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5531 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5532 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5533 5534 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5535 Subtarget.isAIXABI()) 5536 setUsesTOCBasePtr(DAG); 5537 5538 unsigned CallOpc = 5539 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5540 Subtarget, DAG.getTarget()); 5541 5542 if (!CFlags.IsIndirect) 5543 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5544 else if (Subtarget.usesFunctionDescriptors()) 5545 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5546 dl, CFlags.HasNest, Subtarget); 5547 else 5548 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5549 5550 // Build the operand list for the call instruction. 5551 SmallVector<SDValue, 8> Ops; 5552 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5553 SPDiff, Subtarget); 5554 5555 // Emit tail call. 5556 if (CFlags.IsTailCall) { 5557 // Indirect tail call when using PC Relative calls do not have the same 5558 // constraints. 5559 assert(((Callee.getOpcode() == ISD::Register && 5560 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5561 Callee.getOpcode() == ISD::TargetExternalSymbol || 5562 Callee.getOpcode() == ISD::TargetGlobalAddress || 5563 isa<ConstantSDNode>(Callee) || 5564 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5565 "Expecting a global address, external symbol, absolute value, " 5566 "register or an indirect tail call when PC Relative calls are " 5567 "used."); 5568 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5569 assert(CallOpc == PPCISD::TC_RETURN && 5570 "Unexpected call opcode for a tail call."); 5571 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5572 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5573 } 5574 5575 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5576 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5577 Glue = Chain.getValue(1); 5578 5579 // When performing tail call optimization the callee pops its arguments off 5580 // the stack. Account for this here so these bytes can be pushed back on in 5581 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5582 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5583 getTargetMachine().Options.GuaranteedTailCallOpt) 5584 ? NumBytes 5585 : 0; 5586 5587 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5588 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5589 Glue, dl); 5590 Glue = Chain.getValue(1); 5591 5592 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5593 DAG, InVals); 5594 } 5595 5596 SDValue 5597 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5598 SmallVectorImpl<SDValue> &InVals) const { 5599 SelectionDAG &DAG = CLI.DAG; 5600 SDLoc &dl = CLI.DL; 5601 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5602 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5603 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5604 SDValue Chain = CLI.Chain; 5605 SDValue Callee = CLI.Callee; 5606 bool &isTailCall = CLI.IsTailCall; 5607 CallingConv::ID CallConv = CLI.CallConv; 5608 bool isVarArg = CLI.IsVarArg; 5609 bool isPatchPoint = CLI.IsPatchPoint; 5610 const CallBase *CB = CLI.CB; 5611 5612 if (isTailCall) { 5613 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5614 isTailCall = false; 5615 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5616 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5617 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5618 else 5619 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5620 Ins, DAG); 5621 if (isTailCall) { 5622 ++NumTailCalls; 5623 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5624 ++NumSiblingCalls; 5625 5626 // PC Relative calls no longer guarantee that the callee is a Global 5627 // Address Node. The callee could be an indirect tail call in which 5628 // case the SDValue for the callee could be a load (to load the address 5629 // of a function pointer) or it may be a register copy (to move the 5630 // address of the callee from a function parameter into a virtual 5631 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5632 assert((Subtarget.isUsingPCRelativeCalls() || 5633 isa<GlobalAddressSDNode>(Callee)) && 5634 "Callee should be an llvm::Function object."); 5635 5636 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5637 << "\nTCO callee: "); 5638 LLVM_DEBUG(Callee.dump()); 5639 } 5640 } 5641 5642 if (!isTailCall && CB && CB->isMustTailCall()) 5643 report_fatal_error("failed to perform tail call elimination on a call " 5644 "site marked musttail"); 5645 5646 // When long calls (i.e. indirect calls) are always used, calls are always 5647 // made via function pointer. If we have a function name, first translate it 5648 // into a pointer. 5649 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5650 !isTailCall) 5651 Callee = LowerGlobalAddress(Callee, DAG); 5652 5653 CallFlags CFlags( 5654 CallConv, isTailCall, isVarArg, isPatchPoint, 5655 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5656 // hasNest 5657 Subtarget.is64BitELFABI() && 5658 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5659 5660 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5661 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5662 InVals, CB); 5663 5664 if (Subtarget.isSVR4ABI()) 5665 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5666 InVals, CB); 5667 5668 if (Subtarget.isAIXABI()) 5669 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5670 InVals, CB); 5671 5672 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5673 InVals, CB); 5674 } 5675 5676 SDValue PPCTargetLowering::LowerCall_32SVR4( 5677 SDValue Chain, SDValue Callee, CallFlags CFlags, 5678 const SmallVectorImpl<ISD::OutputArg> &Outs, 5679 const SmallVectorImpl<SDValue> &OutVals, 5680 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5681 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5682 const CallBase *CB) const { 5683 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5684 // of the 32-bit SVR4 ABI stack frame layout. 5685 5686 const CallingConv::ID CallConv = CFlags.CallConv; 5687 const bool IsVarArg = CFlags.IsVarArg; 5688 const bool IsTailCall = CFlags.IsTailCall; 5689 5690 assert((CallConv == CallingConv::C || 5691 CallConv == CallingConv::Cold || 5692 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5693 5694 unsigned PtrByteSize = 4; 5695 5696 MachineFunction &MF = DAG.getMachineFunction(); 5697 5698 // Mark this function as potentially containing a function that contains a 5699 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5700 // and restoring the callers stack pointer in this functions epilog. This is 5701 // done because by tail calling the called function might overwrite the value 5702 // in this function's (MF) stack pointer stack slot 0(SP). 5703 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5704 CallConv == CallingConv::Fast) 5705 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5706 5707 // Count how many bytes are to be pushed on the stack, including the linkage 5708 // area, parameter list area and the part of the local variable space which 5709 // contains copies of aggregates which are passed by value. 5710 5711 // Assign locations to all of the outgoing arguments. 5712 SmallVector<CCValAssign, 16> ArgLocs; 5713 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5714 5715 // Reserve space for the linkage area on the stack. 5716 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5717 PtrByteSize); 5718 if (useSoftFloat()) 5719 CCInfo.PreAnalyzeCallOperands(Outs); 5720 5721 if (IsVarArg) { 5722 // Handle fixed and variable vector arguments differently. 5723 // Fixed vector arguments go into registers as long as registers are 5724 // available. Variable vector arguments always go into memory. 5725 unsigned NumArgs = Outs.size(); 5726 5727 for (unsigned i = 0; i != NumArgs; ++i) { 5728 MVT ArgVT = Outs[i].VT; 5729 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5730 bool Result; 5731 5732 if (Outs[i].IsFixed) { 5733 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5734 CCInfo); 5735 } else { 5736 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5737 ArgFlags, CCInfo); 5738 } 5739 5740 if (Result) { 5741 #ifndef NDEBUG 5742 errs() << "Call operand #" << i << " has unhandled type " 5743 << EVT(ArgVT).getEVTString() << "\n"; 5744 #endif 5745 llvm_unreachable(nullptr); 5746 } 5747 } 5748 } else { 5749 // All arguments are treated the same. 5750 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5751 } 5752 CCInfo.clearWasPPCF128(); 5753 5754 // Assign locations to all of the outgoing aggregate by value arguments. 5755 SmallVector<CCValAssign, 16> ByValArgLocs; 5756 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5757 5758 // Reserve stack space for the allocations in CCInfo. 5759 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5760 5761 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5762 5763 // Size of the linkage area, parameter list area and the part of the local 5764 // space variable where copies of aggregates which are passed by value are 5765 // stored. 5766 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5767 5768 // Calculate by how many bytes the stack has to be adjusted in case of tail 5769 // call optimization. 5770 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5771 5772 // Adjust the stack pointer for the new arguments... 5773 // These operations are automatically eliminated by the prolog/epilog pass 5774 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5775 SDValue CallSeqStart = Chain; 5776 5777 // Load the return address and frame pointer so it can be moved somewhere else 5778 // later. 5779 SDValue LROp, FPOp; 5780 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5781 5782 // Set up a copy of the stack pointer for use loading and storing any 5783 // arguments that may not fit in the registers available for argument 5784 // passing. 5785 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5786 5787 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5788 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5789 SmallVector<SDValue, 8> MemOpChains; 5790 5791 bool seenFloatArg = false; 5792 // Walk the register/memloc assignments, inserting copies/loads. 5793 // i - Tracks the index into the list of registers allocated for the call 5794 // RealArgIdx - Tracks the index into the list of actual function arguments 5795 // j - Tracks the index into the list of byval arguments 5796 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5797 i != e; 5798 ++i, ++RealArgIdx) { 5799 CCValAssign &VA = ArgLocs[i]; 5800 SDValue Arg = OutVals[RealArgIdx]; 5801 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5802 5803 if (Flags.isByVal()) { 5804 // Argument is an aggregate which is passed by value, thus we need to 5805 // create a copy of it in the local variable space of the current stack 5806 // frame (which is the stack frame of the caller) and pass the address of 5807 // this copy to the callee. 5808 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5809 CCValAssign &ByValVA = ByValArgLocs[j++]; 5810 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5811 5812 // Memory reserved in the local variable space of the callers stack frame. 5813 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5814 5815 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5816 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5817 StackPtr, PtrOff); 5818 5819 // Create a copy of the argument in the local area of the current 5820 // stack frame. 5821 SDValue MemcpyCall = 5822 CreateCopyOfByValArgument(Arg, PtrOff, 5823 CallSeqStart.getNode()->getOperand(0), 5824 Flags, DAG, dl); 5825 5826 // This must go outside the CALLSEQ_START..END. 5827 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5828 SDLoc(MemcpyCall)); 5829 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5830 NewCallSeqStart.getNode()); 5831 Chain = CallSeqStart = NewCallSeqStart; 5832 5833 // Pass the address of the aggregate copy on the stack either in a 5834 // physical register or in the parameter list area of the current stack 5835 // frame to the callee. 5836 Arg = PtrOff; 5837 } 5838 5839 // When useCRBits() is true, there can be i1 arguments. 5840 // It is because getRegisterType(MVT::i1) => MVT::i1, 5841 // and for other integer types getRegisterType() => MVT::i32. 5842 // Extend i1 and ensure callee will get i32. 5843 if (Arg.getValueType() == MVT::i1) 5844 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5845 dl, MVT::i32, Arg); 5846 5847 if (VA.isRegLoc()) { 5848 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5849 // Put argument in a physical register. 5850 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5851 bool IsLE = Subtarget.isLittleEndian(); 5852 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5853 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5854 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5855 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5856 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5857 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5858 SVal.getValue(0))); 5859 } else 5860 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5861 } else { 5862 // Put argument in the parameter list area of the current stack frame. 5863 assert(VA.isMemLoc()); 5864 unsigned LocMemOffset = VA.getLocMemOffset(); 5865 5866 if (!IsTailCall) { 5867 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5868 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5869 StackPtr, PtrOff); 5870 5871 MemOpChains.push_back( 5872 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5873 } else { 5874 // Calculate and remember argument location. 5875 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5876 TailCallArguments); 5877 } 5878 } 5879 } 5880 5881 if (!MemOpChains.empty()) 5882 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5883 5884 // Build a sequence of copy-to-reg nodes chained together with token chain 5885 // and flag operands which copy the outgoing args into the appropriate regs. 5886 SDValue InFlag; 5887 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5888 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5889 RegsToPass[i].second, InFlag); 5890 InFlag = Chain.getValue(1); 5891 } 5892 5893 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5894 // registers. 5895 if (IsVarArg) { 5896 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5897 SDValue Ops[] = { Chain, InFlag }; 5898 5899 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5900 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5901 5902 InFlag = Chain.getValue(1); 5903 } 5904 5905 if (IsTailCall) 5906 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5907 TailCallArguments); 5908 5909 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5910 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5911 } 5912 5913 // Copy an argument into memory, being careful to do this outside the 5914 // call sequence for the call to which the argument belongs. 5915 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5916 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5917 SelectionDAG &DAG, const SDLoc &dl) const { 5918 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5919 CallSeqStart.getNode()->getOperand(0), 5920 Flags, DAG, dl); 5921 // The MEMCPY must go outside the CALLSEQ_START..END. 5922 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5923 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5924 SDLoc(MemcpyCall)); 5925 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5926 NewCallSeqStart.getNode()); 5927 return NewCallSeqStart; 5928 } 5929 5930 SDValue PPCTargetLowering::LowerCall_64SVR4( 5931 SDValue Chain, SDValue Callee, CallFlags CFlags, 5932 const SmallVectorImpl<ISD::OutputArg> &Outs, 5933 const SmallVectorImpl<SDValue> &OutVals, 5934 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5935 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5936 const CallBase *CB) const { 5937 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5938 bool isLittleEndian = Subtarget.isLittleEndian(); 5939 unsigned NumOps = Outs.size(); 5940 bool IsSibCall = false; 5941 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5942 5943 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5944 unsigned PtrByteSize = 8; 5945 5946 MachineFunction &MF = DAG.getMachineFunction(); 5947 5948 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5949 IsSibCall = true; 5950 5951 // Mark this function as potentially containing a function that contains a 5952 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5953 // and restoring the callers stack pointer in this functions epilog. This is 5954 // done because by tail calling the called function might overwrite the value 5955 // in this function's (MF) stack pointer stack slot 0(SP). 5956 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5957 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5958 5959 assert(!(IsFastCall && CFlags.IsVarArg) && 5960 "fastcc not supported on varargs functions"); 5961 5962 // Count how many bytes are to be pushed on the stack, including the linkage 5963 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5964 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5965 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5966 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5967 unsigned NumBytes = LinkageSize; 5968 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5969 unsigned &QFPR_idx = FPR_idx; 5970 5971 static const MCPhysReg GPR[] = { 5972 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5973 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5974 }; 5975 static const MCPhysReg VR[] = { 5976 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5977 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5978 }; 5979 5980 const unsigned NumGPRs = array_lengthof(GPR); 5981 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5982 const unsigned NumVRs = array_lengthof(VR); 5983 const unsigned NumQFPRs = NumFPRs; 5984 5985 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5986 // can be passed to the callee in registers. 5987 // For the fast calling convention, there is another check below. 5988 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5989 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5990 if (!HasParameterArea) { 5991 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5992 unsigned AvailableFPRs = NumFPRs; 5993 unsigned AvailableVRs = NumVRs; 5994 unsigned NumBytesTmp = NumBytes; 5995 for (unsigned i = 0; i != NumOps; ++i) { 5996 if (Outs[i].Flags.isNest()) continue; 5997 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5998 PtrByteSize, LinkageSize, ParamAreaSize, 5999 NumBytesTmp, AvailableFPRs, AvailableVRs, 6000 Subtarget.hasQPX())) 6001 HasParameterArea = true; 6002 } 6003 } 6004 6005 // When using the fast calling convention, we don't provide backing for 6006 // arguments that will be in registers. 6007 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6008 6009 // Avoid allocating parameter area for fastcc functions if all the arguments 6010 // can be passed in the registers. 6011 if (IsFastCall) 6012 HasParameterArea = false; 6013 6014 // Add up all the space actually used. 6015 for (unsigned i = 0; i != NumOps; ++i) { 6016 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6017 EVT ArgVT = Outs[i].VT; 6018 EVT OrigVT = Outs[i].ArgVT; 6019 6020 if (Flags.isNest()) 6021 continue; 6022 6023 if (IsFastCall) { 6024 if (Flags.isByVal()) { 6025 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6026 if (NumGPRsUsed > NumGPRs) 6027 HasParameterArea = true; 6028 } else { 6029 switch (ArgVT.getSimpleVT().SimpleTy) { 6030 default: llvm_unreachable("Unexpected ValueType for argument!"); 6031 case MVT::i1: 6032 case MVT::i32: 6033 case MVT::i64: 6034 if (++NumGPRsUsed <= NumGPRs) 6035 continue; 6036 break; 6037 case MVT::v4i32: 6038 case MVT::v8i16: 6039 case MVT::v16i8: 6040 case MVT::v2f64: 6041 case MVT::v2i64: 6042 case MVT::v1i128: 6043 case MVT::f128: 6044 if (++NumVRsUsed <= NumVRs) 6045 continue; 6046 break; 6047 case MVT::v4f32: 6048 // When using QPX, this is handled like a FP register, otherwise, it 6049 // is an Altivec register. 6050 if (Subtarget.hasQPX()) { 6051 if (++NumFPRsUsed <= NumFPRs) 6052 continue; 6053 } else { 6054 if (++NumVRsUsed <= NumVRs) 6055 continue; 6056 } 6057 break; 6058 case MVT::f32: 6059 case MVT::f64: 6060 case MVT::v4f64: // QPX 6061 case MVT::v4i1: // QPX 6062 if (++NumFPRsUsed <= NumFPRs) 6063 continue; 6064 break; 6065 } 6066 HasParameterArea = true; 6067 } 6068 } 6069 6070 /* Respect alignment of argument on the stack. */ 6071 auto Alignement = 6072 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6073 NumBytes = alignTo(NumBytes, Alignement); 6074 6075 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6076 if (Flags.isInConsecutiveRegsLast()) 6077 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6078 } 6079 6080 unsigned NumBytesActuallyUsed = NumBytes; 6081 6082 // In the old ELFv1 ABI, 6083 // the prolog code of the callee may store up to 8 GPR argument registers to 6084 // the stack, allowing va_start to index over them in memory if its varargs. 6085 // Because we cannot tell if this is needed on the caller side, we have to 6086 // conservatively assume that it is needed. As such, make sure we have at 6087 // least enough stack space for the caller to store the 8 GPRs. 6088 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6089 // really requires memory operands, e.g. a vararg function. 6090 if (HasParameterArea) 6091 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6092 else 6093 NumBytes = LinkageSize; 6094 6095 // Tail call needs the stack to be aligned. 6096 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6097 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6098 6099 int SPDiff = 0; 6100 6101 // Calculate by how many bytes the stack has to be adjusted in case of tail 6102 // call optimization. 6103 if (!IsSibCall) 6104 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6105 6106 // To protect arguments on the stack from being clobbered in a tail call, 6107 // force all the loads to happen before doing any other lowering. 6108 if (CFlags.IsTailCall) 6109 Chain = DAG.getStackArgumentTokenFactor(Chain); 6110 6111 // Adjust the stack pointer for the new arguments... 6112 // These operations are automatically eliminated by the prolog/epilog pass 6113 if (!IsSibCall) 6114 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6115 SDValue CallSeqStart = Chain; 6116 6117 // Load the return address and frame pointer so it can be move somewhere else 6118 // later. 6119 SDValue LROp, FPOp; 6120 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6121 6122 // Set up a copy of the stack pointer for use loading and storing any 6123 // arguments that may not fit in the registers available for argument 6124 // passing. 6125 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6126 6127 // Figure out which arguments are going to go in registers, and which in 6128 // memory. Also, if this is a vararg function, floating point operations 6129 // must be stored to our stack, and loaded into integer regs as well, if 6130 // any integer regs are available for argument passing. 6131 unsigned ArgOffset = LinkageSize; 6132 6133 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6134 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6135 6136 SmallVector<SDValue, 8> MemOpChains; 6137 for (unsigned i = 0; i != NumOps; ++i) { 6138 SDValue Arg = OutVals[i]; 6139 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6140 EVT ArgVT = Outs[i].VT; 6141 EVT OrigVT = Outs[i].ArgVT; 6142 6143 // PtrOff will be used to store the current argument to the stack if a 6144 // register cannot be found for it. 6145 SDValue PtrOff; 6146 6147 // We re-align the argument offset for each argument, except when using the 6148 // fast calling convention, when we need to make sure we do that only when 6149 // we'll actually use a stack slot. 6150 auto ComputePtrOff = [&]() { 6151 /* Respect alignment of argument on the stack. */ 6152 auto Alignment = 6153 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6154 ArgOffset = alignTo(ArgOffset, Alignment); 6155 6156 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6157 6158 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6159 }; 6160 6161 if (!IsFastCall) { 6162 ComputePtrOff(); 6163 6164 /* Compute GPR index associated with argument offset. */ 6165 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6166 GPR_idx = std::min(GPR_idx, NumGPRs); 6167 } 6168 6169 // Promote integers to 64-bit values. 6170 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6171 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6172 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6173 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6174 } 6175 6176 // FIXME memcpy is used way more than necessary. Correctness first. 6177 // Note: "by value" is code for passing a structure by value, not 6178 // basic types. 6179 if (Flags.isByVal()) { 6180 // Note: Size includes alignment padding, so 6181 // struct x { short a; char b; } 6182 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6183 // These are the proper values we need for right-justifying the 6184 // aggregate in a parameter register. 6185 unsigned Size = Flags.getByValSize(); 6186 6187 // An empty aggregate parameter takes up no storage and no 6188 // registers. 6189 if (Size == 0) 6190 continue; 6191 6192 if (IsFastCall) 6193 ComputePtrOff(); 6194 6195 // All aggregates smaller than 8 bytes must be passed right-justified. 6196 if (Size==1 || Size==2 || Size==4) { 6197 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6198 if (GPR_idx != NumGPRs) { 6199 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6200 MachinePointerInfo(), VT); 6201 MemOpChains.push_back(Load.getValue(1)); 6202 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6203 6204 ArgOffset += PtrByteSize; 6205 continue; 6206 } 6207 } 6208 6209 if (GPR_idx == NumGPRs && Size < 8) { 6210 SDValue AddPtr = PtrOff; 6211 if (!isLittleEndian) { 6212 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6213 PtrOff.getValueType()); 6214 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6215 } 6216 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6217 CallSeqStart, 6218 Flags, DAG, dl); 6219 ArgOffset += PtrByteSize; 6220 continue; 6221 } 6222 // Copy entire object into memory. There are cases where gcc-generated 6223 // code assumes it is there, even if it could be put entirely into 6224 // registers. (This is not what the doc says.) 6225 6226 // FIXME: The above statement is likely due to a misunderstanding of the 6227 // documents. All arguments must be copied into the parameter area BY 6228 // THE CALLEE in the event that the callee takes the address of any 6229 // formal argument. That has not yet been implemented. However, it is 6230 // reasonable to use the stack area as a staging area for the register 6231 // load. 6232 6233 // Skip this for small aggregates, as we will use the same slot for a 6234 // right-justified copy, below. 6235 if (Size >= 8) 6236 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6237 CallSeqStart, 6238 Flags, DAG, dl); 6239 6240 // When a register is available, pass a small aggregate right-justified. 6241 if (Size < 8 && GPR_idx != NumGPRs) { 6242 // The easiest way to get this right-justified in a register 6243 // is to copy the structure into the rightmost portion of a 6244 // local variable slot, then load the whole slot into the 6245 // register. 6246 // FIXME: The memcpy seems to produce pretty awful code for 6247 // small aggregates, particularly for packed ones. 6248 // FIXME: It would be preferable to use the slot in the 6249 // parameter save area instead of a new local variable. 6250 SDValue AddPtr = PtrOff; 6251 if (!isLittleEndian) { 6252 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6253 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6254 } 6255 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6256 CallSeqStart, 6257 Flags, DAG, dl); 6258 6259 // Load the slot into the register. 6260 SDValue Load = 6261 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6262 MemOpChains.push_back(Load.getValue(1)); 6263 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6264 6265 // Done with this argument. 6266 ArgOffset += PtrByteSize; 6267 continue; 6268 } 6269 6270 // For aggregates larger than PtrByteSize, copy the pieces of the 6271 // object that fit into registers from the parameter save area. 6272 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6273 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6274 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6275 if (GPR_idx != NumGPRs) { 6276 SDValue Load = 6277 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6278 MemOpChains.push_back(Load.getValue(1)); 6279 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6280 ArgOffset += PtrByteSize; 6281 } else { 6282 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6283 break; 6284 } 6285 } 6286 continue; 6287 } 6288 6289 switch (Arg.getSimpleValueType().SimpleTy) { 6290 default: llvm_unreachable("Unexpected ValueType for argument!"); 6291 case MVT::i1: 6292 case MVT::i32: 6293 case MVT::i64: 6294 if (Flags.isNest()) { 6295 // The 'nest' parameter, if any, is passed in R11. 6296 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6297 break; 6298 } 6299 6300 // These can be scalar arguments or elements of an integer array type 6301 // passed directly. Clang may use those instead of "byval" aggregate 6302 // types to avoid forcing arguments to memory unnecessarily. 6303 if (GPR_idx != NumGPRs) { 6304 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6305 } else { 6306 if (IsFastCall) 6307 ComputePtrOff(); 6308 6309 assert(HasParameterArea && 6310 "Parameter area must exist to pass an argument in memory."); 6311 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6312 true, CFlags.IsTailCall, false, MemOpChains, 6313 TailCallArguments, dl); 6314 if (IsFastCall) 6315 ArgOffset += PtrByteSize; 6316 } 6317 if (!IsFastCall) 6318 ArgOffset += PtrByteSize; 6319 break; 6320 case MVT::f32: 6321 case MVT::f64: { 6322 // These can be scalar arguments or elements of a float array type 6323 // passed directly. The latter are used to implement ELFv2 homogenous 6324 // float aggregates. 6325 6326 // Named arguments go into FPRs first, and once they overflow, the 6327 // remaining arguments go into GPRs and then the parameter save area. 6328 // Unnamed arguments for vararg functions always go to GPRs and 6329 // then the parameter save area. For now, put all arguments to vararg 6330 // routines always in both locations (FPR *and* GPR or stack slot). 6331 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6332 bool NeededLoad = false; 6333 6334 // First load the argument into the next available FPR. 6335 if (FPR_idx != NumFPRs) 6336 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6337 6338 // Next, load the argument into GPR or stack slot if needed. 6339 if (!NeedGPROrStack) 6340 ; 6341 else if (GPR_idx != NumGPRs && !IsFastCall) { 6342 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6343 // once we support fp <-> gpr moves. 6344 6345 // In the non-vararg case, this can only ever happen in the 6346 // presence of f32 array types, since otherwise we never run 6347 // out of FPRs before running out of GPRs. 6348 SDValue ArgVal; 6349 6350 // Double values are always passed in a single GPR. 6351 if (Arg.getValueType() != MVT::f32) { 6352 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6353 6354 // Non-array float values are extended and passed in a GPR. 6355 } else if (!Flags.isInConsecutiveRegs()) { 6356 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6357 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6358 6359 // If we have an array of floats, we collect every odd element 6360 // together with its predecessor into one GPR. 6361 } else if (ArgOffset % PtrByteSize != 0) { 6362 SDValue Lo, Hi; 6363 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6364 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6365 if (!isLittleEndian) 6366 std::swap(Lo, Hi); 6367 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6368 6369 // The final element, if even, goes into the first half of a GPR. 6370 } else if (Flags.isInConsecutiveRegsLast()) { 6371 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6372 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6373 if (!isLittleEndian) 6374 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6375 DAG.getConstant(32, dl, MVT::i32)); 6376 6377 // Non-final even elements are skipped; they will be handled 6378 // together the with subsequent argument on the next go-around. 6379 } else 6380 ArgVal = SDValue(); 6381 6382 if (ArgVal.getNode()) 6383 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6384 } else { 6385 if (IsFastCall) 6386 ComputePtrOff(); 6387 6388 // Single-precision floating-point values are mapped to the 6389 // second (rightmost) word of the stack doubleword. 6390 if (Arg.getValueType() == MVT::f32 && 6391 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6392 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6393 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6394 } 6395 6396 assert(HasParameterArea && 6397 "Parameter area must exist to pass an argument in memory."); 6398 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6399 true, CFlags.IsTailCall, false, MemOpChains, 6400 TailCallArguments, dl); 6401 6402 NeededLoad = true; 6403 } 6404 // When passing an array of floats, the array occupies consecutive 6405 // space in the argument area; only round up to the next doubleword 6406 // at the end of the array. Otherwise, each float takes 8 bytes. 6407 if (!IsFastCall || NeededLoad) { 6408 ArgOffset += (Arg.getValueType() == MVT::f32 && 6409 Flags.isInConsecutiveRegs()) ? 4 : 8; 6410 if (Flags.isInConsecutiveRegsLast()) 6411 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6412 } 6413 break; 6414 } 6415 case MVT::v4f32: 6416 case MVT::v4i32: 6417 case MVT::v8i16: 6418 case MVT::v16i8: 6419 case MVT::v2f64: 6420 case MVT::v2i64: 6421 case MVT::v1i128: 6422 case MVT::f128: 6423 if (!Subtarget.hasQPX()) { 6424 // These can be scalar arguments or elements of a vector array type 6425 // passed directly. The latter are used to implement ELFv2 homogenous 6426 // vector aggregates. 6427 6428 // For a varargs call, named arguments go into VRs or on the stack as 6429 // usual; unnamed arguments always go to the stack or the corresponding 6430 // GPRs when within range. For now, we always put the value in both 6431 // locations (or even all three). 6432 if (CFlags.IsVarArg) { 6433 assert(HasParameterArea && 6434 "Parameter area must exist if we have a varargs call."); 6435 // We could elide this store in the case where the object fits 6436 // entirely in R registers. Maybe later. 6437 SDValue Store = 6438 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6439 MemOpChains.push_back(Store); 6440 if (VR_idx != NumVRs) { 6441 SDValue Load = 6442 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6443 MemOpChains.push_back(Load.getValue(1)); 6444 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6445 } 6446 ArgOffset += 16; 6447 for (unsigned i=0; i<16; i+=PtrByteSize) { 6448 if (GPR_idx == NumGPRs) 6449 break; 6450 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6451 DAG.getConstant(i, dl, PtrVT)); 6452 SDValue Load = 6453 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6454 MemOpChains.push_back(Load.getValue(1)); 6455 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6456 } 6457 break; 6458 } 6459 6460 // Non-varargs Altivec params go into VRs or on the stack. 6461 if (VR_idx != NumVRs) { 6462 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6463 } else { 6464 if (IsFastCall) 6465 ComputePtrOff(); 6466 6467 assert(HasParameterArea && 6468 "Parameter area must exist to pass an argument in memory."); 6469 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6470 true, CFlags.IsTailCall, true, MemOpChains, 6471 TailCallArguments, dl); 6472 if (IsFastCall) 6473 ArgOffset += 16; 6474 } 6475 6476 if (!IsFastCall) 6477 ArgOffset += 16; 6478 break; 6479 } // not QPX 6480 6481 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6482 "Invalid QPX parameter type"); 6483 6484 LLVM_FALLTHROUGH; 6485 case MVT::v4f64: 6486 case MVT::v4i1: { 6487 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6488 if (CFlags.IsVarArg) { 6489 assert(HasParameterArea && 6490 "Parameter area must exist if we have a varargs call."); 6491 // We could elide this store in the case where the object fits 6492 // entirely in R registers. Maybe later. 6493 SDValue Store = 6494 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6495 MemOpChains.push_back(Store); 6496 if (QFPR_idx != NumQFPRs) { 6497 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6498 PtrOff, MachinePointerInfo()); 6499 MemOpChains.push_back(Load.getValue(1)); 6500 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6501 } 6502 ArgOffset += (IsF32 ? 16 : 32); 6503 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6504 if (GPR_idx == NumGPRs) 6505 break; 6506 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6507 DAG.getConstant(i, dl, PtrVT)); 6508 SDValue Load = 6509 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6510 MemOpChains.push_back(Load.getValue(1)); 6511 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6512 } 6513 break; 6514 } 6515 6516 // Non-varargs QPX params go into registers or on the stack. 6517 if (QFPR_idx != NumQFPRs) { 6518 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6519 } else { 6520 if (IsFastCall) 6521 ComputePtrOff(); 6522 6523 assert(HasParameterArea && 6524 "Parameter area must exist to pass an argument in memory."); 6525 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6526 true, CFlags.IsTailCall, true, MemOpChains, 6527 TailCallArguments, dl); 6528 if (IsFastCall) 6529 ArgOffset += (IsF32 ? 16 : 32); 6530 } 6531 6532 if (!IsFastCall) 6533 ArgOffset += (IsF32 ? 16 : 32); 6534 break; 6535 } 6536 } 6537 } 6538 6539 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6540 "mismatch in size of parameter area"); 6541 (void)NumBytesActuallyUsed; 6542 6543 if (!MemOpChains.empty()) 6544 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6545 6546 // Check if this is an indirect call (MTCTR/BCTRL). 6547 // See prepareDescriptorIndirectCall and buildCallOperands for more 6548 // information about calls through function pointers in the 64-bit SVR4 ABI. 6549 if (CFlags.IsIndirect) { 6550 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6551 // caller in the TOC save area. 6552 if (isTOCSaveRestoreRequired(Subtarget)) { 6553 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6554 // Load r2 into a virtual register and store it to the TOC save area. 6555 setUsesTOCBasePtr(DAG); 6556 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6557 // TOC save area offset. 6558 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6559 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6560 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6561 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6562 MachinePointerInfo::getStack( 6563 DAG.getMachineFunction(), TOCSaveOffset)); 6564 } 6565 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6566 // This does not mean the MTCTR instruction must use R12; it's easier 6567 // to model this as an extra parameter, so do that. 6568 if (isELFv2ABI && !CFlags.IsPatchPoint) 6569 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6570 } 6571 6572 // Build a sequence of copy-to-reg nodes chained together with token chain 6573 // and flag operands which copy the outgoing args into the appropriate regs. 6574 SDValue InFlag; 6575 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6576 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6577 RegsToPass[i].second, InFlag); 6578 InFlag = Chain.getValue(1); 6579 } 6580 6581 if (CFlags.IsTailCall && !IsSibCall) 6582 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6583 TailCallArguments); 6584 6585 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6586 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6587 } 6588 6589 SDValue PPCTargetLowering::LowerCall_Darwin( 6590 SDValue Chain, SDValue Callee, CallFlags CFlags, 6591 const SmallVectorImpl<ISD::OutputArg> &Outs, 6592 const SmallVectorImpl<SDValue> &OutVals, 6593 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6594 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6595 const CallBase *CB) const { 6596 unsigned NumOps = Outs.size(); 6597 6598 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6599 bool isPPC64 = PtrVT == MVT::i64; 6600 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6601 6602 MachineFunction &MF = DAG.getMachineFunction(); 6603 6604 // Mark this function as potentially containing a function that contains a 6605 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6606 // and restoring the callers stack pointer in this functions epilog. This is 6607 // done because by tail calling the called function might overwrite the value 6608 // in this function's (MF) stack pointer stack slot 0(SP). 6609 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6610 CFlags.CallConv == CallingConv::Fast) 6611 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6612 6613 // Count how many bytes are to be pushed on the stack, including the linkage 6614 // area, and parameter passing area. We start with 24/48 bytes, which is 6615 // prereserved space for [SP][CR][LR][3 x unused]. 6616 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6617 unsigned NumBytes = LinkageSize; 6618 6619 // Add up all the space actually used. 6620 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6621 // they all go in registers, but we must reserve stack space for them for 6622 // possible use by the caller. In varargs or 64-bit calls, parameters are 6623 // assigned stack space in order, with padding so Altivec parameters are 6624 // 16-byte aligned. 6625 unsigned nAltivecParamsAtEnd = 0; 6626 for (unsigned i = 0; i != NumOps; ++i) { 6627 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6628 EVT ArgVT = Outs[i].VT; 6629 // Varargs Altivec parameters are padded to a 16 byte boundary. 6630 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6631 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6632 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6633 if (!CFlags.IsVarArg && !isPPC64) { 6634 // Non-varargs Altivec parameters go after all the non-Altivec 6635 // parameters; handle those later so we know how much padding we need. 6636 nAltivecParamsAtEnd++; 6637 continue; 6638 } 6639 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6640 NumBytes = ((NumBytes+15)/16)*16; 6641 } 6642 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6643 } 6644 6645 // Allow for Altivec parameters at the end, if needed. 6646 if (nAltivecParamsAtEnd) { 6647 NumBytes = ((NumBytes+15)/16)*16; 6648 NumBytes += 16*nAltivecParamsAtEnd; 6649 } 6650 6651 // The prolog code of the callee may store up to 8 GPR argument registers to 6652 // the stack, allowing va_start to index over them in memory if its varargs. 6653 // Because we cannot tell if this is needed on the caller side, we have to 6654 // conservatively assume that it is needed. As such, make sure we have at 6655 // least enough stack space for the caller to store the 8 GPRs. 6656 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6657 6658 // Tail call needs the stack to be aligned. 6659 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6660 CFlags.CallConv == CallingConv::Fast) 6661 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6662 6663 // Calculate by how many bytes the stack has to be adjusted in case of tail 6664 // call optimization. 6665 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6666 6667 // To protect arguments on the stack from being clobbered in a tail call, 6668 // force all the loads to happen before doing any other lowering. 6669 if (CFlags.IsTailCall) 6670 Chain = DAG.getStackArgumentTokenFactor(Chain); 6671 6672 // Adjust the stack pointer for the new arguments... 6673 // These operations are automatically eliminated by the prolog/epilog pass 6674 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6675 SDValue CallSeqStart = Chain; 6676 6677 // Load the return address and frame pointer so it can be move somewhere else 6678 // later. 6679 SDValue LROp, FPOp; 6680 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6681 6682 // Set up a copy of the stack pointer for use loading and storing any 6683 // arguments that may not fit in the registers available for argument 6684 // passing. 6685 SDValue StackPtr; 6686 if (isPPC64) 6687 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6688 else 6689 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6690 6691 // Figure out which arguments are going to go in registers, and which in 6692 // memory. Also, if this is a vararg function, floating point operations 6693 // must be stored to our stack, and loaded into integer regs as well, if 6694 // any integer regs are available for argument passing. 6695 unsigned ArgOffset = LinkageSize; 6696 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6697 6698 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6699 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6700 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6701 }; 6702 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6703 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6704 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6705 }; 6706 static const MCPhysReg VR[] = { 6707 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6708 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6709 }; 6710 const unsigned NumGPRs = array_lengthof(GPR_32); 6711 const unsigned NumFPRs = 13; 6712 const unsigned NumVRs = array_lengthof(VR); 6713 6714 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6715 6716 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6717 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6718 6719 SmallVector<SDValue, 8> MemOpChains; 6720 for (unsigned i = 0; i != NumOps; ++i) { 6721 SDValue Arg = OutVals[i]; 6722 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6723 6724 // PtrOff will be used to store the current argument to the stack if a 6725 // register cannot be found for it. 6726 SDValue PtrOff; 6727 6728 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6729 6730 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6731 6732 // On PPC64, promote integers to 64-bit values. 6733 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6734 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6735 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6736 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6737 } 6738 6739 // FIXME memcpy is used way more than necessary. Correctness first. 6740 // Note: "by value" is code for passing a structure by value, not 6741 // basic types. 6742 if (Flags.isByVal()) { 6743 unsigned Size = Flags.getByValSize(); 6744 // Very small objects are passed right-justified. Everything else is 6745 // passed left-justified. 6746 if (Size==1 || Size==2) { 6747 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6748 if (GPR_idx != NumGPRs) { 6749 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6750 MachinePointerInfo(), VT); 6751 MemOpChains.push_back(Load.getValue(1)); 6752 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6753 6754 ArgOffset += PtrByteSize; 6755 } else { 6756 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6757 PtrOff.getValueType()); 6758 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6759 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6760 CallSeqStart, 6761 Flags, DAG, dl); 6762 ArgOffset += PtrByteSize; 6763 } 6764 continue; 6765 } 6766 // Copy entire object into memory. There are cases where gcc-generated 6767 // code assumes it is there, even if it could be put entirely into 6768 // registers. (This is not what the doc says.) 6769 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6770 CallSeqStart, 6771 Flags, DAG, dl); 6772 6773 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6774 // copy the pieces of the object that fit into registers from the 6775 // parameter save area. 6776 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6777 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6778 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6779 if (GPR_idx != NumGPRs) { 6780 SDValue Load = 6781 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6782 MemOpChains.push_back(Load.getValue(1)); 6783 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6784 ArgOffset += PtrByteSize; 6785 } else { 6786 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6787 break; 6788 } 6789 } 6790 continue; 6791 } 6792 6793 switch (Arg.getSimpleValueType().SimpleTy) { 6794 default: llvm_unreachable("Unexpected ValueType for argument!"); 6795 case MVT::i1: 6796 case MVT::i32: 6797 case MVT::i64: 6798 if (GPR_idx != NumGPRs) { 6799 if (Arg.getValueType() == MVT::i1) 6800 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6801 6802 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6803 } else { 6804 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6805 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6806 TailCallArguments, dl); 6807 } 6808 ArgOffset += PtrByteSize; 6809 break; 6810 case MVT::f32: 6811 case MVT::f64: 6812 if (FPR_idx != NumFPRs) { 6813 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6814 6815 if (CFlags.IsVarArg) { 6816 SDValue Store = 6817 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6818 MemOpChains.push_back(Store); 6819 6820 // Float varargs are always shadowed in available integer registers 6821 if (GPR_idx != NumGPRs) { 6822 SDValue Load = 6823 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6824 MemOpChains.push_back(Load.getValue(1)); 6825 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6826 } 6827 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6828 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6829 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6830 SDValue Load = 6831 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6832 MemOpChains.push_back(Load.getValue(1)); 6833 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6834 } 6835 } else { 6836 // If we have any FPRs remaining, we may also have GPRs remaining. 6837 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6838 // GPRs. 6839 if (GPR_idx != NumGPRs) 6840 ++GPR_idx; 6841 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6842 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6843 ++GPR_idx; 6844 } 6845 } else 6846 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6847 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6848 TailCallArguments, dl); 6849 if (isPPC64) 6850 ArgOffset += 8; 6851 else 6852 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6853 break; 6854 case MVT::v4f32: 6855 case MVT::v4i32: 6856 case MVT::v8i16: 6857 case MVT::v16i8: 6858 if (CFlags.IsVarArg) { 6859 // These go aligned on the stack, or in the corresponding R registers 6860 // when within range. The Darwin PPC ABI doc claims they also go in 6861 // V registers; in fact gcc does this only for arguments that are 6862 // prototyped, not for those that match the ... We do it for all 6863 // arguments, seems to work. 6864 while (ArgOffset % 16 !=0) { 6865 ArgOffset += PtrByteSize; 6866 if (GPR_idx != NumGPRs) 6867 GPR_idx++; 6868 } 6869 // We could elide this store in the case where the object fits 6870 // entirely in R registers. Maybe later. 6871 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6872 DAG.getConstant(ArgOffset, dl, PtrVT)); 6873 SDValue Store = 6874 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6875 MemOpChains.push_back(Store); 6876 if (VR_idx != NumVRs) { 6877 SDValue Load = 6878 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6879 MemOpChains.push_back(Load.getValue(1)); 6880 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6881 } 6882 ArgOffset += 16; 6883 for (unsigned i=0; i<16; i+=PtrByteSize) { 6884 if (GPR_idx == NumGPRs) 6885 break; 6886 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6887 DAG.getConstant(i, dl, PtrVT)); 6888 SDValue Load = 6889 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6890 MemOpChains.push_back(Load.getValue(1)); 6891 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6892 } 6893 break; 6894 } 6895 6896 // Non-varargs Altivec params generally go in registers, but have 6897 // stack space allocated at the end. 6898 if (VR_idx != NumVRs) { 6899 // Doesn't have GPR space allocated. 6900 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6901 } else if (nAltivecParamsAtEnd==0) { 6902 // We are emitting Altivec params in order. 6903 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6904 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6905 TailCallArguments, dl); 6906 ArgOffset += 16; 6907 } 6908 break; 6909 } 6910 } 6911 // If all Altivec parameters fit in registers, as they usually do, 6912 // they get stack space following the non-Altivec parameters. We 6913 // don't track this here because nobody below needs it. 6914 // If there are more Altivec parameters than fit in registers emit 6915 // the stores here. 6916 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6917 unsigned j = 0; 6918 // Offset is aligned; skip 1st 12 params which go in V registers. 6919 ArgOffset = ((ArgOffset+15)/16)*16; 6920 ArgOffset += 12*16; 6921 for (unsigned i = 0; i != NumOps; ++i) { 6922 SDValue Arg = OutVals[i]; 6923 EVT ArgType = Outs[i].VT; 6924 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6925 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6926 if (++j > NumVRs) { 6927 SDValue PtrOff; 6928 // We are emitting Altivec params in order. 6929 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6930 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6931 TailCallArguments, dl); 6932 ArgOffset += 16; 6933 } 6934 } 6935 } 6936 } 6937 6938 if (!MemOpChains.empty()) 6939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6940 6941 // On Darwin, R12 must contain the address of an indirect callee. This does 6942 // not mean the MTCTR instruction must use R12; it's easier to model this as 6943 // an extra parameter, so do that. 6944 if (CFlags.IsIndirect) { 6945 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6946 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6947 PPC::R12), Callee)); 6948 } 6949 6950 // Build a sequence of copy-to-reg nodes chained together with token chain 6951 // and flag operands which copy the outgoing args into the appropriate regs. 6952 SDValue InFlag; 6953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6954 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6955 RegsToPass[i].second, InFlag); 6956 InFlag = Chain.getValue(1); 6957 } 6958 6959 if (CFlags.IsTailCall) 6960 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6961 TailCallArguments); 6962 6963 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6964 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6965 } 6966 6967 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6968 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6969 CCState &State) { 6970 6971 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6972 State.getMachineFunction().getSubtarget()); 6973 const bool IsPPC64 = Subtarget.isPPC64(); 6974 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6975 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6976 6977 assert((!ValVT.isInteger() || 6978 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6979 "Integer argument exceeds register size: should have been legalized"); 6980 6981 if (ValVT == MVT::f128) 6982 report_fatal_error("f128 is unimplemented on AIX."); 6983 6984 if (ArgFlags.isNest()) 6985 report_fatal_error("Nest arguments are unimplemented."); 6986 6987 if (ValVT.isVector() || LocVT.isVector()) 6988 report_fatal_error("Vector arguments are unimplemented on AIX."); 6989 6990 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6991 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6992 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6993 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6994 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6995 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6996 6997 if (ArgFlags.isByVal()) { 6998 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 6999 report_fatal_error("Pass-by-value arguments with alignment greater than " 7000 "register width are not supported."); 7001 7002 const unsigned ByValSize = ArgFlags.getByValSize(); 7003 7004 // An empty aggregate parameter takes up no storage and no registers, 7005 // but needs a MemLoc for a stack slot for the formal arguments side. 7006 if (ByValSize == 0) { 7007 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7008 State.getNextStackOffset(), RegVT, 7009 LocInfo)); 7010 return false; 7011 } 7012 7013 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 7014 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 7015 for (const unsigned E = Offset + StackSize; Offset < E; 7016 Offset += PtrByteSize) { 7017 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7018 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7019 else { 7020 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7021 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7022 LocInfo)); 7023 break; 7024 } 7025 } 7026 return false; 7027 } 7028 7029 // Arguments always reserve parameter save area. 7030 switch (ValVT.SimpleTy) { 7031 default: 7032 report_fatal_error("Unhandled value type for argument."); 7033 case MVT::i64: 7034 // i64 arguments should have been split to i32 for PPC32. 7035 assert(IsPPC64 && "PPC32 should have split i64 values."); 7036 LLVM_FALLTHROUGH; 7037 case MVT::i1: 7038 case MVT::i32: { 7039 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 7040 // AIX integer arguments are always passed in register width. 7041 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7042 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7043 : CCValAssign::LocInfo::ZExt; 7044 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7045 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7046 else 7047 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7048 7049 return false; 7050 } 7051 case MVT::f32: 7052 case MVT::f64: { 7053 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7054 const unsigned StoreSize = LocVT.getStoreSize(); 7055 // Floats are always 4-byte aligned in the PSA on AIX. 7056 // This includes f64 in 64-bit mode for ABI compatibility. 7057 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 7058 unsigned FReg = State.AllocateReg(FPR); 7059 if (FReg) 7060 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7061 7062 // Reserve and initialize GPRs or initialize the PSA as required. 7063 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 7064 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7065 assert(FReg && "An FPR should be available when a GPR is reserved."); 7066 if (State.isVarArg()) { 7067 // Successfully reserved GPRs are only initialized for vararg calls. 7068 // Custom handling is required for: 7069 // f64 in PPC32 needs to be split into 2 GPRs. 7070 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7071 State.addLoc( 7072 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7073 } 7074 } else { 7075 // If there are insufficient GPRs, the PSA needs to be initialized. 7076 // Initialization occurs even if an FPR was initialized for 7077 // compatibility with the AIX XL compiler. The full memory for the 7078 // argument will be initialized even if a prior word is saved in GPR. 7079 // A custom memLoc is used when the argument also passes in FPR so 7080 // that the callee handling can skip over it easily. 7081 State.addLoc( 7082 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7083 LocInfo) 7084 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7085 break; 7086 } 7087 } 7088 7089 return false; 7090 } 7091 } 7092 return true; 7093 } 7094 7095 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7096 bool IsPPC64) { 7097 assert((IsPPC64 || SVT != MVT::i64) && 7098 "i64 should have been split for 32-bit codegen."); 7099 7100 switch (SVT) { 7101 default: 7102 report_fatal_error("Unexpected value type for formal argument"); 7103 case MVT::i1: 7104 case MVT::i32: 7105 case MVT::i64: 7106 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7107 case MVT::f32: 7108 return &PPC::F4RCRegClass; 7109 case MVT::f64: 7110 return &PPC::F8RCRegClass; 7111 } 7112 } 7113 7114 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7115 SelectionDAG &DAG, SDValue ArgValue, 7116 MVT LocVT, const SDLoc &dl) { 7117 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7118 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7119 7120 if (Flags.isSExt()) 7121 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7122 DAG.getValueType(ValVT)); 7123 else if (Flags.isZExt()) 7124 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7125 DAG.getValueType(ValVT)); 7126 7127 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7128 } 7129 7130 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7131 const unsigned LASize = FL->getLinkageSize(); 7132 7133 if (PPC::GPRCRegClass.contains(Reg)) { 7134 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7135 "Reg must be a valid argument register!"); 7136 return LASize + 4 * (Reg - PPC::R3); 7137 } 7138 7139 if (PPC::G8RCRegClass.contains(Reg)) { 7140 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7141 "Reg must be a valid argument register!"); 7142 return LASize + 8 * (Reg - PPC::X3); 7143 } 7144 7145 llvm_unreachable("Only general purpose registers expected."); 7146 } 7147 7148 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7149 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7150 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7151 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7152 7153 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7154 CallConv == CallingConv::Fast) && 7155 "Unexpected calling convention!"); 7156 7157 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7158 report_fatal_error("Tail call support is unimplemented on AIX."); 7159 7160 if (useSoftFloat()) 7161 report_fatal_error("Soft float support is unimplemented on AIX."); 7162 7163 const PPCSubtarget &Subtarget = 7164 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7165 if (Subtarget.hasQPX()) 7166 report_fatal_error("QPX support is not supported on AIX."); 7167 7168 const bool IsPPC64 = Subtarget.isPPC64(); 7169 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7170 7171 // Assign locations to all of the incoming arguments. 7172 SmallVector<CCValAssign, 16> ArgLocs; 7173 MachineFunction &MF = DAG.getMachineFunction(); 7174 MachineFrameInfo &MFI = MF.getFrameInfo(); 7175 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7176 7177 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7178 // Reserve space for the linkage area on the stack. 7179 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7180 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7181 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7182 7183 SmallVector<SDValue, 8> MemOps; 7184 7185 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7186 CCValAssign &VA = ArgLocs[I++]; 7187 MVT LocVT = VA.getLocVT(); 7188 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7189 7190 // For compatibility with the AIX XL compiler, the float args in the 7191 // parameter save area are initialized even if the argument is available 7192 // in register. The caller is required to initialize both the register 7193 // and memory, however, the callee can choose to expect it in either. 7194 // The memloc is dismissed here because the argument is retrieved from 7195 // the register. 7196 if (VA.isMemLoc() && VA.needsCustom()) 7197 continue; 7198 7199 if (Flags.isByVal() && VA.isMemLoc()) { 7200 const unsigned Size = 7201 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7202 PtrByteSize); 7203 const int FI = MF.getFrameInfo().CreateFixedObject( 7204 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7205 /* IsAliased */ true); 7206 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7207 InVals.push_back(FIN); 7208 7209 continue; 7210 } 7211 7212 if (Flags.isByVal()) { 7213 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7214 7215 const MCPhysReg ArgReg = VA.getLocReg(); 7216 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7217 7218 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7219 report_fatal_error("Over aligned byvals not supported yet."); 7220 7221 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7222 const int FI = MF.getFrameInfo().CreateFixedObject( 7223 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7224 /* IsAliased */ true); 7225 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7226 InVals.push_back(FIN); 7227 7228 // Add live ins for all the RegLocs for the same ByVal. 7229 const TargetRegisterClass *RegClass = 7230 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7231 7232 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7233 unsigned Offset) { 7234 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7235 // Since the callers side has left justified the aggregate in the 7236 // register, we can simply store the entire register into the stack 7237 // slot. 7238 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7239 // The store to the fixedstack object is needed becuase accessing a 7240 // field of the ByVal will use a gep and load. Ideally we will optimize 7241 // to extracting the value from the register directly, and elide the 7242 // stores when the arguments address is not taken, but that will need to 7243 // be future work. 7244 SDValue Store = 7245 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7246 DAG.getObjectPtrOffset(dl, FIN, Offset), 7247 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7248 7249 MemOps.push_back(Store); 7250 }; 7251 7252 unsigned Offset = 0; 7253 HandleRegLoc(VA.getLocReg(), Offset); 7254 Offset += PtrByteSize; 7255 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7256 Offset += PtrByteSize) { 7257 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7258 "RegLocs should be for ByVal argument."); 7259 7260 const CCValAssign RL = ArgLocs[I++]; 7261 HandleRegLoc(RL.getLocReg(), Offset); 7262 } 7263 7264 if (Offset != StackSize) { 7265 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7266 "Expected MemLoc for remaining bytes."); 7267 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7268 // Consume the MemLoc.The InVal has already been emitted, so nothing 7269 // more needs to be done. 7270 ++I; 7271 } 7272 7273 continue; 7274 } 7275 7276 EVT ValVT = VA.getValVT(); 7277 if (VA.isRegLoc() && !VA.needsCustom()) { 7278 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7279 unsigned VReg = 7280 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7281 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7282 if (ValVT.isScalarInteger() && 7283 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7284 ArgValue = 7285 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7286 } 7287 InVals.push_back(ArgValue); 7288 continue; 7289 } 7290 if (VA.isMemLoc()) { 7291 const unsigned LocSize = LocVT.getStoreSize(); 7292 const unsigned ValSize = ValVT.getStoreSize(); 7293 assert((ValSize <= LocSize) && 7294 "Object size is larger than size of MemLoc"); 7295 int CurArgOffset = VA.getLocMemOffset(); 7296 // Objects are right-justified because AIX is big-endian. 7297 if (LocSize > ValSize) 7298 CurArgOffset += LocSize - ValSize; 7299 // Potential tail calls could cause overwriting of argument stack slots. 7300 const bool IsImmutable = 7301 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7302 (CallConv == CallingConv::Fast)); 7303 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7304 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7305 SDValue ArgValue = 7306 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7307 InVals.push_back(ArgValue); 7308 continue; 7309 } 7310 } 7311 7312 // On AIX a minimum of 8 words is saved to the parameter save area. 7313 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7314 // Area that is at least reserved in the caller of this function. 7315 unsigned CallerReservedArea = 7316 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7317 7318 // Set the size that is at least reserved in caller of this function. Tail 7319 // call optimized function's reserved stack space needs to be aligned so 7320 // that taking the difference between two stack areas will result in an 7321 // aligned stack. 7322 CallerReservedArea = 7323 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7324 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7325 FuncInfo->setMinReservedArea(CallerReservedArea); 7326 7327 if (isVarArg) { 7328 FuncInfo->setVarArgsFrameIndex( 7329 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7330 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7331 7332 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7333 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7334 7335 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7336 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7337 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7338 7339 // The fixed integer arguments of a variadic function are stored to the 7340 // VarArgsFrameIndex on the stack so that they may be loaded by 7341 // dereferencing the result of va_next. 7342 for (unsigned GPRIndex = 7343 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7344 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7345 7346 const unsigned VReg = 7347 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7348 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7349 7350 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7351 SDValue Store = 7352 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7353 MemOps.push_back(Store); 7354 // Increment the address for the next argument to store. 7355 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7356 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7357 } 7358 } 7359 7360 if (!MemOps.empty()) 7361 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7362 7363 return Chain; 7364 } 7365 7366 SDValue PPCTargetLowering::LowerCall_AIX( 7367 SDValue Chain, SDValue Callee, CallFlags CFlags, 7368 const SmallVectorImpl<ISD::OutputArg> &Outs, 7369 const SmallVectorImpl<SDValue> &OutVals, 7370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7372 const CallBase *CB) const { 7373 7374 assert((CFlags.CallConv == CallingConv::C || 7375 CFlags.CallConv == CallingConv::Cold || 7376 CFlags.CallConv == CallingConv::Fast) && 7377 "Unexpected calling convention!"); 7378 7379 if (CFlags.IsPatchPoint) 7380 report_fatal_error("This call type is unimplemented on AIX."); 7381 7382 const PPCSubtarget& Subtarget = 7383 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7384 if (Subtarget.hasQPX()) 7385 report_fatal_error("QPX is not supported on AIX."); 7386 if (Subtarget.hasAltivec()) 7387 report_fatal_error("Altivec support is unimplemented on AIX."); 7388 7389 MachineFunction &MF = DAG.getMachineFunction(); 7390 SmallVector<CCValAssign, 16> ArgLocs; 7391 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7392 *DAG.getContext()); 7393 7394 // Reserve space for the linkage save area (LSA) on the stack. 7395 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7396 // [SP][CR][LR][2 x reserved][TOC]. 7397 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7398 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7399 const bool IsPPC64 = Subtarget.isPPC64(); 7400 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7401 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7402 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7403 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7404 7405 // The prolog code of the callee may store up to 8 GPR argument registers to 7406 // the stack, allowing va_start to index over them in memory if the callee 7407 // is variadic. 7408 // Because we cannot tell if this is needed on the caller side, we have to 7409 // conservatively assume that it is needed. As such, make sure we have at 7410 // least enough stack space for the caller to store the 8 GPRs. 7411 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7412 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7413 CCInfo.getNextStackOffset()); 7414 7415 // Adjust the stack pointer for the new arguments... 7416 // These operations are automatically eliminated by the prolog/epilog pass. 7417 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7418 SDValue CallSeqStart = Chain; 7419 7420 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7421 SmallVector<SDValue, 8> MemOpChains; 7422 7423 // Set up a copy of the stack pointer for loading and storing any 7424 // arguments that may not fit in the registers available for argument 7425 // passing. 7426 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7427 : DAG.getRegister(PPC::R1, MVT::i32); 7428 7429 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7430 const unsigned ValNo = ArgLocs[I].getValNo(); 7431 SDValue Arg = OutVals[ValNo]; 7432 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7433 7434 if (Flags.isByVal()) { 7435 const unsigned ByValSize = Flags.getByValSize(); 7436 7437 // Nothing to do for zero-sized ByVals on the caller side. 7438 if (!ByValSize) { 7439 ++I; 7440 continue; 7441 } 7442 7443 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7444 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7445 (LoadOffset != 0) 7446 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7447 : Arg, 7448 MachinePointerInfo(), VT); 7449 }; 7450 7451 unsigned LoadOffset = 0; 7452 7453 // Initialize registers, which are fully occupied by the by-val argument. 7454 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7455 SDValue Load = GetLoad(PtrVT, LoadOffset); 7456 MemOpChains.push_back(Load.getValue(1)); 7457 LoadOffset += PtrByteSize; 7458 const CCValAssign &ByValVA = ArgLocs[I++]; 7459 assert(ByValVA.getValNo() == ValNo && 7460 "Unexpected location for pass-by-value argument."); 7461 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7462 } 7463 7464 if (LoadOffset == ByValSize) 7465 continue; 7466 7467 // There must be one more loc to handle the remainder. 7468 assert(ArgLocs[I].getValNo() == ValNo && 7469 "Expected additional location for by-value argument."); 7470 7471 if (ArgLocs[I].isMemLoc()) { 7472 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7473 const CCValAssign &ByValVA = ArgLocs[I++]; 7474 ISD::ArgFlagsTy MemcpyFlags = Flags; 7475 // Only memcpy the bytes that don't pass in register. 7476 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7477 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7478 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7479 : Arg, 7480 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7481 CallSeqStart, MemcpyFlags, DAG, dl); 7482 continue; 7483 } 7484 7485 // Initialize the final register residue. 7486 // Any residue that occupies the final by-val arg register must be 7487 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7488 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7489 // 2 and 1 byte loads. 7490 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7491 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7492 "Unexpected register residue for by-value argument."); 7493 SDValue ResidueVal; 7494 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7495 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7496 const MVT VT = 7497 N == 1 ? MVT::i8 7498 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7499 SDValue Load = GetLoad(VT, LoadOffset); 7500 MemOpChains.push_back(Load.getValue(1)); 7501 LoadOffset += N; 7502 Bytes += N; 7503 7504 // By-val arguments are passed left-justfied in register. 7505 // Every load here needs to be shifted, otherwise a full register load 7506 // should have been used. 7507 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7508 "Unexpected load emitted during handling of pass-by-value " 7509 "argument."); 7510 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7511 EVT ShiftAmountTy = 7512 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7513 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7514 SDValue ShiftedLoad = 7515 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7516 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7517 ShiftedLoad) 7518 : ShiftedLoad; 7519 } 7520 7521 const CCValAssign &ByValVA = ArgLocs[I++]; 7522 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7523 continue; 7524 } 7525 7526 CCValAssign &VA = ArgLocs[I++]; 7527 const MVT LocVT = VA.getLocVT(); 7528 const MVT ValVT = VA.getValVT(); 7529 7530 switch (VA.getLocInfo()) { 7531 default: 7532 report_fatal_error("Unexpected argument extension type."); 7533 case CCValAssign::Full: 7534 break; 7535 case CCValAssign::ZExt: 7536 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7537 break; 7538 case CCValAssign::SExt: 7539 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7540 break; 7541 } 7542 7543 if (VA.isRegLoc() && !VA.needsCustom()) { 7544 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7545 continue; 7546 } 7547 7548 if (VA.isMemLoc()) { 7549 SDValue PtrOff = 7550 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7551 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7552 MemOpChains.push_back( 7553 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7554 7555 continue; 7556 } 7557 7558 // Custom handling is used for GPR initializations for vararg float 7559 // arguments. 7560 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7561 ValVT.isFloatingPoint() && LocVT.isInteger() && 7562 "Unexpected register handling for calling convention."); 7563 7564 SDValue ArgAsInt = 7565 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7566 7567 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7568 // f32 in 32-bit GPR 7569 // f64 in 64-bit GPR 7570 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7571 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7572 // f32 in 64-bit GPR. 7573 RegsToPass.push_back(std::make_pair( 7574 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7575 else { 7576 // f64 in two 32-bit GPRs 7577 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7578 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7579 "Unexpected custom register for argument!"); 7580 CCValAssign &GPR1 = VA; 7581 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7582 DAG.getConstant(32, dl, MVT::i8)); 7583 RegsToPass.push_back(std::make_pair( 7584 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7585 7586 if (I != E) { 7587 // If only 1 GPR was available, there will only be one custom GPR and 7588 // the argument will also pass in memory. 7589 CCValAssign &PeekArg = ArgLocs[I]; 7590 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7591 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7592 CCValAssign &GPR2 = ArgLocs[I++]; 7593 RegsToPass.push_back(std::make_pair( 7594 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7595 } 7596 } 7597 } 7598 } 7599 7600 if (!MemOpChains.empty()) 7601 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7602 7603 // For indirect calls, we need to save the TOC base to the stack for 7604 // restoration after the call. 7605 if (CFlags.IsIndirect) { 7606 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7607 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7608 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7609 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7610 const unsigned TOCSaveOffset = 7611 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7612 7613 setUsesTOCBasePtr(DAG); 7614 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7615 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7616 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7617 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7618 Chain = DAG.getStore( 7619 Val.getValue(1), dl, Val, AddPtr, 7620 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7621 } 7622 7623 // Build a sequence of copy-to-reg nodes chained together with token chain 7624 // and flag operands which copy the outgoing args into the appropriate regs. 7625 SDValue InFlag; 7626 for (auto Reg : RegsToPass) { 7627 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7628 InFlag = Chain.getValue(1); 7629 } 7630 7631 const int SPDiff = 0; 7632 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7633 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7634 } 7635 7636 bool 7637 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7638 MachineFunction &MF, bool isVarArg, 7639 const SmallVectorImpl<ISD::OutputArg> &Outs, 7640 LLVMContext &Context) const { 7641 SmallVector<CCValAssign, 16> RVLocs; 7642 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7643 return CCInfo.CheckReturn( 7644 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7645 ? RetCC_PPC_Cold 7646 : RetCC_PPC); 7647 } 7648 7649 SDValue 7650 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7651 bool isVarArg, 7652 const SmallVectorImpl<ISD::OutputArg> &Outs, 7653 const SmallVectorImpl<SDValue> &OutVals, 7654 const SDLoc &dl, SelectionDAG &DAG) const { 7655 SmallVector<CCValAssign, 16> RVLocs; 7656 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7657 *DAG.getContext()); 7658 CCInfo.AnalyzeReturn(Outs, 7659 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7660 ? RetCC_PPC_Cold 7661 : RetCC_PPC); 7662 7663 SDValue Flag; 7664 SmallVector<SDValue, 4> RetOps(1, Chain); 7665 7666 // Copy the result values into the output registers. 7667 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7668 CCValAssign &VA = RVLocs[i]; 7669 assert(VA.isRegLoc() && "Can only return in registers!"); 7670 7671 SDValue Arg = OutVals[RealResIdx]; 7672 7673 switch (VA.getLocInfo()) { 7674 default: llvm_unreachable("Unknown loc info!"); 7675 case CCValAssign::Full: break; 7676 case CCValAssign::AExt: 7677 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7678 break; 7679 case CCValAssign::ZExt: 7680 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7681 break; 7682 case CCValAssign::SExt: 7683 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7684 break; 7685 } 7686 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7687 bool isLittleEndian = Subtarget.isLittleEndian(); 7688 // Legalize ret f64 -> ret 2 x i32. 7689 SDValue SVal = 7690 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7691 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7692 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7693 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7694 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7695 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7696 Flag = Chain.getValue(1); 7697 VA = RVLocs[++i]; // skip ahead to next loc 7698 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7699 } else 7700 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7701 Flag = Chain.getValue(1); 7702 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7703 } 7704 7705 RetOps[0] = Chain; // Update chain. 7706 7707 // Add the flag if we have it. 7708 if (Flag.getNode()) 7709 RetOps.push_back(Flag); 7710 7711 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7712 } 7713 7714 SDValue 7715 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7716 SelectionDAG &DAG) const { 7717 SDLoc dl(Op); 7718 7719 // Get the correct type for integers. 7720 EVT IntVT = Op.getValueType(); 7721 7722 // Get the inputs. 7723 SDValue Chain = Op.getOperand(0); 7724 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7725 // Build a DYNAREAOFFSET node. 7726 SDValue Ops[2] = {Chain, FPSIdx}; 7727 SDVTList VTs = DAG.getVTList(IntVT); 7728 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7729 } 7730 7731 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7732 SelectionDAG &DAG) const { 7733 // When we pop the dynamic allocation we need to restore the SP link. 7734 SDLoc dl(Op); 7735 7736 // Get the correct type for pointers. 7737 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7738 7739 // Construct the stack pointer operand. 7740 bool isPPC64 = Subtarget.isPPC64(); 7741 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7742 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7743 7744 // Get the operands for the STACKRESTORE. 7745 SDValue Chain = Op.getOperand(0); 7746 SDValue SaveSP = Op.getOperand(1); 7747 7748 // Load the old link SP. 7749 SDValue LoadLinkSP = 7750 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7751 7752 // Restore the stack pointer. 7753 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7754 7755 // Store the old link SP. 7756 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7757 } 7758 7759 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7760 MachineFunction &MF = DAG.getMachineFunction(); 7761 bool isPPC64 = Subtarget.isPPC64(); 7762 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7763 7764 // Get current frame pointer save index. The users of this index will be 7765 // primarily DYNALLOC instructions. 7766 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7767 int RASI = FI->getReturnAddrSaveIndex(); 7768 7769 // If the frame pointer save index hasn't been defined yet. 7770 if (!RASI) { 7771 // Find out what the fix offset of the frame pointer save area. 7772 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7773 // Allocate the frame index for frame pointer save area. 7774 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7775 // Save the result. 7776 FI->setReturnAddrSaveIndex(RASI); 7777 } 7778 return DAG.getFrameIndex(RASI, PtrVT); 7779 } 7780 7781 SDValue 7782 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7783 MachineFunction &MF = DAG.getMachineFunction(); 7784 bool isPPC64 = Subtarget.isPPC64(); 7785 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7786 7787 // Get current frame pointer save index. The users of this index will be 7788 // primarily DYNALLOC instructions. 7789 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7790 int FPSI = FI->getFramePointerSaveIndex(); 7791 7792 // If the frame pointer save index hasn't been defined yet. 7793 if (!FPSI) { 7794 // Find out what the fix offset of the frame pointer save area. 7795 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7796 // Allocate the frame index for frame pointer save area. 7797 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7798 // Save the result. 7799 FI->setFramePointerSaveIndex(FPSI); 7800 } 7801 return DAG.getFrameIndex(FPSI, PtrVT); 7802 } 7803 7804 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7805 SelectionDAG &DAG) const { 7806 // Get the inputs. 7807 SDValue Chain = Op.getOperand(0); 7808 SDValue Size = Op.getOperand(1); 7809 SDLoc dl(Op); 7810 7811 // Get the correct type for pointers. 7812 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7813 // Negate the size. 7814 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7815 DAG.getConstant(0, dl, PtrVT), Size); 7816 // Construct a node for the frame pointer save index. 7817 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7818 // Build a DYNALLOC node. 7819 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7820 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7821 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7822 } 7823 7824 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7825 SelectionDAG &DAG) const { 7826 MachineFunction &MF = DAG.getMachineFunction(); 7827 7828 bool isPPC64 = Subtarget.isPPC64(); 7829 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7830 7831 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7832 return DAG.getFrameIndex(FI, PtrVT); 7833 } 7834 7835 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7836 SelectionDAG &DAG) const { 7837 SDLoc DL(Op); 7838 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7839 DAG.getVTList(MVT::i32, MVT::Other), 7840 Op.getOperand(0), Op.getOperand(1)); 7841 } 7842 7843 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7844 SelectionDAG &DAG) const { 7845 SDLoc DL(Op); 7846 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7847 Op.getOperand(0), Op.getOperand(1)); 7848 } 7849 7850 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7851 if (Op.getValueType().isVector()) 7852 return LowerVectorLoad(Op, DAG); 7853 7854 assert(Op.getValueType() == MVT::i1 && 7855 "Custom lowering only for i1 loads"); 7856 7857 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7858 7859 SDLoc dl(Op); 7860 LoadSDNode *LD = cast<LoadSDNode>(Op); 7861 7862 SDValue Chain = LD->getChain(); 7863 SDValue BasePtr = LD->getBasePtr(); 7864 MachineMemOperand *MMO = LD->getMemOperand(); 7865 7866 SDValue NewLD = 7867 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7868 BasePtr, MVT::i8, MMO); 7869 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7870 7871 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7872 return DAG.getMergeValues(Ops, dl); 7873 } 7874 7875 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7876 if (Op.getOperand(1).getValueType().isVector()) 7877 return LowerVectorStore(Op, DAG); 7878 7879 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7880 "Custom lowering only for i1 stores"); 7881 7882 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7883 7884 SDLoc dl(Op); 7885 StoreSDNode *ST = cast<StoreSDNode>(Op); 7886 7887 SDValue Chain = ST->getChain(); 7888 SDValue BasePtr = ST->getBasePtr(); 7889 SDValue Value = ST->getValue(); 7890 MachineMemOperand *MMO = ST->getMemOperand(); 7891 7892 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7893 Value); 7894 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7895 } 7896 7897 // FIXME: Remove this once the ANDI glue bug is fixed: 7898 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7899 assert(Op.getValueType() == MVT::i1 && 7900 "Custom lowering only for i1 results"); 7901 7902 SDLoc DL(Op); 7903 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7904 } 7905 7906 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7907 SelectionDAG &DAG) const { 7908 7909 // Implements a vector truncate that fits in a vector register as a shuffle. 7910 // We want to legalize vector truncates down to where the source fits in 7911 // a vector register (and target is therefore smaller than vector register 7912 // size). At that point legalization will try to custom lower the sub-legal 7913 // result and get here - where we can contain the truncate as a single target 7914 // operation. 7915 7916 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7917 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7918 // 7919 // We will implement it for big-endian ordering as this (where x denotes 7920 // undefined): 7921 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7922 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7923 // 7924 // The same operation in little-endian ordering will be: 7925 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7926 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7927 7928 assert(Op.getValueType().isVector() && "Vector type expected."); 7929 7930 SDLoc DL(Op); 7931 SDValue N1 = Op.getOperand(0); 7932 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7933 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7934 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7935 7936 EVT TrgVT = Op.getValueType(); 7937 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7938 EVT EltVT = TrgVT.getVectorElementType(); 7939 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7940 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7941 7942 // First list the elements we want to keep. 7943 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7944 SmallVector<int, 16> ShuffV; 7945 if (Subtarget.isLittleEndian()) 7946 for (unsigned i = 0; i < TrgNumElts; ++i) 7947 ShuffV.push_back(i * SizeMult); 7948 else 7949 for (unsigned i = 1; i <= TrgNumElts; ++i) 7950 ShuffV.push_back(i * SizeMult - 1); 7951 7952 // Populate the remaining elements with undefs. 7953 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7954 // ShuffV.push_back(i + WideNumElts); 7955 ShuffV.push_back(WideNumElts + 1); 7956 7957 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7958 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7959 } 7960 7961 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7962 /// possible. 7963 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7964 // Not FP? Not a fsel. 7965 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7966 !Op.getOperand(2).getValueType().isFloatingPoint()) 7967 return Op; 7968 7969 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7970 7971 EVT ResVT = Op.getValueType(); 7972 EVT CmpVT = Op.getOperand(0).getValueType(); 7973 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7974 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7975 SDLoc dl(Op); 7976 SDNodeFlags Flags = Op.getNode()->getFlags(); 7977 7978 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7979 // presence of infinities. 7980 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7981 switch (CC) { 7982 default: 7983 break; 7984 case ISD::SETOGT: 7985 case ISD::SETGT: 7986 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7987 case ISD::SETOLT: 7988 case ISD::SETLT: 7989 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7990 } 7991 } 7992 7993 // We might be able to do better than this under some circumstances, but in 7994 // general, fsel-based lowering of select is a finite-math-only optimization. 7995 // For more information, see section F.3 of the 2.06 ISA specification. 7996 // With ISA 3.0 7997 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7998 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7999 return Op; 8000 8001 // If the RHS of the comparison is a 0.0, we don't need to do the 8002 // subtraction at all. 8003 SDValue Sel1; 8004 if (isFloatingPointZero(RHS)) 8005 switch (CC) { 8006 default: break; // SETUO etc aren't handled by fsel. 8007 case ISD::SETNE: 8008 std::swap(TV, FV); 8009 LLVM_FALLTHROUGH; 8010 case ISD::SETEQ: 8011 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8012 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8013 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8014 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8015 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8016 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8017 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8018 case ISD::SETULT: 8019 case ISD::SETLT: 8020 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8021 LLVM_FALLTHROUGH; 8022 case ISD::SETOGE: 8023 case ISD::SETGE: 8024 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8025 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8026 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8027 case ISD::SETUGT: 8028 case ISD::SETGT: 8029 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8030 LLVM_FALLTHROUGH; 8031 case ISD::SETOLE: 8032 case ISD::SETLE: 8033 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8034 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8035 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8036 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8037 } 8038 8039 SDValue Cmp; 8040 switch (CC) { 8041 default: break; // SETUO etc aren't handled by fsel. 8042 case ISD::SETNE: 8043 std::swap(TV, FV); 8044 LLVM_FALLTHROUGH; 8045 case ISD::SETEQ: 8046 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8047 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8048 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8049 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8050 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8051 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8052 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8053 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8054 case ISD::SETULT: 8055 case ISD::SETLT: 8056 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8057 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8058 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8059 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8060 case ISD::SETOGE: 8061 case ISD::SETGE: 8062 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8063 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8064 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8065 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8066 case ISD::SETUGT: 8067 case ISD::SETGT: 8068 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8069 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8070 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8071 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8072 case ISD::SETOLE: 8073 case ISD::SETLE: 8074 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8075 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8076 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8077 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8078 } 8079 return Op; 8080 } 8081 8082 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8083 SelectionDAG &DAG, 8084 const SDLoc &dl) const { 8085 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8086 SDValue Src = Op.getOperand(0); 8087 if (Src.getValueType() == MVT::f32) 8088 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8089 8090 SDValue Tmp; 8091 switch (Op.getSimpleValueType().SimpleTy) { 8092 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8093 case MVT::i32: 8094 Tmp = DAG.getNode( 8095 Op.getOpcode() == ISD::FP_TO_SINT 8096 ? PPCISD::FCTIWZ 8097 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8098 dl, MVT::f64, Src); 8099 break; 8100 case MVT::i64: 8101 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8102 "i64 FP_TO_UINT is supported only with FPCVT"); 8103 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8104 PPCISD::FCTIDUZ, 8105 dl, MVT::f64, Src); 8106 break; 8107 } 8108 8109 // Convert the FP value to an int value through memory. 8110 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8111 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8112 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8113 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8114 MachinePointerInfo MPI = 8115 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8116 8117 // Emit a store to the stack slot. 8118 SDValue Chain; 8119 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8120 if (i32Stack) { 8121 MachineFunction &MF = DAG.getMachineFunction(); 8122 Alignment = Align(4); 8123 MachineMemOperand *MMO = 8124 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8125 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8126 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8127 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8128 } else 8129 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8130 8131 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8132 // add in a bias on big endian. 8133 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8134 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8135 DAG.getConstant(4, dl, FIPtr.getValueType())); 8136 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8137 } 8138 8139 RLI.Chain = Chain; 8140 RLI.Ptr = FIPtr; 8141 RLI.MPI = MPI; 8142 RLI.Alignment = Alignment; 8143 } 8144 8145 /// Custom lowers floating point to integer conversions to use 8146 /// the direct move instructions available in ISA 2.07 to avoid the 8147 /// need for load/store combinations. 8148 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8149 SelectionDAG &DAG, 8150 const SDLoc &dl) const { 8151 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8152 SDValue Src = Op.getOperand(0); 8153 8154 if (Src.getValueType() == MVT::f32) 8155 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8156 8157 SDValue Tmp; 8158 switch (Op.getSimpleValueType().SimpleTy) { 8159 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8160 case MVT::i32: 8161 Tmp = DAG.getNode( 8162 Op.getOpcode() == ISD::FP_TO_SINT 8163 ? PPCISD::FCTIWZ 8164 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8165 dl, MVT::f64, Src); 8166 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8167 break; 8168 case MVT::i64: 8169 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8170 "i64 FP_TO_UINT is supported only with FPCVT"); 8171 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8172 PPCISD::FCTIDUZ, 8173 dl, MVT::f64, Src); 8174 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8175 break; 8176 } 8177 return Tmp; 8178 } 8179 8180 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8181 const SDLoc &dl) const { 8182 8183 // FP to INT conversions are legal for f128. 8184 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8185 return Op; 8186 8187 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8188 // PPC (the libcall is not available). 8189 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8190 if (Op.getValueType() == MVT::i32) { 8191 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8192 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8193 MVT::f64, Op.getOperand(0), 8194 DAG.getIntPtrConstant(0, dl)); 8195 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8196 MVT::f64, Op.getOperand(0), 8197 DAG.getIntPtrConstant(1, dl)); 8198 8199 // Add the two halves of the long double in round-to-zero mode. 8200 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8201 8202 // Now use a smaller FP_TO_SINT. 8203 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8204 } 8205 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8206 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8207 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8208 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8209 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8210 // FIXME: generated code sucks. 8211 // TODO: Are there fast-math-flags to propagate to this FSUB? 8212 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8213 Op.getOperand(0), Tmp); 8214 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8215 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8216 DAG.getConstant(0x80000000, dl, MVT::i32)); 8217 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8218 Op.getOperand(0)); 8219 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8220 ISD::SETGE); 8221 } 8222 } 8223 8224 return SDValue(); 8225 } 8226 8227 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8228 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8229 8230 ReuseLoadInfo RLI; 8231 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8232 8233 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8234 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8235 } 8236 8237 // We're trying to insert a regular store, S, and then a load, L. If the 8238 // incoming value, O, is a load, we might just be able to have our load use the 8239 // address used by O. However, we don't know if anything else will store to 8240 // that address before we can load from it. To prevent this situation, we need 8241 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8242 // the same chain operand as O, we create a token factor from the chain results 8243 // of O and L, and we replace all uses of O's chain result with that token 8244 // factor (see spliceIntoChain below for this last part). 8245 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8246 ReuseLoadInfo &RLI, 8247 SelectionDAG &DAG, 8248 ISD::LoadExtType ET) const { 8249 SDLoc dl(Op); 8250 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8251 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8252 if (ET == ISD::NON_EXTLOAD && 8253 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8254 isOperationLegalOrCustom(Op.getOpcode(), 8255 Op.getOperand(0).getValueType())) { 8256 8257 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8258 return true; 8259 } 8260 8261 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8262 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8263 LD->isNonTemporal()) 8264 return false; 8265 if (LD->getMemoryVT() != MemVT) 8266 return false; 8267 8268 RLI.Ptr = LD->getBasePtr(); 8269 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8270 assert(LD->getAddressingMode() == ISD::PRE_INC && 8271 "Non-pre-inc AM on PPC?"); 8272 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8273 LD->getOffset()); 8274 } 8275 8276 RLI.Chain = LD->getChain(); 8277 RLI.MPI = LD->getPointerInfo(); 8278 RLI.IsDereferenceable = LD->isDereferenceable(); 8279 RLI.IsInvariant = LD->isInvariant(); 8280 RLI.Alignment = LD->getAlign(); 8281 RLI.AAInfo = LD->getAAInfo(); 8282 RLI.Ranges = LD->getRanges(); 8283 8284 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8285 return true; 8286 } 8287 8288 // Given the head of the old chain, ResChain, insert a token factor containing 8289 // it and NewResChain, and make users of ResChain now be users of that token 8290 // factor. 8291 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8292 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8293 SDValue NewResChain, 8294 SelectionDAG &DAG) const { 8295 if (!ResChain) 8296 return; 8297 8298 SDLoc dl(NewResChain); 8299 8300 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8301 NewResChain, DAG.getUNDEF(MVT::Other)); 8302 assert(TF.getNode() != NewResChain.getNode() && 8303 "A new TF really is required here"); 8304 8305 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8306 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8307 } 8308 8309 /// Analyze profitability of direct move 8310 /// prefer float load to int load plus direct move 8311 /// when there is no integer use of int load 8312 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8313 SDNode *Origin = Op.getOperand(0).getNode(); 8314 if (Origin->getOpcode() != ISD::LOAD) 8315 return true; 8316 8317 // If there is no LXSIBZX/LXSIHZX, like Power8, 8318 // prefer direct move if the memory size is 1 or 2 bytes. 8319 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8320 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8321 return true; 8322 8323 for (SDNode::use_iterator UI = Origin->use_begin(), 8324 UE = Origin->use_end(); 8325 UI != UE; ++UI) { 8326 8327 // Only look at the users of the loaded value. 8328 if (UI.getUse().get().getResNo() != 0) 8329 continue; 8330 8331 if (UI->getOpcode() != ISD::SINT_TO_FP && 8332 UI->getOpcode() != ISD::UINT_TO_FP) 8333 return true; 8334 } 8335 8336 return false; 8337 } 8338 8339 /// Custom lowers integer to floating point conversions to use 8340 /// the direct move instructions available in ISA 2.07 to avoid the 8341 /// need for load/store combinations. 8342 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8343 SelectionDAG &DAG, 8344 const SDLoc &dl) const { 8345 assert((Op.getValueType() == MVT::f32 || 8346 Op.getValueType() == MVT::f64) && 8347 "Invalid floating point type as target of conversion"); 8348 assert(Subtarget.hasFPCVT() && 8349 "Int to FP conversions with direct moves require FPCVT"); 8350 SDValue FP; 8351 SDValue Src = Op.getOperand(0); 8352 bool SinglePrec = Op.getValueType() == MVT::f32; 8353 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8354 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8355 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8356 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8357 8358 if (WordInt) { 8359 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8360 dl, MVT::f64, Src); 8361 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8362 } 8363 else { 8364 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8365 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8366 } 8367 8368 return FP; 8369 } 8370 8371 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8372 8373 EVT VecVT = Vec.getValueType(); 8374 assert(VecVT.isVector() && "Expected a vector type."); 8375 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8376 8377 EVT EltVT = VecVT.getVectorElementType(); 8378 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8379 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8380 8381 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8382 SmallVector<SDValue, 16> Ops(NumConcat); 8383 Ops[0] = Vec; 8384 SDValue UndefVec = DAG.getUNDEF(VecVT); 8385 for (unsigned i = 1; i < NumConcat; ++i) 8386 Ops[i] = UndefVec; 8387 8388 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8389 } 8390 8391 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8392 const SDLoc &dl) const { 8393 8394 unsigned Opc = Op.getOpcode(); 8395 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8396 "Unexpected conversion type"); 8397 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8398 "Supports conversions to v2f64/v4f32 only."); 8399 8400 bool SignedConv = Opc == ISD::SINT_TO_FP; 8401 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8402 8403 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8404 EVT WideVT = Wide.getValueType(); 8405 unsigned WideNumElts = WideVT.getVectorNumElements(); 8406 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8407 8408 SmallVector<int, 16> ShuffV; 8409 for (unsigned i = 0; i < WideNumElts; ++i) 8410 ShuffV.push_back(i + WideNumElts); 8411 8412 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8413 int SaveElts = FourEltRes ? 4 : 2; 8414 if (Subtarget.isLittleEndian()) 8415 for (int i = 0; i < SaveElts; i++) 8416 ShuffV[i * Stride] = i; 8417 else 8418 for (int i = 1; i <= SaveElts; i++) 8419 ShuffV[i * Stride - 1] = i - 1; 8420 8421 SDValue ShuffleSrc2 = 8422 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8423 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8424 8425 SDValue Extend; 8426 if (SignedConv) { 8427 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8428 EVT ExtVT = Op.getOperand(0).getValueType(); 8429 if (Subtarget.hasP9Altivec()) 8430 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8431 IntermediateVT.getVectorNumElements()); 8432 8433 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8434 DAG.getValueType(ExtVT)); 8435 } else 8436 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8437 8438 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8439 } 8440 8441 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8442 SelectionDAG &DAG) const { 8443 SDLoc dl(Op); 8444 8445 EVT InVT = Op.getOperand(0).getValueType(); 8446 EVT OutVT = Op.getValueType(); 8447 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8448 isOperationCustom(Op.getOpcode(), InVT)) 8449 return LowerINT_TO_FPVector(Op, DAG, dl); 8450 8451 // Conversions to f128 are legal. 8452 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8453 return Op; 8454 8455 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8456 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8457 return SDValue(); 8458 8459 SDValue Value = Op.getOperand(0); 8460 // The values are now known to be -1 (false) or 1 (true). To convert this 8461 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8462 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8463 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8464 8465 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8466 8467 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8468 8469 if (Op.getValueType() != MVT::v4f64) 8470 Value = DAG.getNode(ISD::FP_ROUND, dl, 8471 Op.getValueType(), Value, 8472 DAG.getIntPtrConstant(1, dl)); 8473 return Value; 8474 } 8475 8476 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8477 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8478 return SDValue(); 8479 8480 if (Op.getOperand(0).getValueType() == MVT::i1) 8481 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8482 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8483 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8484 8485 // If we have direct moves, we can do all the conversion, skip the store/load 8486 // however, without FPCVT we can't do most conversions. 8487 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8488 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8489 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8490 8491 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8492 "UINT_TO_FP is supported only with FPCVT"); 8493 8494 // If we have FCFIDS, then use it when converting to single-precision. 8495 // Otherwise, convert to double-precision and then round. 8496 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8497 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8498 : PPCISD::FCFIDS) 8499 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8500 : PPCISD::FCFID); 8501 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8502 ? MVT::f32 8503 : MVT::f64; 8504 8505 if (Op.getOperand(0).getValueType() == MVT::i64) { 8506 SDValue SINT = Op.getOperand(0); 8507 // When converting to single-precision, we actually need to convert 8508 // to double-precision first and then round to single-precision. 8509 // To avoid double-rounding effects during that operation, we have 8510 // to prepare the input operand. Bits that might be truncated when 8511 // converting to double-precision are replaced by a bit that won't 8512 // be lost at this stage, but is below the single-precision rounding 8513 // position. 8514 // 8515 // However, if -enable-unsafe-fp-math is in effect, accept double 8516 // rounding to avoid the extra overhead. 8517 if (Op.getValueType() == MVT::f32 && 8518 !Subtarget.hasFPCVT() && 8519 !DAG.getTarget().Options.UnsafeFPMath) { 8520 8521 // Twiddle input to make sure the low 11 bits are zero. (If this 8522 // is the case, we are guaranteed the value will fit into the 53 bit 8523 // mantissa of an IEEE double-precision value without rounding.) 8524 // If any of those low 11 bits were not zero originally, make sure 8525 // bit 12 (value 2048) is set instead, so that the final rounding 8526 // to single-precision gets the correct result. 8527 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8528 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8529 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8530 Round, DAG.getConstant(2047, dl, MVT::i64)); 8531 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8532 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8533 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8534 8535 // However, we cannot use that value unconditionally: if the magnitude 8536 // of the input value is small, the bit-twiddling we did above might 8537 // end up visibly changing the output. Fortunately, in that case, we 8538 // don't need to twiddle bits since the original input will convert 8539 // exactly to double-precision floating-point already. Therefore, 8540 // construct a conditional to use the original value if the top 11 8541 // bits are all sign-bit copies, and use the rounded value computed 8542 // above otherwise. 8543 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8544 SINT, DAG.getConstant(53, dl, MVT::i32)); 8545 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8546 Cond, DAG.getConstant(1, dl, MVT::i64)); 8547 Cond = DAG.getSetCC( 8548 dl, 8549 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8550 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8551 8552 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8553 } 8554 8555 ReuseLoadInfo RLI; 8556 SDValue Bits; 8557 8558 MachineFunction &MF = DAG.getMachineFunction(); 8559 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8560 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8561 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8562 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8563 } else if (Subtarget.hasLFIWAX() && 8564 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8565 MachineMemOperand *MMO = 8566 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8567 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8568 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8569 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8570 DAG.getVTList(MVT::f64, MVT::Other), 8571 Ops, MVT::i32, MMO); 8572 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8573 } else if (Subtarget.hasFPCVT() && 8574 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8575 MachineMemOperand *MMO = 8576 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8577 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8578 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8579 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8580 DAG.getVTList(MVT::f64, MVT::Other), 8581 Ops, MVT::i32, MMO); 8582 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8583 } else if (((Subtarget.hasLFIWAX() && 8584 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8585 (Subtarget.hasFPCVT() && 8586 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8587 SINT.getOperand(0).getValueType() == MVT::i32) { 8588 MachineFrameInfo &MFI = MF.getFrameInfo(); 8589 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8590 8591 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8592 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8593 8594 SDValue Store = 8595 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8596 MachinePointerInfo::getFixedStack( 8597 DAG.getMachineFunction(), FrameIdx)); 8598 8599 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8600 "Expected an i32 store"); 8601 8602 RLI.Ptr = FIdx; 8603 RLI.Chain = Store; 8604 RLI.MPI = 8605 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8606 RLI.Alignment = Align(4); 8607 8608 MachineMemOperand *MMO = 8609 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8610 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8611 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8612 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8613 PPCISD::LFIWZX : PPCISD::LFIWAX, 8614 dl, DAG.getVTList(MVT::f64, MVT::Other), 8615 Ops, MVT::i32, MMO); 8616 } else 8617 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8618 8619 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8620 8621 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8622 FP = DAG.getNode(ISD::FP_ROUND, dl, 8623 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8624 return FP; 8625 } 8626 8627 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8628 "Unhandled INT_TO_FP type in custom expander!"); 8629 // Since we only generate this in 64-bit mode, we can take advantage of 8630 // 64-bit registers. In particular, sign extend the input value into the 8631 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8632 // then lfd it and fcfid it. 8633 MachineFunction &MF = DAG.getMachineFunction(); 8634 MachineFrameInfo &MFI = MF.getFrameInfo(); 8635 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8636 8637 SDValue Ld; 8638 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8639 ReuseLoadInfo RLI; 8640 bool ReusingLoad; 8641 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8642 DAG))) { 8643 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8644 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8645 8646 SDValue Store = 8647 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8648 MachinePointerInfo::getFixedStack( 8649 DAG.getMachineFunction(), FrameIdx)); 8650 8651 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8652 "Expected an i32 store"); 8653 8654 RLI.Ptr = FIdx; 8655 RLI.Chain = Store; 8656 RLI.MPI = 8657 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8658 RLI.Alignment = Align(4); 8659 } 8660 8661 MachineMemOperand *MMO = 8662 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8663 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8664 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8665 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8666 PPCISD::LFIWZX : PPCISD::LFIWAX, 8667 dl, DAG.getVTList(MVT::f64, MVT::Other), 8668 Ops, MVT::i32, MMO); 8669 if (ReusingLoad) 8670 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8671 } else { 8672 assert(Subtarget.isPPC64() && 8673 "i32->FP without LFIWAX supported only on PPC64"); 8674 8675 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8676 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8677 8678 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8679 Op.getOperand(0)); 8680 8681 // STD the extended value into the stack slot. 8682 SDValue Store = DAG.getStore( 8683 DAG.getEntryNode(), dl, Ext64, FIdx, 8684 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8685 8686 // Load the value as a double. 8687 Ld = DAG.getLoad( 8688 MVT::f64, dl, Store, FIdx, 8689 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8690 } 8691 8692 // FCFID it and return it. 8693 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8694 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8695 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8696 DAG.getIntPtrConstant(0, dl)); 8697 return FP; 8698 } 8699 8700 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8701 SelectionDAG &DAG) const { 8702 SDLoc dl(Op); 8703 /* 8704 The rounding mode is in bits 30:31 of FPSR, and has the following 8705 settings: 8706 00 Round to nearest 8707 01 Round to 0 8708 10 Round to +inf 8709 11 Round to -inf 8710 8711 FLT_ROUNDS, on the other hand, expects the following: 8712 -1 Undefined 8713 0 Round to 0 8714 1 Round to nearest 8715 2 Round to +inf 8716 3 Round to -inf 8717 8718 To perform the conversion, we do: 8719 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8720 */ 8721 8722 MachineFunction &MF = DAG.getMachineFunction(); 8723 EVT VT = Op.getValueType(); 8724 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8725 8726 // Save FP Control Word to register 8727 SDValue Chain = Op.getOperand(0); 8728 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8729 Chain = MFFS.getValue(1); 8730 8731 // Save FP register to stack slot 8732 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8733 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8734 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8735 8736 // Load FP Control Word from low 32 bits of stack slot. 8737 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8738 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8739 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8740 Chain = CWD.getValue(1); 8741 8742 // Transform as necessary 8743 SDValue CWD1 = 8744 DAG.getNode(ISD::AND, dl, MVT::i32, 8745 CWD, DAG.getConstant(3, dl, MVT::i32)); 8746 SDValue CWD2 = 8747 DAG.getNode(ISD::SRL, dl, MVT::i32, 8748 DAG.getNode(ISD::AND, dl, MVT::i32, 8749 DAG.getNode(ISD::XOR, dl, MVT::i32, 8750 CWD, DAG.getConstant(3, dl, MVT::i32)), 8751 DAG.getConstant(3, dl, MVT::i32)), 8752 DAG.getConstant(1, dl, MVT::i32)); 8753 8754 SDValue RetVal = 8755 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8756 8757 RetVal = 8758 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8759 dl, VT, RetVal); 8760 8761 return DAG.getMergeValues({RetVal, Chain}, dl); 8762 } 8763 8764 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8765 EVT VT = Op.getValueType(); 8766 unsigned BitWidth = VT.getSizeInBits(); 8767 SDLoc dl(Op); 8768 assert(Op.getNumOperands() == 3 && 8769 VT == Op.getOperand(1).getValueType() && 8770 "Unexpected SHL!"); 8771 8772 // Expand into a bunch of logical ops. Note that these ops 8773 // depend on the PPC behavior for oversized shift amounts. 8774 SDValue Lo = Op.getOperand(0); 8775 SDValue Hi = Op.getOperand(1); 8776 SDValue Amt = Op.getOperand(2); 8777 EVT AmtVT = Amt.getValueType(); 8778 8779 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8780 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8781 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8782 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8783 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8784 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8785 DAG.getConstant(-BitWidth, dl, AmtVT)); 8786 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8787 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8788 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8789 SDValue OutOps[] = { OutLo, OutHi }; 8790 return DAG.getMergeValues(OutOps, dl); 8791 } 8792 8793 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8794 EVT VT = Op.getValueType(); 8795 SDLoc dl(Op); 8796 unsigned BitWidth = VT.getSizeInBits(); 8797 assert(Op.getNumOperands() == 3 && 8798 VT == Op.getOperand(1).getValueType() && 8799 "Unexpected SRL!"); 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::SRL, dl, VT, Lo, Amt); 8811 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, 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::SRL, dl, VT, Hi, Tmp5); 8816 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8817 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8818 SDValue OutOps[] = { OutLo, OutHi }; 8819 return DAG.getMergeValues(OutOps, dl); 8820 } 8821 8822 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8823 SDLoc dl(Op); 8824 EVT VT = Op.getValueType(); 8825 unsigned BitWidth = VT.getSizeInBits(); 8826 assert(Op.getNumOperands() == 3 && 8827 VT == Op.getOperand(1).getValueType() && 8828 "Unexpected SRA!"); 8829 8830 // Expand into a bunch of logical ops, followed by a select_cc. 8831 SDValue Lo = Op.getOperand(0); 8832 SDValue Hi = Op.getOperand(1); 8833 SDValue Amt = Op.getOperand(2); 8834 EVT AmtVT = Amt.getValueType(); 8835 8836 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8837 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8838 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8839 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8840 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8841 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8842 DAG.getConstant(-BitWidth, dl, AmtVT)); 8843 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8844 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8845 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8846 Tmp4, Tmp6, ISD::SETLE); 8847 SDValue OutOps[] = { OutLo, OutHi }; 8848 return DAG.getMergeValues(OutOps, dl); 8849 } 8850 8851 //===----------------------------------------------------------------------===// 8852 // Vector related lowering. 8853 // 8854 8855 /// BuildSplatI - Build a canonical splati of Val with an element size of 8856 /// SplatSize. Cast the result to VT. 8857 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8858 SelectionDAG &DAG, const SDLoc &dl) { 8859 static const MVT VTys[] = { // canonical VT to use for each size. 8860 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8861 }; 8862 8863 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8864 8865 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8866 if (Val == -1) 8867 SplatSize = 1; 8868 8869 EVT CanonicalVT = VTys[SplatSize-1]; 8870 8871 // Build a canonical splat for this value. 8872 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8873 } 8874 8875 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8876 /// specified intrinsic ID. 8877 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8878 const SDLoc &dl, EVT DestVT = MVT::Other) { 8879 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8880 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8881 DAG.getConstant(IID, dl, MVT::i32), Op); 8882 } 8883 8884 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8885 /// specified intrinsic ID. 8886 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8887 SelectionDAG &DAG, const SDLoc &dl, 8888 EVT DestVT = MVT::Other) { 8889 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8890 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8891 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8892 } 8893 8894 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8895 /// specified intrinsic ID. 8896 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8897 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8898 EVT DestVT = MVT::Other) { 8899 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8900 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8901 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8902 } 8903 8904 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8905 /// amount. The result has the specified value type. 8906 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8907 SelectionDAG &DAG, const SDLoc &dl) { 8908 // Force LHS/RHS to be the right type. 8909 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8910 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8911 8912 int Ops[16]; 8913 for (unsigned i = 0; i != 16; ++i) 8914 Ops[i] = i + Amt; 8915 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8916 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8917 } 8918 8919 /// Do we have an efficient pattern in a .td file for this node? 8920 /// 8921 /// \param V - pointer to the BuildVectorSDNode being matched 8922 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8923 /// 8924 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8925 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8926 /// the opposite is true (expansion is beneficial) are: 8927 /// - The node builds a vector out of integers that are not 32 or 64-bits 8928 /// - The node builds a vector out of constants 8929 /// - The node is a "load-and-splat" 8930 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8931 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8932 bool HasDirectMove, 8933 bool HasP8Vector) { 8934 EVT VecVT = V->getValueType(0); 8935 bool RightType = VecVT == MVT::v2f64 || 8936 (HasP8Vector && VecVT == MVT::v4f32) || 8937 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8938 if (!RightType) 8939 return false; 8940 8941 bool IsSplat = true; 8942 bool IsLoad = false; 8943 SDValue Op0 = V->getOperand(0); 8944 8945 // This function is called in a block that confirms the node is not a constant 8946 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8947 // different constants. 8948 if (V->isConstant()) 8949 return false; 8950 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8951 if (V->getOperand(i).isUndef()) 8952 return false; 8953 // We want to expand nodes that represent load-and-splat even if the 8954 // loaded value is a floating point truncation or conversion to int. 8955 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8956 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8957 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8958 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8959 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8960 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8961 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8962 IsLoad = true; 8963 // If the operands are different or the input is not a load and has more 8964 // uses than just this BV node, then it isn't a splat. 8965 if (V->getOperand(i) != Op0 || 8966 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8967 IsSplat = false; 8968 } 8969 return !(IsSplat && IsLoad); 8970 } 8971 8972 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8973 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8974 8975 SDLoc dl(Op); 8976 SDValue Op0 = Op->getOperand(0); 8977 8978 if (!EnableQuadPrecision || 8979 (Op.getValueType() != MVT::f128 ) || 8980 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8981 (Op0.getOperand(0).getValueType() != MVT::i64) || 8982 (Op0.getOperand(1).getValueType() != MVT::i64)) 8983 return SDValue(); 8984 8985 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8986 Op0.getOperand(1)); 8987 } 8988 8989 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8990 const SDValue *InputLoad = &Op; 8991 if (InputLoad->getOpcode() == ISD::BITCAST) 8992 InputLoad = &InputLoad->getOperand(0); 8993 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8994 InputLoad = &InputLoad->getOperand(0); 8995 if (InputLoad->getOpcode() != ISD::LOAD) 8996 return nullptr; 8997 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8998 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8999 } 9000 9001 // If this is a case we can't handle, return null and let the default 9002 // expansion code take care of it. If we CAN select this case, and if it 9003 // selects to a single instruction, return Op. Otherwise, if we can codegen 9004 // this case more efficiently than a constant pool load, lower it to the 9005 // sequence of ops that should be used. 9006 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9007 SelectionDAG &DAG) const { 9008 SDLoc dl(Op); 9009 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9010 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9011 9012 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9013 // We first build an i32 vector, load it into a QPX register, 9014 // then convert it to a floating-point vector and compare it 9015 // to a zero vector to get the boolean result. 9016 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9017 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9018 MachinePointerInfo PtrInfo = 9019 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9020 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9021 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9022 9023 assert(BVN->getNumOperands() == 4 && 9024 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9025 9026 bool IsConst = true; 9027 for (unsigned i = 0; i < 4; ++i) { 9028 if (BVN->getOperand(i).isUndef()) continue; 9029 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9030 IsConst = false; 9031 break; 9032 } 9033 } 9034 9035 if (IsConst) { 9036 Constant *One = 9037 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9038 Constant *NegOne = 9039 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9040 9041 Constant *CV[4]; 9042 for (unsigned i = 0; i < 4; ++i) { 9043 if (BVN->getOperand(i).isUndef()) 9044 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9045 else if (isNullConstant(BVN->getOperand(i))) 9046 CV[i] = NegOne; 9047 else 9048 CV[i] = One; 9049 } 9050 9051 Constant *CP = ConstantVector::get(CV); 9052 SDValue CPIdx = 9053 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9054 9055 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9056 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9057 return DAG.getMemIntrinsicNode( 9058 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9059 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9060 } 9061 9062 SmallVector<SDValue, 4> Stores; 9063 for (unsigned i = 0; i < 4; ++i) { 9064 if (BVN->getOperand(i).isUndef()) continue; 9065 9066 unsigned Offset = 4*i; 9067 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9068 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9069 9070 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9071 if (StoreSize > 4) { 9072 Stores.push_back( 9073 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9074 PtrInfo.getWithOffset(Offset), MVT::i32)); 9075 } else { 9076 SDValue StoreValue = BVN->getOperand(i); 9077 if (StoreSize < 4) 9078 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9079 9080 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9081 PtrInfo.getWithOffset(Offset))); 9082 } 9083 } 9084 9085 SDValue StoreChain; 9086 if (!Stores.empty()) 9087 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9088 else 9089 StoreChain = DAG.getEntryNode(); 9090 9091 // Now load from v4i32 into the QPX register; this will extend it to 9092 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9093 // is typed as v4f64 because the QPX register integer states are not 9094 // explicitly represented. 9095 9096 SDValue Ops[] = {StoreChain, 9097 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9098 FIdx}; 9099 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9100 9101 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9102 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9103 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9104 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9105 LoadedVect); 9106 9107 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9108 9109 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9110 } 9111 9112 // All other QPX vectors are handled by generic code. 9113 if (Subtarget.hasQPX()) 9114 return SDValue(); 9115 9116 // Check if this is a splat of a constant value. 9117 APInt APSplatBits, APSplatUndef; 9118 unsigned SplatBitSize; 9119 bool HasAnyUndefs; 9120 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9121 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9122 SplatBitSize > 32) { 9123 9124 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9125 // Handle load-and-splat patterns as we have instructions that will do this 9126 // in one go. 9127 if (InputLoad && DAG.isSplatValue(Op, true)) { 9128 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9129 9130 // We have handling for 4 and 8 byte elements. 9131 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9132 9133 // Checking for a single use of this load, we have to check for vector 9134 // width (128 bits) / ElementSize uses (since each operand of the 9135 // BUILD_VECTOR is a separate use of the value. 9136 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9137 ((Subtarget.hasVSX() && ElementSize == 64) || 9138 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9139 SDValue Ops[] = { 9140 LD->getChain(), // Chain 9141 LD->getBasePtr(), // Ptr 9142 DAG.getValueType(Op.getValueType()) // VT 9143 }; 9144 return 9145 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9146 DAG.getVTList(Op.getValueType(), MVT::Other), 9147 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9148 } 9149 } 9150 9151 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9152 // lowered to VSX instructions under certain conditions. 9153 // Without VSX, there is no pattern more efficient than expanding the node. 9154 if (Subtarget.hasVSX() && 9155 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9156 Subtarget.hasP8Vector())) 9157 return Op; 9158 return SDValue(); 9159 } 9160 9161 unsigned SplatBits = APSplatBits.getZExtValue(); 9162 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9163 unsigned SplatSize = SplatBitSize / 8; 9164 9165 // First, handle single instruction cases. 9166 9167 // All zeros? 9168 if (SplatBits == 0) { 9169 // Canonicalize all zero vectors to be v4i32. 9170 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9171 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9172 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9173 } 9174 return Op; 9175 } 9176 9177 // We have XXSPLTIB for constant splats one byte wide 9178 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9179 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9180 if (Subtarget.hasP9Vector() && SplatSize == 1) 9181 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9182 9183 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9184 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9185 (32-SplatBitSize)); 9186 if (SextVal >= -16 && SextVal <= 15) 9187 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9188 9189 // Two instruction sequences. 9190 9191 // If this value is in the range [-32,30] and is even, use: 9192 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9193 // If this value is in the range [17,31] and is odd, use: 9194 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9195 // If this value is in the range [-31,-17] and is odd, use: 9196 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9197 // Note the last two are three-instruction sequences. 9198 if (SextVal >= -32 && SextVal <= 31) { 9199 // To avoid having these optimizations undone by constant folding, 9200 // we convert to a pseudo that will be expanded later into one of 9201 // the above forms. 9202 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9203 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9204 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9205 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9206 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9207 if (VT == Op.getValueType()) 9208 return RetVal; 9209 else 9210 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9211 } 9212 9213 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9214 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9215 // for fneg/fabs. 9216 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9217 // Make -1 and vspltisw -1: 9218 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9219 9220 // Make the VSLW intrinsic, computing 0x8000_0000. 9221 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9222 OnesV, DAG, dl); 9223 9224 // xor by OnesV to invert it. 9225 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9226 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9227 } 9228 9229 // Check to see if this is a wide variety of vsplti*, binop self cases. 9230 static const signed char SplatCsts[] = { 9231 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9232 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9233 }; 9234 9235 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9236 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9237 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9238 int i = SplatCsts[idx]; 9239 9240 // Figure out what shift amount will be used by altivec if shifted by i in 9241 // this splat size. 9242 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9243 9244 // vsplti + shl self. 9245 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9246 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9247 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9248 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9249 Intrinsic::ppc_altivec_vslw 9250 }; 9251 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9252 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9253 } 9254 9255 // vsplti + srl self. 9256 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9257 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9258 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9259 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9260 Intrinsic::ppc_altivec_vsrw 9261 }; 9262 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9263 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9264 } 9265 9266 // vsplti + sra self. 9267 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9268 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9269 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9270 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9271 Intrinsic::ppc_altivec_vsraw 9272 }; 9273 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9274 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9275 } 9276 9277 // vsplti + rol self. 9278 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9279 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9280 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9281 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9282 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9283 Intrinsic::ppc_altivec_vrlw 9284 }; 9285 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9286 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9287 } 9288 9289 // t = vsplti c, result = vsldoi t, t, 1 9290 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9291 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9292 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9293 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9294 } 9295 // t = vsplti c, result = vsldoi t, t, 2 9296 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9297 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9298 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9299 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9300 } 9301 // t = vsplti c, result = vsldoi t, t, 3 9302 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9303 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9304 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9305 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9306 } 9307 } 9308 9309 return SDValue(); 9310 } 9311 9312 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9313 /// the specified operations to build the shuffle. 9314 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9315 SDValue RHS, SelectionDAG &DAG, 9316 const SDLoc &dl) { 9317 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9318 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9319 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9320 9321 enum { 9322 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9323 OP_VMRGHW, 9324 OP_VMRGLW, 9325 OP_VSPLTISW0, 9326 OP_VSPLTISW1, 9327 OP_VSPLTISW2, 9328 OP_VSPLTISW3, 9329 OP_VSLDOI4, 9330 OP_VSLDOI8, 9331 OP_VSLDOI12 9332 }; 9333 9334 if (OpNum == OP_COPY) { 9335 if (LHSID == (1*9+2)*9+3) return LHS; 9336 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9337 return RHS; 9338 } 9339 9340 SDValue OpLHS, OpRHS; 9341 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9342 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9343 9344 int ShufIdxs[16]; 9345 switch (OpNum) { 9346 default: llvm_unreachable("Unknown i32 permute!"); 9347 case OP_VMRGHW: 9348 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9349 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9350 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9351 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9352 break; 9353 case OP_VMRGLW: 9354 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9355 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9356 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9357 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9358 break; 9359 case OP_VSPLTISW0: 9360 for (unsigned i = 0; i != 16; ++i) 9361 ShufIdxs[i] = (i&3)+0; 9362 break; 9363 case OP_VSPLTISW1: 9364 for (unsigned i = 0; i != 16; ++i) 9365 ShufIdxs[i] = (i&3)+4; 9366 break; 9367 case OP_VSPLTISW2: 9368 for (unsigned i = 0; i != 16; ++i) 9369 ShufIdxs[i] = (i&3)+8; 9370 break; 9371 case OP_VSPLTISW3: 9372 for (unsigned i = 0; i != 16; ++i) 9373 ShufIdxs[i] = (i&3)+12; 9374 break; 9375 case OP_VSLDOI4: 9376 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9377 case OP_VSLDOI8: 9378 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9379 case OP_VSLDOI12: 9380 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9381 } 9382 EVT VT = OpLHS.getValueType(); 9383 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9384 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9385 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9386 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9387 } 9388 9389 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9390 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9391 /// SDValue. 9392 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9393 SelectionDAG &DAG) const { 9394 const unsigned BytesInVector = 16; 9395 bool IsLE = Subtarget.isLittleEndian(); 9396 SDLoc dl(N); 9397 SDValue V1 = N->getOperand(0); 9398 SDValue V2 = N->getOperand(1); 9399 unsigned ShiftElts = 0, InsertAtByte = 0; 9400 bool Swap = false; 9401 9402 // Shifts required to get the byte we want at element 7. 9403 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9404 0, 15, 14, 13, 12, 11, 10, 9}; 9405 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9406 1, 2, 3, 4, 5, 6, 7, 8}; 9407 9408 ArrayRef<int> Mask = N->getMask(); 9409 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9410 9411 // For each mask element, find out if we're just inserting something 9412 // from V2 into V1 or vice versa. 9413 // Possible permutations inserting an element from V2 into V1: 9414 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9415 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9416 // ... 9417 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9418 // Inserting from V1 into V2 will be similar, except mask range will be 9419 // [16,31]. 9420 9421 bool FoundCandidate = false; 9422 // If both vector operands for the shuffle are the same vector, the mask 9423 // will contain only elements from the first one and the second one will be 9424 // undef. 9425 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9426 // Go through the mask of half-words to find an element that's being moved 9427 // from one vector to the other. 9428 for (unsigned i = 0; i < BytesInVector; ++i) { 9429 unsigned CurrentElement = Mask[i]; 9430 // If 2nd operand is undefined, we should only look for element 7 in the 9431 // Mask. 9432 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9433 continue; 9434 9435 bool OtherElementsInOrder = true; 9436 // Examine the other elements in the Mask to see if they're in original 9437 // order. 9438 for (unsigned j = 0; j < BytesInVector; ++j) { 9439 if (j == i) 9440 continue; 9441 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9442 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9443 // in which we always assume we're always picking from the 1st operand. 9444 int MaskOffset = 9445 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9446 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9447 OtherElementsInOrder = false; 9448 break; 9449 } 9450 } 9451 // If other elements are in original order, we record the number of shifts 9452 // we need to get the element we want into element 7. Also record which byte 9453 // in the vector we should insert into. 9454 if (OtherElementsInOrder) { 9455 // If 2nd operand is undefined, we assume no shifts and no swapping. 9456 if (V2.isUndef()) { 9457 ShiftElts = 0; 9458 Swap = false; 9459 } else { 9460 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9461 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9462 : BigEndianShifts[CurrentElement & 0xF]; 9463 Swap = CurrentElement < BytesInVector; 9464 } 9465 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9466 FoundCandidate = true; 9467 break; 9468 } 9469 } 9470 9471 if (!FoundCandidate) 9472 return SDValue(); 9473 9474 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9475 // optionally with VECSHL if shift is required. 9476 if (Swap) 9477 std::swap(V1, V2); 9478 if (V2.isUndef()) 9479 V2 = V1; 9480 if (ShiftElts) { 9481 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9482 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9483 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9484 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9485 } 9486 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9487 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9488 } 9489 9490 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9491 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9492 /// SDValue. 9493 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9494 SelectionDAG &DAG) const { 9495 const unsigned NumHalfWords = 8; 9496 const unsigned BytesInVector = NumHalfWords * 2; 9497 // Check that the shuffle is on half-words. 9498 if (!isNByteElemShuffleMask(N, 2, 1)) 9499 return SDValue(); 9500 9501 bool IsLE = Subtarget.isLittleEndian(); 9502 SDLoc dl(N); 9503 SDValue V1 = N->getOperand(0); 9504 SDValue V2 = N->getOperand(1); 9505 unsigned ShiftElts = 0, InsertAtByte = 0; 9506 bool Swap = false; 9507 9508 // Shifts required to get the half-word we want at element 3. 9509 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9510 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9511 9512 uint32_t Mask = 0; 9513 uint32_t OriginalOrderLow = 0x1234567; 9514 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9515 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9516 // 32-bit space, only need 4-bit nibbles per element. 9517 for (unsigned i = 0; i < NumHalfWords; ++i) { 9518 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9519 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9520 } 9521 9522 // For each mask element, find out if we're just inserting something 9523 // from V2 into V1 or vice versa. Possible permutations inserting an element 9524 // from V2 into V1: 9525 // X, 1, 2, 3, 4, 5, 6, 7 9526 // 0, X, 2, 3, 4, 5, 6, 7 9527 // 0, 1, X, 3, 4, 5, 6, 7 9528 // 0, 1, 2, X, 4, 5, 6, 7 9529 // 0, 1, 2, 3, X, 5, 6, 7 9530 // 0, 1, 2, 3, 4, X, 6, 7 9531 // 0, 1, 2, 3, 4, 5, X, 7 9532 // 0, 1, 2, 3, 4, 5, 6, X 9533 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9534 9535 bool FoundCandidate = false; 9536 // Go through the mask of half-words to find an element that's being moved 9537 // from one vector to the other. 9538 for (unsigned i = 0; i < NumHalfWords; ++i) { 9539 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9540 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9541 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9542 uint32_t TargetOrder = 0x0; 9543 9544 // If both vector operands for the shuffle are the same vector, the mask 9545 // will contain only elements from the first one and the second one will be 9546 // undef. 9547 if (V2.isUndef()) { 9548 ShiftElts = 0; 9549 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9550 TargetOrder = OriginalOrderLow; 9551 Swap = false; 9552 // Skip if not the correct element or mask of other elements don't equal 9553 // to our expected order. 9554 if (MaskOneElt == VINSERTHSrcElem && 9555 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9556 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9557 FoundCandidate = true; 9558 break; 9559 } 9560 } else { // If both operands are defined. 9561 // Target order is [8,15] if the current mask is between [0,7]. 9562 TargetOrder = 9563 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9564 // Skip if mask of other elements don't equal our expected order. 9565 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9566 // We only need the last 3 bits for the number of shifts. 9567 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9568 : BigEndianShifts[MaskOneElt & 0x7]; 9569 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9570 Swap = MaskOneElt < NumHalfWords; 9571 FoundCandidate = true; 9572 break; 9573 } 9574 } 9575 } 9576 9577 if (!FoundCandidate) 9578 return SDValue(); 9579 9580 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9581 // optionally with VECSHL if shift is required. 9582 if (Swap) 9583 std::swap(V1, V2); 9584 if (V2.isUndef()) 9585 V2 = V1; 9586 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9587 if (ShiftElts) { 9588 // Double ShiftElts because we're left shifting on v16i8 type. 9589 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9590 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9591 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9592 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9593 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9594 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9595 } 9596 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9597 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9598 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9599 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9600 } 9601 9602 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9603 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9604 /// return the code it can be lowered into. Worst case, it can always be 9605 /// lowered into a vperm. 9606 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9607 SelectionDAG &DAG) const { 9608 SDLoc dl(Op); 9609 SDValue V1 = Op.getOperand(0); 9610 SDValue V2 = Op.getOperand(1); 9611 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9612 EVT VT = Op.getValueType(); 9613 bool isLittleEndian = Subtarget.isLittleEndian(); 9614 9615 unsigned ShiftElts, InsertAtByte; 9616 bool Swap = false; 9617 9618 // If this is a load-and-splat, we can do that with a single instruction 9619 // in some cases. However if the load has multiple uses, we don't want to 9620 // combine it because that will just produce multiple loads. 9621 const SDValue *InputLoad = getNormalLoadInput(V1); 9622 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9623 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9624 InputLoad->hasOneUse()) { 9625 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9626 int SplatIdx = 9627 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9628 9629 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9630 // For 4-byte load-and-splat, we need Power9. 9631 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9632 uint64_t Offset = 0; 9633 if (IsFourByte) 9634 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9635 else 9636 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9637 SDValue BasePtr = LD->getBasePtr(); 9638 if (Offset != 0) 9639 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9640 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9641 SDValue Ops[] = { 9642 LD->getChain(), // Chain 9643 BasePtr, // BasePtr 9644 DAG.getValueType(Op.getValueType()) // VT 9645 }; 9646 SDVTList VTL = 9647 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9648 SDValue LdSplt = 9649 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9650 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9651 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9652 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9653 return LdSplt; 9654 } 9655 } 9656 if (Subtarget.hasP9Vector() && 9657 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9658 isLittleEndian)) { 9659 if (Swap) 9660 std::swap(V1, V2); 9661 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9662 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9663 if (ShiftElts) { 9664 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9665 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9666 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9667 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9668 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9669 } 9670 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9671 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9672 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9673 } 9674 9675 if (Subtarget.hasP9Altivec()) { 9676 SDValue NewISDNode; 9677 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9678 return NewISDNode; 9679 9680 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9681 return NewISDNode; 9682 } 9683 9684 if (Subtarget.hasVSX() && 9685 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9686 if (Swap) 9687 std::swap(V1, V2); 9688 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9689 SDValue Conv2 = 9690 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9691 9692 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9693 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9694 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9695 } 9696 9697 if (Subtarget.hasVSX() && 9698 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9699 if (Swap) 9700 std::swap(V1, V2); 9701 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9702 SDValue Conv2 = 9703 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9704 9705 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9706 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9707 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9708 } 9709 9710 if (Subtarget.hasP9Vector()) { 9711 if (PPC::isXXBRHShuffleMask(SVOp)) { 9712 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9713 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9714 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9715 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9716 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9717 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9718 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9719 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9720 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9721 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9722 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9723 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9724 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9725 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9726 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9727 } 9728 } 9729 9730 if (Subtarget.hasVSX()) { 9731 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9732 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9733 9734 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9735 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9736 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9737 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9738 } 9739 9740 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9741 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9742 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9743 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9744 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9745 } 9746 } 9747 9748 if (Subtarget.hasQPX()) { 9749 if (VT.getVectorNumElements() != 4) 9750 return SDValue(); 9751 9752 if (V2.isUndef()) V2 = V1; 9753 9754 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9755 if (AlignIdx != -1) { 9756 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9757 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9758 } else if (SVOp->isSplat()) { 9759 int SplatIdx = SVOp->getSplatIndex(); 9760 if (SplatIdx >= 4) { 9761 std::swap(V1, V2); 9762 SplatIdx -= 4; 9763 } 9764 9765 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9766 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9767 } 9768 9769 // Lower this into a qvgpci/qvfperm pair. 9770 9771 // Compute the qvgpci literal 9772 unsigned idx = 0; 9773 for (unsigned i = 0; i < 4; ++i) { 9774 int m = SVOp->getMaskElt(i); 9775 unsigned mm = m >= 0 ? (unsigned) m : i; 9776 idx |= mm << (3-i)*3; 9777 } 9778 9779 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9780 DAG.getConstant(idx, dl, MVT::i32)); 9781 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9782 } 9783 9784 // Cases that are handled by instructions that take permute immediates 9785 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9786 // selected by the instruction selector. 9787 if (V2.isUndef()) { 9788 if (PPC::isSplatShuffleMask(SVOp, 1) || 9789 PPC::isSplatShuffleMask(SVOp, 2) || 9790 PPC::isSplatShuffleMask(SVOp, 4) || 9791 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9792 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9793 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9794 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9795 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9796 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9797 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9798 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9799 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9800 (Subtarget.hasP8Altivec() && ( 9801 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9802 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9803 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9804 return Op; 9805 } 9806 } 9807 9808 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9809 // and produce a fixed permutation. If any of these match, do not lower to 9810 // VPERM. 9811 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9812 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9813 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9814 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9815 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9816 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9817 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9818 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9819 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9820 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9821 (Subtarget.hasP8Altivec() && ( 9822 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9823 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9824 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9825 return Op; 9826 9827 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9828 // perfect shuffle table to emit an optimal matching sequence. 9829 ArrayRef<int> PermMask = SVOp->getMask(); 9830 9831 unsigned PFIndexes[4]; 9832 bool isFourElementShuffle = true; 9833 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9834 unsigned EltNo = 8; // Start out undef. 9835 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9836 if (PermMask[i*4+j] < 0) 9837 continue; // Undef, ignore it. 9838 9839 unsigned ByteSource = PermMask[i*4+j]; 9840 if ((ByteSource & 3) != j) { 9841 isFourElementShuffle = false; 9842 break; 9843 } 9844 9845 if (EltNo == 8) { 9846 EltNo = ByteSource/4; 9847 } else if (EltNo != ByteSource/4) { 9848 isFourElementShuffle = false; 9849 break; 9850 } 9851 } 9852 PFIndexes[i] = EltNo; 9853 } 9854 9855 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9856 // perfect shuffle vector to determine if it is cost effective to do this as 9857 // discrete instructions, or whether we should use a vperm. 9858 // For now, we skip this for little endian until such time as we have a 9859 // little-endian perfect shuffle table. 9860 if (isFourElementShuffle && !isLittleEndian) { 9861 // Compute the index in the perfect shuffle table. 9862 unsigned PFTableIndex = 9863 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9864 9865 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9866 unsigned Cost = (PFEntry >> 30); 9867 9868 // Determining when to avoid vperm is tricky. Many things affect the cost 9869 // of vperm, particularly how many times the perm mask needs to be computed. 9870 // For example, if the perm mask can be hoisted out of a loop or is already 9871 // used (perhaps because there are multiple permutes with the same shuffle 9872 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9873 // the loop requires an extra register. 9874 // 9875 // As a compromise, we only emit discrete instructions if the shuffle can be 9876 // generated in 3 or fewer operations. When we have loop information 9877 // available, if this block is within a loop, we should avoid using vperm 9878 // for 3-operation perms and use a constant pool load instead. 9879 if (Cost < 3) 9880 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9881 } 9882 9883 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9884 // vector that will get spilled to the constant pool. 9885 if (V2.isUndef()) V2 = V1; 9886 9887 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9888 // that it is in input element units, not in bytes. Convert now. 9889 9890 // For little endian, the order of the input vectors is reversed, and 9891 // the permutation mask is complemented with respect to 31. This is 9892 // necessary to produce proper semantics with the big-endian-biased vperm 9893 // instruction. 9894 EVT EltVT = V1.getValueType().getVectorElementType(); 9895 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9896 9897 SmallVector<SDValue, 16> ResultMask; 9898 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9899 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9900 9901 for (unsigned j = 0; j != BytesPerElement; ++j) 9902 if (isLittleEndian) 9903 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9904 dl, MVT::i32)); 9905 else 9906 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9907 MVT::i32)); 9908 } 9909 9910 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9911 if (isLittleEndian) 9912 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9913 V2, V1, VPermMask); 9914 else 9915 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9916 V1, V2, VPermMask); 9917 } 9918 9919 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9920 /// vector comparison. If it is, return true and fill in Opc/isDot with 9921 /// information about the intrinsic. 9922 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9923 bool &isDot, const PPCSubtarget &Subtarget) { 9924 unsigned IntrinsicID = 9925 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9926 CompareOpc = -1; 9927 isDot = false; 9928 switch (IntrinsicID) { 9929 default: 9930 return false; 9931 // Comparison predicates. 9932 case Intrinsic::ppc_altivec_vcmpbfp_p: 9933 CompareOpc = 966; 9934 isDot = true; 9935 break; 9936 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9937 CompareOpc = 198; 9938 isDot = true; 9939 break; 9940 case Intrinsic::ppc_altivec_vcmpequb_p: 9941 CompareOpc = 6; 9942 isDot = true; 9943 break; 9944 case Intrinsic::ppc_altivec_vcmpequh_p: 9945 CompareOpc = 70; 9946 isDot = true; 9947 break; 9948 case Intrinsic::ppc_altivec_vcmpequw_p: 9949 CompareOpc = 134; 9950 isDot = true; 9951 break; 9952 case Intrinsic::ppc_altivec_vcmpequd_p: 9953 if (Subtarget.hasP8Altivec()) { 9954 CompareOpc = 199; 9955 isDot = true; 9956 } else 9957 return false; 9958 break; 9959 case Intrinsic::ppc_altivec_vcmpneb_p: 9960 case Intrinsic::ppc_altivec_vcmpneh_p: 9961 case Intrinsic::ppc_altivec_vcmpnew_p: 9962 case Intrinsic::ppc_altivec_vcmpnezb_p: 9963 case Intrinsic::ppc_altivec_vcmpnezh_p: 9964 case Intrinsic::ppc_altivec_vcmpnezw_p: 9965 if (Subtarget.hasP9Altivec()) { 9966 switch (IntrinsicID) { 9967 default: 9968 llvm_unreachable("Unknown comparison intrinsic."); 9969 case Intrinsic::ppc_altivec_vcmpneb_p: 9970 CompareOpc = 7; 9971 break; 9972 case Intrinsic::ppc_altivec_vcmpneh_p: 9973 CompareOpc = 71; 9974 break; 9975 case Intrinsic::ppc_altivec_vcmpnew_p: 9976 CompareOpc = 135; 9977 break; 9978 case Intrinsic::ppc_altivec_vcmpnezb_p: 9979 CompareOpc = 263; 9980 break; 9981 case Intrinsic::ppc_altivec_vcmpnezh_p: 9982 CompareOpc = 327; 9983 break; 9984 case Intrinsic::ppc_altivec_vcmpnezw_p: 9985 CompareOpc = 391; 9986 break; 9987 } 9988 isDot = true; 9989 } else 9990 return false; 9991 break; 9992 case Intrinsic::ppc_altivec_vcmpgefp_p: 9993 CompareOpc = 454; 9994 isDot = true; 9995 break; 9996 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9997 CompareOpc = 710; 9998 isDot = true; 9999 break; 10000 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10001 CompareOpc = 774; 10002 isDot = true; 10003 break; 10004 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10005 CompareOpc = 838; 10006 isDot = true; 10007 break; 10008 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10009 CompareOpc = 902; 10010 isDot = true; 10011 break; 10012 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10013 if (Subtarget.hasP8Altivec()) { 10014 CompareOpc = 967; 10015 isDot = true; 10016 } else 10017 return false; 10018 break; 10019 case Intrinsic::ppc_altivec_vcmpgtub_p: 10020 CompareOpc = 518; 10021 isDot = true; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10024 CompareOpc = 582; 10025 isDot = true; 10026 break; 10027 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10028 CompareOpc = 646; 10029 isDot = true; 10030 break; 10031 case Intrinsic::ppc_altivec_vcmpgtud_p: 10032 if (Subtarget.hasP8Altivec()) { 10033 CompareOpc = 711; 10034 isDot = true; 10035 } else 10036 return false; 10037 break; 10038 10039 // VSX predicate comparisons use the same infrastructure 10040 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10041 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10042 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10043 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10044 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10045 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10046 if (Subtarget.hasVSX()) { 10047 switch (IntrinsicID) { 10048 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10049 CompareOpc = 99; 10050 break; 10051 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10052 CompareOpc = 115; 10053 break; 10054 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10055 CompareOpc = 107; 10056 break; 10057 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10058 CompareOpc = 67; 10059 break; 10060 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10061 CompareOpc = 83; 10062 break; 10063 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10064 CompareOpc = 75; 10065 break; 10066 } 10067 isDot = true; 10068 } else 10069 return false; 10070 break; 10071 10072 // Normal Comparisons. 10073 case Intrinsic::ppc_altivec_vcmpbfp: 10074 CompareOpc = 966; 10075 break; 10076 case Intrinsic::ppc_altivec_vcmpeqfp: 10077 CompareOpc = 198; 10078 break; 10079 case Intrinsic::ppc_altivec_vcmpequb: 10080 CompareOpc = 6; 10081 break; 10082 case Intrinsic::ppc_altivec_vcmpequh: 10083 CompareOpc = 70; 10084 break; 10085 case Intrinsic::ppc_altivec_vcmpequw: 10086 CompareOpc = 134; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpequd: 10089 if (Subtarget.hasP8Altivec()) 10090 CompareOpc = 199; 10091 else 10092 return false; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpneb: 10095 case Intrinsic::ppc_altivec_vcmpneh: 10096 case Intrinsic::ppc_altivec_vcmpnew: 10097 case Intrinsic::ppc_altivec_vcmpnezb: 10098 case Intrinsic::ppc_altivec_vcmpnezh: 10099 case Intrinsic::ppc_altivec_vcmpnezw: 10100 if (Subtarget.hasP9Altivec()) 10101 switch (IntrinsicID) { 10102 default: 10103 llvm_unreachable("Unknown comparison intrinsic."); 10104 case Intrinsic::ppc_altivec_vcmpneb: 10105 CompareOpc = 7; 10106 break; 10107 case Intrinsic::ppc_altivec_vcmpneh: 10108 CompareOpc = 71; 10109 break; 10110 case Intrinsic::ppc_altivec_vcmpnew: 10111 CompareOpc = 135; 10112 break; 10113 case Intrinsic::ppc_altivec_vcmpnezb: 10114 CompareOpc = 263; 10115 break; 10116 case Intrinsic::ppc_altivec_vcmpnezh: 10117 CompareOpc = 327; 10118 break; 10119 case Intrinsic::ppc_altivec_vcmpnezw: 10120 CompareOpc = 391; 10121 break; 10122 } 10123 else 10124 return false; 10125 break; 10126 case Intrinsic::ppc_altivec_vcmpgefp: 10127 CompareOpc = 454; 10128 break; 10129 case Intrinsic::ppc_altivec_vcmpgtfp: 10130 CompareOpc = 710; 10131 break; 10132 case Intrinsic::ppc_altivec_vcmpgtsb: 10133 CompareOpc = 774; 10134 break; 10135 case Intrinsic::ppc_altivec_vcmpgtsh: 10136 CompareOpc = 838; 10137 break; 10138 case Intrinsic::ppc_altivec_vcmpgtsw: 10139 CompareOpc = 902; 10140 break; 10141 case Intrinsic::ppc_altivec_vcmpgtsd: 10142 if (Subtarget.hasP8Altivec()) 10143 CompareOpc = 967; 10144 else 10145 return false; 10146 break; 10147 case Intrinsic::ppc_altivec_vcmpgtub: 10148 CompareOpc = 518; 10149 break; 10150 case Intrinsic::ppc_altivec_vcmpgtuh: 10151 CompareOpc = 582; 10152 break; 10153 case Intrinsic::ppc_altivec_vcmpgtuw: 10154 CompareOpc = 646; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpgtud: 10157 if (Subtarget.hasP8Altivec()) 10158 CompareOpc = 711; 10159 else 10160 return false; 10161 break; 10162 } 10163 return true; 10164 } 10165 10166 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10167 /// lower, do it, otherwise return null. 10168 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10169 SelectionDAG &DAG) const { 10170 unsigned IntrinsicID = 10171 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10172 10173 SDLoc dl(Op); 10174 10175 if (IntrinsicID == Intrinsic::thread_pointer) { 10176 // Reads the thread pointer register, used for __builtin_thread_pointer. 10177 if (Subtarget.isPPC64()) 10178 return DAG.getRegister(PPC::X13, MVT::i64); 10179 return DAG.getRegister(PPC::R2, MVT::i32); 10180 } 10181 10182 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10183 // opcode number of the comparison. 10184 int CompareOpc; 10185 bool isDot; 10186 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10187 return SDValue(); // Don't custom lower most intrinsics. 10188 10189 // If this is a non-dot comparison, make the VCMP node and we are done. 10190 if (!isDot) { 10191 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10192 Op.getOperand(1), Op.getOperand(2), 10193 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10194 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10195 } 10196 10197 // Create the PPCISD altivec 'dot' comparison node. 10198 SDValue Ops[] = { 10199 Op.getOperand(2), // LHS 10200 Op.getOperand(3), // RHS 10201 DAG.getConstant(CompareOpc, dl, MVT::i32) 10202 }; 10203 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10204 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10205 10206 // Now that we have the comparison, emit a copy from the CR to a GPR. 10207 // This is flagged to the above dot comparison. 10208 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10209 DAG.getRegister(PPC::CR6, MVT::i32), 10210 CompNode.getValue(1)); 10211 10212 // Unpack the result based on how the target uses it. 10213 unsigned BitNo; // Bit # of CR6. 10214 bool InvertBit; // Invert result? 10215 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10216 default: // Can't happen, don't crash on invalid number though. 10217 case 0: // Return the value of the EQ bit of CR6. 10218 BitNo = 0; InvertBit = false; 10219 break; 10220 case 1: // Return the inverted value of the EQ bit of CR6. 10221 BitNo = 0; InvertBit = true; 10222 break; 10223 case 2: // Return the value of the LT bit of CR6. 10224 BitNo = 2; InvertBit = false; 10225 break; 10226 case 3: // Return the inverted value of the LT bit of CR6. 10227 BitNo = 2; InvertBit = true; 10228 break; 10229 } 10230 10231 // Shift the bit into the low position. 10232 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10233 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10234 // Isolate the bit. 10235 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10236 DAG.getConstant(1, dl, MVT::i32)); 10237 10238 // If we are supposed to, toggle the bit. 10239 if (InvertBit) 10240 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10241 DAG.getConstant(1, dl, MVT::i32)); 10242 return Flags; 10243 } 10244 10245 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10246 SelectionDAG &DAG) const { 10247 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10248 // the beginning of the argument list. 10249 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10250 SDLoc DL(Op); 10251 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10252 case Intrinsic::ppc_cfence: { 10253 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10254 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10255 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10256 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10257 Op.getOperand(ArgStart + 1)), 10258 Op.getOperand(0)), 10259 0); 10260 } 10261 default: 10262 break; 10263 } 10264 return SDValue(); 10265 } 10266 10267 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10268 // Check for a DIV with the same operands as this REM. 10269 for (auto UI : Op.getOperand(1)->uses()) { 10270 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10271 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10272 if (UI->getOperand(0) == Op.getOperand(0) && 10273 UI->getOperand(1) == Op.getOperand(1)) 10274 return SDValue(); 10275 } 10276 return Op; 10277 } 10278 10279 // Lower scalar BSWAP64 to xxbrd. 10280 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10281 SDLoc dl(Op); 10282 // MTVSRDD 10283 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10284 Op.getOperand(0)); 10285 // XXBRD 10286 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10287 // MFVSRD 10288 int VectorIndex = 0; 10289 if (Subtarget.isLittleEndian()) 10290 VectorIndex = 1; 10291 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10292 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10293 return Op; 10294 } 10295 10296 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10297 // compared to a value that is atomically loaded (atomic loads zero-extend). 10298 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10299 SelectionDAG &DAG) const { 10300 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10301 "Expecting an atomic compare-and-swap here."); 10302 SDLoc dl(Op); 10303 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10304 EVT MemVT = AtomicNode->getMemoryVT(); 10305 if (MemVT.getSizeInBits() >= 32) 10306 return Op; 10307 10308 SDValue CmpOp = Op.getOperand(2); 10309 // If this is already correctly zero-extended, leave it alone. 10310 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10311 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10312 return Op; 10313 10314 // Clear the high bits of the compare operand. 10315 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10316 SDValue NewCmpOp = 10317 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10318 DAG.getConstant(MaskVal, dl, MVT::i32)); 10319 10320 // Replace the existing compare operand with the properly zero-extended one. 10321 SmallVector<SDValue, 4> Ops; 10322 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10323 Ops.push_back(AtomicNode->getOperand(i)); 10324 Ops[2] = NewCmpOp; 10325 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10326 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10327 auto NodeTy = 10328 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10329 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10330 } 10331 10332 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10333 SelectionDAG &DAG) const { 10334 SDLoc dl(Op); 10335 // Create a stack slot that is 16-byte aligned. 10336 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10337 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10338 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10339 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10340 10341 // Store the input value into Value#0 of the stack slot. 10342 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10343 MachinePointerInfo()); 10344 // Load it out. 10345 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10346 } 10347 10348 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10349 SelectionDAG &DAG) const { 10350 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10351 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10352 10353 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10354 // We have legal lowering for constant indices but not for variable ones. 10355 if (!C) 10356 return SDValue(); 10357 10358 EVT VT = Op.getValueType(); 10359 SDLoc dl(Op); 10360 SDValue V1 = Op.getOperand(0); 10361 SDValue V2 = Op.getOperand(1); 10362 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10363 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10364 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10365 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10366 unsigned InsertAtElement = C->getZExtValue(); 10367 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10368 if (Subtarget.isLittleEndian()) { 10369 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10370 } 10371 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10372 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10373 } 10374 return Op; 10375 } 10376 10377 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10378 SelectionDAG &DAG) const { 10379 SDLoc dl(Op); 10380 SDNode *N = Op.getNode(); 10381 10382 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10383 "Unknown extract_vector_elt type"); 10384 10385 SDValue Value = N->getOperand(0); 10386 10387 // The first part of this is like the store lowering except that we don't 10388 // need to track the chain. 10389 10390 // The values are now known to be -1 (false) or 1 (true). To convert this 10391 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10392 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10393 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10394 10395 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10396 // understand how to form the extending load. 10397 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10398 10399 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10400 10401 // Now convert to an integer and store. 10402 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10403 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10404 Value); 10405 10406 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10407 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10408 MachinePointerInfo PtrInfo = 10409 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10410 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10411 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10412 10413 SDValue StoreChain = DAG.getEntryNode(); 10414 SDValue Ops[] = {StoreChain, 10415 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10416 Value, FIdx}; 10417 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10418 10419 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10420 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10421 10422 // Extract the value requested. 10423 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10424 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10425 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10426 10427 SDValue IntVal = 10428 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10429 10430 if (!Subtarget.useCRBits()) 10431 return IntVal; 10432 10433 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10434 } 10435 10436 /// Lowering for QPX v4i1 loads 10437 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10438 SelectionDAG &DAG) const { 10439 SDLoc dl(Op); 10440 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10441 SDValue LoadChain = LN->getChain(); 10442 SDValue BasePtr = LN->getBasePtr(); 10443 10444 if (Op.getValueType() == MVT::v4f64 || 10445 Op.getValueType() == MVT::v4f32) { 10446 EVT MemVT = LN->getMemoryVT(); 10447 unsigned Alignment = LN->getAlignment(); 10448 10449 // If this load is properly aligned, then it is legal. 10450 if (Alignment >= MemVT.getStoreSize()) 10451 return Op; 10452 10453 EVT ScalarVT = Op.getValueType().getScalarType(), 10454 ScalarMemVT = MemVT.getScalarType(); 10455 unsigned Stride = ScalarMemVT.getStoreSize(); 10456 10457 SDValue Vals[4], LoadChains[4]; 10458 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10459 SDValue Load; 10460 if (ScalarVT != ScalarMemVT) 10461 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10462 BasePtr, 10463 LN->getPointerInfo().getWithOffset(Idx * Stride), 10464 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10465 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10466 else 10467 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10468 LN->getPointerInfo().getWithOffset(Idx * Stride), 10469 MinAlign(Alignment, Idx * Stride), 10470 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10471 10472 if (Idx == 0 && LN->isIndexed()) { 10473 assert(LN->getAddressingMode() == ISD::PRE_INC && 10474 "Unknown addressing mode on vector load"); 10475 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10476 LN->getAddressingMode()); 10477 } 10478 10479 Vals[Idx] = Load; 10480 LoadChains[Idx] = Load.getValue(1); 10481 10482 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10483 DAG.getConstant(Stride, dl, 10484 BasePtr.getValueType())); 10485 } 10486 10487 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10488 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10489 10490 if (LN->isIndexed()) { 10491 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10492 return DAG.getMergeValues(RetOps, dl); 10493 } 10494 10495 SDValue RetOps[] = { Value, TF }; 10496 return DAG.getMergeValues(RetOps, dl); 10497 } 10498 10499 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10500 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10501 10502 // To lower v4i1 from a byte array, we load the byte elements of the 10503 // vector and then reuse the BUILD_VECTOR logic. 10504 10505 SDValue VectElmts[4], VectElmtChains[4]; 10506 for (unsigned i = 0; i < 4; ++i) { 10507 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10508 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10509 10510 VectElmts[i] = DAG.getExtLoad( 10511 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10512 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10513 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10514 VectElmtChains[i] = VectElmts[i].getValue(1); 10515 } 10516 10517 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10518 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10519 10520 SDValue RVals[] = { Value, LoadChain }; 10521 return DAG.getMergeValues(RVals, dl); 10522 } 10523 10524 /// Lowering for QPX v4i1 stores 10525 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10526 SelectionDAG &DAG) const { 10527 SDLoc dl(Op); 10528 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10529 SDValue StoreChain = SN->getChain(); 10530 SDValue BasePtr = SN->getBasePtr(); 10531 SDValue Value = SN->getValue(); 10532 10533 if (Value.getValueType() == MVT::v4f64 || 10534 Value.getValueType() == MVT::v4f32) { 10535 EVT MemVT = SN->getMemoryVT(); 10536 unsigned Alignment = SN->getAlignment(); 10537 10538 // If this store is properly aligned, then it is legal. 10539 if (Alignment >= MemVT.getStoreSize()) 10540 return Op; 10541 10542 EVT ScalarVT = Value.getValueType().getScalarType(), 10543 ScalarMemVT = MemVT.getScalarType(); 10544 unsigned Stride = ScalarMemVT.getStoreSize(); 10545 10546 SDValue Stores[4]; 10547 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10548 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10549 DAG.getVectorIdxConstant(Idx, dl)); 10550 SDValue Store; 10551 if (ScalarVT != ScalarMemVT) 10552 Store = 10553 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10554 SN->getPointerInfo().getWithOffset(Idx * Stride), 10555 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10556 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10557 else 10558 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10559 SN->getPointerInfo().getWithOffset(Idx * Stride), 10560 MinAlign(Alignment, Idx * Stride), 10561 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10562 10563 if (Idx == 0 && SN->isIndexed()) { 10564 assert(SN->getAddressingMode() == ISD::PRE_INC && 10565 "Unknown addressing mode on vector store"); 10566 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10567 SN->getAddressingMode()); 10568 } 10569 10570 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10571 DAG.getConstant(Stride, dl, 10572 BasePtr.getValueType())); 10573 Stores[Idx] = Store; 10574 } 10575 10576 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10577 10578 if (SN->isIndexed()) { 10579 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10580 return DAG.getMergeValues(RetOps, dl); 10581 } 10582 10583 return TF; 10584 } 10585 10586 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10587 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10588 10589 // The values are now known to be -1 (false) or 1 (true). To convert this 10590 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10591 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10592 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10593 10594 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10595 // understand how to form the extending load. 10596 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10597 10598 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10599 10600 // Now convert to an integer and store. 10601 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10602 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10603 Value); 10604 10605 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10606 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10607 MachinePointerInfo PtrInfo = 10608 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10609 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10610 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10611 10612 SDValue Ops[] = {StoreChain, 10613 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10614 Value, FIdx}; 10615 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10616 10617 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10618 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10619 10620 // Move data into the byte array. 10621 SDValue Loads[4], LoadChains[4]; 10622 for (unsigned i = 0; i < 4; ++i) { 10623 unsigned Offset = 4*i; 10624 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10625 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10626 10627 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10628 PtrInfo.getWithOffset(Offset)); 10629 LoadChains[i] = Loads[i].getValue(1); 10630 } 10631 10632 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10633 10634 SDValue Stores[4]; 10635 for (unsigned i = 0; i < 4; ++i) { 10636 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10637 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10638 10639 Stores[i] = DAG.getTruncStore( 10640 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10641 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10642 SN->getAAInfo()); 10643 } 10644 10645 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10646 10647 return StoreChain; 10648 } 10649 10650 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10651 SDLoc dl(Op); 10652 if (Op.getValueType() == MVT::v4i32) { 10653 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10654 10655 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10656 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10657 10658 SDValue RHSSwap = // = vrlw RHS, 16 10659 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10660 10661 // Shrinkify inputs to v8i16. 10662 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10663 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10664 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10665 10666 // Low parts multiplied together, generating 32-bit results (we ignore the 10667 // top parts). 10668 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10669 LHS, RHS, DAG, dl, MVT::v4i32); 10670 10671 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10672 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10673 // Shift the high parts up 16 bits. 10674 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10675 Neg16, DAG, dl); 10676 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10677 } else if (Op.getValueType() == MVT::v16i8) { 10678 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10679 bool isLittleEndian = Subtarget.isLittleEndian(); 10680 10681 // Multiply the even 8-bit parts, producing 16-bit sums. 10682 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10683 LHS, RHS, DAG, dl, MVT::v8i16); 10684 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10685 10686 // Multiply the odd 8-bit parts, producing 16-bit sums. 10687 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10688 LHS, RHS, DAG, dl, MVT::v8i16); 10689 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10690 10691 // Merge the results together. Because vmuleub and vmuloub are 10692 // instructions with a big-endian bias, we must reverse the 10693 // element numbering and reverse the meaning of "odd" and "even" 10694 // when generating little endian code. 10695 int Ops[16]; 10696 for (unsigned i = 0; i != 8; ++i) { 10697 if (isLittleEndian) { 10698 Ops[i*2 ] = 2*i; 10699 Ops[i*2+1] = 2*i+16; 10700 } else { 10701 Ops[i*2 ] = 2*i+1; 10702 Ops[i*2+1] = 2*i+1+16; 10703 } 10704 } 10705 if (isLittleEndian) 10706 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10707 else 10708 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10709 } else { 10710 llvm_unreachable("Unknown mul to lower!"); 10711 } 10712 } 10713 10714 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10715 10716 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10717 10718 EVT VT = Op.getValueType(); 10719 assert(VT.isVector() && 10720 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10721 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10722 VT == MVT::v16i8) && 10723 "Unexpected vector element type!"); 10724 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10725 "Current subtarget doesn't support smax v2i64!"); 10726 10727 // For vector abs, it can be lowered to: 10728 // abs x 10729 // ==> 10730 // y = -x 10731 // smax(x, y) 10732 10733 SDLoc dl(Op); 10734 SDValue X = Op.getOperand(0); 10735 SDValue Zero = DAG.getConstant(0, dl, VT); 10736 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10737 10738 // SMAX patch https://reviews.llvm.org/D47332 10739 // hasn't landed yet, so use intrinsic first here. 10740 // TODO: Should use SMAX directly once SMAX patch landed 10741 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10742 if (VT == MVT::v2i64) 10743 BifID = Intrinsic::ppc_altivec_vmaxsd; 10744 else if (VT == MVT::v8i16) 10745 BifID = Intrinsic::ppc_altivec_vmaxsh; 10746 else if (VT == MVT::v16i8) 10747 BifID = Intrinsic::ppc_altivec_vmaxsb; 10748 10749 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10750 } 10751 10752 // Custom lowering for fpext vf32 to v2f64 10753 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10754 10755 assert(Op.getOpcode() == ISD::FP_EXTEND && 10756 "Should only be called for ISD::FP_EXTEND"); 10757 10758 // FIXME: handle extends from half precision float vectors on P9. 10759 // We only want to custom lower an extend from v2f32 to v2f64. 10760 if (Op.getValueType() != MVT::v2f64 || 10761 Op.getOperand(0).getValueType() != MVT::v2f32) 10762 return SDValue(); 10763 10764 SDLoc dl(Op); 10765 SDValue Op0 = Op.getOperand(0); 10766 10767 switch (Op0.getOpcode()) { 10768 default: 10769 return SDValue(); 10770 case ISD::EXTRACT_SUBVECTOR: { 10771 assert(Op0.getNumOperands() == 2 && 10772 isa<ConstantSDNode>(Op0->getOperand(1)) && 10773 "Node should have 2 operands with second one being a constant!"); 10774 10775 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10776 return SDValue(); 10777 10778 // Custom lower is only done for high or low doubleword. 10779 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10780 if (Idx % 2 != 0) 10781 return SDValue(); 10782 10783 // Since input is v4f32, at this point Idx is either 0 or 2. 10784 // Shift to get the doubleword position we want. 10785 int DWord = Idx >> 1; 10786 10787 // High and low word positions are different on little endian. 10788 if (Subtarget.isLittleEndian()) 10789 DWord ^= 0x1; 10790 10791 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10792 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10793 } 10794 case ISD::FADD: 10795 case ISD::FMUL: 10796 case ISD::FSUB: { 10797 SDValue NewLoad[2]; 10798 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10799 // Ensure both input are loads. 10800 SDValue LdOp = Op0.getOperand(i); 10801 if (LdOp.getOpcode() != ISD::LOAD) 10802 return SDValue(); 10803 // Generate new load node. 10804 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10805 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10806 NewLoad[i] = DAG.getMemIntrinsicNode( 10807 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10808 LD->getMemoryVT(), LD->getMemOperand()); 10809 } 10810 SDValue NewOp = 10811 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10812 NewLoad[1], Op0.getNode()->getFlags()); 10813 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10814 DAG.getConstant(0, dl, MVT::i32)); 10815 } 10816 case ISD::LOAD: { 10817 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10818 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10819 SDValue NewLd = DAG.getMemIntrinsicNode( 10820 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10821 LD->getMemoryVT(), LD->getMemOperand()); 10822 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10823 DAG.getConstant(0, dl, MVT::i32)); 10824 } 10825 } 10826 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10827 } 10828 10829 /// LowerOperation - Provide custom lowering hooks for some operations. 10830 /// 10831 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10832 switch (Op.getOpcode()) { 10833 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10834 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10835 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10836 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10837 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10838 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10839 case ISD::SETCC: return LowerSETCC(Op, DAG); 10840 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10841 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10842 10843 // Variable argument lowering. 10844 case ISD::VASTART: return LowerVASTART(Op, DAG); 10845 case ISD::VAARG: return LowerVAARG(Op, DAG); 10846 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10847 10848 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10849 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10850 case ISD::GET_DYNAMIC_AREA_OFFSET: 10851 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10852 10853 // Exception handling lowering. 10854 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10855 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10856 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10857 10858 case ISD::LOAD: return LowerLOAD(Op, DAG); 10859 case ISD::STORE: return LowerSTORE(Op, DAG); 10860 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10861 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10862 case ISD::FP_TO_UINT: 10863 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10864 case ISD::UINT_TO_FP: 10865 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10866 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10867 10868 // Lower 64-bit shifts. 10869 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10870 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10871 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10872 10873 // Vector-related lowering. 10874 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10875 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10876 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10877 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10878 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10879 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10880 case ISD::MUL: return LowerMUL(Op, DAG); 10881 case ISD::ABS: return LowerABS(Op, DAG); 10882 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10883 10884 // For counter-based loop handling. 10885 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10886 10887 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10888 10889 // Frame & Return address. 10890 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10891 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10892 10893 case ISD::INTRINSIC_VOID: 10894 return LowerINTRINSIC_VOID(Op, DAG); 10895 case ISD::SREM: 10896 case ISD::UREM: 10897 return LowerREM(Op, DAG); 10898 case ISD::BSWAP: 10899 return LowerBSWAP(Op, DAG); 10900 case ISD::ATOMIC_CMP_SWAP: 10901 return LowerATOMIC_CMP_SWAP(Op, DAG); 10902 } 10903 } 10904 10905 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10906 SmallVectorImpl<SDValue>&Results, 10907 SelectionDAG &DAG) const { 10908 SDLoc dl(N); 10909 switch (N->getOpcode()) { 10910 default: 10911 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10912 case ISD::READCYCLECOUNTER: { 10913 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10914 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10915 10916 Results.push_back( 10917 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10918 Results.push_back(RTB.getValue(2)); 10919 break; 10920 } 10921 case ISD::INTRINSIC_W_CHAIN: { 10922 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10923 Intrinsic::loop_decrement) 10924 break; 10925 10926 assert(N->getValueType(0) == MVT::i1 && 10927 "Unexpected result type for CTR decrement intrinsic"); 10928 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10929 N->getValueType(0)); 10930 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10931 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10932 N->getOperand(1)); 10933 10934 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10935 Results.push_back(NewInt.getValue(1)); 10936 break; 10937 } 10938 case ISD::VAARG: { 10939 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10940 return; 10941 10942 EVT VT = N->getValueType(0); 10943 10944 if (VT == MVT::i64) { 10945 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10946 10947 Results.push_back(NewNode); 10948 Results.push_back(NewNode.getValue(1)); 10949 } 10950 return; 10951 } 10952 case ISD::FP_TO_SINT: 10953 case ISD::FP_TO_UINT: 10954 // LowerFP_TO_INT() can only handle f32 and f64. 10955 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10956 return; 10957 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10958 return; 10959 case ISD::TRUNCATE: { 10960 EVT TrgVT = N->getValueType(0); 10961 EVT OpVT = N->getOperand(0).getValueType(); 10962 if (TrgVT.isVector() && 10963 isOperationCustom(N->getOpcode(), TrgVT) && 10964 OpVT.getSizeInBits() <= 128 && 10965 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10966 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10967 return; 10968 } 10969 case ISD::BITCAST: 10970 // Don't handle bitcast here. 10971 return; 10972 case ISD::FP_EXTEND: 10973 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10974 if (Lowered) 10975 Results.push_back(Lowered); 10976 return; 10977 } 10978 } 10979 10980 //===----------------------------------------------------------------------===// 10981 // Other Lowering Code 10982 //===----------------------------------------------------------------------===// 10983 10984 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10985 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10986 Function *Func = Intrinsic::getDeclaration(M, Id); 10987 return Builder.CreateCall(Func, {}); 10988 } 10989 10990 // The mappings for emitLeading/TrailingFence is taken from 10991 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10992 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10993 Instruction *Inst, 10994 AtomicOrdering Ord) const { 10995 if (Ord == AtomicOrdering::SequentiallyConsistent) 10996 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10997 if (isReleaseOrStronger(Ord)) 10998 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10999 return nullptr; 11000 } 11001 11002 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11003 Instruction *Inst, 11004 AtomicOrdering Ord) const { 11005 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11006 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11007 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11008 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11009 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11010 return Builder.CreateCall( 11011 Intrinsic::getDeclaration( 11012 Builder.GetInsertBlock()->getParent()->getParent(), 11013 Intrinsic::ppc_cfence, {Inst->getType()}), 11014 {Inst}); 11015 // FIXME: Can use isync for rmw operation. 11016 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11017 } 11018 return nullptr; 11019 } 11020 11021 MachineBasicBlock * 11022 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11023 unsigned AtomicSize, 11024 unsigned BinOpcode, 11025 unsigned CmpOpcode, 11026 unsigned CmpPred) const { 11027 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11028 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11029 11030 auto LoadMnemonic = PPC::LDARX; 11031 auto StoreMnemonic = PPC::STDCX; 11032 switch (AtomicSize) { 11033 default: 11034 llvm_unreachable("Unexpected size of atomic entity"); 11035 case 1: 11036 LoadMnemonic = PPC::LBARX; 11037 StoreMnemonic = PPC::STBCX; 11038 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11039 break; 11040 case 2: 11041 LoadMnemonic = PPC::LHARX; 11042 StoreMnemonic = PPC::STHCX; 11043 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11044 break; 11045 case 4: 11046 LoadMnemonic = PPC::LWARX; 11047 StoreMnemonic = PPC::STWCX; 11048 break; 11049 case 8: 11050 LoadMnemonic = PPC::LDARX; 11051 StoreMnemonic = PPC::STDCX; 11052 break; 11053 } 11054 11055 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11056 MachineFunction *F = BB->getParent(); 11057 MachineFunction::iterator It = ++BB->getIterator(); 11058 11059 Register dest = MI.getOperand(0).getReg(); 11060 Register ptrA = MI.getOperand(1).getReg(); 11061 Register ptrB = MI.getOperand(2).getReg(); 11062 Register incr = MI.getOperand(3).getReg(); 11063 DebugLoc dl = MI.getDebugLoc(); 11064 11065 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11066 MachineBasicBlock *loop2MBB = 11067 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11068 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11069 F->insert(It, loopMBB); 11070 if (CmpOpcode) 11071 F->insert(It, loop2MBB); 11072 F->insert(It, exitMBB); 11073 exitMBB->splice(exitMBB->begin(), BB, 11074 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11075 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11076 11077 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11078 Register TmpReg = (!BinOpcode) ? incr : 11079 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11080 : &PPC::GPRCRegClass); 11081 11082 // thisMBB: 11083 // ... 11084 // fallthrough --> loopMBB 11085 BB->addSuccessor(loopMBB); 11086 11087 // loopMBB: 11088 // l[wd]arx dest, ptr 11089 // add r0, dest, incr 11090 // st[wd]cx. r0, ptr 11091 // bne- loopMBB 11092 // fallthrough --> exitMBB 11093 11094 // For max/min... 11095 // loopMBB: 11096 // l[wd]arx dest, ptr 11097 // cmpl?[wd] incr, dest 11098 // bgt exitMBB 11099 // loop2MBB: 11100 // st[wd]cx. dest, ptr 11101 // bne- loopMBB 11102 // fallthrough --> exitMBB 11103 11104 BB = loopMBB; 11105 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11106 .addReg(ptrA).addReg(ptrB); 11107 if (BinOpcode) 11108 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11109 if (CmpOpcode) { 11110 // Signed comparisons of byte or halfword values must be sign-extended. 11111 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11112 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11113 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11114 ExtReg).addReg(dest); 11115 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11116 .addReg(incr).addReg(ExtReg); 11117 } else 11118 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11119 .addReg(incr).addReg(dest); 11120 11121 BuildMI(BB, dl, TII->get(PPC::BCC)) 11122 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11123 BB->addSuccessor(loop2MBB); 11124 BB->addSuccessor(exitMBB); 11125 BB = loop2MBB; 11126 } 11127 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11128 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11129 BuildMI(BB, dl, TII->get(PPC::BCC)) 11130 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11131 BB->addSuccessor(loopMBB); 11132 BB->addSuccessor(exitMBB); 11133 11134 // exitMBB: 11135 // ... 11136 BB = exitMBB; 11137 return BB; 11138 } 11139 11140 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11141 MachineInstr &MI, MachineBasicBlock *BB, 11142 bool is8bit, // operation 11143 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11144 // If we support part-word atomic mnemonics, just use them 11145 if (Subtarget.hasPartwordAtomics()) 11146 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11147 CmpPred); 11148 11149 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11150 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11151 // In 64 bit mode we have to use 64 bits for addresses, even though the 11152 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11153 // registers without caring whether they're 32 or 64, but here we're 11154 // doing actual arithmetic on the addresses. 11155 bool is64bit = Subtarget.isPPC64(); 11156 bool isLittleEndian = Subtarget.isLittleEndian(); 11157 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11158 11159 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11160 MachineFunction *F = BB->getParent(); 11161 MachineFunction::iterator It = ++BB->getIterator(); 11162 11163 Register dest = MI.getOperand(0).getReg(); 11164 Register ptrA = MI.getOperand(1).getReg(); 11165 Register ptrB = MI.getOperand(2).getReg(); 11166 Register incr = MI.getOperand(3).getReg(); 11167 DebugLoc dl = MI.getDebugLoc(); 11168 11169 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11170 MachineBasicBlock *loop2MBB = 11171 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11172 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11173 F->insert(It, loopMBB); 11174 if (CmpOpcode) 11175 F->insert(It, loop2MBB); 11176 F->insert(It, exitMBB); 11177 exitMBB->splice(exitMBB->begin(), BB, 11178 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11179 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11180 11181 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11182 const TargetRegisterClass *RC = 11183 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11184 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11185 11186 Register PtrReg = RegInfo.createVirtualRegister(RC); 11187 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11188 Register ShiftReg = 11189 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11190 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11191 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11192 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11193 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11194 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11195 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11196 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11197 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11198 Register Ptr1Reg; 11199 Register TmpReg = 11200 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11201 11202 // thisMBB: 11203 // ... 11204 // fallthrough --> loopMBB 11205 BB->addSuccessor(loopMBB); 11206 11207 // The 4-byte load must be aligned, while a char or short may be 11208 // anywhere in the word. Hence all this nasty bookkeeping code. 11209 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11210 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11211 // xori shift, shift1, 24 [16] 11212 // rlwinm ptr, ptr1, 0, 0, 29 11213 // slw incr2, incr, shift 11214 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11215 // slw mask, mask2, shift 11216 // loopMBB: 11217 // lwarx tmpDest, ptr 11218 // add tmp, tmpDest, incr2 11219 // andc tmp2, tmpDest, mask 11220 // and tmp3, tmp, mask 11221 // or tmp4, tmp3, tmp2 11222 // stwcx. tmp4, ptr 11223 // bne- loopMBB 11224 // fallthrough --> exitMBB 11225 // srw dest, tmpDest, shift 11226 if (ptrA != ZeroReg) { 11227 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11228 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11229 .addReg(ptrA) 11230 .addReg(ptrB); 11231 } else { 11232 Ptr1Reg = ptrB; 11233 } 11234 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11235 // mode. 11236 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11237 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11238 .addImm(3) 11239 .addImm(27) 11240 .addImm(is8bit ? 28 : 27); 11241 if (!isLittleEndian) 11242 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11243 .addReg(Shift1Reg) 11244 .addImm(is8bit ? 24 : 16); 11245 if (is64bit) 11246 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11247 .addReg(Ptr1Reg) 11248 .addImm(0) 11249 .addImm(61); 11250 else 11251 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11252 .addReg(Ptr1Reg) 11253 .addImm(0) 11254 .addImm(0) 11255 .addImm(29); 11256 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11257 if (is8bit) 11258 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11259 else { 11260 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11261 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11262 .addReg(Mask3Reg) 11263 .addImm(65535); 11264 } 11265 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11266 .addReg(Mask2Reg) 11267 .addReg(ShiftReg); 11268 11269 BB = loopMBB; 11270 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11271 .addReg(ZeroReg) 11272 .addReg(PtrReg); 11273 if (BinOpcode) 11274 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11275 .addReg(Incr2Reg) 11276 .addReg(TmpDestReg); 11277 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11278 .addReg(TmpDestReg) 11279 .addReg(MaskReg); 11280 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11281 if (CmpOpcode) { 11282 // For unsigned comparisons, we can directly compare the shifted values. 11283 // For signed comparisons we shift and sign extend. 11284 Register SReg = RegInfo.createVirtualRegister(GPRC); 11285 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11286 .addReg(TmpDestReg) 11287 .addReg(MaskReg); 11288 unsigned ValueReg = SReg; 11289 unsigned CmpReg = Incr2Reg; 11290 if (CmpOpcode == PPC::CMPW) { 11291 ValueReg = RegInfo.createVirtualRegister(GPRC); 11292 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11293 .addReg(SReg) 11294 .addReg(ShiftReg); 11295 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11296 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11297 .addReg(ValueReg); 11298 ValueReg = ValueSReg; 11299 CmpReg = incr; 11300 } 11301 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11302 .addReg(CmpReg) 11303 .addReg(ValueReg); 11304 BuildMI(BB, dl, TII->get(PPC::BCC)) 11305 .addImm(CmpPred) 11306 .addReg(PPC::CR0) 11307 .addMBB(exitMBB); 11308 BB->addSuccessor(loop2MBB); 11309 BB->addSuccessor(exitMBB); 11310 BB = loop2MBB; 11311 } 11312 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11313 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11314 .addReg(Tmp4Reg) 11315 .addReg(ZeroReg) 11316 .addReg(PtrReg); 11317 BuildMI(BB, dl, TII->get(PPC::BCC)) 11318 .addImm(PPC::PRED_NE) 11319 .addReg(PPC::CR0) 11320 .addMBB(loopMBB); 11321 BB->addSuccessor(loopMBB); 11322 BB->addSuccessor(exitMBB); 11323 11324 // exitMBB: 11325 // ... 11326 BB = exitMBB; 11327 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11328 .addReg(TmpDestReg) 11329 .addReg(ShiftReg); 11330 return BB; 11331 } 11332 11333 llvm::MachineBasicBlock * 11334 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11335 MachineBasicBlock *MBB) const { 11336 DebugLoc DL = MI.getDebugLoc(); 11337 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11338 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11339 11340 MachineFunction *MF = MBB->getParent(); 11341 MachineRegisterInfo &MRI = MF->getRegInfo(); 11342 11343 const BasicBlock *BB = MBB->getBasicBlock(); 11344 MachineFunction::iterator I = ++MBB->getIterator(); 11345 11346 Register DstReg = MI.getOperand(0).getReg(); 11347 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11348 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11349 Register mainDstReg = MRI.createVirtualRegister(RC); 11350 Register restoreDstReg = MRI.createVirtualRegister(RC); 11351 11352 MVT PVT = getPointerTy(MF->getDataLayout()); 11353 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11354 "Invalid Pointer Size!"); 11355 // For v = setjmp(buf), we generate 11356 // 11357 // thisMBB: 11358 // SjLjSetup mainMBB 11359 // bl mainMBB 11360 // v_restore = 1 11361 // b sinkMBB 11362 // 11363 // mainMBB: 11364 // buf[LabelOffset] = LR 11365 // v_main = 0 11366 // 11367 // sinkMBB: 11368 // v = phi(main, restore) 11369 // 11370 11371 MachineBasicBlock *thisMBB = MBB; 11372 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11373 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11374 MF->insert(I, mainMBB); 11375 MF->insert(I, sinkMBB); 11376 11377 MachineInstrBuilder MIB; 11378 11379 // Transfer the remainder of BB and its successor edges to sinkMBB. 11380 sinkMBB->splice(sinkMBB->begin(), MBB, 11381 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11382 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11383 11384 // Note that the structure of the jmp_buf used here is not compatible 11385 // with that used by libc, and is not designed to be. Specifically, it 11386 // stores only those 'reserved' registers that LLVM does not otherwise 11387 // understand how to spill. Also, by convention, by the time this 11388 // intrinsic is called, Clang has already stored the frame address in the 11389 // first slot of the buffer and stack address in the third. Following the 11390 // X86 target code, we'll store the jump address in the second slot. We also 11391 // need to save the TOC pointer (R2) to handle jumps between shared 11392 // libraries, and that will be stored in the fourth slot. The thread 11393 // identifier (R13) is not affected. 11394 11395 // thisMBB: 11396 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11397 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11398 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11399 11400 // Prepare IP either in reg. 11401 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11402 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11403 Register BufReg = MI.getOperand(1).getReg(); 11404 11405 if (Subtarget.is64BitELFABI()) { 11406 setUsesTOCBasePtr(*MBB->getParent()); 11407 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11408 .addReg(PPC::X2) 11409 .addImm(TOCOffset) 11410 .addReg(BufReg) 11411 .cloneMemRefs(MI); 11412 } 11413 11414 // Naked functions never have a base pointer, and so we use r1. For all 11415 // other functions, this decision must be delayed until during PEI. 11416 unsigned BaseReg; 11417 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11418 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11419 else 11420 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11421 11422 MIB = BuildMI(*thisMBB, MI, DL, 11423 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11424 .addReg(BaseReg) 11425 .addImm(BPOffset) 11426 .addReg(BufReg) 11427 .cloneMemRefs(MI); 11428 11429 // Setup 11430 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11431 MIB.addRegMask(TRI->getNoPreservedMask()); 11432 11433 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11434 11435 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11436 .addMBB(mainMBB); 11437 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11438 11439 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11440 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11441 11442 // mainMBB: 11443 // mainDstReg = 0 11444 MIB = 11445 BuildMI(mainMBB, DL, 11446 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11447 11448 // Store IP 11449 if (Subtarget.isPPC64()) { 11450 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11451 .addReg(LabelReg) 11452 .addImm(LabelOffset) 11453 .addReg(BufReg); 11454 } else { 11455 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11456 .addReg(LabelReg) 11457 .addImm(LabelOffset) 11458 .addReg(BufReg); 11459 } 11460 MIB.cloneMemRefs(MI); 11461 11462 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11463 mainMBB->addSuccessor(sinkMBB); 11464 11465 // sinkMBB: 11466 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11467 TII->get(PPC::PHI), DstReg) 11468 .addReg(mainDstReg).addMBB(mainMBB) 11469 .addReg(restoreDstReg).addMBB(thisMBB); 11470 11471 MI.eraseFromParent(); 11472 return sinkMBB; 11473 } 11474 11475 MachineBasicBlock * 11476 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11477 MachineBasicBlock *MBB) const { 11478 DebugLoc DL = MI.getDebugLoc(); 11479 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11480 11481 MachineFunction *MF = MBB->getParent(); 11482 MachineRegisterInfo &MRI = MF->getRegInfo(); 11483 11484 MVT PVT = getPointerTy(MF->getDataLayout()); 11485 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11486 "Invalid Pointer Size!"); 11487 11488 const TargetRegisterClass *RC = 11489 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11490 Register Tmp = MRI.createVirtualRegister(RC); 11491 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11492 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11493 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11494 unsigned BP = 11495 (PVT == MVT::i64) 11496 ? PPC::X30 11497 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11498 : PPC::R30); 11499 11500 MachineInstrBuilder MIB; 11501 11502 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11503 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11504 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11505 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11506 11507 Register BufReg = MI.getOperand(0).getReg(); 11508 11509 // Reload FP (the jumped-to function may not have had a 11510 // frame pointer, and if so, then its r31 will be restored 11511 // as necessary). 11512 if (PVT == MVT::i64) { 11513 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11514 .addImm(0) 11515 .addReg(BufReg); 11516 } else { 11517 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11518 .addImm(0) 11519 .addReg(BufReg); 11520 } 11521 MIB.cloneMemRefs(MI); 11522 11523 // Reload IP 11524 if (PVT == MVT::i64) { 11525 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11526 .addImm(LabelOffset) 11527 .addReg(BufReg); 11528 } else { 11529 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11530 .addImm(LabelOffset) 11531 .addReg(BufReg); 11532 } 11533 MIB.cloneMemRefs(MI); 11534 11535 // Reload SP 11536 if (PVT == MVT::i64) { 11537 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11538 .addImm(SPOffset) 11539 .addReg(BufReg); 11540 } else { 11541 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11542 .addImm(SPOffset) 11543 .addReg(BufReg); 11544 } 11545 MIB.cloneMemRefs(MI); 11546 11547 // Reload BP 11548 if (PVT == MVT::i64) { 11549 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11550 .addImm(BPOffset) 11551 .addReg(BufReg); 11552 } else { 11553 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11554 .addImm(BPOffset) 11555 .addReg(BufReg); 11556 } 11557 MIB.cloneMemRefs(MI); 11558 11559 // Reload TOC 11560 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11561 setUsesTOCBasePtr(*MBB->getParent()); 11562 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11563 .addImm(TOCOffset) 11564 .addReg(BufReg) 11565 .cloneMemRefs(MI); 11566 } 11567 11568 // Jump 11569 BuildMI(*MBB, MI, DL, 11570 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11571 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11572 11573 MI.eraseFromParent(); 11574 return MBB; 11575 } 11576 11577 MachineBasicBlock * 11578 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11579 MachineBasicBlock *BB) const { 11580 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11581 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11582 if (Subtarget.is64BitELFABI() && 11583 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11584 !Subtarget.isUsingPCRelativeCalls()) { 11585 // Call lowering should have added an r2 operand to indicate a dependence 11586 // on the TOC base pointer value. It can't however, because there is no 11587 // way to mark the dependence as implicit there, and so the stackmap code 11588 // will confuse it with a regular operand. Instead, add the dependence 11589 // here. 11590 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11591 } 11592 11593 return emitPatchPoint(MI, BB); 11594 } 11595 11596 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11597 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11598 return emitEHSjLjSetJmp(MI, BB); 11599 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11600 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11601 return emitEHSjLjLongJmp(MI, BB); 11602 } 11603 11604 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11605 11606 // To "insert" these instructions we actually have to insert their 11607 // control-flow patterns. 11608 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11609 MachineFunction::iterator It = ++BB->getIterator(); 11610 11611 MachineFunction *F = BB->getParent(); 11612 11613 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11614 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11615 MI.getOpcode() == PPC::SELECT_I8) { 11616 SmallVector<MachineOperand, 2> Cond; 11617 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11618 MI.getOpcode() == PPC::SELECT_CC_I8) 11619 Cond.push_back(MI.getOperand(4)); 11620 else 11621 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11622 Cond.push_back(MI.getOperand(1)); 11623 11624 DebugLoc dl = MI.getDebugLoc(); 11625 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11626 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11627 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11628 MI.getOpcode() == PPC::SELECT_CC_F8 || 11629 MI.getOpcode() == PPC::SELECT_CC_F16 || 11630 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11631 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11632 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11633 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11634 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11635 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11636 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11637 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11638 MI.getOpcode() == PPC::SELECT_CC_SPE || 11639 MI.getOpcode() == PPC::SELECT_F4 || 11640 MI.getOpcode() == PPC::SELECT_F8 || 11641 MI.getOpcode() == PPC::SELECT_F16 || 11642 MI.getOpcode() == PPC::SELECT_QFRC || 11643 MI.getOpcode() == PPC::SELECT_QSRC || 11644 MI.getOpcode() == PPC::SELECT_QBRC || 11645 MI.getOpcode() == PPC::SELECT_SPE || 11646 MI.getOpcode() == PPC::SELECT_SPE4 || 11647 MI.getOpcode() == PPC::SELECT_VRRC || 11648 MI.getOpcode() == PPC::SELECT_VSFRC || 11649 MI.getOpcode() == PPC::SELECT_VSSRC || 11650 MI.getOpcode() == PPC::SELECT_VSRC) { 11651 // The incoming instruction knows the destination vreg to set, the 11652 // condition code register to branch on, the true/false values to 11653 // select between, and a branch opcode to use. 11654 11655 // thisMBB: 11656 // ... 11657 // TrueVal = ... 11658 // cmpTY ccX, r1, r2 11659 // bCC copy1MBB 11660 // fallthrough --> copy0MBB 11661 MachineBasicBlock *thisMBB = BB; 11662 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11663 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11664 DebugLoc dl = MI.getDebugLoc(); 11665 F->insert(It, copy0MBB); 11666 F->insert(It, sinkMBB); 11667 11668 // Transfer the remainder of BB and its successor edges to sinkMBB. 11669 sinkMBB->splice(sinkMBB->begin(), BB, 11670 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11671 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11672 11673 // Next, add the true and fallthrough blocks as its successors. 11674 BB->addSuccessor(copy0MBB); 11675 BB->addSuccessor(sinkMBB); 11676 11677 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11678 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11679 MI.getOpcode() == PPC::SELECT_F16 || 11680 MI.getOpcode() == PPC::SELECT_SPE4 || 11681 MI.getOpcode() == PPC::SELECT_SPE || 11682 MI.getOpcode() == PPC::SELECT_QFRC || 11683 MI.getOpcode() == PPC::SELECT_QSRC || 11684 MI.getOpcode() == PPC::SELECT_QBRC || 11685 MI.getOpcode() == PPC::SELECT_VRRC || 11686 MI.getOpcode() == PPC::SELECT_VSFRC || 11687 MI.getOpcode() == PPC::SELECT_VSSRC || 11688 MI.getOpcode() == PPC::SELECT_VSRC) { 11689 BuildMI(BB, dl, TII->get(PPC::BC)) 11690 .addReg(MI.getOperand(1).getReg()) 11691 .addMBB(sinkMBB); 11692 } else { 11693 unsigned SelectPred = MI.getOperand(4).getImm(); 11694 BuildMI(BB, dl, TII->get(PPC::BCC)) 11695 .addImm(SelectPred) 11696 .addReg(MI.getOperand(1).getReg()) 11697 .addMBB(sinkMBB); 11698 } 11699 11700 // copy0MBB: 11701 // %FalseValue = ... 11702 // # fallthrough to sinkMBB 11703 BB = copy0MBB; 11704 11705 // Update machine-CFG edges 11706 BB->addSuccessor(sinkMBB); 11707 11708 // sinkMBB: 11709 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11710 // ... 11711 BB = sinkMBB; 11712 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11713 .addReg(MI.getOperand(3).getReg()) 11714 .addMBB(copy0MBB) 11715 .addReg(MI.getOperand(2).getReg()) 11716 .addMBB(thisMBB); 11717 } else if (MI.getOpcode() == PPC::ReadTB) { 11718 // To read the 64-bit time-base register on a 32-bit target, we read the 11719 // two halves. Should the counter have wrapped while it was being read, we 11720 // need to try again. 11721 // ... 11722 // readLoop: 11723 // mfspr Rx,TBU # load from TBU 11724 // mfspr Ry,TB # load from TB 11725 // mfspr Rz,TBU # load from TBU 11726 // cmpw crX,Rx,Rz # check if 'old'='new' 11727 // bne readLoop # branch if they're not equal 11728 // ... 11729 11730 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11731 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11732 DebugLoc dl = MI.getDebugLoc(); 11733 F->insert(It, readMBB); 11734 F->insert(It, sinkMBB); 11735 11736 // Transfer the remainder of BB and its successor edges to sinkMBB. 11737 sinkMBB->splice(sinkMBB->begin(), BB, 11738 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11739 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11740 11741 BB->addSuccessor(readMBB); 11742 BB = readMBB; 11743 11744 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11745 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11746 Register LoReg = MI.getOperand(0).getReg(); 11747 Register HiReg = MI.getOperand(1).getReg(); 11748 11749 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11750 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11751 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11752 11753 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11754 11755 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11756 .addReg(HiReg) 11757 .addReg(ReadAgainReg); 11758 BuildMI(BB, dl, TII->get(PPC::BCC)) 11759 .addImm(PPC::PRED_NE) 11760 .addReg(CmpReg) 11761 .addMBB(readMBB); 11762 11763 BB->addSuccessor(readMBB); 11764 BB->addSuccessor(sinkMBB); 11765 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11766 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11767 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11768 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11769 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11770 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11771 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11772 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11773 11774 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11775 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11776 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11777 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11778 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11779 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11780 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11781 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11782 11783 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11784 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11785 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11786 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11787 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11788 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11789 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11790 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11791 11792 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11793 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11794 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11795 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11796 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11797 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11798 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11799 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11800 11801 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11802 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11803 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11804 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11805 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11806 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11807 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11808 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11809 11810 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11811 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11812 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11813 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11814 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11815 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11817 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11818 11819 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11820 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11821 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11822 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11824 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11826 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11827 11828 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11829 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11830 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11831 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11833 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11835 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11836 11837 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11838 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11839 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11840 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11842 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11844 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11845 11846 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11847 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11848 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11849 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11851 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11853 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11854 11855 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11856 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11857 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11858 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11859 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11860 BB = EmitAtomicBinary(MI, BB, 4, 0); 11861 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11862 BB = EmitAtomicBinary(MI, BB, 8, 0); 11863 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11864 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11865 (Subtarget.hasPartwordAtomics() && 11866 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11867 (Subtarget.hasPartwordAtomics() && 11868 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11869 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11870 11871 auto LoadMnemonic = PPC::LDARX; 11872 auto StoreMnemonic = PPC::STDCX; 11873 switch (MI.getOpcode()) { 11874 default: 11875 llvm_unreachable("Compare and swap of unknown size"); 11876 case PPC::ATOMIC_CMP_SWAP_I8: 11877 LoadMnemonic = PPC::LBARX; 11878 StoreMnemonic = PPC::STBCX; 11879 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11880 break; 11881 case PPC::ATOMIC_CMP_SWAP_I16: 11882 LoadMnemonic = PPC::LHARX; 11883 StoreMnemonic = PPC::STHCX; 11884 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11885 break; 11886 case PPC::ATOMIC_CMP_SWAP_I32: 11887 LoadMnemonic = PPC::LWARX; 11888 StoreMnemonic = PPC::STWCX; 11889 break; 11890 case PPC::ATOMIC_CMP_SWAP_I64: 11891 LoadMnemonic = PPC::LDARX; 11892 StoreMnemonic = PPC::STDCX; 11893 break; 11894 } 11895 Register dest = MI.getOperand(0).getReg(); 11896 Register ptrA = MI.getOperand(1).getReg(); 11897 Register ptrB = MI.getOperand(2).getReg(); 11898 Register oldval = MI.getOperand(3).getReg(); 11899 Register newval = MI.getOperand(4).getReg(); 11900 DebugLoc dl = MI.getDebugLoc(); 11901 11902 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11903 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11904 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11905 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11906 F->insert(It, loop1MBB); 11907 F->insert(It, loop2MBB); 11908 F->insert(It, midMBB); 11909 F->insert(It, exitMBB); 11910 exitMBB->splice(exitMBB->begin(), BB, 11911 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11912 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11913 11914 // thisMBB: 11915 // ... 11916 // fallthrough --> loopMBB 11917 BB->addSuccessor(loop1MBB); 11918 11919 // loop1MBB: 11920 // l[bhwd]arx dest, ptr 11921 // cmp[wd] dest, oldval 11922 // bne- midMBB 11923 // loop2MBB: 11924 // st[bhwd]cx. newval, ptr 11925 // bne- loopMBB 11926 // b exitBB 11927 // midMBB: 11928 // st[bhwd]cx. dest, ptr 11929 // exitBB: 11930 BB = loop1MBB; 11931 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11932 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11933 .addReg(oldval) 11934 .addReg(dest); 11935 BuildMI(BB, dl, TII->get(PPC::BCC)) 11936 .addImm(PPC::PRED_NE) 11937 .addReg(PPC::CR0) 11938 .addMBB(midMBB); 11939 BB->addSuccessor(loop2MBB); 11940 BB->addSuccessor(midMBB); 11941 11942 BB = loop2MBB; 11943 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11944 .addReg(newval) 11945 .addReg(ptrA) 11946 .addReg(ptrB); 11947 BuildMI(BB, dl, TII->get(PPC::BCC)) 11948 .addImm(PPC::PRED_NE) 11949 .addReg(PPC::CR0) 11950 .addMBB(loop1MBB); 11951 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11952 BB->addSuccessor(loop1MBB); 11953 BB->addSuccessor(exitMBB); 11954 11955 BB = midMBB; 11956 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11957 .addReg(dest) 11958 .addReg(ptrA) 11959 .addReg(ptrB); 11960 BB->addSuccessor(exitMBB); 11961 11962 // exitMBB: 11963 // ... 11964 BB = exitMBB; 11965 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11966 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11967 // We must use 64-bit registers for addresses when targeting 64-bit, 11968 // since we're actually doing arithmetic on them. Other registers 11969 // can be 32-bit. 11970 bool is64bit = Subtarget.isPPC64(); 11971 bool isLittleEndian = Subtarget.isLittleEndian(); 11972 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11973 11974 Register dest = MI.getOperand(0).getReg(); 11975 Register ptrA = MI.getOperand(1).getReg(); 11976 Register ptrB = MI.getOperand(2).getReg(); 11977 Register oldval = MI.getOperand(3).getReg(); 11978 Register newval = MI.getOperand(4).getReg(); 11979 DebugLoc dl = MI.getDebugLoc(); 11980 11981 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11982 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11983 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11984 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11985 F->insert(It, loop1MBB); 11986 F->insert(It, loop2MBB); 11987 F->insert(It, midMBB); 11988 F->insert(It, exitMBB); 11989 exitMBB->splice(exitMBB->begin(), BB, 11990 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11991 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11992 11993 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11994 const TargetRegisterClass *RC = 11995 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11996 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11997 11998 Register PtrReg = RegInfo.createVirtualRegister(RC); 11999 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12000 Register ShiftReg = 12001 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12002 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12003 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12004 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12005 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12006 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12007 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12008 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12009 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12010 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12011 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12012 Register Ptr1Reg; 12013 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12014 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12015 // thisMBB: 12016 // ... 12017 // fallthrough --> loopMBB 12018 BB->addSuccessor(loop1MBB); 12019 12020 // The 4-byte load must be aligned, while a char or short may be 12021 // anywhere in the word. Hence all this nasty bookkeeping code. 12022 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12023 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12024 // xori shift, shift1, 24 [16] 12025 // rlwinm ptr, ptr1, 0, 0, 29 12026 // slw newval2, newval, shift 12027 // slw oldval2, oldval,shift 12028 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12029 // slw mask, mask2, shift 12030 // and newval3, newval2, mask 12031 // and oldval3, oldval2, mask 12032 // loop1MBB: 12033 // lwarx tmpDest, ptr 12034 // and tmp, tmpDest, mask 12035 // cmpw tmp, oldval3 12036 // bne- midMBB 12037 // loop2MBB: 12038 // andc tmp2, tmpDest, mask 12039 // or tmp4, tmp2, newval3 12040 // stwcx. tmp4, ptr 12041 // bne- loop1MBB 12042 // b exitBB 12043 // midMBB: 12044 // stwcx. tmpDest, ptr 12045 // exitBB: 12046 // srw dest, tmpDest, shift 12047 if (ptrA != ZeroReg) { 12048 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12049 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12050 .addReg(ptrA) 12051 .addReg(ptrB); 12052 } else { 12053 Ptr1Reg = ptrB; 12054 } 12055 12056 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12057 // mode. 12058 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12059 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12060 .addImm(3) 12061 .addImm(27) 12062 .addImm(is8bit ? 28 : 27); 12063 if (!isLittleEndian) 12064 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12065 .addReg(Shift1Reg) 12066 .addImm(is8bit ? 24 : 16); 12067 if (is64bit) 12068 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12069 .addReg(Ptr1Reg) 12070 .addImm(0) 12071 .addImm(61); 12072 else 12073 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12074 .addReg(Ptr1Reg) 12075 .addImm(0) 12076 .addImm(0) 12077 .addImm(29); 12078 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12079 .addReg(newval) 12080 .addReg(ShiftReg); 12081 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12082 .addReg(oldval) 12083 .addReg(ShiftReg); 12084 if (is8bit) 12085 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12086 else { 12087 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12088 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12089 .addReg(Mask3Reg) 12090 .addImm(65535); 12091 } 12092 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12093 .addReg(Mask2Reg) 12094 .addReg(ShiftReg); 12095 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12096 .addReg(NewVal2Reg) 12097 .addReg(MaskReg); 12098 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12099 .addReg(OldVal2Reg) 12100 .addReg(MaskReg); 12101 12102 BB = loop1MBB; 12103 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12104 .addReg(ZeroReg) 12105 .addReg(PtrReg); 12106 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12107 .addReg(TmpDestReg) 12108 .addReg(MaskReg); 12109 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12110 .addReg(TmpReg) 12111 .addReg(OldVal3Reg); 12112 BuildMI(BB, dl, TII->get(PPC::BCC)) 12113 .addImm(PPC::PRED_NE) 12114 .addReg(PPC::CR0) 12115 .addMBB(midMBB); 12116 BB->addSuccessor(loop2MBB); 12117 BB->addSuccessor(midMBB); 12118 12119 BB = loop2MBB; 12120 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12121 .addReg(TmpDestReg) 12122 .addReg(MaskReg); 12123 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12124 .addReg(Tmp2Reg) 12125 .addReg(NewVal3Reg); 12126 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12127 .addReg(Tmp4Reg) 12128 .addReg(ZeroReg) 12129 .addReg(PtrReg); 12130 BuildMI(BB, dl, TII->get(PPC::BCC)) 12131 .addImm(PPC::PRED_NE) 12132 .addReg(PPC::CR0) 12133 .addMBB(loop1MBB); 12134 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12135 BB->addSuccessor(loop1MBB); 12136 BB->addSuccessor(exitMBB); 12137 12138 BB = midMBB; 12139 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12140 .addReg(TmpDestReg) 12141 .addReg(ZeroReg) 12142 .addReg(PtrReg); 12143 BB->addSuccessor(exitMBB); 12144 12145 // exitMBB: 12146 // ... 12147 BB = exitMBB; 12148 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12149 .addReg(TmpReg) 12150 .addReg(ShiftReg); 12151 } else if (MI.getOpcode() == PPC::FADDrtz) { 12152 // This pseudo performs an FADD with rounding mode temporarily forced 12153 // to round-to-zero. We emit this via custom inserter since the FPSCR 12154 // is not modeled at the SelectionDAG level. 12155 Register Dest = MI.getOperand(0).getReg(); 12156 Register Src1 = MI.getOperand(1).getReg(); 12157 Register Src2 = MI.getOperand(2).getReg(); 12158 DebugLoc dl = MI.getDebugLoc(); 12159 12160 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12161 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12162 12163 // Save FPSCR value. 12164 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12165 12166 // Set rounding mode to round-to-zero. 12167 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12168 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12169 12170 // Perform addition. 12171 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12172 12173 // Restore FPSCR value. 12174 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12175 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12176 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12177 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12178 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12179 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12180 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12181 ? PPC::ANDI8_rec 12182 : PPC::ANDI_rec; 12183 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12184 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12185 12186 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12187 Register Dest = RegInfo.createVirtualRegister( 12188 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12189 12190 DebugLoc Dl = MI.getDebugLoc(); 12191 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12192 .addReg(MI.getOperand(1).getReg()) 12193 .addImm(1); 12194 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12195 MI.getOperand(0).getReg()) 12196 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12197 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12198 DebugLoc Dl = MI.getDebugLoc(); 12199 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12200 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12201 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12202 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12203 MI.getOperand(0).getReg()) 12204 .addReg(CRReg); 12205 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12206 DebugLoc Dl = MI.getDebugLoc(); 12207 unsigned Imm = MI.getOperand(1).getImm(); 12208 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12209 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12210 MI.getOperand(0).getReg()) 12211 .addReg(PPC::CR0EQ); 12212 } else if (MI.getOpcode() == PPC::SETRNDi) { 12213 DebugLoc dl = MI.getDebugLoc(); 12214 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12215 12216 // Save FPSCR value. 12217 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12218 12219 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12220 // the following settings: 12221 // 00 Round to nearest 12222 // 01 Round to 0 12223 // 10 Round to +inf 12224 // 11 Round to -inf 12225 12226 // When the operand is immediate, using the two least significant bits of 12227 // the immediate to set the bits 62:63 of FPSCR. 12228 unsigned Mode = MI.getOperand(1).getImm(); 12229 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12230 .addImm(31); 12231 12232 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12233 .addImm(30); 12234 } else if (MI.getOpcode() == PPC::SETRND) { 12235 DebugLoc dl = MI.getDebugLoc(); 12236 12237 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12238 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12239 // If the target doesn't have DirectMove, we should use stack to do the 12240 // conversion, because the target doesn't have the instructions like mtvsrd 12241 // or mfvsrd to do this conversion directly. 12242 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12243 if (Subtarget.hasDirectMove()) { 12244 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12245 .addReg(SrcReg); 12246 } else { 12247 // Use stack to do the register copy. 12248 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12249 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12250 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12251 if (RC == &PPC::F8RCRegClass) { 12252 // Copy register from F8RCRegClass to G8RCRegclass. 12253 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12254 "Unsupported RegClass."); 12255 12256 StoreOp = PPC::STFD; 12257 LoadOp = PPC::LD; 12258 } else { 12259 // Copy register from G8RCRegClass to F8RCRegclass. 12260 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12261 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12262 "Unsupported RegClass."); 12263 } 12264 12265 MachineFrameInfo &MFI = F->getFrameInfo(); 12266 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12267 12268 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12269 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12270 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12271 MFI.getObjectAlign(FrameIdx)); 12272 12273 // Store the SrcReg into the stack. 12274 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12275 .addReg(SrcReg) 12276 .addImm(0) 12277 .addFrameIndex(FrameIdx) 12278 .addMemOperand(MMOStore); 12279 12280 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12281 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12282 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12283 MFI.getObjectAlign(FrameIdx)); 12284 12285 // Load from the stack where SrcReg is stored, and save to DestReg, 12286 // so we have done the RegClass conversion from RegClass::SrcReg to 12287 // RegClass::DestReg. 12288 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12289 .addImm(0) 12290 .addFrameIndex(FrameIdx) 12291 .addMemOperand(MMOLoad); 12292 } 12293 }; 12294 12295 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12296 12297 // Save FPSCR value. 12298 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12299 12300 // When the operand is gprc register, use two least significant bits of the 12301 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12302 // 12303 // copy OldFPSCRTmpReg, OldFPSCRReg 12304 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12305 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12306 // copy NewFPSCRReg, NewFPSCRTmpReg 12307 // mtfsf 255, NewFPSCRReg 12308 MachineOperand SrcOp = MI.getOperand(1); 12309 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12310 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12311 12312 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12313 12314 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12315 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12316 12317 // The first operand of INSERT_SUBREG should be a register which has 12318 // subregisters, we only care about its RegClass, so we should use an 12319 // IMPLICIT_DEF register. 12320 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12321 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12322 .addReg(ImDefReg) 12323 .add(SrcOp) 12324 .addImm(1); 12325 12326 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12327 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12328 .addReg(OldFPSCRTmpReg) 12329 .addReg(ExtSrcReg) 12330 .addImm(0) 12331 .addImm(62); 12332 12333 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12334 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12335 12336 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12337 // bits of FPSCR. 12338 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12339 .addImm(255) 12340 .addReg(NewFPSCRReg) 12341 .addImm(0) 12342 .addImm(0); 12343 } else { 12344 llvm_unreachable("Unexpected instr type to insert"); 12345 } 12346 12347 MI.eraseFromParent(); // The pseudo instruction is gone now. 12348 return BB; 12349 } 12350 12351 //===----------------------------------------------------------------------===// 12352 // Target Optimization Hooks 12353 //===----------------------------------------------------------------------===// 12354 12355 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12356 // For the estimates, convergence is quadratic, so we essentially double the 12357 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12358 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12359 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12360 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12361 if (VT.getScalarType() == MVT::f64) 12362 RefinementSteps++; 12363 return RefinementSteps; 12364 } 12365 12366 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12367 int Enabled, int &RefinementSteps, 12368 bool &UseOneConstNR, 12369 bool Reciprocal) const { 12370 EVT VT = Operand.getValueType(); 12371 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12372 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12373 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12374 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12375 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12376 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12377 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12378 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12379 12380 // The Newton-Raphson computation with a single constant does not provide 12381 // enough accuracy on some CPUs. 12382 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12383 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12384 } 12385 return SDValue(); 12386 } 12387 12388 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12389 int Enabled, 12390 int &RefinementSteps) const { 12391 EVT VT = Operand.getValueType(); 12392 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12393 (VT == MVT::f64 && Subtarget.hasFRE()) || 12394 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12395 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12396 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12397 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12398 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12399 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12400 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12401 } 12402 return SDValue(); 12403 } 12404 12405 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12406 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12407 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12408 // enabled for division), this functionality is redundant with the default 12409 // combiner logic (once the division -> reciprocal/multiply transformation 12410 // has taken place). As a result, this matters more for older cores than for 12411 // newer ones. 12412 12413 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12414 // reciprocal if there are two or more FDIVs (for embedded cores with only 12415 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12416 switch (Subtarget.getCPUDirective()) { 12417 default: 12418 return 3; 12419 case PPC::DIR_440: 12420 case PPC::DIR_A2: 12421 case PPC::DIR_E500: 12422 case PPC::DIR_E500mc: 12423 case PPC::DIR_E5500: 12424 return 2; 12425 } 12426 } 12427 12428 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12429 // collapsed, and so we need to look through chains of them. 12430 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12431 int64_t& Offset, SelectionDAG &DAG) { 12432 if (DAG.isBaseWithConstantOffset(Loc)) { 12433 Base = Loc.getOperand(0); 12434 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12435 12436 // The base might itself be a base plus an offset, and if so, accumulate 12437 // that as well. 12438 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12439 } 12440 } 12441 12442 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12443 unsigned Bytes, int Dist, 12444 SelectionDAG &DAG) { 12445 if (VT.getSizeInBits() / 8 != Bytes) 12446 return false; 12447 12448 SDValue BaseLoc = Base->getBasePtr(); 12449 if (Loc.getOpcode() == ISD::FrameIndex) { 12450 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12451 return false; 12452 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12453 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12454 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12455 int FS = MFI.getObjectSize(FI); 12456 int BFS = MFI.getObjectSize(BFI); 12457 if (FS != BFS || FS != (int)Bytes) return false; 12458 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12459 } 12460 12461 SDValue Base1 = Loc, Base2 = BaseLoc; 12462 int64_t Offset1 = 0, Offset2 = 0; 12463 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12464 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12465 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12466 return true; 12467 12468 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12469 const GlobalValue *GV1 = nullptr; 12470 const GlobalValue *GV2 = nullptr; 12471 Offset1 = 0; 12472 Offset2 = 0; 12473 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12474 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12475 if (isGA1 && isGA2 && GV1 == GV2) 12476 return Offset1 == (Offset2 + Dist*Bytes); 12477 return false; 12478 } 12479 12480 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12481 // not enforce equality of the chain operands. 12482 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12483 unsigned Bytes, int Dist, 12484 SelectionDAG &DAG) { 12485 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12486 EVT VT = LS->getMemoryVT(); 12487 SDValue Loc = LS->getBasePtr(); 12488 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12489 } 12490 12491 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12492 EVT VT; 12493 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12494 default: return false; 12495 case Intrinsic::ppc_qpx_qvlfd: 12496 case Intrinsic::ppc_qpx_qvlfda: 12497 VT = MVT::v4f64; 12498 break; 12499 case Intrinsic::ppc_qpx_qvlfs: 12500 case Intrinsic::ppc_qpx_qvlfsa: 12501 VT = MVT::v4f32; 12502 break; 12503 case Intrinsic::ppc_qpx_qvlfcd: 12504 case Intrinsic::ppc_qpx_qvlfcda: 12505 VT = MVT::v2f64; 12506 break; 12507 case Intrinsic::ppc_qpx_qvlfcs: 12508 case Intrinsic::ppc_qpx_qvlfcsa: 12509 VT = MVT::v2f32; 12510 break; 12511 case Intrinsic::ppc_qpx_qvlfiwa: 12512 case Intrinsic::ppc_qpx_qvlfiwz: 12513 case Intrinsic::ppc_altivec_lvx: 12514 case Intrinsic::ppc_altivec_lvxl: 12515 case Intrinsic::ppc_vsx_lxvw4x: 12516 case Intrinsic::ppc_vsx_lxvw4x_be: 12517 VT = MVT::v4i32; 12518 break; 12519 case Intrinsic::ppc_vsx_lxvd2x: 12520 case Intrinsic::ppc_vsx_lxvd2x_be: 12521 VT = MVT::v2f64; 12522 break; 12523 case Intrinsic::ppc_altivec_lvebx: 12524 VT = MVT::i8; 12525 break; 12526 case Intrinsic::ppc_altivec_lvehx: 12527 VT = MVT::i16; 12528 break; 12529 case Intrinsic::ppc_altivec_lvewx: 12530 VT = MVT::i32; 12531 break; 12532 } 12533 12534 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12535 } 12536 12537 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12538 EVT VT; 12539 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12540 default: return false; 12541 case Intrinsic::ppc_qpx_qvstfd: 12542 case Intrinsic::ppc_qpx_qvstfda: 12543 VT = MVT::v4f64; 12544 break; 12545 case Intrinsic::ppc_qpx_qvstfs: 12546 case Intrinsic::ppc_qpx_qvstfsa: 12547 VT = MVT::v4f32; 12548 break; 12549 case Intrinsic::ppc_qpx_qvstfcd: 12550 case Intrinsic::ppc_qpx_qvstfcda: 12551 VT = MVT::v2f64; 12552 break; 12553 case Intrinsic::ppc_qpx_qvstfcs: 12554 case Intrinsic::ppc_qpx_qvstfcsa: 12555 VT = MVT::v2f32; 12556 break; 12557 case Intrinsic::ppc_qpx_qvstfiw: 12558 case Intrinsic::ppc_qpx_qvstfiwa: 12559 case Intrinsic::ppc_altivec_stvx: 12560 case Intrinsic::ppc_altivec_stvxl: 12561 case Intrinsic::ppc_vsx_stxvw4x: 12562 VT = MVT::v4i32; 12563 break; 12564 case Intrinsic::ppc_vsx_stxvd2x: 12565 VT = MVT::v2f64; 12566 break; 12567 case Intrinsic::ppc_vsx_stxvw4x_be: 12568 VT = MVT::v4i32; 12569 break; 12570 case Intrinsic::ppc_vsx_stxvd2x_be: 12571 VT = MVT::v2f64; 12572 break; 12573 case Intrinsic::ppc_altivec_stvebx: 12574 VT = MVT::i8; 12575 break; 12576 case Intrinsic::ppc_altivec_stvehx: 12577 VT = MVT::i16; 12578 break; 12579 case Intrinsic::ppc_altivec_stvewx: 12580 VT = MVT::i32; 12581 break; 12582 } 12583 12584 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12585 } 12586 12587 return false; 12588 } 12589 12590 // Return true is there is a nearyby consecutive load to the one provided 12591 // (regardless of alignment). We search up and down the chain, looking though 12592 // token factors and other loads (but nothing else). As a result, a true result 12593 // indicates that it is safe to create a new consecutive load adjacent to the 12594 // load provided. 12595 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12596 SDValue Chain = LD->getChain(); 12597 EVT VT = LD->getMemoryVT(); 12598 12599 SmallSet<SDNode *, 16> LoadRoots; 12600 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12601 SmallSet<SDNode *, 16> Visited; 12602 12603 // First, search up the chain, branching to follow all token-factor operands. 12604 // If we find a consecutive load, then we're done, otherwise, record all 12605 // nodes just above the top-level loads and token factors. 12606 while (!Queue.empty()) { 12607 SDNode *ChainNext = Queue.pop_back_val(); 12608 if (!Visited.insert(ChainNext).second) 12609 continue; 12610 12611 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12612 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12613 return true; 12614 12615 if (!Visited.count(ChainLD->getChain().getNode())) 12616 Queue.push_back(ChainLD->getChain().getNode()); 12617 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12618 for (const SDUse &O : ChainNext->ops()) 12619 if (!Visited.count(O.getNode())) 12620 Queue.push_back(O.getNode()); 12621 } else 12622 LoadRoots.insert(ChainNext); 12623 } 12624 12625 // Second, search down the chain, starting from the top-level nodes recorded 12626 // in the first phase. These top-level nodes are the nodes just above all 12627 // loads and token factors. Starting with their uses, recursively look though 12628 // all loads (just the chain uses) and token factors to find a consecutive 12629 // load. 12630 Visited.clear(); 12631 Queue.clear(); 12632 12633 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12634 IE = LoadRoots.end(); I != IE; ++I) { 12635 Queue.push_back(*I); 12636 12637 while (!Queue.empty()) { 12638 SDNode *LoadRoot = Queue.pop_back_val(); 12639 if (!Visited.insert(LoadRoot).second) 12640 continue; 12641 12642 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12643 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12644 return true; 12645 12646 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12647 UE = LoadRoot->use_end(); UI != UE; ++UI) 12648 if (((isa<MemSDNode>(*UI) && 12649 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12650 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12651 Queue.push_back(*UI); 12652 } 12653 } 12654 12655 return false; 12656 } 12657 12658 /// This function is called when we have proved that a SETCC node can be replaced 12659 /// by subtraction (and other supporting instructions) so that the result of 12660 /// comparison is kept in a GPR instead of CR. This function is purely for 12661 /// codegen purposes and has some flags to guide the codegen process. 12662 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12663 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12664 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12665 12666 // Zero extend the operands to the largest legal integer. Originally, they 12667 // must be of a strictly smaller size. 12668 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12669 DAG.getConstant(Size, DL, MVT::i32)); 12670 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12671 DAG.getConstant(Size, DL, MVT::i32)); 12672 12673 // Swap if needed. Depends on the condition code. 12674 if (Swap) 12675 std::swap(Op0, Op1); 12676 12677 // Subtract extended integers. 12678 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12679 12680 // Move the sign bit to the least significant position and zero out the rest. 12681 // Now the least significant bit carries the result of original comparison. 12682 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12683 DAG.getConstant(Size - 1, DL, MVT::i32)); 12684 auto Final = Shifted; 12685 12686 // Complement the result if needed. Based on the condition code. 12687 if (Complement) 12688 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12689 DAG.getConstant(1, DL, MVT::i64)); 12690 12691 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12692 } 12693 12694 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12695 DAGCombinerInfo &DCI) const { 12696 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12697 12698 SelectionDAG &DAG = DCI.DAG; 12699 SDLoc DL(N); 12700 12701 // Size of integers being compared has a critical role in the following 12702 // analysis, so we prefer to do this when all types are legal. 12703 if (!DCI.isAfterLegalizeDAG()) 12704 return SDValue(); 12705 12706 // If all users of SETCC extend its value to a legal integer type 12707 // then we replace SETCC with a subtraction 12708 for (SDNode::use_iterator UI = N->use_begin(), 12709 UE = N->use_end(); UI != UE; ++UI) { 12710 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12711 return SDValue(); 12712 } 12713 12714 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12715 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12716 12717 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12718 12719 if (OpSize < Size) { 12720 switch (CC) { 12721 default: break; 12722 case ISD::SETULT: 12723 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12724 case ISD::SETULE: 12725 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12726 case ISD::SETUGT: 12727 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12728 case ISD::SETUGE: 12729 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12730 } 12731 } 12732 12733 return SDValue(); 12734 } 12735 12736 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12737 DAGCombinerInfo &DCI) const { 12738 SelectionDAG &DAG = DCI.DAG; 12739 SDLoc dl(N); 12740 12741 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12742 // If we're tracking CR bits, we need to be careful that we don't have: 12743 // trunc(binary-ops(zext(x), zext(y))) 12744 // or 12745 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12746 // such that we're unnecessarily moving things into GPRs when it would be 12747 // better to keep them in CR bits. 12748 12749 // Note that trunc here can be an actual i1 trunc, or can be the effective 12750 // truncation that comes from a setcc or select_cc. 12751 if (N->getOpcode() == ISD::TRUNCATE && 12752 N->getValueType(0) != MVT::i1) 12753 return SDValue(); 12754 12755 if (N->getOperand(0).getValueType() != MVT::i32 && 12756 N->getOperand(0).getValueType() != MVT::i64) 12757 return SDValue(); 12758 12759 if (N->getOpcode() == ISD::SETCC || 12760 N->getOpcode() == ISD::SELECT_CC) { 12761 // If we're looking at a comparison, then we need to make sure that the 12762 // high bits (all except for the first) don't matter the result. 12763 ISD::CondCode CC = 12764 cast<CondCodeSDNode>(N->getOperand( 12765 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12766 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12767 12768 if (ISD::isSignedIntSetCC(CC)) { 12769 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12770 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12771 return SDValue(); 12772 } else if (ISD::isUnsignedIntSetCC(CC)) { 12773 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12774 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12775 !DAG.MaskedValueIsZero(N->getOperand(1), 12776 APInt::getHighBitsSet(OpBits, OpBits-1))) 12777 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12778 : SDValue()); 12779 } else { 12780 // This is neither a signed nor an unsigned comparison, just make sure 12781 // that the high bits are equal. 12782 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12783 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12784 12785 // We don't really care about what is known about the first bit (if 12786 // anything), so clear it in all masks prior to comparing them. 12787 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12788 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12789 12790 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12791 return SDValue(); 12792 } 12793 } 12794 12795 // We now know that the higher-order bits are irrelevant, we just need to 12796 // make sure that all of the intermediate operations are bit operations, and 12797 // all inputs are extensions. 12798 if (N->getOperand(0).getOpcode() != ISD::AND && 12799 N->getOperand(0).getOpcode() != ISD::OR && 12800 N->getOperand(0).getOpcode() != ISD::XOR && 12801 N->getOperand(0).getOpcode() != ISD::SELECT && 12802 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12803 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12804 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12805 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12806 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12807 return SDValue(); 12808 12809 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12810 N->getOperand(1).getOpcode() != ISD::AND && 12811 N->getOperand(1).getOpcode() != ISD::OR && 12812 N->getOperand(1).getOpcode() != ISD::XOR && 12813 N->getOperand(1).getOpcode() != ISD::SELECT && 12814 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12815 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12816 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12817 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12818 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12819 return SDValue(); 12820 12821 SmallVector<SDValue, 4> Inputs; 12822 SmallVector<SDValue, 8> BinOps, PromOps; 12823 SmallPtrSet<SDNode *, 16> Visited; 12824 12825 for (unsigned i = 0; i < 2; ++i) { 12826 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12827 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12828 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12829 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12830 isa<ConstantSDNode>(N->getOperand(i))) 12831 Inputs.push_back(N->getOperand(i)); 12832 else 12833 BinOps.push_back(N->getOperand(i)); 12834 12835 if (N->getOpcode() == ISD::TRUNCATE) 12836 break; 12837 } 12838 12839 // Visit all inputs, collect all binary operations (and, or, xor and 12840 // select) that are all fed by extensions. 12841 while (!BinOps.empty()) { 12842 SDValue BinOp = BinOps.back(); 12843 BinOps.pop_back(); 12844 12845 if (!Visited.insert(BinOp.getNode()).second) 12846 continue; 12847 12848 PromOps.push_back(BinOp); 12849 12850 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12851 // The condition of the select is not promoted. 12852 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12853 continue; 12854 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12855 continue; 12856 12857 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12858 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12859 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12860 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12861 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12862 Inputs.push_back(BinOp.getOperand(i)); 12863 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12864 BinOp.getOperand(i).getOpcode() == ISD::OR || 12865 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12866 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12867 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12868 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12869 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12870 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12871 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12872 BinOps.push_back(BinOp.getOperand(i)); 12873 } else { 12874 // We have an input that is not an extension or another binary 12875 // operation; we'll abort this transformation. 12876 return SDValue(); 12877 } 12878 } 12879 } 12880 12881 // Make sure that this is a self-contained cluster of operations (which 12882 // is not quite the same thing as saying that everything has only one 12883 // use). 12884 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12885 if (isa<ConstantSDNode>(Inputs[i])) 12886 continue; 12887 12888 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12889 UE = Inputs[i].getNode()->use_end(); 12890 UI != UE; ++UI) { 12891 SDNode *User = *UI; 12892 if (User != N && !Visited.count(User)) 12893 return SDValue(); 12894 12895 // Make sure that we're not going to promote the non-output-value 12896 // operand(s) or SELECT or SELECT_CC. 12897 // FIXME: Although we could sometimes handle this, and it does occur in 12898 // practice that one of the condition inputs to the select is also one of 12899 // the outputs, we currently can't deal with this. 12900 if (User->getOpcode() == ISD::SELECT) { 12901 if (User->getOperand(0) == Inputs[i]) 12902 return SDValue(); 12903 } else if (User->getOpcode() == ISD::SELECT_CC) { 12904 if (User->getOperand(0) == Inputs[i] || 12905 User->getOperand(1) == Inputs[i]) 12906 return SDValue(); 12907 } 12908 } 12909 } 12910 12911 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12912 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12913 UE = PromOps[i].getNode()->use_end(); 12914 UI != UE; ++UI) { 12915 SDNode *User = *UI; 12916 if (User != N && !Visited.count(User)) 12917 return SDValue(); 12918 12919 // Make sure that we're not going to promote the non-output-value 12920 // operand(s) or SELECT or SELECT_CC. 12921 // FIXME: Although we could sometimes handle this, and it does occur in 12922 // practice that one of the condition inputs to the select is also one of 12923 // the outputs, we currently can't deal with this. 12924 if (User->getOpcode() == ISD::SELECT) { 12925 if (User->getOperand(0) == PromOps[i]) 12926 return SDValue(); 12927 } else if (User->getOpcode() == ISD::SELECT_CC) { 12928 if (User->getOperand(0) == PromOps[i] || 12929 User->getOperand(1) == PromOps[i]) 12930 return SDValue(); 12931 } 12932 } 12933 } 12934 12935 // Replace all inputs with the extension operand. 12936 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12937 // Constants may have users outside the cluster of to-be-promoted nodes, 12938 // and so we need to replace those as we do the promotions. 12939 if (isa<ConstantSDNode>(Inputs[i])) 12940 continue; 12941 else 12942 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12943 } 12944 12945 std::list<HandleSDNode> PromOpHandles; 12946 for (auto &PromOp : PromOps) 12947 PromOpHandles.emplace_back(PromOp); 12948 12949 // Replace all operations (these are all the same, but have a different 12950 // (i1) return type). DAG.getNode will validate that the types of 12951 // a binary operator match, so go through the list in reverse so that 12952 // we've likely promoted both operands first. Any intermediate truncations or 12953 // extensions disappear. 12954 while (!PromOpHandles.empty()) { 12955 SDValue PromOp = PromOpHandles.back().getValue(); 12956 PromOpHandles.pop_back(); 12957 12958 if (PromOp.getOpcode() == ISD::TRUNCATE || 12959 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12960 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12961 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12962 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12963 PromOp.getOperand(0).getValueType() != MVT::i1) { 12964 // The operand is not yet ready (see comment below). 12965 PromOpHandles.emplace_front(PromOp); 12966 continue; 12967 } 12968 12969 SDValue RepValue = PromOp.getOperand(0); 12970 if (isa<ConstantSDNode>(RepValue)) 12971 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12972 12973 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12974 continue; 12975 } 12976 12977 unsigned C; 12978 switch (PromOp.getOpcode()) { 12979 default: C = 0; break; 12980 case ISD::SELECT: C = 1; break; 12981 case ISD::SELECT_CC: C = 2; break; 12982 } 12983 12984 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12985 PromOp.getOperand(C).getValueType() != MVT::i1) || 12986 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12987 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12988 // The to-be-promoted operands of this node have not yet been 12989 // promoted (this should be rare because we're going through the 12990 // list backward, but if one of the operands has several users in 12991 // this cluster of to-be-promoted nodes, it is possible). 12992 PromOpHandles.emplace_front(PromOp); 12993 continue; 12994 } 12995 12996 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12997 PromOp.getNode()->op_end()); 12998 12999 // If there are any constant inputs, make sure they're replaced now. 13000 for (unsigned i = 0; i < 2; ++i) 13001 if (isa<ConstantSDNode>(Ops[C+i])) 13002 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13003 13004 DAG.ReplaceAllUsesOfValueWith(PromOp, 13005 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13006 } 13007 13008 // Now we're left with the initial truncation itself. 13009 if (N->getOpcode() == ISD::TRUNCATE) 13010 return N->getOperand(0); 13011 13012 // Otherwise, this is a comparison. The operands to be compared have just 13013 // changed type (to i1), but everything else is the same. 13014 return SDValue(N, 0); 13015 } 13016 13017 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13018 DAGCombinerInfo &DCI) const { 13019 SelectionDAG &DAG = DCI.DAG; 13020 SDLoc dl(N); 13021 13022 // If we're tracking CR bits, we need to be careful that we don't have: 13023 // zext(binary-ops(trunc(x), trunc(y))) 13024 // or 13025 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13026 // such that we're unnecessarily moving things into CR bits that can more 13027 // efficiently stay in GPRs. Note that if we're not certain that the high 13028 // bits are set as required by the final extension, we still may need to do 13029 // some masking to get the proper behavior. 13030 13031 // This same functionality is important on PPC64 when dealing with 13032 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13033 // the return values of functions. Because it is so similar, it is handled 13034 // here as well. 13035 13036 if (N->getValueType(0) != MVT::i32 && 13037 N->getValueType(0) != MVT::i64) 13038 return SDValue(); 13039 13040 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13041 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13042 return SDValue(); 13043 13044 if (N->getOperand(0).getOpcode() != ISD::AND && 13045 N->getOperand(0).getOpcode() != ISD::OR && 13046 N->getOperand(0).getOpcode() != ISD::XOR && 13047 N->getOperand(0).getOpcode() != ISD::SELECT && 13048 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13049 return SDValue(); 13050 13051 SmallVector<SDValue, 4> Inputs; 13052 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13053 SmallPtrSet<SDNode *, 16> Visited; 13054 13055 // Visit all inputs, collect all binary operations (and, or, xor and 13056 // select) that are all fed by truncations. 13057 while (!BinOps.empty()) { 13058 SDValue BinOp = BinOps.back(); 13059 BinOps.pop_back(); 13060 13061 if (!Visited.insert(BinOp.getNode()).second) 13062 continue; 13063 13064 PromOps.push_back(BinOp); 13065 13066 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13067 // The condition of the select is not promoted. 13068 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13069 continue; 13070 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13071 continue; 13072 13073 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13074 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13075 Inputs.push_back(BinOp.getOperand(i)); 13076 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13077 BinOp.getOperand(i).getOpcode() == ISD::OR || 13078 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13079 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13080 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13081 BinOps.push_back(BinOp.getOperand(i)); 13082 } else { 13083 // We have an input that is not a truncation or another binary 13084 // operation; we'll abort this transformation. 13085 return SDValue(); 13086 } 13087 } 13088 } 13089 13090 // The operands of a select that must be truncated when the select is 13091 // promoted because the operand is actually part of the to-be-promoted set. 13092 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13093 13094 // Make sure that this is a self-contained cluster of operations (which 13095 // is not quite the same thing as saying that everything has only one 13096 // use). 13097 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13098 if (isa<ConstantSDNode>(Inputs[i])) 13099 continue; 13100 13101 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13102 UE = Inputs[i].getNode()->use_end(); 13103 UI != UE; ++UI) { 13104 SDNode *User = *UI; 13105 if (User != N && !Visited.count(User)) 13106 return SDValue(); 13107 13108 // If we're going to promote the non-output-value operand(s) or SELECT or 13109 // SELECT_CC, record them for truncation. 13110 if (User->getOpcode() == ISD::SELECT) { 13111 if (User->getOperand(0) == Inputs[i]) 13112 SelectTruncOp[0].insert(std::make_pair(User, 13113 User->getOperand(0).getValueType())); 13114 } else if (User->getOpcode() == ISD::SELECT_CC) { 13115 if (User->getOperand(0) == Inputs[i]) 13116 SelectTruncOp[0].insert(std::make_pair(User, 13117 User->getOperand(0).getValueType())); 13118 if (User->getOperand(1) == Inputs[i]) 13119 SelectTruncOp[1].insert(std::make_pair(User, 13120 User->getOperand(1).getValueType())); 13121 } 13122 } 13123 } 13124 13125 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13126 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13127 UE = PromOps[i].getNode()->use_end(); 13128 UI != UE; ++UI) { 13129 SDNode *User = *UI; 13130 if (User != N && !Visited.count(User)) 13131 return SDValue(); 13132 13133 // If we're going to promote the non-output-value operand(s) or SELECT or 13134 // SELECT_CC, record them for truncation. 13135 if (User->getOpcode() == ISD::SELECT) { 13136 if (User->getOperand(0) == PromOps[i]) 13137 SelectTruncOp[0].insert(std::make_pair(User, 13138 User->getOperand(0).getValueType())); 13139 } else if (User->getOpcode() == ISD::SELECT_CC) { 13140 if (User->getOperand(0) == PromOps[i]) 13141 SelectTruncOp[0].insert(std::make_pair(User, 13142 User->getOperand(0).getValueType())); 13143 if (User->getOperand(1) == PromOps[i]) 13144 SelectTruncOp[1].insert(std::make_pair(User, 13145 User->getOperand(1).getValueType())); 13146 } 13147 } 13148 } 13149 13150 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13151 bool ReallyNeedsExt = false; 13152 if (N->getOpcode() != ISD::ANY_EXTEND) { 13153 // If all of the inputs are not already sign/zero extended, then 13154 // we'll still need to do that at the end. 13155 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13156 if (isa<ConstantSDNode>(Inputs[i])) 13157 continue; 13158 13159 unsigned OpBits = 13160 Inputs[i].getOperand(0).getValueSizeInBits(); 13161 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13162 13163 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13164 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13165 APInt::getHighBitsSet(OpBits, 13166 OpBits-PromBits))) || 13167 (N->getOpcode() == ISD::SIGN_EXTEND && 13168 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13169 (OpBits-(PromBits-1)))) { 13170 ReallyNeedsExt = true; 13171 break; 13172 } 13173 } 13174 } 13175 13176 // Replace all inputs, either with the truncation operand, or a 13177 // truncation or extension to the final output type. 13178 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13179 // Constant inputs need to be replaced with the to-be-promoted nodes that 13180 // use them because they might have users outside of the cluster of 13181 // promoted nodes. 13182 if (isa<ConstantSDNode>(Inputs[i])) 13183 continue; 13184 13185 SDValue InSrc = Inputs[i].getOperand(0); 13186 if (Inputs[i].getValueType() == N->getValueType(0)) 13187 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13188 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13189 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13190 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13191 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13192 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13193 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13194 else 13195 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13196 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13197 } 13198 13199 std::list<HandleSDNode> PromOpHandles; 13200 for (auto &PromOp : PromOps) 13201 PromOpHandles.emplace_back(PromOp); 13202 13203 // Replace all operations (these are all the same, but have a different 13204 // (promoted) return type). DAG.getNode will validate that the types of 13205 // a binary operator match, so go through the list in reverse so that 13206 // we've likely promoted both operands first. 13207 while (!PromOpHandles.empty()) { 13208 SDValue PromOp = PromOpHandles.back().getValue(); 13209 PromOpHandles.pop_back(); 13210 13211 unsigned C; 13212 switch (PromOp.getOpcode()) { 13213 default: C = 0; break; 13214 case ISD::SELECT: C = 1; break; 13215 case ISD::SELECT_CC: C = 2; break; 13216 } 13217 13218 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13219 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13220 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13221 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13222 // The to-be-promoted operands of this node have not yet been 13223 // promoted (this should be rare because we're going through the 13224 // list backward, but if one of the operands has several users in 13225 // this cluster of to-be-promoted nodes, it is possible). 13226 PromOpHandles.emplace_front(PromOp); 13227 continue; 13228 } 13229 13230 // For SELECT and SELECT_CC nodes, we do a similar check for any 13231 // to-be-promoted comparison inputs. 13232 if (PromOp.getOpcode() == ISD::SELECT || 13233 PromOp.getOpcode() == ISD::SELECT_CC) { 13234 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13235 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13236 (SelectTruncOp[1].count(PromOp.getNode()) && 13237 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13238 PromOpHandles.emplace_front(PromOp); 13239 continue; 13240 } 13241 } 13242 13243 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13244 PromOp.getNode()->op_end()); 13245 13246 // If this node has constant inputs, then they'll need to be promoted here. 13247 for (unsigned i = 0; i < 2; ++i) { 13248 if (!isa<ConstantSDNode>(Ops[C+i])) 13249 continue; 13250 if (Ops[C+i].getValueType() == N->getValueType(0)) 13251 continue; 13252 13253 if (N->getOpcode() == ISD::SIGN_EXTEND) 13254 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13255 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13256 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13257 else 13258 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13259 } 13260 13261 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13262 // truncate them again to the original value type. 13263 if (PromOp.getOpcode() == ISD::SELECT || 13264 PromOp.getOpcode() == ISD::SELECT_CC) { 13265 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13266 if (SI0 != SelectTruncOp[0].end()) 13267 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13268 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13269 if (SI1 != SelectTruncOp[1].end()) 13270 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13271 } 13272 13273 DAG.ReplaceAllUsesOfValueWith(PromOp, 13274 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13275 } 13276 13277 // Now we're left with the initial extension itself. 13278 if (!ReallyNeedsExt) 13279 return N->getOperand(0); 13280 13281 // To zero extend, just mask off everything except for the first bit (in the 13282 // i1 case). 13283 if (N->getOpcode() == ISD::ZERO_EXTEND) 13284 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13285 DAG.getConstant(APInt::getLowBitsSet( 13286 N->getValueSizeInBits(0), PromBits), 13287 dl, N->getValueType(0))); 13288 13289 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13290 "Invalid extension type"); 13291 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13292 SDValue ShiftCst = 13293 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13294 return DAG.getNode( 13295 ISD::SRA, dl, N->getValueType(0), 13296 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13297 ShiftCst); 13298 } 13299 13300 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13301 DAGCombinerInfo &DCI) const { 13302 assert(N->getOpcode() == ISD::SETCC && 13303 "Should be called with a SETCC node"); 13304 13305 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13306 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13307 SDValue LHS = N->getOperand(0); 13308 SDValue RHS = N->getOperand(1); 13309 13310 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13311 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13312 LHS.hasOneUse()) 13313 std::swap(LHS, RHS); 13314 13315 // x == 0-y --> x+y == 0 13316 // x != 0-y --> x+y != 0 13317 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13318 RHS.hasOneUse()) { 13319 SDLoc DL(N); 13320 SelectionDAG &DAG = DCI.DAG; 13321 EVT VT = N->getValueType(0); 13322 EVT OpVT = LHS.getValueType(); 13323 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13324 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13325 } 13326 } 13327 13328 return DAGCombineTruncBoolExt(N, DCI); 13329 } 13330 13331 // Is this an extending load from an f32 to an f64? 13332 static bool isFPExtLoad(SDValue Op) { 13333 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13334 return LD->getExtensionType() == ISD::EXTLOAD && 13335 Op.getValueType() == MVT::f64; 13336 return false; 13337 } 13338 13339 /// Reduces the number of fp-to-int conversion when building a vector. 13340 /// 13341 /// If this vector is built out of floating to integer conversions, 13342 /// transform it to a vector built out of floating point values followed by a 13343 /// single floating to integer conversion of the vector. 13344 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13345 /// becomes (fptosi (build_vector ($A, $B, ...))) 13346 SDValue PPCTargetLowering:: 13347 combineElementTruncationToVectorTruncation(SDNode *N, 13348 DAGCombinerInfo &DCI) const { 13349 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13350 "Should be called with a BUILD_VECTOR node"); 13351 13352 SelectionDAG &DAG = DCI.DAG; 13353 SDLoc dl(N); 13354 13355 SDValue FirstInput = N->getOperand(0); 13356 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13357 "The input operand must be an fp-to-int conversion."); 13358 13359 // This combine happens after legalization so the fp_to_[su]i nodes are 13360 // already converted to PPCSISD nodes. 13361 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13362 if (FirstConversion == PPCISD::FCTIDZ || 13363 FirstConversion == PPCISD::FCTIDUZ || 13364 FirstConversion == PPCISD::FCTIWZ || 13365 FirstConversion == PPCISD::FCTIWUZ) { 13366 bool IsSplat = true; 13367 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13368 FirstConversion == PPCISD::FCTIWUZ; 13369 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13370 SmallVector<SDValue, 4> Ops; 13371 EVT TargetVT = N->getValueType(0); 13372 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13373 SDValue NextOp = N->getOperand(i); 13374 if (NextOp.getOpcode() != PPCISD::MFVSR) 13375 return SDValue(); 13376 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13377 if (NextConversion != FirstConversion) 13378 return SDValue(); 13379 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13380 // This is not valid if the input was originally double precision. It is 13381 // also not profitable to do unless this is an extending load in which 13382 // case doing this combine will allow us to combine consecutive loads. 13383 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13384 return SDValue(); 13385 if (N->getOperand(i) != FirstInput) 13386 IsSplat = false; 13387 } 13388 13389 // If this is a splat, we leave it as-is since there will be only a single 13390 // fp-to-int conversion followed by a splat of the integer. This is better 13391 // for 32-bit and smaller ints and neutral for 64-bit ints. 13392 if (IsSplat) 13393 return SDValue(); 13394 13395 // Now that we know we have the right type of node, get its operands 13396 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13397 SDValue In = N->getOperand(i).getOperand(0); 13398 if (Is32Bit) { 13399 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13400 // here, we know that all inputs are extending loads so this is safe). 13401 if (In.isUndef()) 13402 Ops.push_back(DAG.getUNDEF(SrcVT)); 13403 else { 13404 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13405 MVT::f32, In.getOperand(0), 13406 DAG.getIntPtrConstant(1, dl)); 13407 Ops.push_back(Trunc); 13408 } 13409 } else 13410 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13411 } 13412 13413 unsigned Opcode; 13414 if (FirstConversion == PPCISD::FCTIDZ || 13415 FirstConversion == PPCISD::FCTIWZ) 13416 Opcode = ISD::FP_TO_SINT; 13417 else 13418 Opcode = ISD::FP_TO_UINT; 13419 13420 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13421 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13422 return DAG.getNode(Opcode, dl, TargetVT, BV); 13423 } 13424 return SDValue(); 13425 } 13426 13427 /// Reduce the number of loads when building a vector. 13428 /// 13429 /// Building a vector out of multiple loads can be converted to a load 13430 /// of the vector type if the loads are consecutive. If the loads are 13431 /// consecutive but in descending order, a shuffle is added at the end 13432 /// to reorder the vector. 13433 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13434 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13435 "Should be called with a BUILD_VECTOR node"); 13436 13437 SDLoc dl(N); 13438 13439 // Return early for non byte-sized type, as they can't be consecutive. 13440 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13441 return SDValue(); 13442 13443 bool InputsAreConsecutiveLoads = true; 13444 bool InputsAreReverseConsecutive = true; 13445 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13446 SDValue FirstInput = N->getOperand(0); 13447 bool IsRoundOfExtLoad = false; 13448 13449 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13450 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13451 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13452 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13453 } 13454 // Not a build vector of (possibly fp_rounded) loads. 13455 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13456 N->getNumOperands() == 1) 13457 return SDValue(); 13458 13459 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13460 // If any inputs are fp_round(extload), they all must be. 13461 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13462 return SDValue(); 13463 13464 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13465 N->getOperand(i); 13466 if (NextInput.getOpcode() != ISD::LOAD) 13467 return SDValue(); 13468 13469 SDValue PreviousInput = 13470 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13471 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13472 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13473 13474 // If any inputs are fp_round(extload), they all must be. 13475 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13476 return SDValue(); 13477 13478 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13479 InputsAreConsecutiveLoads = false; 13480 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13481 InputsAreReverseConsecutive = false; 13482 13483 // Exit early if the loads are neither consecutive nor reverse consecutive. 13484 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13485 return SDValue(); 13486 } 13487 13488 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13489 "The loads cannot be both consecutive and reverse consecutive."); 13490 13491 SDValue FirstLoadOp = 13492 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13493 SDValue LastLoadOp = 13494 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13495 N->getOperand(N->getNumOperands()-1); 13496 13497 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13498 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13499 if (InputsAreConsecutiveLoads) { 13500 assert(LD1 && "Input needs to be a LoadSDNode."); 13501 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13502 LD1->getBasePtr(), LD1->getPointerInfo(), 13503 LD1->getAlignment()); 13504 } 13505 if (InputsAreReverseConsecutive) { 13506 assert(LDL && "Input needs to be a LoadSDNode."); 13507 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13508 LDL->getBasePtr(), LDL->getPointerInfo(), 13509 LDL->getAlignment()); 13510 SmallVector<int, 16> Ops; 13511 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13512 Ops.push_back(i); 13513 13514 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13515 DAG.getUNDEF(N->getValueType(0)), Ops); 13516 } 13517 return SDValue(); 13518 } 13519 13520 // This function adds the required vector_shuffle needed to get 13521 // the elements of the vector extract in the correct position 13522 // as specified by the CorrectElems encoding. 13523 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13524 SDValue Input, uint64_t Elems, 13525 uint64_t CorrectElems) { 13526 SDLoc dl(N); 13527 13528 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13529 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13530 13531 // Knowing the element indices being extracted from the original 13532 // vector and the order in which they're being inserted, just put 13533 // them at element indices required for the instruction. 13534 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13535 if (DAG.getDataLayout().isLittleEndian()) 13536 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13537 else 13538 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13539 CorrectElems = CorrectElems >> 8; 13540 Elems = Elems >> 8; 13541 } 13542 13543 SDValue Shuffle = 13544 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13545 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13546 13547 EVT VT = N->getValueType(0); 13548 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13549 13550 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13551 Input.getValueType().getVectorElementType(), 13552 VT.getVectorNumElements()); 13553 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13554 DAG.getValueType(ExtVT)); 13555 } 13556 13557 // Look for build vector patterns where input operands come from sign 13558 // extended vector_extract elements of specific indices. If the correct indices 13559 // aren't used, add a vector shuffle to fix up the indices and create 13560 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13561 // during instruction selection. 13562 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13563 // This array encodes the indices that the vector sign extend instructions 13564 // extract from when extending from one type to another for both BE and LE. 13565 // The right nibble of each byte corresponds to the LE incides. 13566 // and the left nibble of each byte corresponds to the BE incides. 13567 // For example: 0x3074B8FC byte->word 13568 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13569 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13570 // For example: 0x000070F8 byte->double word 13571 // For LE: the allowed indices are: 0x0,0x8 13572 // For BE: the allowed indices are: 0x7,0xF 13573 uint64_t TargetElems[] = { 13574 0x3074B8FC, // b->w 13575 0x000070F8, // b->d 13576 0x10325476, // h->w 13577 0x00003074, // h->d 13578 0x00001032, // w->d 13579 }; 13580 13581 uint64_t Elems = 0; 13582 int Index; 13583 SDValue Input; 13584 13585 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13586 if (!Op) 13587 return false; 13588 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13589 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13590 return false; 13591 13592 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13593 // of the right width. 13594 SDValue Extract = Op.getOperand(0); 13595 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13596 Extract = Extract.getOperand(0); 13597 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13598 return false; 13599 13600 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13601 if (!ExtOp) 13602 return false; 13603 13604 Index = ExtOp->getZExtValue(); 13605 if (Input && Input != Extract.getOperand(0)) 13606 return false; 13607 13608 if (!Input) 13609 Input = Extract.getOperand(0); 13610 13611 Elems = Elems << 8; 13612 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13613 Elems |= Index; 13614 13615 return true; 13616 }; 13617 13618 // If the build vector operands aren't sign extended vector extracts, 13619 // of the same input vector, then return. 13620 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13621 if (!isSExtOfVecExtract(N->getOperand(i))) { 13622 return SDValue(); 13623 } 13624 } 13625 13626 // If the vector extract indicies are not correct, add the appropriate 13627 // vector_shuffle. 13628 int TgtElemArrayIdx; 13629 int InputSize = Input.getValueType().getScalarSizeInBits(); 13630 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13631 if (InputSize + OutputSize == 40) 13632 TgtElemArrayIdx = 0; 13633 else if (InputSize + OutputSize == 72) 13634 TgtElemArrayIdx = 1; 13635 else if (InputSize + OutputSize == 48) 13636 TgtElemArrayIdx = 2; 13637 else if (InputSize + OutputSize == 80) 13638 TgtElemArrayIdx = 3; 13639 else if (InputSize + OutputSize == 96) 13640 TgtElemArrayIdx = 4; 13641 else 13642 return SDValue(); 13643 13644 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13645 CorrectElems = DAG.getDataLayout().isLittleEndian() 13646 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13647 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13648 if (Elems != CorrectElems) { 13649 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13650 } 13651 13652 // Regular lowering will catch cases where a shuffle is not needed. 13653 return SDValue(); 13654 } 13655 13656 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13657 DAGCombinerInfo &DCI) const { 13658 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13659 "Should be called with a BUILD_VECTOR node"); 13660 13661 SelectionDAG &DAG = DCI.DAG; 13662 SDLoc dl(N); 13663 13664 if (!Subtarget.hasVSX()) 13665 return SDValue(); 13666 13667 // The target independent DAG combiner will leave a build_vector of 13668 // float-to-int conversions intact. We can generate MUCH better code for 13669 // a float-to-int conversion of a vector of floats. 13670 SDValue FirstInput = N->getOperand(0); 13671 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13672 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13673 if (Reduced) 13674 return Reduced; 13675 } 13676 13677 // If we're building a vector out of consecutive loads, just load that 13678 // vector type. 13679 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13680 if (Reduced) 13681 return Reduced; 13682 13683 // If we're building a vector out of extended elements from another vector 13684 // we have P9 vector integer extend instructions. The code assumes legal 13685 // input types (i.e. it can't handle things like v4i16) so do not run before 13686 // legalization. 13687 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13688 Reduced = combineBVOfVecSExt(N, DAG); 13689 if (Reduced) 13690 return Reduced; 13691 } 13692 13693 13694 if (N->getValueType(0) != MVT::v2f64) 13695 return SDValue(); 13696 13697 // Looking for: 13698 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13699 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13700 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13701 return SDValue(); 13702 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13703 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13704 return SDValue(); 13705 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13706 return SDValue(); 13707 13708 SDValue Ext1 = FirstInput.getOperand(0); 13709 SDValue Ext2 = N->getOperand(1).getOperand(0); 13710 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13711 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13712 return SDValue(); 13713 13714 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13715 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13716 if (!Ext1Op || !Ext2Op) 13717 return SDValue(); 13718 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13719 Ext1.getOperand(0) != Ext2.getOperand(0)) 13720 return SDValue(); 13721 13722 int FirstElem = Ext1Op->getZExtValue(); 13723 int SecondElem = Ext2Op->getZExtValue(); 13724 int SubvecIdx; 13725 if (FirstElem == 0 && SecondElem == 1) 13726 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13727 else if (FirstElem == 2 && SecondElem == 3) 13728 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13729 else 13730 return SDValue(); 13731 13732 SDValue SrcVec = Ext1.getOperand(0); 13733 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13734 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13735 return DAG.getNode(NodeType, dl, MVT::v2f64, 13736 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13737 } 13738 13739 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13740 DAGCombinerInfo &DCI) const { 13741 assert((N->getOpcode() == ISD::SINT_TO_FP || 13742 N->getOpcode() == ISD::UINT_TO_FP) && 13743 "Need an int -> FP conversion node here"); 13744 13745 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13746 return SDValue(); 13747 13748 SelectionDAG &DAG = DCI.DAG; 13749 SDLoc dl(N); 13750 SDValue Op(N, 0); 13751 13752 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13753 // from the hardware. 13754 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13755 return SDValue(); 13756 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13757 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13758 return SDValue(); 13759 13760 SDValue FirstOperand(Op.getOperand(0)); 13761 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13762 (FirstOperand.getValueType() == MVT::i8 || 13763 FirstOperand.getValueType() == MVT::i16); 13764 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13765 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13766 bool DstDouble = Op.getValueType() == MVT::f64; 13767 unsigned ConvOp = Signed ? 13768 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13769 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13770 SDValue WidthConst = 13771 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13772 dl, false); 13773 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13774 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13775 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13776 DAG.getVTList(MVT::f64, MVT::Other), 13777 Ops, MVT::i8, LDN->getMemOperand()); 13778 13779 // For signed conversion, we need to sign-extend the value in the VSR 13780 if (Signed) { 13781 SDValue ExtOps[] = { Ld, WidthConst }; 13782 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13783 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13784 } else 13785 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13786 } 13787 13788 13789 // For i32 intermediate values, unfortunately, the conversion functions 13790 // leave the upper 32 bits of the value are undefined. Within the set of 13791 // scalar instructions, we have no method for zero- or sign-extending the 13792 // value. Thus, we cannot handle i32 intermediate values here. 13793 if (Op.getOperand(0).getValueType() == MVT::i32) 13794 return SDValue(); 13795 13796 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13797 "UINT_TO_FP is supported only with FPCVT"); 13798 13799 // If we have FCFIDS, then use it when converting to single-precision. 13800 // Otherwise, convert to double-precision and then round. 13801 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13802 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13803 : PPCISD::FCFIDS) 13804 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13805 : PPCISD::FCFID); 13806 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13807 ? MVT::f32 13808 : MVT::f64; 13809 13810 // If we're converting from a float, to an int, and back to a float again, 13811 // then we don't need the store/load pair at all. 13812 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13813 Subtarget.hasFPCVT()) || 13814 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13815 SDValue Src = Op.getOperand(0).getOperand(0); 13816 if (Src.getValueType() == MVT::f32) { 13817 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13818 DCI.AddToWorklist(Src.getNode()); 13819 } else if (Src.getValueType() != MVT::f64) { 13820 // Make sure that we don't pick up a ppc_fp128 source value. 13821 return SDValue(); 13822 } 13823 13824 unsigned FCTOp = 13825 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13826 PPCISD::FCTIDUZ; 13827 13828 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13829 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13830 13831 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13832 FP = DAG.getNode(ISD::FP_ROUND, dl, 13833 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13834 DCI.AddToWorklist(FP.getNode()); 13835 } 13836 13837 return FP; 13838 } 13839 13840 return SDValue(); 13841 } 13842 13843 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13844 // builtins) into loads with swaps. 13845 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13846 DAGCombinerInfo &DCI) const { 13847 SelectionDAG &DAG = DCI.DAG; 13848 SDLoc dl(N); 13849 SDValue Chain; 13850 SDValue Base; 13851 MachineMemOperand *MMO; 13852 13853 switch (N->getOpcode()) { 13854 default: 13855 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13856 case ISD::LOAD: { 13857 LoadSDNode *LD = cast<LoadSDNode>(N); 13858 Chain = LD->getChain(); 13859 Base = LD->getBasePtr(); 13860 MMO = LD->getMemOperand(); 13861 // If the MMO suggests this isn't a load of a full vector, leave 13862 // things alone. For a built-in, we have to make the change for 13863 // correctness, so if there is a size problem that will be a bug. 13864 if (MMO->getSize() < 16) 13865 return SDValue(); 13866 break; 13867 } 13868 case ISD::INTRINSIC_W_CHAIN: { 13869 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13870 Chain = Intrin->getChain(); 13871 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13872 // us what we want. Get operand 2 instead. 13873 Base = Intrin->getOperand(2); 13874 MMO = Intrin->getMemOperand(); 13875 break; 13876 } 13877 } 13878 13879 MVT VecTy = N->getValueType(0).getSimpleVT(); 13880 13881 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13882 // aligned and the type is a vector with elements up to 4 bytes 13883 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13884 VecTy.getScalarSizeInBits() <= 32) { 13885 return SDValue(); 13886 } 13887 13888 SDValue LoadOps[] = { Chain, Base }; 13889 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13890 DAG.getVTList(MVT::v2f64, MVT::Other), 13891 LoadOps, MVT::v2f64, MMO); 13892 13893 DCI.AddToWorklist(Load.getNode()); 13894 Chain = Load.getValue(1); 13895 SDValue Swap = DAG.getNode( 13896 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13897 DCI.AddToWorklist(Swap.getNode()); 13898 13899 // Add a bitcast if the resulting load type doesn't match v2f64. 13900 if (VecTy != MVT::v2f64) { 13901 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13902 DCI.AddToWorklist(N.getNode()); 13903 // Package {bitcast value, swap's chain} to match Load's shape. 13904 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13905 N, Swap.getValue(1)); 13906 } 13907 13908 return Swap; 13909 } 13910 13911 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13912 // builtins) into stores with swaps. 13913 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13914 DAGCombinerInfo &DCI) const { 13915 SelectionDAG &DAG = DCI.DAG; 13916 SDLoc dl(N); 13917 SDValue Chain; 13918 SDValue Base; 13919 unsigned SrcOpnd; 13920 MachineMemOperand *MMO; 13921 13922 switch (N->getOpcode()) { 13923 default: 13924 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13925 case ISD::STORE: { 13926 StoreSDNode *ST = cast<StoreSDNode>(N); 13927 Chain = ST->getChain(); 13928 Base = ST->getBasePtr(); 13929 MMO = ST->getMemOperand(); 13930 SrcOpnd = 1; 13931 // If the MMO suggests this isn't a store of a full vector, leave 13932 // things alone. For a built-in, we have to make the change for 13933 // correctness, so if there is a size problem that will be a bug. 13934 if (MMO->getSize() < 16) 13935 return SDValue(); 13936 break; 13937 } 13938 case ISD::INTRINSIC_VOID: { 13939 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13940 Chain = Intrin->getChain(); 13941 // Intrin->getBasePtr() oddly does not get what we want. 13942 Base = Intrin->getOperand(3); 13943 MMO = Intrin->getMemOperand(); 13944 SrcOpnd = 2; 13945 break; 13946 } 13947 } 13948 13949 SDValue Src = N->getOperand(SrcOpnd); 13950 MVT VecTy = Src.getValueType().getSimpleVT(); 13951 13952 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13953 // aligned and the type is a vector with elements up to 4 bytes 13954 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13955 VecTy.getScalarSizeInBits() <= 32) { 13956 return SDValue(); 13957 } 13958 13959 // All stores are done as v2f64 and possible bit cast. 13960 if (VecTy != MVT::v2f64) { 13961 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13962 DCI.AddToWorklist(Src.getNode()); 13963 } 13964 13965 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13966 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13967 DCI.AddToWorklist(Swap.getNode()); 13968 Chain = Swap.getValue(1); 13969 SDValue StoreOps[] = { Chain, Swap, Base }; 13970 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13971 DAG.getVTList(MVT::Other), 13972 StoreOps, VecTy, MMO); 13973 DCI.AddToWorklist(Store.getNode()); 13974 return Store; 13975 } 13976 13977 // Handle DAG combine for STORE (FP_TO_INT F). 13978 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13979 DAGCombinerInfo &DCI) const { 13980 13981 SelectionDAG &DAG = DCI.DAG; 13982 SDLoc dl(N); 13983 unsigned Opcode = N->getOperand(1).getOpcode(); 13984 13985 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13986 && "Not a FP_TO_INT Instruction!"); 13987 13988 SDValue Val = N->getOperand(1).getOperand(0); 13989 EVT Op1VT = N->getOperand(1).getValueType(); 13990 EVT ResVT = Val.getValueType(); 13991 13992 // Floating point types smaller than 32 bits are not legal on Power. 13993 if (ResVT.getScalarSizeInBits() < 32) 13994 return SDValue(); 13995 13996 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13997 bool ValidTypeForStoreFltAsInt = 13998 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13999 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14000 14001 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14002 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14003 return SDValue(); 14004 14005 // Extend f32 values to f64 14006 if (ResVT.getScalarSizeInBits() == 32) { 14007 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14008 DCI.AddToWorklist(Val.getNode()); 14009 } 14010 14011 // Set signed or unsigned conversion opcode. 14012 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14013 PPCISD::FP_TO_SINT_IN_VSR : 14014 PPCISD::FP_TO_UINT_IN_VSR; 14015 14016 Val = DAG.getNode(ConvOpcode, 14017 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14018 DCI.AddToWorklist(Val.getNode()); 14019 14020 // Set number of bytes being converted. 14021 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14022 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14023 DAG.getIntPtrConstant(ByteSize, dl, false), 14024 DAG.getValueType(Op1VT) }; 14025 14026 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14027 DAG.getVTList(MVT::Other), Ops, 14028 cast<StoreSDNode>(N)->getMemoryVT(), 14029 cast<StoreSDNode>(N)->getMemOperand()); 14030 14031 DCI.AddToWorklist(Val.getNode()); 14032 return Val; 14033 } 14034 14035 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14036 LSBaseSDNode *LSBase, 14037 DAGCombinerInfo &DCI) const { 14038 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14039 "Not a reverse memop pattern!"); 14040 14041 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14042 auto Mask = SVN->getMask(); 14043 int i = 0; 14044 auto I = Mask.rbegin(); 14045 auto E = Mask.rend(); 14046 14047 for (; I != E; ++I) { 14048 if (*I != i) 14049 return false; 14050 i++; 14051 } 14052 return true; 14053 }; 14054 14055 SelectionDAG &DAG = DCI.DAG; 14056 EVT VT = SVN->getValueType(0); 14057 14058 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14059 return SDValue(); 14060 14061 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14062 // See comment in PPCVSXSwapRemoval.cpp. 14063 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14064 if (!Subtarget.hasP9Vector()) 14065 return SDValue(); 14066 14067 if(!IsElementReverse(SVN)) 14068 return SDValue(); 14069 14070 if (LSBase->getOpcode() == ISD::LOAD) { 14071 SDLoc dl(SVN); 14072 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14073 return DAG.getMemIntrinsicNode( 14074 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14075 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14076 } 14077 14078 if (LSBase->getOpcode() == ISD::STORE) { 14079 SDLoc dl(LSBase); 14080 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14081 LSBase->getBasePtr()}; 14082 return DAG.getMemIntrinsicNode( 14083 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14084 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14085 } 14086 14087 llvm_unreachable("Expected a load or store node here"); 14088 } 14089 14090 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14091 DAGCombinerInfo &DCI) const { 14092 SelectionDAG &DAG = DCI.DAG; 14093 SDLoc dl(N); 14094 switch (N->getOpcode()) { 14095 default: break; 14096 case ISD::ADD: 14097 return combineADD(N, DCI); 14098 case ISD::SHL: 14099 return combineSHL(N, DCI); 14100 case ISD::SRA: 14101 return combineSRA(N, DCI); 14102 case ISD::SRL: 14103 return combineSRL(N, DCI); 14104 case ISD::MUL: 14105 return combineMUL(N, DCI); 14106 case PPCISD::SHL: 14107 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14108 return N->getOperand(0); 14109 break; 14110 case PPCISD::SRL: 14111 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14112 return N->getOperand(0); 14113 break; 14114 case PPCISD::SRA: 14115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14116 if (C->isNullValue() || // 0 >>s V -> 0. 14117 C->isAllOnesValue()) // -1 >>s V -> -1. 14118 return N->getOperand(0); 14119 } 14120 break; 14121 case ISD::SIGN_EXTEND: 14122 case ISD::ZERO_EXTEND: 14123 case ISD::ANY_EXTEND: 14124 return DAGCombineExtBoolTrunc(N, DCI); 14125 case ISD::TRUNCATE: 14126 return combineTRUNCATE(N, DCI); 14127 case ISD::SETCC: 14128 if (SDValue CSCC = combineSetCC(N, DCI)) 14129 return CSCC; 14130 LLVM_FALLTHROUGH; 14131 case ISD::SELECT_CC: 14132 return DAGCombineTruncBoolExt(N, DCI); 14133 case ISD::SINT_TO_FP: 14134 case ISD::UINT_TO_FP: 14135 return combineFPToIntToFP(N, DCI); 14136 case ISD::VECTOR_SHUFFLE: 14137 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14138 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14139 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14140 } 14141 break; 14142 case ISD::STORE: { 14143 14144 EVT Op1VT = N->getOperand(1).getValueType(); 14145 unsigned Opcode = N->getOperand(1).getOpcode(); 14146 14147 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14148 SDValue Val= combineStoreFPToInt(N, DCI); 14149 if (Val) 14150 return Val; 14151 } 14152 14153 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14154 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14155 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14156 if (Val) 14157 return Val; 14158 } 14159 14160 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14161 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14162 N->getOperand(1).getNode()->hasOneUse() && 14163 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14164 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14165 14166 // STBRX can only handle simple types and it makes no sense to store less 14167 // two bytes in byte-reversed order. 14168 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14169 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14170 break; 14171 14172 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14173 // Do an any-extend to 32-bits if this is a half-word input. 14174 if (BSwapOp.getValueType() == MVT::i16) 14175 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14176 14177 // If the type of BSWAP operand is wider than stored memory width 14178 // it need to be shifted to the right side before STBRX. 14179 if (Op1VT.bitsGT(mVT)) { 14180 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14181 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14182 DAG.getConstant(Shift, dl, MVT::i32)); 14183 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14184 if (Op1VT == MVT::i64) 14185 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14186 } 14187 14188 SDValue Ops[] = { 14189 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14190 }; 14191 return 14192 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14193 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14194 cast<StoreSDNode>(N)->getMemOperand()); 14195 } 14196 14197 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14198 // So it can increase the chance of CSE constant construction. 14199 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14200 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14201 // Need to sign-extended to 64-bits to handle negative values. 14202 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14203 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14204 MemVT.getSizeInBits()); 14205 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14206 14207 // DAG.getTruncStore() can't be used here because it doesn't accept 14208 // the general (base + offset) addressing mode. 14209 // So we use UpdateNodeOperands and setTruncatingStore instead. 14210 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14211 N->getOperand(3)); 14212 cast<StoreSDNode>(N)->setTruncatingStore(true); 14213 return SDValue(N, 0); 14214 } 14215 14216 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14217 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14218 if (Op1VT.isSimple()) { 14219 MVT StoreVT = Op1VT.getSimpleVT(); 14220 if (Subtarget.needsSwapsForVSXMemOps() && 14221 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14222 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14223 return expandVSXStoreForLE(N, DCI); 14224 } 14225 break; 14226 } 14227 case ISD::LOAD: { 14228 LoadSDNode *LD = cast<LoadSDNode>(N); 14229 EVT VT = LD->getValueType(0); 14230 14231 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14232 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14233 if (VT.isSimple()) { 14234 MVT LoadVT = VT.getSimpleVT(); 14235 if (Subtarget.needsSwapsForVSXMemOps() && 14236 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14237 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14238 return expandVSXLoadForLE(N, DCI); 14239 } 14240 14241 // We sometimes end up with a 64-bit integer load, from which we extract 14242 // two single-precision floating-point numbers. This happens with 14243 // std::complex<float>, and other similar structures, because of the way we 14244 // canonicalize structure copies. However, if we lack direct moves, 14245 // then the final bitcasts from the extracted integer values to the 14246 // floating-point numbers turn into store/load pairs. Even with direct moves, 14247 // just loading the two floating-point numbers is likely better. 14248 auto ReplaceTwoFloatLoad = [&]() { 14249 if (VT != MVT::i64) 14250 return false; 14251 14252 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14253 LD->isVolatile()) 14254 return false; 14255 14256 // We're looking for a sequence like this: 14257 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14258 // t16: i64 = srl t13, Constant:i32<32> 14259 // t17: i32 = truncate t16 14260 // t18: f32 = bitcast t17 14261 // t19: i32 = truncate t13 14262 // t20: f32 = bitcast t19 14263 14264 if (!LD->hasNUsesOfValue(2, 0)) 14265 return false; 14266 14267 auto UI = LD->use_begin(); 14268 while (UI.getUse().getResNo() != 0) ++UI; 14269 SDNode *Trunc = *UI++; 14270 while (UI.getUse().getResNo() != 0) ++UI; 14271 SDNode *RightShift = *UI; 14272 if (Trunc->getOpcode() != ISD::TRUNCATE) 14273 std::swap(Trunc, RightShift); 14274 14275 if (Trunc->getOpcode() != ISD::TRUNCATE || 14276 Trunc->getValueType(0) != MVT::i32 || 14277 !Trunc->hasOneUse()) 14278 return false; 14279 if (RightShift->getOpcode() != ISD::SRL || 14280 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14281 RightShift->getConstantOperandVal(1) != 32 || 14282 !RightShift->hasOneUse()) 14283 return false; 14284 14285 SDNode *Trunc2 = *RightShift->use_begin(); 14286 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14287 Trunc2->getValueType(0) != MVT::i32 || 14288 !Trunc2->hasOneUse()) 14289 return false; 14290 14291 SDNode *Bitcast = *Trunc->use_begin(); 14292 SDNode *Bitcast2 = *Trunc2->use_begin(); 14293 14294 if (Bitcast->getOpcode() != ISD::BITCAST || 14295 Bitcast->getValueType(0) != MVT::f32) 14296 return false; 14297 if (Bitcast2->getOpcode() != ISD::BITCAST || 14298 Bitcast2->getValueType(0) != MVT::f32) 14299 return false; 14300 14301 if (Subtarget.isLittleEndian()) 14302 std::swap(Bitcast, Bitcast2); 14303 14304 // Bitcast has the second float (in memory-layout order) and Bitcast2 14305 // has the first one. 14306 14307 SDValue BasePtr = LD->getBasePtr(); 14308 if (LD->isIndexed()) { 14309 assert(LD->getAddressingMode() == ISD::PRE_INC && 14310 "Non-pre-inc AM on PPC?"); 14311 BasePtr = 14312 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14313 LD->getOffset()); 14314 } 14315 14316 auto MMOFlags = 14317 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14318 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14319 LD->getPointerInfo(), LD->getAlignment(), 14320 MMOFlags, LD->getAAInfo()); 14321 SDValue AddPtr = 14322 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14323 BasePtr, DAG.getIntPtrConstant(4, dl)); 14324 SDValue FloatLoad2 = DAG.getLoad( 14325 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14326 LD->getPointerInfo().getWithOffset(4), 14327 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14328 14329 if (LD->isIndexed()) { 14330 // Note that DAGCombine should re-form any pre-increment load(s) from 14331 // what is produced here if that makes sense. 14332 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14333 } 14334 14335 DCI.CombineTo(Bitcast2, FloatLoad); 14336 DCI.CombineTo(Bitcast, FloatLoad2); 14337 14338 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14339 SDValue(FloatLoad2.getNode(), 1)); 14340 return true; 14341 }; 14342 14343 if (ReplaceTwoFloatLoad()) 14344 return SDValue(N, 0); 14345 14346 EVT MemVT = LD->getMemoryVT(); 14347 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14348 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14349 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14350 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14351 if (LD->isUnindexed() && VT.isVector() && 14352 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14353 // P8 and later hardware should just use LOAD. 14354 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14355 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14356 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14357 LD->getAlignment() >= ScalarABIAlignment)) && 14358 LD->getAlignment() < ABIAlignment) { 14359 // This is a type-legal unaligned Altivec or QPX load. 14360 SDValue Chain = LD->getChain(); 14361 SDValue Ptr = LD->getBasePtr(); 14362 bool isLittleEndian = Subtarget.isLittleEndian(); 14363 14364 // This implements the loading of unaligned vectors as described in 14365 // the venerable Apple Velocity Engine overview. Specifically: 14366 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14367 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14368 // 14369 // The general idea is to expand a sequence of one or more unaligned 14370 // loads into an alignment-based permutation-control instruction (lvsl 14371 // or lvsr), a series of regular vector loads (which always truncate 14372 // their input address to an aligned address), and a series of 14373 // permutations. The results of these permutations are the requested 14374 // loaded values. The trick is that the last "extra" load is not taken 14375 // from the address you might suspect (sizeof(vector) bytes after the 14376 // last requested load), but rather sizeof(vector) - 1 bytes after the 14377 // last requested vector. The point of this is to avoid a page fault if 14378 // the base address happened to be aligned. This works because if the 14379 // base address is aligned, then adding less than a full vector length 14380 // will cause the last vector in the sequence to be (re)loaded. 14381 // Otherwise, the next vector will be fetched as you might suspect was 14382 // necessary. 14383 14384 // We might be able to reuse the permutation generation from 14385 // a different base address offset from this one by an aligned amount. 14386 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14387 // optimization later. 14388 Intrinsic::ID Intr, IntrLD, IntrPerm; 14389 MVT PermCntlTy, PermTy, LDTy; 14390 if (Subtarget.hasAltivec()) { 14391 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14392 Intrinsic::ppc_altivec_lvsl; 14393 IntrLD = Intrinsic::ppc_altivec_lvx; 14394 IntrPerm = Intrinsic::ppc_altivec_vperm; 14395 PermCntlTy = MVT::v16i8; 14396 PermTy = MVT::v4i32; 14397 LDTy = MVT::v4i32; 14398 } else { 14399 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14400 Intrinsic::ppc_qpx_qvlpcls; 14401 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14402 Intrinsic::ppc_qpx_qvlfs; 14403 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14404 PermCntlTy = MVT::v4f64; 14405 PermTy = MVT::v4f64; 14406 LDTy = MemVT.getSimpleVT(); 14407 } 14408 14409 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14410 14411 // Create the new MMO for the new base load. It is like the original MMO, 14412 // but represents an area in memory almost twice the vector size centered 14413 // on the original address. If the address is unaligned, we might start 14414 // reading up to (sizeof(vector)-1) bytes below the address of the 14415 // original unaligned load. 14416 MachineFunction &MF = DAG.getMachineFunction(); 14417 MachineMemOperand *BaseMMO = 14418 MF.getMachineMemOperand(LD->getMemOperand(), 14419 -(long)MemVT.getStoreSize()+1, 14420 2*MemVT.getStoreSize()-1); 14421 14422 // Create the new base load. 14423 SDValue LDXIntID = 14424 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14425 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14426 SDValue BaseLoad = 14427 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14428 DAG.getVTList(PermTy, MVT::Other), 14429 BaseLoadOps, LDTy, BaseMMO); 14430 14431 // Note that the value of IncOffset (which is provided to the next 14432 // load's pointer info offset value, and thus used to calculate the 14433 // alignment), and the value of IncValue (which is actually used to 14434 // increment the pointer value) are different! This is because we 14435 // require the next load to appear to be aligned, even though it 14436 // is actually offset from the base pointer by a lesser amount. 14437 int IncOffset = VT.getSizeInBits() / 8; 14438 int IncValue = IncOffset; 14439 14440 // Walk (both up and down) the chain looking for another load at the real 14441 // (aligned) offset (the alignment of the other load does not matter in 14442 // this case). If found, then do not use the offset reduction trick, as 14443 // that will prevent the loads from being later combined (as they would 14444 // otherwise be duplicates). 14445 if (!findConsecutiveLoad(LD, DAG)) 14446 --IncValue; 14447 14448 SDValue Increment = 14449 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14450 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14451 14452 MachineMemOperand *ExtraMMO = 14453 MF.getMachineMemOperand(LD->getMemOperand(), 14454 1, 2*MemVT.getStoreSize()-1); 14455 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14456 SDValue ExtraLoad = 14457 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14458 DAG.getVTList(PermTy, MVT::Other), 14459 ExtraLoadOps, LDTy, ExtraMMO); 14460 14461 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14462 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14463 14464 // Because vperm has a big-endian bias, we must reverse the order 14465 // of the input vectors and complement the permute control vector 14466 // when generating little endian code. We have already handled the 14467 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14468 // and ExtraLoad here. 14469 SDValue Perm; 14470 if (isLittleEndian) 14471 Perm = BuildIntrinsicOp(IntrPerm, 14472 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14473 else 14474 Perm = BuildIntrinsicOp(IntrPerm, 14475 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14476 14477 if (VT != PermTy) 14478 Perm = Subtarget.hasAltivec() ? 14479 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14480 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14481 DAG.getTargetConstant(1, dl, MVT::i64)); 14482 // second argument is 1 because this rounding 14483 // is always exact. 14484 14485 // The output of the permutation is our loaded result, the TokenFactor is 14486 // our new chain. 14487 DCI.CombineTo(N, Perm, TF); 14488 return SDValue(N, 0); 14489 } 14490 } 14491 break; 14492 case ISD::INTRINSIC_WO_CHAIN: { 14493 bool isLittleEndian = Subtarget.isLittleEndian(); 14494 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14495 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14496 : Intrinsic::ppc_altivec_lvsl); 14497 if ((IID == Intr || 14498 IID == Intrinsic::ppc_qpx_qvlpcld || 14499 IID == Intrinsic::ppc_qpx_qvlpcls) && 14500 N->getOperand(1)->getOpcode() == ISD::ADD) { 14501 SDValue Add = N->getOperand(1); 14502 14503 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14504 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14505 14506 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14507 APInt::getAllOnesValue(Bits /* alignment */) 14508 .zext(Add.getScalarValueSizeInBits()))) { 14509 SDNode *BasePtr = Add->getOperand(0).getNode(); 14510 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14511 UE = BasePtr->use_end(); 14512 UI != UE; ++UI) { 14513 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14514 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14515 // We've found another LVSL/LVSR, and this address is an aligned 14516 // multiple of that one. The results will be the same, so use the 14517 // one we've just found instead. 14518 14519 return SDValue(*UI, 0); 14520 } 14521 } 14522 } 14523 14524 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14525 SDNode *BasePtr = Add->getOperand(0).getNode(); 14526 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14527 UE = BasePtr->use_end(); UI != UE; ++UI) { 14528 if (UI->getOpcode() == ISD::ADD && 14529 isa<ConstantSDNode>(UI->getOperand(1)) && 14530 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14531 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14532 (1ULL << Bits) == 0) { 14533 SDNode *OtherAdd = *UI; 14534 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14535 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14536 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14537 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14538 return SDValue(*VI, 0); 14539 } 14540 } 14541 } 14542 } 14543 } 14544 } 14545 14546 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14547 // Expose the vabsduw/h/b opportunity for down stream 14548 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14549 (IID == Intrinsic::ppc_altivec_vmaxsw || 14550 IID == Intrinsic::ppc_altivec_vmaxsh || 14551 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14552 SDValue V1 = N->getOperand(1); 14553 SDValue V2 = N->getOperand(2); 14554 if ((V1.getSimpleValueType() == MVT::v4i32 || 14555 V1.getSimpleValueType() == MVT::v8i16 || 14556 V1.getSimpleValueType() == MVT::v16i8) && 14557 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14558 // (0-a, a) 14559 if (V1.getOpcode() == ISD::SUB && 14560 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14561 V1.getOperand(1) == V2) { 14562 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14563 } 14564 // (a, 0-a) 14565 if (V2.getOpcode() == ISD::SUB && 14566 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14567 V2.getOperand(1) == V1) { 14568 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14569 } 14570 // (x-y, y-x) 14571 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14572 V1.getOperand(0) == V2.getOperand(1) && 14573 V1.getOperand(1) == V2.getOperand(0)) { 14574 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14575 } 14576 } 14577 } 14578 } 14579 14580 break; 14581 case ISD::INTRINSIC_W_CHAIN: 14582 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14583 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14584 if (Subtarget.needsSwapsForVSXMemOps()) { 14585 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14586 default: 14587 break; 14588 case Intrinsic::ppc_vsx_lxvw4x: 14589 case Intrinsic::ppc_vsx_lxvd2x: 14590 return expandVSXLoadForLE(N, DCI); 14591 } 14592 } 14593 break; 14594 case ISD::INTRINSIC_VOID: 14595 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14596 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14597 if (Subtarget.needsSwapsForVSXMemOps()) { 14598 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14599 default: 14600 break; 14601 case Intrinsic::ppc_vsx_stxvw4x: 14602 case Intrinsic::ppc_vsx_stxvd2x: 14603 return expandVSXStoreForLE(N, DCI); 14604 } 14605 } 14606 break; 14607 case ISD::BSWAP: 14608 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14609 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14610 N->getOperand(0).hasOneUse() && 14611 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14612 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14613 N->getValueType(0) == MVT::i64))) { 14614 SDValue Load = N->getOperand(0); 14615 LoadSDNode *LD = cast<LoadSDNode>(Load); 14616 // Create the byte-swapping load. 14617 SDValue Ops[] = { 14618 LD->getChain(), // Chain 14619 LD->getBasePtr(), // Ptr 14620 DAG.getValueType(N->getValueType(0)) // VT 14621 }; 14622 SDValue BSLoad = 14623 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14624 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14625 MVT::i64 : MVT::i32, MVT::Other), 14626 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14627 14628 // If this is an i16 load, insert the truncate. 14629 SDValue ResVal = BSLoad; 14630 if (N->getValueType(0) == MVT::i16) 14631 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14632 14633 // First, combine the bswap away. This makes the value produced by the 14634 // load dead. 14635 DCI.CombineTo(N, ResVal); 14636 14637 // Next, combine the load away, we give it a bogus result value but a real 14638 // chain result. The result value is dead because the bswap is dead. 14639 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14640 14641 // Return N so it doesn't get rechecked! 14642 return SDValue(N, 0); 14643 } 14644 break; 14645 case PPCISD::VCMP: 14646 // If a VCMPo node already exists with exactly the same operands as this 14647 // node, use its result instead of this node (VCMPo computes both a CR6 and 14648 // a normal output). 14649 // 14650 if (!N->getOperand(0).hasOneUse() && 14651 !N->getOperand(1).hasOneUse() && 14652 !N->getOperand(2).hasOneUse()) { 14653 14654 // Scan all of the users of the LHS, looking for VCMPo's that match. 14655 SDNode *VCMPoNode = nullptr; 14656 14657 SDNode *LHSN = N->getOperand(0).getNode(); 14658 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14659 UI != E; ++UI) 14660 if (UI->getOpcode() == PPCISD::VCMPo && 14661 UI->getOperand(1) == N->getOperand(1) && 14662 UI->getOperand(2) == N->getOperand(2) && 14663 UI->getOperand(0) == N->getOperand(0)) { 14664 VCMPoNode = *UI; 14665 break; 14666 } 14667 14668 // If there is no VCMPo node, or if the flag value has a single use, don't 14669 // transform this. 14670 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14671 break; 14672 14673 // Look at the (necessarily single) use of the flag value. If it has a 14674 // chain, this transformation is more complex. Note that multiple things 14675 // could use the value result, which we should ignore. 14676 SDNode *FlagUser = nullptr; 14677 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14678 FlagUser == nullptr; ++UI) { 14679 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14680 SDNode *User = *UI; 14681 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14682 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14683 FlagUser = User; 14684 break; 14685 } 14686 } 14687 } 14688 14689 // If the user is a MFOCRF instruction, we know this is safe. 14690 // Otherwise we give up for right now. 14691 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14692 return SDValue(VCMPoNode, 0); 14693 } 14694 break; 14695 case ISD::BRCOND: { 14696 SDValue Cond = N->getOperand(1); 14697 SDValue Target = N->getOperand(2); 14698 14699 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14700 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14701 Intrinsic::loop_decrement) { 14702 14703 // We now need to make the intrinsic dead (it cannot be instruction 14704 // selected). 14705 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14706 assert(Cond.getNode()->hasOneUse() && 14707 "Counter decrement has more than one use"); 14708 14709 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14710 N->getOperand(0), Target); 14711 } 14712 } 14713 break; 14714 case ISD::BR_CC: { 14715 // If this is a branch on an altivec predicate comparison, lower this so 14716 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14717 // lowering is done pre-legalize, because the legalizer lowers the predicate 14718 // compare down to code that is difficult to reassemble. 14719 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14720 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14721 14722 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14723 // value. If so, pass-through the AND to get to the intrinsic. 14724 if (LHS.getOpcode() == ISD::AND && 14725 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14726 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14727 Intrinsic::loop_decrement && 14728 isa<ConstantSDNode>(LHS.getOperand(1)) && 14729 !isNullConstant(LHS.getOperand(1))) 14730 LHS = LHS.getOperand(0); 14731 14732 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14733 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14734 Intrinsic::loop_decrement && 14735 isa<ConstantSDNode>(RHS)) { 14736 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14737 "Counter decrement comparison is not EQ or NE"); 14738 14739 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14740 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14741 (CC == ISD::SETNE && !Val); 14742 14743 // We now need to make the intrinsic dead (it cannot be instruction 14744 // selected). 14745 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14746 assert(LHS.getNode()->hasOneUse() && 14747 "Counter decrement has more than one use"); 14748 14749 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14750 N->getOperand(0), N->getOperand(4)); 14751 } 14752 14753 int CompareOpc; 14754 bool isDot; 14755 14756 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14757 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14758 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14759 assert(isDot && "Can't compare against a vector result!"); 14760 14761 // If this is a comparison against something other than 0/1, then we know 14762 // that the condition is never/always true. 14763 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14764 if (Val != 0 && Val != 1) { 14765 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14766 return N->getOperand(0); 14767 // Always !=, turn it into an unconditional branch. 14768 return DAG.getNode(ISD::BR, dl, MVT::Other, 14769 N->getOperand(0), N->getOperand(4)); 14770 } 14771 14772 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14773 14774 // Create the PPCISD altivec 'dot' comparison node. 14775 SDValue Ops[] = { 14776 LHS.getOperand(2), // LHS of compare 14777 LHS.getOperand(3), // RHS of compare 14778 DAG.getConstant(CompareOpc, dl, MVT::i32) 14779 }; 14780 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14781 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14782 14783 // Unpack the result based on how the target uses it. 14784 PPC::Predicate CompOpc; 14785 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14786 default: // Can't happen, don't crash on invalid number though. 14787 case 0: // Branch on the value of the EQ bit of CR6. 14788 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14789 break; 14790 case 1: // Branch on the inverted value of the EQ bit of CR6. 14791 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14792 break; 14793 case 2: // Branch on the value of the LT bit of CR6. 14794 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14795 break; 14796 case 3: // Branch on the inverted value of the LT bit of CR6. 14797 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14798 break; 14799 } 14800 14801 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14802 DAG.getConstant(CompOpc, dl, MVT::i32), 14803 DAG.getRegister(PPC::CR6, MVT::i32), 14804 N->getOperand(4), CompNode.getValue(1)); 14805 } 14806 break; 14807 } 14808 case ISD::BUILD_VECTOR: 14809 return DAGCombineBuildVector(N, DCI); 14810 case ISD::ABS: 14811 return combineABS(N, DCI); 14812 case ISD::VSELECT: 14813 return combineVSelect(N, DCI); 14814 } 14815 14816 return SDValue(); 14817 } 14818 14819 SDValue 14820 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14821 SelectionDAG &DAG, 14822 SmallVectorImpl<SDNode *> &Created) const { 14823 // fold (sdiv X, pow2) 14824 EVT VT = N->getValueType(0); 14825 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14826 return SDValue(); 14827 if ((VT != MVT::i32 && VT != MVT::i64) || 14828 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14829 return SDValue(); 14830 14831 SDLoc DL(N); 14832 SDValue N0 = N->getOperand(0); 14833 14834 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14835 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14836 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14837 14838 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14839 Created.push_back(Op.getNode()); 14840 14841 if (IsNegPow2) { 14842 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14843 Created.push_back(Op.getNode()); 14844 } 14845 14846 return Op; 14847 } 14848 14849 //===----------------------------------------------------------------------===// 14850 // Inline Assembly Support 14851 //===----------------------------------------------------------------------===// 14852 14853 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14854 KnownBits &Known, 14855 const APInt &DemandedElts, 14856 const SelectionDAG &DAG, 14857 unsigned Depth) const { 14858 Known.resetAll(); 14859 switch (Op.getOpcode()) { 14860 default: break; 14861 case PPCISD::LBRX: { 14862 // lhbrx is known to have the top bits cleared out. 14863 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14864 Known.Zero = 0xFFFF0000; 14865 break; 14866 } 14867 case ISD::INTRINSIC_WO_CHAIN: { 14868 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14869 default: break; 14870 case Intrinsic::ppc_altivec_vcmpbfp_p: 14871 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14872 case Intrinsic::ppc_altivec_vcmpequb_p: 14873 case Intrinsic::ppc_altivec_vcmpequh_p: 14874 case Intrinsic::ppc_altivec_vcmpequw_p: 14875 case Intrinsic::ppc_altivec_vcmpequd_p: 14876 case Intrinsic::ppc_altivec_vcmpgefp_p: 14877 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14878 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14879 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14880 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14881 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14882 case Intrinsic::ppc_altivec_vcmpgtub_p: 14883 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14884 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14885 case Intrinsic::ppc_altivec_vcmpgtud_p: 14886 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14887 break; 14888 } 14889 } 14890 } 14891 } 14892 14893 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14894 switch (Subtarget.getCPUDirective()) { 14895 default: break; 14896 case PPC::DIR_970: 14897 case PPC::DIR_PWR4: 14898 case PPC::DIR_PWR5: 14899 case PPC::DIR_PWR5X: 14900 case PPC::DIR_PWR6: 14901 case PPC::DIR_PWR6X: 14902 case PPC::DIR_PWR7: 14903 case PPC::DIR_PWR8: 14904 case PPC::DIR_PWR9: 14905 case PPC::DIR_PWR_FUTURE: { 14906 if (!ML) 14907 break; 14908 14909 if (!DisableInnermostLoopAlign32) { 14910 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14911 // so that we can decrease cache misses and branch-prediction misses. 14912 // Actual alignment of the loop will depend on the hotness check and other 14913 // logic in alignBlocks. 14914 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14915 return Align(32); 14916 } 14917 14918 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14919 14920 // For small loops (between 5 and 8 instructions), align to a 32-byte 14921 // boundary so that the entire loop fits in one instruction-cache line. 14922 uint64_t LoopSize = 0; 14923 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14924 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14925 LoopSize += TII->getInstSizeInBytes(*J); 14926 if (LoopSize > 32) 14927 break; 14928 } 14929 14930 if (LoopSize > 16 && LoopSize <= 32) 14931 return Align(32); 14932 14933 break; 14934 } 14935 } 14936 14937 return TargetLowering::getPrefLoopAlignment(ML); 14938 } 14939 14940 /// getConstraintType - Given a constraint, return the type of 14941 /// constraint it is for this target. 14942 PPCTargetLowering::ConstraintType 14943 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14944 if (Constraint.size() == 1) { 14945 switch (Constraint[0]) { 14946 default: break; 14947 case 'b': 14948 case 'r': 14949 case 'f': 14950 case 'd': 14951 case 'v': 14952 case 'y': 14953 return C_RegisterClass; 14954 case 'Z': 14955 // FIXME: While Z does indicate a memory constraint, it specifically 14956 // indicates an r+r address (used in conjunction with the 'y' modifier 14957 // in the replacement string). Currently, we're forcing the base 14958 // register to be r0 in the asm printer (which is interpreted as zero) 14959 // and forming the complete address in the second register. This is 14960 // suboptimal. 14961 return C_Memory; 14962 } 14963 } else if (Constraint == "wc") { // individual CR bits. 14964 return C_RegisterClass; 14965 } else if (Constraint == "wa" || Constraint == "wd" || 14966 Constraint == "wf" || Constraint == "ws" || 14967 Constraint == "wi" || Constraint == "ww") { 14968 return C_RegisterClass; // VSX registers. 14969 } 14970 return TargetLowering::getConstraintType(Constraint); 14971 } 14972 14973 /// Examine constraint type and operand type and determine a weight value. 14974 /// This object must already have been set up with the operand type 14975 /// and the current alternative constraint selected. 14976 TargetLowering::ConstraintWeight 14977 PPCTargetLowering::getSingleConstraintMatchWeight( 14978 AsmOperandInfo &info, const char *constraint) const { 14979 ConstraintWeight weight = CW_Invalid; 14980 Value *CallOperandVal = info.CallOperandVal; 14981 // If we don't have a value, we can't do a match, 14982 // but allow it at the lowest weight. 14983 if (!CallOperandVal) 14984 return CW_Default; 14985 Type *type = CallOperandVal->getType(); 14986 14987 // Look at the constraint type. 14988 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14989 return CW_Register; // an individual CR bit. 14990 else if ((StringRef(constraint) == "wa" || 14991 StringRef(constraint) == "wd" || 14992 StringRef(constraint) == "wf") && 14993 type->isVectorTy()) 14994 return CW_Register; 14995 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14996 return CW_Register; // just hold 64-bit integers data. 14997 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14998 return CW_Register; 14999 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15000 return CW_Register; 15001 15002 switch (*constraint) { 15003 default: 15004 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15005 break; 15006 case 'b': 15007 if (type->isIntegerTy()) 15008 weight = CW_Register; 15009 break; 15010 case 'f': 15011 if (type->isFloatTy()) 15012 weight = CW_Register; 15013 break; 15014 case 'd': 15015 if (type->isDoubleTy()) 15016 weight = CW_Register; 15017 break; 15018 case 'v': 15019 if (type->isVectorTy()) 15020 weight = CW_Register; 15021 break; 15022 case 'y': 15023 weight = CW_Register; 15024 break; 15025 case 'Z': 15026 weight = CW_Memory; 15027 break; 15028 } 15029 return weight; 15030 } 15031 15032 std::pair<unsigned, const TargetRegisterClass *> 15033 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15034 StringRef Constraint, 15035 MVT VT) const { 15036 if (Constraint.size() == 1) { 15037 // GCC RS6000 Constraint Letters 15038 switch (Constraint[0]) { 15039 case 'b': // R1-R31 15040 if (VT == MVT::i64 && Subtarget.isPPC64()) 15041 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15042 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15043 case 'r': // R0-R31 15044 if (VT == MVT::i64 && Subtarget.isPPC64()) 15045 return std::make_pair(0U, &PPC::G8RCRegClass); 15046 return std::make_pair(0U, &PPC::GPRCRegClass); 15047 // 'd' and 'f' constraints are both defined to be "the floating point 15048 // registers", where one is for 32-bit and the other for 64-bit. We don't 15049 // really care overly much here so just give them all the same reg classes. 15050 case 'd': 15051 case 'f': 15052 if (Subtarget.hasSPE()) { 15053 if (VT == MVT::f32 || VT == MVT::i32) 15054 return std::make_pair(0U, &PPC::GPRCRegClass); 15055 if (VT == MVT::f64 || VT == MVT::i64) 15056 return std::make_pair(0U, &PPC::SPERCRegClass); 15057 } else { 15058 if (VT == MVT::f32 || VT == MVT::i32) 15059 return std::make_pair(0U, &PPC::F4RCRegClass); 15060 if (VT == MVT::f64 || VT == MVT::i64) 15061 return std::make_pair(0U, &PPC::F8RCRegClass); 15062 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15063 return std::make_pair(0U, &PPC::QFRCRegClass); 15064 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15065 return std::make_pair(0U, &PPC::QSRCRegClass); 15066 } 15067 break; 15068 case 'v': 15069 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15070 return std::make_pair(0U, &PPC::QFRCRegClass); 15071 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15072 return std::make_pair(0U, &PPC::QSRCRegClass); 15073 if (Subtarget.hasAltivec()) 15074 return std::make_pair(0U, &PPC::VRRCRegClass); 15075 break; 15076 case 'y': // crrc 15077 return std::make_pair(0U, &PPC::CRRCRegClass); 15078 } 15079 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15080 // An individual CR bit. 15081 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15082 } else if ((Constraint == "wa" || Constraint == "wd" || 15083 Constraint == "wf" || Constraint == "wi") && 15084 Subtarget.hasVSX()) { 15085 return std::make_pair(0U, &PPC::VSRCRegClass); 15086 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15087 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15088 return std::make_pair(0U, &PPC::VSSRCRegClass); 15089 else 15090 return std::make_pair(0U, &PPC::VSFRCRegClass); 15091 } 15092 15093 // If we name a VSX register, we can't defer to the base class because it 15094 // will not recognize the correct register (their names will be VSL{0-31} 15095 // and V{0-31} so they won't match). So we match them here. 15096 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15097 int VSNum = atoi(Constraint.data() + 3); 15098 assert(VSNum >= 0 && VSNum <= 63 && 15099 "Attempted to access a vsr out of range"); 15100 if (VSNum < 32) 15101 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15102 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15103 } 15104 std::pair<unsigned, const TargetRegisterClass *> R = 15105 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15106 15107 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15108 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15109 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15110 // register. 15111 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15112 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15113 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15114 PPC::GPRCRegClass.contains(R.first)) 15115 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15116 PPC::sub_32, &PPC::G8RCRegClass), 15117 &PPC::G8RCRegClass); 15118 15119 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15120 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15121 R.first = PPC::CR0; 15122 R.second = &PPC::CRRCRegClass; 15123 } 15124 15125 return R; 15126 } 15127 15128 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15129 /// vector. If it is invalid, don't add anything to Ops. 15130 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15131 std::string &Constraint, 15132 std::vector<SDValue>&Ops, 15133 SelectionDAG &DAG) const { 15134 SDValue Result; 15135 15136 // Only support length 1 constraints. 15137 if (Constraint.length() > 1) return; 15138 15139 char Letter = Constraint[0]; 15140 switch (Letter) { 15141 default: break; 15142 case 'I': 15143 case 'J': 15144 case 'K': 15145 case 'L': 15146 case 'M': 15147 case 'N': 15148 case 'O': 15149 case 'P': { 15150 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15151 if (!CST) return; // Must be an immediate to match. 15152 SDLoc dl(Op); 15153 int64_t Value = CST->getSExtValue(); 15154 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15155 // numbers are printed as such. 15156 switch (Letter) { 15157 default: llvm_unreachable("Unknown constraint letter!"); 15158 case 'I': // "I" is a signed 16-bit constant. 15159 if (isInt<16>(Value)) 15160 Result = DAG.getTargetConstant(Value, dl, TCVT); 15161 break; 15162 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15163 if (isShiftedUInt<16, 16>(Value)) 15164 Result = DAG.getTargetConstant(Value, dl, TCVT); 15165 break; 15166 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15167 if (isShiftedInt<16, 16>(Value)) 15168 Result = DAG.getTargetConstant(Value, dl, TCVT); 15169 break; 15170 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15171 if (isUInt<16>(Value)) 15172 Result = DAG.getTargetConstant(Value, dl, TCVT); 15173 break; 15174 case 'M': // "M" is a constant that is greater than 31. 15175 if (Value > 31) 15176 Result = DAG.getTargetConstant(Value, dl, TCVT); 15177 break; 15178 case 'N': // "N" is a positive constant that is an exact power of two. 15179 if (Value > 0 && isPowerOf2_64(Value)) 15180 Result = DAG.getTargetConstant(Value, dl, TCVT); 15181 break; 15182 case 'O': // "O" is the constant zero. 15183 if (Value == 0) 15184 Result = DAG.getTargetConstant(Value, dl, TCVT); 15185 break; 15186 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15187 if (isInt<16>(-Value)) 15188 Result = DAG.getTargetConstant(Value, dl, TCVT); 15189 break; 15190 } 15191 break; 15192 } 15193 } 15194 15195 if (Result.getNode()) { 15196 Ops.push_back(Result); 15197 return; 15198 } 15199 15200 // Handle standard constraint letters. 15201 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15202 } 15203 15204 // isLegalAddressingMode - Return true if the addressing mode represented 15205 // by AM is legal for this target, for a load/store of the specified type. 15206 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15207 const AddrMode &AM, Type *Ty, 15208 unsigned AS, Instruction *I) const { 15209 // PPC does not allow r+i addressing modes for vectors! 15210 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15211 return false; 15212 15213 // PPC allows a sign-extended 16-bit immediate field. 15214 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15215 return false; 15216 15217 // No global is ever allowed as a base. 15218 if (AM.BaseGV) 15219 return false; 15220 15221 // PPC only support r+r, 15222 switch (AM.Scale) { 15223 case 0: // "r+i" or just "i", depending on HasBaseReg. 15224 break; 15225 case 1: 15226 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15227 return false; 15228 // Otherwise we have r+r or r+i. 15229 break; 15230 case 2: 15231 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15232 return false; 15233 // Allow 2*r as r+r. 15234 break; 15235 default: 15236 // No other scales are supported. 15237 return false; 15238 } 15239 15240 return true; 15241 } 15242 15243 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15244 SelectionDAG &DAG) const { 15245 MachineFunction &MF = DAG.getMachineFunction(); 15246 MachineFrameInfo &MFI = MF.getFrameInfo(); 15247 MFI.setReturnAddressIsTaken(true); 15248 15249 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15250 return SDValue(); 15251 15252 SDLoc dl(Op); 15253 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15254 15255 // Make sure the function does not optimize away the store of the RA to 15256 // the stack. 15257 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15258 FuncInfo->setLRStoreRequired(); 15259 bool isPPC64 = Subtarget.isPPC64(); 15260 auto PtrVT = getPointerTy(MF.getDataLayout()); 15261 15262 if (Depth > 0) { 15263 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15264 SDValue Offset = 15265 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15266 isPPC64 ? MVT::i64 : MVT::i32); 15267 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15268 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15269 MachinePointerInfo()); 15270 } 15271 15272 // Just load the return address off the stack. 15273 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15274 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15275 MachinePointerInfo()); 15276 } 15277 15278 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15279 SelectionDAG &DAG) const { 15280 SDLoc dl(Op); 15281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15282 15283 MachineFunction &MF = DAG.getMachineFunction(); 15284 MachineFrameInfo &MFI = MF.getFrameInfo(); 15285 MFI.setFrameAddressIsTaken(true); 15286 15287 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15288 bool isPPC64 = PtrVT == MVT::i64; 15289 15290 // Naked functions never have a frame pointer, and so we use r1. For all 15291 // other functions, this decision must be delayed until during PEI. 15292 unsigned FrameReg; 15293 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15294 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15295 else 15296 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15297 15298 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15299 PtrVT); 15300 while (Depth--) 15301 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15302 FrameAddr, MachinePointerInfo()); 15303 return FrameAddr; 15304 } 15305 15306 // FIXME? Maybe this could be a TableGen attribute on some registers and 15307 // this table could be generated automatically from RegInfo. 15308 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15309 const MachineFunction &MF) const { 15310 bool isPPC64 = Subtarget.isPPC64(); 15311 15312 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15313 if (!is64Bit && VT != LLT::scalar(32)) 15314 report_fatal_error("Invalid register global variable type"); 15315 15316 Register Reg = StringSwitch<Register>(RegName) 15317 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15318 .Case("r2", isPPC64 ? Register() : PPC::R2) 15319 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15320 .Default(Register()); 15321 15322 if (Reg) 15323 return Reg; 15324 report_fatal_error("Invalid register name global variable"); 15325 } 15326 15327 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15328 // 32-bit SVR4 ABI access everything as got-indirect. 15329 if (Subtarget.is32BitELFABI()) 15330 return true; 15331 15332 // AIX accesses everything indirectly through the TOC, which is similar to 15333 // the GOT. 15334 if (Subtarget.isAIXABI()) 15335 return true; 15336 15337 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15338 // If it is small or large code model, module locals are accessed 15339 // indirectly by loading their address from .toc/.got. 15340 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15341 return true; 15342 15343 // JumpTable and BlockAddress are accessed as got-indirect. 15344 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15345 return true; 15346 15347 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15348 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15349 15350 return false; 15351 } 15352 15353 bool 15354 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15355 // The PowerPC target isn't yet aware of offsets. 15356 return false; 15357 } 15358 15359 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15360 const CallInst &I, 15361 MachineFunction &MF, 15362 unsigned Intrinsic) const { 15363 switch (Intrinsic) { 15364 case Intrinsic::ppc_qpx_qvlfd: 15365 case Intrinsic::ppc_qpx_qvlfs: 15366 case Intrinsic::ppc_qpx_qvlfcd: 15367 case Intrinsic::ppc_qpx_qvlfcs: 15368 case Intrinsic::ppc_qpx_qvlfiwa: 15369 case Intrinsic::ppc_qpx_qvlfiwz: 15370 case Intrinsic::ppc_altivec_lvx: 15371 case Intrinsic::ppc_altivec_lvxl: 15372 case Intrinsic::ppc_altivec_lvebx: 15373 case Intrinsic::ppc_altivec_lvehx: 15374 case Intrinsic::ppc_altivec_lvewx: 15375 case Intrinsic::ppc_vsx_lxvd2x: 15376 case Intrinsic::ppc_vsx_lxvw4x: { 15377 EVT VT; 15378 switch (Intrinsic) { 15379 case Intrinsic::ppc_altivec_lvebx: 15380 VT = MVT::i8; 15381 break; 15382 case Intrinsic::ppc_altivec_lvehx: 15383 VT = MVT::i16; 15384 break; 15385 case Intrinsic::ppc_altivec_lvewx: 15386 VT = MVT::i32; 15387 break; 15388 case Intrinsic::ppc_vsx_lxvd2x: 15389 VT = MVT::v2f64; 15390 break; 15391 case Intrinsic::ppc_qpx_qvlfd: 15392 VT = MVT::v4f64; 15393 break; 15394 case Intrinsic::ppc_qpx_qvlfs: 15395 VT = MVT::v4f32; 15396 break; 15397 case Intrinsic::ppc_qpx_qvlfcd: 15398 VT = MVT::v2f64; 15399 break; 15400 case Intrinsic::ppc_qpx_qvlfcs: 15401 VT = MVT::v2f32; 15402 break; 15403 default: 15404 VT = MVT::v4i32; 15405 break; 15406 } 15407 15408 Info.opc = ISD::INTRINSIC_W_CHAIN; 15409 Info.memVT = VT; 15410 Info.ptrVal = I.getArgOperand(0); 15411 Info.offset = -VT.getStoreSize()+1; 15412 Info.size = 2*VT.getStoreSize()-1; 15413 Info.align = Align(1); 15414 Info.flags = MachineMemOperand::MOLoad; 15415 return true; 15416 } 15417 case Intrinsic::ppc_qpx_qvlfda: 15418 case Intrinsic::ppc_qpx_qvlfsa: 15419 case Intrinsic::ppc_qpx_qvlfcda: 15420 case Intrinsic::ppc_qpx_qvlfcsa: 15421 case Intrinsic::ppc_qpx_qvlfiwaa: 15422 case Intrinsic::ppc_qpx_qvlfiwza: { 15423 EVT VT; 15424 switch (Intrinsic) { 15425 case Intrinsic::ppc_qpx_qvlfda: 15426 VT = MVT::v4f64; 15427 break; 15428 case Intrinsic::ppc_qpx_qvlfsa: 15429 VT = MVT::v4f32; 15430 break; 15431 case Intrinsic::ppc_qpx_qvlfcda: 15432 VT = MVT::v2f64; 15433 break; 15434 case Intrinsic::ppc_qpx_qvlfcsa: 15435 VT = MVT::v2f32; 15436 break; 15437 default: 15438 VT = MVT::v4i32; 15439 break; 15440 } 15441 15442 Info.opc = ISD::INTRINSIC_W_CHAIN; 15443 Info.memVT = VT; 15444 Info.ptrVal = I.getArgOperand(0); 15445 Info.offset = 0; 15446 Info.size = VT.getStoreSize(); 15447 Info.align = Align(1); 15448 Info.flags = MachineMemOperand::MOLoad; 15449 return true; 15450 } 15451 case Intrinsic::ppc_qpx_qvstfd: 15452 case Intrinsic::ppc_qpx_qvstfs: 15453 case Intrinsic::ppc_qpx_qvstfcd: 15454 case Intrinsic::ppc_qpx_qvstfcs: 15455 case Intrinsic::ppc_qpx_qvstfiw: 15456 case Intrinsic::ppc_altivec_stvx: 15457 case Intrinsic::ppc_altivec_stvxl: 15458 case Intrinsic::ppc_altivec_stvebx: 15459 case Intrinsic::ppc_altivec_stvehx: 15460 case Intrinsic::ppc_altivec_stvewx: 15461 case Intrinsic::ppc_vsx_stxvd2x: 15462 case Intrinsic::ppc_vsx_stxvw4x: { 15463 EVT VT; 15464 switch (Intrinsic) { 15465 case Intrinsic::ppc_altivec_stvebx: 15466 VT = MVT::i8; 15467 break; 15468 case Intrinsic::ppc_altivec_stvehx: 15469 VT = MVT::i16; 15470 break; 15471 case Intrinsic::ppc_altivec_stvewx: 15472 VT = MVT::i32; 15473 break; 15474 case Intrinsic::ppc_vsx_stxvd2x: 15475 VT = MVT::v2f64; 15476 break; 15477 case Intrinsic::ppc_qpx_qvstfd: 15478 VT = MVT::v4f64; 15479 break; 15480 case Intrinsic::ppc_qpx_qvstfs: 15481 VT = MVT::v4f32; 15482 break; 15483 case Intrinsic::ppc_qpx_qvstfcd: 15484 VT = MVT::v2f64; 15485 break; 15486 case Intrinsic::ppc_qpx_qvstfcs: 15487 VT = MVT::v2f32; 15488 break; 15489 default: 15490 VT = MVT::v4i32; 15491 break; 15492 } 15493 15494 Info.opc = ISD::INTRINSIC_VOID; 15495 Info.memVT = VT; 15496 Info.ptrVal = I.getArgOperand(1); 15497 Info.offset = -VT.getStoreSize()+1; 15498 Info.size = 2*VT.getStoreSize()-1; 15499 Info.align = Align(1); 15500 Info.flags = MachineMemOperand::MOStore; 15501 return true; 15502 } 15503 case Intrinsic::ppc_qpx_qvstfda: 15504 case Intrinsic::ppc_qpx_qvstfsa: 15505 case Intrinsic::ppc_qpx_qvstfcda: 15506 case Intrinsic::ppc_qpx_qvstfcsa: 15507 case Intrinsic::ppc_qpx_qvstfiwa: { 15508 EVT VT; 15509 switch (Intrinsic) { 15510 case Intrinsic::ppc_qpx_qvstfda: 15511 VT = MVT::v4f64; 15512 break; 15513 case Intrinsic::ppc_qpx_qvstfsa: 15514 VT = MVT::v4f32; 15515 break; 15516 case Intrinsic::ppc_qpx_qvstfcda: 15517 VT = MVT::v2f64; 15518 break; 15519 case Intrinsic::ppc_qpx_qvstfcsa: 15520 VT = MVT::v2f32; 15521 break; 15522 default: 15523 VT = MVT::v4i32; 15524 break; 15525 } 15526 15527 Info.opc = ISD::INTRINSIC_VOID; 15528 Info.memVT = VT; 15529 Info.ptrVal = I.getArgOperand(1); 15530 Info.offset = 0; 15531 Info.size = VT.getStoreSize(); 15532 Info.align = Align(1); 15533 Info.flags = MachineMemOperand::MOStore; 15534 return true; 15535 } 15536 default: 15537 break; 15538 } 15539 15540 return false; 15541 } 15542 15543 /// It returns EVT::Other if the type should be determined using generic 15544 /// target-independent logic. 15545 EVT PPCTargetLowering::getOptimalMemOpType( 15546 const MemOp &Op, const AttributeList &FuncAttributes) const { 15547 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15548 // When expanding a memset, require at least two QPX instructions to cover 15549 // the cost of loading the value to be stored from the constant pool. 15550 if (Subtarget.hasQPX() && Op.size() >= 32 && 15551 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15552 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15553 return MVT::v4f64; 15554 } 15555 15556 // We should use Altivec/VSX loads and stores when available. For unaligned 15557 // addresses, unaligned VSX loads are only fast starting with the P8. 15558 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15559 (Op.isAligned(Align(16)) || 15560 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15561 return MVT::v4i32; 15562 } 15563 15564 if (Subtarget.isPPC64()) { 15565 return MVT::i64; 15566 } 15567 15568 return MVT::i32; 15569 } 15570 15571 /// Returns true if it is beneficial to convert a load of a constant 15572 /// to just the constant itself. 15573 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15574 Type *Ty) const { 15575 assert(Ty->isIntegerTy()); 15576 15577 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15578 return !(BitSize == 0 || BitSize > 64); 15579 } 15580 15581 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15582 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15583 return false; 15584 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15585 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15586 return NumBits1 == 64 && NumBits2 == 32; 15587 } 15588 15589 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15590 if (!VT1.isInteger() || !VT2.isInteger()) 15591 return false; 15592 unsigned NumBits1 = VT1.getSizeInBits(); 15593 unsigned NumBits2 = VT2.getSizeInBits(); 15594 return NumBits1 == 64 && NumBits2 == 32; 15595 } 15596 15597 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15598 // Generally speaking, zexts are not free, but they are free when they can be 15599 // folded with other operations. 15600 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15601 EVT MemVT = LD->getMemoryVT(); 15602 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15603 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15604 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15605 LD->getExtensionType() == ISD::ZEXTLOAD)) 15606 return true; 15607 } 15608 15609 // FIXME: Add other cases... 15610 // - 32-bit shifts with a zext to i64 15611 // - zext after ctlz, bswap, etc. 15612 // - zext after and by a constant mask 15613 15614 return TargetLowering::isZExtFree(Val, VT2); 15615 } 15616 15617 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15618 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15619 "invalid fpext types"); 15620 // Extending to float128 is not free. 15621 if (DestVT == MVT::f128) 15622 return false; 15623 return true; 15624 } 15625 15626 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15627 return isInt<16>(Imm) || isUInt<16>(Imm); 15628 } 15629 15630 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15631 return isInt<16>(Imm) || isUInt<16>(Imm); 15632 } 15633 15634 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15635 unsigned, 15636 unsigned, 15637 MachineMemOperand::Flags, 15638 bool *Fast) const { 15639 if (DisablePPCUnaligned) 15640 return false; 15641 15642 // PowerPC supports unaligned memory access for simple non-vector types. 15643 // Although accessing unaligned addresses is not as efficient as accessing 15644 // aligned addresses, it is generally more efficient than manual expansion, 15645 // and generally only traps for software emulation when crossing page 15646 // boundaries. 15647 15648 if (!VT.isSimple()) 15649 return false; 15650 15651 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15652 return false; 15653 15654 if (VT.getSimpleVT().isVector()) { 15655 if (Subtarget.hasVSX()) { 15656 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15657 VT != MVT::v4f32 && VT != MVT::v4i32) 15658 return false; 15659 } else { 15660 return false; 15661 } 15662 } 15663 15664 if (VT == MVT::ppcf128) 15665 return false; 15666 15667 if (Fast) 15668 *Fast = true; 15669 15670 return true; 15671 } 15672 15673 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15674 EVT VT) const { 15675 return isFMAFasterThanFMulAndFAdd( 15676 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15677 } 15678 15679 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15680 Type *Ty) const { 15681 switch (Ty->getScalarType()->getTypeID()) { 15682 case Type::FloatTyID: 15683 case Type::DoubleTyID: 15684 return true; 15685 case Type::FP128TyID: 15686 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15687 default: 15688 return false; 15689 } 15690 } 15691 15692 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15693 // FIXME: add more patterns which are profitable to hoist. 15694 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15695 if (I->getOpcode() != Instruction::FMul) 15696 return true; 15697 15698 if (!I->hasOneUse()) 15699 return true; 15700 15701 Instruction *User = I->user_back(); 15702 assert(User && "A single use instruction with no uses."); 15703 15704 if (User->getOpcode() != Instruction::FSub && 15705 User->getOpcode() != Instruction::FAdd) 15706 return true; 15707 15708 const TargetOptions &Options = getTargetMachine().Options; 15709 const Function *F = I->getFunction(); 15710 const DataLayout &DL = F->getParent()->getDataLayout(); 15711 Type *Ty = User->getOperand(0)->getType(); 15712 15713 return !( 15714 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15715 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15716 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15717 } 15718 15719 const MCPhysReg * 15720 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15721 // LR is a callee-save register, but we must treat it as clobbered by any call 15722 // site. Hence we include LR in the scratch registers, which are in turn added 15723 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15724 // to CTR, which is used by any indirect call. 15725 static const MCPhysReg ScratchRegs[] = { 15726 PPC::X12, PPC::LR8, PPC::CTR8, 0 15727 }; 15728 15729 return ScratchRegs; 15730 } 15731 15732 Register PPCTargetLowering::getExceptionPointerRegister( 15733 const Constant *PersonalityFn) const { 15734 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15735 } 15736 15737 Register PPCTargetLowering::getExceptionSelectorRegister( 15738 const Constant *PersonalityFn) const { 15739 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15740 } 15741 15742 bool 15743 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15744 EVT VT , unsigned DefinedValues) const { 15745 if (VT == MVT::v2i64) 15746 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15747 15748 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15749 return true; 15750 15751 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15752 } 15753 15754 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15755 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15756 return TargetLowering::getSchedulingPreference(N); 15757 15758 return Sched::ILP; 15759 } 15760 15761 // Create a fast isel object. 15762 FastISel * 15763 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15764 const TargetLibraryInfo *LibInfo) const { 15765 return PPC::createFastISel(FuncInfo, LibInfo); 15766 } 15767 15768 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15769 bool PPCTargetLowering::useLoadStackGuardNode() const { 15770 if (!Subtarget.isTargetLinux()) 15771 return TargetLowering::useLoadStackGuardNode(); 15772 return true; 15773 } 15774 15775 // Override to disable global variable loading on Linux. 15776 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15777 if (!Subtarget.isTargetLinux()) 15778 return TargetLowering::insertSSPDeclarations(M); 15779 } 15780 15781 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15782 bool ForCodeSize) const { 15783 if (!VT.isSimple() || !Subtarget.hasVSX()) 15784 return false; 15785 15786 switch(VT.getSimpleVT().SimpleTy) { 15787 default: 15788 // For FP types that are currently not supported by PPC backend, return 15789 // false. Examples: f16, f80. 15790 return false; 15791 case MVT::f32: 15792 case MVT::f64: 15793 case MVT::ppcf128: 15794 return Imm.isPosZero(); 15795 } 15796 } 15797 15798 // For vector shift operation op, fold 15799 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15800 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15801 SelectionDAG &DAG) { 15802 SDValue N0 = N->getOperand(0); 15803 SDValue N1 = N->getOperand(1); 15804 EVT VT = N0.getValueType(); 15805 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15806 unsigned Opcode = N->getOpcode(); 15807 unsigned TargetOpcode; 15808 15809 switch (Opcode) { 15810 default: 15811 llvm_unreachable("Unexpected shift operation"); 15812 case ISD::SHL: 15813 TargetOpcode = PPCISD::SHL; 15814 break; 15815 case ISD::SRL: 15816 TargetOpcode = PPCISD::SRL; 15817 break; 15818 case ISD::SRA: 15819 TargetOpcode = PPCISD::SRA; 15820 break; 15821 } 15822 15823 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15824 N1->getOpcode() == ISD::AND) 15825 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15826 if (Mask->getZExtValue() == OpSizeInBits - 1) 15827 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15828 15829 return SDValue(); 15830 } 15831 15832 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15833 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15834 return Value; 15835 15836 SDValue N0 = N->getOperand(0); 15837 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15838 if (!Subtarget.isISA3_0() || 15839 N0.getOpcode() != ISD::SIGN_EXTEND || 15840 N0.getOperand(0).getValueType() != MVT::i32 || 15841 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15842 return SDValue(); 15843 15844 // We can't save an operation here if the value is already extended, and 15845 // the existing shift is easier to combine. 15846 SDValue ExtsSrc = N0.getOperand(0); 15847 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15848 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15849 return SDValue(); 15850 15851 SDLoc DL(N0); 15852 SDValue ShiftBy = SDValue(CN1, 0); 15853 // We want the shift amount to be i32 on the extswli, but the shift could 15854 // have an i64. 15855 if (ShiftBy.getValueType() == MVT::i64) 15856 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15857 15858 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15859 ShiftBy); 15860 } 15861 15862 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15863 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15864 return Value; 15865 15866 return SDValue(); 15867 } 15868 15869 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15870 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15871 return Value; 15872 15873 return SDValue(); 15874 } 15875 15876 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15877 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15878 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15879 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15880 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15881 const PPCSubtarget &Subtarget) { 15882 if (!Subtarget.isPPC64()) 15883 return SDValue(); 15884 15885 SDValue LHS = N->getOperand(0); 15886 SDValue RHS = N->getOperand(1); 15887 15888 auto isZextOfCompareWithConstant = [](SDValue Op) { 15889 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15890 Op.getValueType() != MVT::i64) 15891 return false; 15892 15893 SDValue Cmp = Op.getOperand(0); 15894 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15895 Cmp.getOperand(0).getValueType() != MVT::i64) 15896 return false; 15897 15898 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15899 int64_t NegConstant = 0 - Constant->getSExtValue(); 15900 // Due to the limitations of the addi instruction, 15901 // -C is required to be [-32768, 32767]. 15902 return isInt<16>(NegConstant); 15903 } 15904 15905 return false; 15906 }; 15907 15908 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15909 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15910 15911 // If there is a pattern, canonicalize a zext operand to the RHS. 15912 if (LHSHasPattern && !RHSHasPattern) 15913 std::swap(LHS, RHS); 15914 else if (!LHSHasPattern && !RHSHasPattern) 15915 return SDValue(); 15916 15917 SDLoc DL(N); 15918 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15919 SDValue Cmp = RHS.getOperand(0); 15920 SDValue Z = Cmp.getOperand(0); 15921 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15922 15923 assert(Constant && "Constant Should not be a null pointer."); 15924 int64_t NegConstant = 0 - Constant->getSExtValue(); 15925 15926 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15927 default: break; 15928 case ISD::SETNE: { 15929 // when C == 0 15930 // --> addze X, (addic Z, -1).carry 15931 // / 15932 // add X, (zext(setne Z, C))-- 15933 // \ when -32768 <= -C <= 32767 && C != 0 15934 // --> addze X, (addic (addi Z, -C), -1).carry 15935 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15936 DAG.getConstant(NegConstant, DL, MVT::i64)); 15937 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15938 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15939 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15940 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15941 SDValue(Addc.getNode(), 1)); 15942 } 15943 case ISD::SETEQ: { 15944 // when C == 0 15945 // --> addze X, (subfic Z, 0).carry 15946 // / 15947 // add X, (zext(sete Z, C))-- 15948 // \ when -32768 <= -C <= 32767 && C != 0 15949 // --> addze X, (subfic (addi Z, -C), 0).carry 15950 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15951 DAG.getConstant(NegConstant, DL, MVT::i64)); 15952 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15953 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15954 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15955 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15956 SDValue(Subc.getNode(), 1)); 15957 } 15958 } 15959 15960 return SDValue(); 15961 } 15962 15963 // Transform 15964 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 15965 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 15966 // In this case both C1 and C2 must be known constants. 15967 // C1+C2 must fit into a 34 bit signed integer. 15968 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 15969 const PPCSubtarget &Subtarget) { 15970 if (!Subtarget.isUsingPCRelativeCalls()) 15971 return SDValue(); 15972 15973 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 15974 // If we find that node try to cast the Global Address and the Constant. 15975 SDValue LHS = N->getOperand(0); 15976 SDValue RHS = N->getOperand(1); 15977 15978 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15979 std::swap(LHS, RHS); 15980 15981 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15982 return SDValue(); 15983 15984 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 15985 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 15986 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 15987 15988 // Check that both casts succeeded. 15989 if (!GSDN || !ConstNode) 15990 return SDValue(); 15991 15992 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 15993 SDLoc DL(GSDN); 15994 15995 // The signed int offset needs to fit in 34 bits. 15996 if (!isInt<34>(NewOffset)) 15997 return SDValue(); 15998 15999 // The new global address is a copy of the old global address except 16000 // that it has the updated Offset. 16001 SDValue GA = 16002 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16003 NewOffset, GSDN->getTargetFlags()); 16004 SDValue MatPCRel = 16005 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16006 return MatPCRel; 16007 } 16008 16009 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16010 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16011 return Value; 16012 16013 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16014 return Value; 16015 16016 return SDValue(); 16017 } 16018 16019 // Detect TRUNCATE operations on bitcasts of float128 values. 16020 // What we are looking for here is the situtation where we extract a subset 16021 // of bits from a 128 bit float. 16022 // This can be of two forms: 16023 // 1) BITCAST of f128 feeding TRUNCATE 16024 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16025 // The reason this is required is because we do not have a legal i128 type 16026 // and so we want to prevent having to store the f128 and then reload part 16027 // of it. 16028 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16029 DAGCombinerInfo &DCI) const { 16030 // If we are using CRBits then try that first. 16031 if (Subtarget.useCRBits()) { 16032 // Check if CRBits did anything and return that if it did. 16033 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16034 return CRTruncValue; 16035 } 16036 16037 SDLoc dl(N); 16038 SDValue Op0 = N->getOperand(0); 16039 16040 // Looking for a truncate of i128 to i64. 16041 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16042 return SDValue(); 16043 16044 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16045 16046 // SRL feeding TRUNCATE. 16047 if (Op0.getOpcode() == ISD::SRL) { 16048 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16049 // The right shift has to be by 64 bits. 16050 if (!ConstNode || ConstNode->getZExtValue() != 64) 16051 return SDValue(); 16052 16053 // Switch the element number to extract. 16054 EltToExtract = EltToExtract ? 0 : 1; 16055 // Update Op0 past the SRL. 16056 Op0 = Op0.getOperand(0); 16057 } 16058 16059 // BITCAST feeding a TRUNCATE possibly via SRL. 16060 if (Op0.getOpcode() == ISD::BITCAST && 16061 Op0.getValueType() == MVT::i128 && 16062 Op0.getOperand(0).getValueType() == MVT::f128) { 16063 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16064 return DCI.DAG.getNode( 16065 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16066 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16067 } 16068 return SDValue(); 16069 } 16070 16071 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16072 SelectionDAG &DAG = DCI.DAG; 16073 16074 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16075 if (!ConstOpOrElement) 16076 return SDValue(); 16077 16078 // An imul is usually smaller than the alternative sequence for legal type. 16079 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16080 isOperationLegal(ISD::MUL, N->getValueType(0))) 16081 return SDValue(); 16082 16083 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16084 switch (this->Subtarget.getCPUDirective()) { 16085 default: 16086 // TODO: enhance the condition for subtarget before pwr8 16087 return false; 16088 case PPC::DIR_PWR8: 16089 // type mul add shl 16090 // scalar 4 1 1 16091 // vector 7 2 2 16092 return true; 16093 case PPC::DIR_PWR9: 16094 case PPC::DIR_PWR_FUTURE: 16095 // type mul add shl 16096 // scalar 5 2 2 16097 // vector 7 2 2 16098 16099 // The cycle RATIO of related operations are showed as a table above. 16100 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16101 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16102 // are 4, it is always profitable; but for 3 instrs patterns 16103 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16104 // So we should only do it for vector type. 16105 return IsAddOne && IsNeg ? VT.isVector() : true; 16106 } 16107 }; 16108 16109 EVT VT = N->getValueType(0); 16110 SDLoc DL(N); 16111 16112 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16113 bool IsNeg = MulAmt.isNegative(); 16114 APInt MulAmtAbs = MulAmt.abs(); 16115 16116 if ((MulAmtAbs - 1).isPowerOf2()) { 16117 // (mul x, 2^N + 1) => (add (shl x, N), x) 16118 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16119 16120 if (!IsProfitable(IsNeg, true, VT)) 16121 return SDValue(); 16122 16123 SDValue Op0 = N->getOperand(0); 16124 SDValue Op1 = 16125 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16126 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16127 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16128 16129 if (!IsNeg) 16130 return Res; 16131 16132 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16133 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16134 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16135 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16136 16137 if (!IsProfitable(IsNeg, false, VT)) 16138 return SDValue(); 16139 16140 SDValue Op0 = N->getOperand(0); 16141 SDValue Op1 = 16142 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16143 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16144 16145 if (!IsNeg) 16146 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16147 else 16148 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16149 16150 } else { 16151 return SDValue(); 16152 } 16153 } 16154 16155 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16156 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16157 if (!Subtarget.is64BitELFABI()) 16158 return false; 16159 16160 // If not a tail call then no need to proceed. 16161 if (!CI->isTailCall()) 16162 return false; 16163 16164 // If sibling calls have been disabled and tail-calls aren't guaranteed 16165 // there is no reason to duplicate. 16166 auto &TM = getTargetMachine(); 16167 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16168 return false; 16169 16170 // Can't tail call a function called indirectly, or if it has variadic args. 16171 const Function *Callee = CI->getCalledFunction(); 16172 if (!Callee || Callee->isVarArg()) 16173 return false; 16174 16175 // Make sure the callee and caller calling conventions are eligible for tco. 16176 const Function *Caller = CI->getParent()->getParent(); 16177 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16178 CI->getCallingConv())) 16179 return false; 16180 16181 // If the function is local then we have a good chance at tail-calling it 16182 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16183 } 16184 16185 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16186 if (!Subtarget.hasVSX()) 16187 return false; 16188 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16189 return true; 16190 return VT == MVT::f32 || VT == MVT::f64 || 16191 VT == MVT::v4f32 || VT == MVT::v2f64; 16192 } 16193 16194 bool PPCTargetLowering:: 16195 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16196 const Value *Mask = AndI.getOperand(1); 16197 // If the mask is suitable for andi. or andis. we should sink the and. 16198 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16199 // Can't handle constants wider than 64-bits. 16200 if (CI->getBitWidth() > 64) 16201 return false; 16202 int64_t ConstVal = CI->getZExtValue(); 16203 return isUInt<16>(ConstVal) || 16204 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16205 } 16206 16207 // For non-constant masks, we can always use the record-form and. 16208 return true; 16209 } 16210 16211 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16212 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16213 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16214 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16215 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16216 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16217 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16218 assert(Subtarget.hasP9Altivec() && 16219 "Only combine this when P9 altivec supported!"); 16220 EVT VT = N->getValueType(0); 16221 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16222 return SDValue(); 16223 16224 SelectionDAG &DAG = DCI.DAG; 16225 SDLoc dl(N); 16226 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16227 // Even for signed integers, if it's known to be positive (as signed 16228 // integer) due to zero-extended inputs. 16229 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16230 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16231 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16232 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16233 (SubOpcd1 == ISD::ZERO_EXTEND || 16234 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16235 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16236 N->getOperand(0)->getOperand(0), 16237 N->getOperand(0)->getOperand(1), 16238 DAG.getTargetConstant(0, dl, MVT::i32)); 16239 } 16240 16241 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16242 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16243 N->getOperand(0).hasOneUse()) { 16244 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16245 N->getOperand(0)->getOperand(0), 16246 N->getOperand(0)->getOperand(1), 16247 DAG.getTargetConstant(1, dl, MVT::i32)); 16248 } 16249 } 16250 16251 return SDValue(); 16252 } 16253 16254 // For type v4i32/v8ii16/v16i8, transform 16255 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16256 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16257 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16258 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16259 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16260 DAGCombinerInfo &DCI) const { 16261 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16262 assert(Subtarget.hasP9Altivec() && 16263 "Only combine this when P9 altivec supported!"); 16264 16265 SelectionDAG &DAG = DCI.DAG; 16266 SDLoc dl(N); 16267 SDValue Cond = N->getOperand(0); 16268 SDValue TrueOpnd = N->getOperand(1); 16269 SDValue FalseOpnd = N->getOperand(2); 16270 EVT VT = N->getOperand(1).getValueType(); 16271 16272 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16273 FalseOpnd.getOpcode() != ISD::SUB) 16274 return SDValue(); 16275 16276 // ABSD only available for type v4i32/v8i16/v16i8 16277 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16278 return SDValue(); 16279 16280 // At least to save one more dependent computation 16281 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16282 return SDValue(); 16283 16284 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16285 16286 // Can only handle unsigned comparison here 16287 switch (CC) { 16288 default: 16289 return SDValue(); 16290 case ISD::SETUGT: 16291 case ISD::SETUGE: 16292 break; 16293 case ISD::SETULT: 16294 case ISD::SETULE: 16295 std::swap(TrueOpnd, FalseOpnd); 16296 break; 16297 } 16298 16299 SDValue CmpOpnd1 = Cond.getOperand(0); 16300 SDValue CmpOpnd2 = Cond.getOperand(1); 16301 16302 // SETCC CmpOpnd1 CmpOpnd2 cond 16303 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16304 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16305 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16306 TrueOpnd.getOperand(1) == CmpOpnd2 && 16307 FalseOpnd.getOperand(0) == CmpOpnd2 && 16308 FalseOpnd.getOperand(1) == CmpOpnd1) { 16309 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16310 CmpOpnd1, CmpOpnd2, 16311 DAG.getTargetConstant(0, dl, MVT::i32)); 16312 } 16313 16314 return SDValue(); 16315 } 16316