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 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 722 if (!Subtarget.hasP8Vector()) { 723 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 724 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 725 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 726 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 727 } 728 729 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 730 setOperationAction(ISD::ABS, VT, Custom); 731 732 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 733 // with merges, splats, etc. 734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 735 736 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 737 // are cheap, so handle them before they get expanded to scalar. 738 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 739 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 740 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 741 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 742 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 743 744 setOperationAction(ISD::AND , MVT::v4i32, Legal); 745 setOperationAction(ISD::OR , MVT::v4i32, Legal); 746 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 747 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 748 setOperationAction(ISD::SELECT, MVT::v4i32, 749 Subtarget.useCRBits() ? Legal : Expand); 750 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 751 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 752 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 753 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 754 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 755 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 756 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 757 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 758 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 759 760 // Without hasP8Altivec set, v2i64 SMAX isn't available. 761 // But ABS custom lowering requires SMAX support. 762 if (!Subtarget.hasP8Altivec()) 763 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 764 765 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 766 if (Subtarget.hasAltivec()) 767 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 768 setOperationAction(ISD::ROTL, VT, Legal); 769 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 770 if (Subtarget.hasP8Altivec()) 771 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 772 773 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 774 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 775 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 776 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 777 778 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 779 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 780 781 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 782 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 783 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 784 } 785 786 if (Subtarget.hasP8Altivec()) 787 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 788 else 789 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 790 791 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 792 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 793 794 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 795 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 796 797 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 800 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 801 802 // Altivec does not contain unordered floating-point compare instructions 803 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 804 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 805 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 806 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 807 808 if (Subtarget.hasVSX()) { 809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 811 if (Subtarget.hasP8Vector()) { 812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 814 } 815 if (Subtarget.hasDirectMove() && isPPC64) { 816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 818 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 819 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 823 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 824 } 825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 826 827 // The nearbyint variants are not allowed to raise the inexact exception 828 // so we can only code-gen them with unsafe math. 829 if (TM.Options.UnsafeFPMath) { 830 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 831 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 832 } 833 834 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 835 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 836 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 837 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 838 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 839 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 840 setOperationAction(ISD::FROUND, MVT::f64, Legal); 841 setOperationAction(ISD::FRINT, MVT::f64, Legal); 842 843 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 844 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 845 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 846 setOperationAction(ISD::FROUND, MVT::f32, Legal); 847 setOperationAction(ISD::FRINT, MVT::f32, Legal); 848 849 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 850 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 851 852 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 853 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 854 855 // Share the Altivec comparison restrictions. 856 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 857 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 858 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 859 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 860 861 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 862 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 863 864 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 865 866 if (Subtarget.hasP8Vector()) 867 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 868 869 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 870 871 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 872 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 873 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 874 875 if (Subtarget.hasP8Altivec()) { 876 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 877 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 878 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 879 880 // 128 bit shifts can be accomplished via 3 instructions for SHL and 881 // SRL, but not for SRA because of the instructions available: 882 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 883 // doing 884 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 885 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 886 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 887 888 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 889 } 890 else { 891 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 892 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 893 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 894 895 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 896 897 // VSX v2i64 only supports non-arithmetic operations. 898 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 899 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 900 } 901 902 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 903 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 904 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 905 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 906 907 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 908 909 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 911 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 912 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 913 914 // Custom handling for partial vectors of integers converted to 915 // floating point. We already have optimal handling for v2i32 through 916 // the DAG combine, so those aren't necessary. 917 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 918 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 919 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 920 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 921 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 922 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 923 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 924 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 925 926 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 927 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 928 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 929 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 930 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 931 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 932 933 if (Subtarget.hasDirectMove()) 934 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 935 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 936 937 // Handle constrained floating-point operations of vector. 938 // The predictor is `hasVSX` because altivec instruction has 939 // no exception but VSX vector instruction has. 940 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 941 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 942 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 943 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 944 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 945 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 946 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 947 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 948 949 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 950 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 951 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 952 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 953 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 954 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 955 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 956 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 957 958 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 959 } 960 961 if (Subtarget.hasP8Altivec()) { 962 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 963 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 964 } 965 966 if (Subtarget.hasP9Vector()) { 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 969 970 // 128 bit shifts can be accomplished via 3 instructions for SHL and 971 // SRL, but not for SRA because of the instructions available: 972 // VS{RL} and VS{RL}O. 973 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 974 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 975 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 976 977 if (EnableQuadPrecision) { 978 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 979 setOperationAction(ISD::FADD, MVT::f128, Legal); 980 setOperationAction(ISD::FSUB, MVT::f128, Legal); 981 setOperationAction(ISD::FDIV, MVT::f128, Legal); 982 setOperationAction(ISD::FMUL, MVT::f128, Legal); 983 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 984 // No extending loads to f128 on PPC. 985 for (MVT FPT : MVT::fp_valuetypes()) 986 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 987 setOperationAction(ISD::FMA, MVT::f128, Legal); 988 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 989 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 990 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 991 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 992 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 993 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 994 995 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 996 setOperationAction(ISD::FRINT, MVT::f128, Legal); 997 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 998 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 999 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1000 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1001 1002 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1003 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1004 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1005 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1006 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1007 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1008 // No implementation for these ops for PowerPC. 1009 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1010 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1011 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1012 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1013 setOperationAction(ISD::FREM, MVT::f128, Expand); 1014 1015 // Handle constrained floating-point operations of fp128 1016 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1017 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1018 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1019 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1020 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1021 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1022 } 1023 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1024 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1025 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1026 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1027 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1028 } 1029 1030 if (Subtarget.hasP9Altivec()) { 1031 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1032 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1033 1034 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1035 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1036 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1037 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1038 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1039 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1040 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1041 } 1042 } 1043 1044 if (Subtarget.hasQPX()) { 1045 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1046 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1047 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1048 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1049 1050 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1051 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1052 1053 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1054 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1055 1056 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1057 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1058 1059 if (!Subtarget.useCRBits()) 1060 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1061 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1062 1063 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1064 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1065 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1066 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1067 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1068 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1069 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1070 1071 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1072 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1073 1074 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1075 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1076 1077 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1078 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1079 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1080 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1081 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1082 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1083 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1084 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1085 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1086 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1087 1088 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1089 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1090 1091 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1092 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1093 1094 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1095 1096 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1097 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1098 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1099 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1100 1101 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1102 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1103 1104 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1105 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1106 1107 if (!Subtarget.useCRBits()) 1108 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1109 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1110 1111 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1112 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1113 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1114 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1115 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1116 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1117 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1118 1119 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1120 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1121 1122 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1123 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1124 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1125 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1126 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1127 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1128 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1129 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1130 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1131 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1132 1133 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1134 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1135 1136 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1137 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1138 1139 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1140 1141 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1142 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1143 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1144 1145 if (!Subtarget.useCRBits()) 1146 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1147 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1148 1149 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1150 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1151 1152 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1153 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1154 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1155 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1156 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1157 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1158 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1159 1160 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1161 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1162 1163 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1164 1165 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1166 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1167 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1168 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1169 1170 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1172 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1173 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1174 1175 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1176 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1177 1178 // These need to set FE_INEXACT, and so cannot be vectorized here. 1179 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1180 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1181 1182 if (TM.Options.UnsafeFPMath) { 1183 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1184 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1185 1186 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1187 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1188 } else { 1189 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1190 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1191 1192 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1193 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1194 } 1195 1196 // TODO: Handle constrained floating-point operations of v4f64 1197 } 1198 1199 if (Subtarget.has64BitSupport()) 1200 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1201 1202 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1203 1204 if (!isPPC64) { 1205 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1206 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1207 } 1208 1209 setBooleanContents(ZeroOrOneBooleanContent); 1210 1211 if (Subtarget.hasAltivec()) { 1212 // Altivec instructions set fields to all zeros or all ones. 1213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1214 } 1215 1216 if (!isPPC64) { 1217 // These libcalls are not available in 32-bit. 1218 setLibcallName(RTLIB::SHL_I128, nullptr); 1219 setLibcallName(RTLIB::SRL_I128, nullptr); 1220 setLibcallName(RTLIB::SRA_I128, nullptr); 1221 } 1222 1223 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1224 1225 // We have target-specific dag combine patterns for the following nodes: 1226 setTargetDAGCombine(ISD::ADD); 1227 setTargetDAGCombine(ISD::SHL); 1228 setTargetDAGCombine(ISD::SRA); 1229 setTargetDAGCombine(ISD::SRL); 1230 setTargetDAGCombine(ISD::MUL); 1231 setTargetDAGCombine(ISD::SINT_TO_FP); 1232 setTargetDAGCombine(ISD::BUILD_VECTOR); 1233 if (Subtarget.hasFPCVT()) 1234 setTargetDAGCombine(ISD::UINT_TO_FP); 1235 setTargetDAGCombine(ISD::LOAD); 1236 setTargetDAGCombine(ISD::STORE); 1237 setTargetDAGCombine(ISD::BR_CC); 1238 if (Subtarget.useCRBits()) 1239 setTargetDAGCombine(ISD::BRCOND); 1240 setTargetDAGCombine(ISD::BSWAP); 1241 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1242 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1243 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1244 1245 setTargetDAGCombine(ISD::SIGN_EXTEND); 1246 setTargetDAGCombine(ISD::ZERO_EXTEND); 1247 setTargetDAGCombine(ISD::ANY_EXTEND); 1248 1249 setTargetDAGCombine(ISD::TRUNCATE); 1250 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1251 1252 1253 if (Subtarget.useCRBits()) { 1254 setTargetDAGCombine(ISD::TRUNCATE); 1255 setTargetDAGCombine(ISD::SETCC); 1256 setTargetDAGCombine(ISD::SELECT_CC); 1257 } 1258 1259 // Use reciprocal estimates. 1260 if (TM.Options.UnsafeFPMath) { 1261 setTargetDAGCombine(ISD::FDIV); 1262 setTargetDAGCombine(ISD::FSQRT); 1263 } 1264 1265 if (Subtarget.hasP9Altivec()) { 1266 setTargetDAGCombine(ISD::ABS); 1267 setTargetDAGCombine(ISD::VSELECT); 1268 } 1269 1270 if (EnableQuadPrecision) { 1271 setLibcallName(RTLIB::LOG_F128, "logf128"); 1272 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1273 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1274 setLibcallName(RTLIB::EXP_F128, "expf128"); 1275 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1276 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1277 setLibcallName(RTLIB::COS_F128, "cosf128"); 1278 setLibcallName(RTLIB::POW_F128, "powf128"); 1279 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1280 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1281 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1282 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1283 } 1284 1285 // With 32 condition bits, we don't need to sink (and duplicate) compares 1286 // aggressively in CodeGenPrep. 1287 if (Subtarget.useCRBits()) { 1288 setHasMultipleConditionRegisters(); 1289 setJumpIsExpensive(); 1290 } 1291 1292 setMinFunctionAlignment(Align(4)); 1293 1294 switch (Subtarget.getCPUDirective()) { 1295 default: break; 1296 case PPC::DIR_970: 1297 case PPC::DIR_A2: 1298 case PPC::DIR_E500: 1299 case PPC::DIR_E500mc: 1300 case PPC::DIR_E5500: 1301 case PPC::DIR_PWR4: 1302 case PPC::DIR_PWR5: 1303 case PPC::DIR_PWR5X: 1304 case PPC::DIR_PWR6: 1305 case PPC::DIR_PWR6X: 1306 case PPC::DIR_PWR7: 1307 case PPC::DIR_PWR8: 1308 case PPC::DIR_PWR9: 1309 case PPC::DIR_PWR10: 1310 case PPC::DIR_PWR_FUTURE: 1311 setPrefLoopAlignment(Align(16)); 1312 setPrefFunctionAlignment(Align(16)); 1313 break; 1314 } 1315 1316 if (Subtarget.enableMachineScheduler()) 1317 setSchedulingPreference(Sched::Source); 1318 else 1319 setSchedulingPreference(Sched::Hybrid); 1320 1321 computeRegisterProperties(STI.getRegisterInfo()); 1322 1323 // The Freescale cores do better with aggressive inlining of memcpy and 1324 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1325 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1326 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1327 MaxStoresPerMemset = 32; 1328 MaxStoresPerMemsetOptSize = 16; 1329 MaxStoresPerMemcpy = 32; 1330 MaxStoresPerMemcpyOptSize = 8; 1331 MaxStoresPerMemmove = 32; 1332 MaxStoresPerMemmoveOptSize = 8; 1333 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1334 // The A2 also benefits from (very) aggressive inlining of memcpy and 1335 // friends. The overhead of a the function call, even when warm, can be 1336 // over one hundred cycles. 1337 MaxStoresPerMemset = 128; 1338 MaxStoresPerMemcpy = 128; 1339 MaxStoresPerMemmove = 128; 1340 MaxLoadsPerMemcmp = 128; 1341 } else { 1342 MaxLoadsPerMemcmp = 8; 1343 MaxLoadsPerMemcmpOptSize = 4; 1344 } 1345 1346 // Let the subtarget (CPU) decide if a predictable select is more expensive 1347 // than the corresponding branch. This information is used in CGP to decide 1348 // when to convert selects into branches. 1349 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1350 } 1351 1352 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1353 /// the desired ByVal argument alignment. 1354 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1355 unsigned MaxMaxAlign) { 1356 if (MaxAlign == MaxMaxAlign) 1357 return; 1358 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1359 if (MaxMaxAlign >= 32 && 1360 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1361 MaxAlign = 32; 1362 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1363 MaxAlign < 16) 1364 MaxAlign = 16; 1365 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1366 unsigned EltAlign = 0; 1367 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1368 if (EltAlign > MaxAlign) 1369 MaxAlign = EltAlign; 1370 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1371 for (auto *EltTy : STy->elements()) { 1372 unsigned EltAlign = 0; 1373 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1374 if (EltAlign > MaxAlign) 1375 MaxAlign = EltAlign; 1376 if (MaxAlign == MaxMaxAlign) 1377 break; 1378 } 1379 } 1380 } 1381 1382 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1383 /// function arguments in the caller parameter area. 1384 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1385 const DataLayout &DL) const { 1386 // 16byte and wider vectors are passed on 16byte boundary. 1387 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1388 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1389 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1390 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1391 return Align; 1392 } 1393 1394 bool PPCTargetLowering::useSoftFloat() const { 1395 return Subtarget.useSoftFloat(); 1396 } 1397 1398 bool PPCTargetLowering::hasSPE() const { 1399 return Subtarget.hasSPE(); 1400 } 1401 1402 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1403 return VT.isScalarInteger(); 1404 } 1405 1406 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1407 /// type is cheaper than a multiply followed by a shift. 1408 /// This is true for words and doublewords on 64-bit PowerPC. 1409 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1410 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1411 isOperationLegal(ISD::MULHU, Type))) 1412 return true; 1413 return TargetLowering::isMulhCheaperThanMulShift(Type); 1414 } 1415 1416 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1417 switch ((PPCISD::NodeType)Opcode) { 1418 case PPCISD::FIRST_NUMBER: break; 1419 case PPCISD::FSEL: return "PPCISD::FSEL"; 1420 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1421 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1422 case PPCISD::FCFID: return "PPCISD::FCFID"; 1423 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1424 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1425 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1426 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1427 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1428 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1429 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1430 case PPCISD::FP_TO_UINT_IN_VSR: 1431 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1432 case PPCISD::FP_TO_SINT_IN_VSR: 1433 return "PPCISD::FP_TO_SINT_IN_VSR"; 1434 case PPCISD::FRE: return "PPCISD::FRE"; 1435 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1436 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1437 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1438 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1439 case PPCISD::VPERM: return "PPCISD::VPERM"; 1440 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1441 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1442 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1443 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1444 case PPCISD::CMPB: return "PPCISD::CMPB"; 1445 case PPCISD::Hi: return "PPCISD::Hi"; 1446 case PPCISD::Lo: return "PPCISD::Lo"; 1447 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1448 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1449 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1450 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1451 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1452 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1453 case PPCISD::SRL: return "PPCISD::SRL"; 1454 case PPCISD::SRA: return "PPCISD::SRA"; 1455 case PPCISD::SHL: return "PPCISD::SHL"; 1456 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1457 case PPCISD::CALL: return "PPCISD::CALL"; 1458 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1459 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1460 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1461 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1462 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1463 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1464 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1465 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1466 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1467 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1468 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1469 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1470 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1471 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1472 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1473 case PPCISD::ANDI_rec_1_EQ_BIT: 1474 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1475 case PPCISD::ANDI_rec_1_GT_BIT: 1476 return "PPCISD::ANDI_rec_1_GT_BIT"; 1477 case PPCISD::VCMP: return "PPCISD::VCMP"; 1478 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1479 case PPCISD::LBRX: return "PPCISD::LBRX"; 1480 case PPCISD::STBRX: return "PPCISD::STBRX"; 1481 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1482 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1483 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1484 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1485 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1486 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1487 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1488 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1489 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1490 case PPCISD::ST_VSR_SCAL_INT: 1491 return "PPCISD::ST_VSR_SCAL_INT"; 1492 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1493 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1494 case PPCISD::BDZ: return "PPCISD::BDZ"; 1495 case PPCISD::MFFS: return "PPCISD::MFFS"; 1496 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1497 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1498 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1499 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1500 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1501 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1502 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1503 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1504 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1505 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1506 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1507 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1508 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1509 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1510 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1511 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1512 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1513 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1514 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1515 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1516 case PPCISD::SC: return "PPCISD::SC"; 1517 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1518 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1519 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1520 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1521 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1522 case PPCISD::VABSD: return "PPCISD::VABSD"; 1523 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1524 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1525 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1526 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1527 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1528 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1529 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1530 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1531 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1532 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1533 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1534 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1535 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1536 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1537 } 1538 return nullptr; 1539 } 1540 1541 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1542 EVT VT) const { 1543 if (!VT.isVector()) 1544 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1545 1546 if (Subtarget.hasQPX()) 1547 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1548 1549 return VT.changeVectorElementTypeToInteger(); 1550 } 1551 1552 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1553 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1554 return true; 1555 } 1556 1557 //===----------------------------------------------------------------------===// 1558 // Node matching predicates, for use by the tblgen matching code. 1559 //===----------------------------------------------------------------------===// 1560 1561 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1562 static bool isFloatingPointZero(SDValue Op) { 1563 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1564 return CFP->getValueAPF().isZero(); 1565 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1566 // Maybe this has already been legalized into the constant pool? 1567 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1568 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1569 return CFP->getValueAPF().isZero(); 1570 } 1571 return false; 1572 } 1573 1574 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1575 /// true if Op is undef or if it matches the specified value. 1576 static bool isConstantOrUndef(int Op, int Val) { 1577 return Op < 0 || Op == Val; 1578 } 1579 1580 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1581 /// VPKUHUM instruction. 1582 /// The ShuffleKind distinguishes between big-endian operations with 1583 /// two different inputs (0), either-endian operations with two identical 1584 /// inputs (1), and little-endian operations with two different inputs (2). 1585 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1586 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1587 SelectionDAG &DAG) { 1588 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1589 if (ShuffleKind == 0) { 1590 if (IsLE) 1591 return false; 1592 for (unsigned i = 0; i != 16; ++i) 1593 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1594 return false; 1595 } else if (ShuffleKind == 2) { 1596 if (!IsLE) 1597 return false; 1598 for (unsigned i = 0; i != 16; ++i) 1599 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1600 return false; 1601 } else if (ShuffleKind == 1) { 1602 unsigned j = IsLE ? 0 : 1; 1603 for (unsigned i = 0; i != 8; ++i) 1604 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1605 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1606 return false; 1607 } 1608 return true; 1609 } 1610 1611 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1612 /// VPKUWUM instruction. 1613 /// The ShuffleKind distinguishes between big-endian operations with 1614 /// two different inputs (0), either-endian operations with two identical 1615 /// inputs (1), and little-endian operations with two different inputs (2). 1616 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1617 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1618 SelectionDAG &DAG) { 1619 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1620 if (ShuffleKind == 0) { 1621 if (IsLE) 1622 return false; 1623 for (unsigned i = 0; i != 16; i += 2) 1624 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1625 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1626 return false; 1627 } else if (ShuffleKind == 2) { 1628 if (!IsLE) 1629 return false; 1630 for (unsigned i = 0; i != 16; i += 2) 1631 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1632 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1633 return false; 1634 } else if (ShuffleKind == 1) { 1635 unsigned j = IsLE ? 0 : 2; 1636 for (unsigned i = 0; i != 8; i += 2) 1637 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1638 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1639 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1640 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1641 return false; 1642 } 1643 return true; 1644 } 1645 1646 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1647 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1648 /// current subtarget. 1649 /// 1650 /// The ShuffleKind distinguishes between big-endian operations with 1651 /// two different inputs (0), either-endian operations with two identical 1652 /// inputs (1), and little-endian operations with two different inputs (2). 1653 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1654 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1655 SelectionDAG &DAG) { 1656 const PPCSubtarget& Subtarget = 1657 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1658 if (!Subtarget.hasP8Vector()) 1659 return false; 1660 1661 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1662 if (ShuffleKind == 0) { 1663 if (IsLE) 1664 return false; 1665 for (unsigned i = 0; i != 16; i += 4) 1666 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1667 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1668 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1669 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1670 return false; 1671 } else if (ShuffleKind == 2) { 1672 if (!IsLE) 1673 return false; 1674 for (unsigned i = 0; i != 16; i += 4) 1675 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1676 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1678 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1679 return false; 1680 } else if (ShuffleKind == 1) { 1681 unsigned j = IsLE ? 0 : 4; 1682 for (unsigned i = 0; i != 8; i += 4) 1683 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1684 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1685 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1686 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1687 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1688 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1689 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1690 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1691 return false; 1692 } 1693 return true; 1694 } 1695 1696 /// isVMerge - Common function, used to match vmrg* shuffles. 1697 /// 1698 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1699 unsigned LHSStart, unsigned RHSStart) { 1700 if (N->getValueType(0) != MVT::v16i8) 1701 return false; 1702 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1703 "Unsupported merge size!"); 1704 1705 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1706 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1707 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1708 LHSStart+j+i*UnitSize) || 1709 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1710 RHSStart+j+i*UnitSize)) 1711 return false; 1712 } 1713 return true; 1714 } 1715 1716 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1717 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1718 /// The ShuffleKind distinguishes between big-endian merges with two 1719 /// different inputs (0), either-endian merges with two identical inputs (1), 1720 /// and little-endian merges with two different inputs (2). For the latter, 1721 /// the input operands are swapped (see PPCInstrAltivec.td). 1722 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1723 unsigned ShuffleKind, SelectionDAG &DAG) { 1724 if (DAG.getDataLayout().isLittleEndian()) { 1725 if (ShuffleKind == 1) // unary 1726 return isVMerge(N, UnitSize, 0, 0); 1727 else if (ShuffleKind == 2) // swapped 1728 return isVMerge(N, UnitSize, 0, 16); 1729 else 1730 return false; 1731 } else { 1732 if (ShuffleKind == 1) // unary 1733 return isVMerge(N, UnitSize, 8, 8); 1734 else if (ShuffleKind == 0) // normal 1735 return isVMerge(N, UnitSize, 8, 24); 1736 else 1737 return false; 1738 } 1739 } 1740 1741 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1742 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1743 /// The ShuffleKind distinguishes between big-endian merges with two 1744 /// different inputs (0), either-endian merges with two identical inputs (1), 1745 /// and little-endian merges with two different inputs (2). For the latter, 1746 /// the input operands are swapped (see PPCInstrAltivec.td). 1747 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1748 unsigned ShuffleKind, SelectionDAG &DAG) { 1749 if (DAG.getDataLayout().isLittleEndian()) { 1750 if (ShuffleKind == 1) // unary 1751 return isVMerge(N, UnitSize, 8, 8); 1752 else if (ShuffleKind == 2) // swapped 1753 return isVMerge(N, UnitSize, 8, 24); 1754 else 1755 return false; 1756 } else { 1757 if (ShuffleKind == 1) // unary 1758 return isVMerge(N, UnitSize, 0, 0); 1759 else if (ShuffleKind == 0) // normal 1760 return isVMerge(N, UnitSize, 0, 16); 1761 else 1762 return false; 1763 } 1764 } 1765 1766 /** 1767 * Common function used to match vmrgew and vmrgow shuffles 1768 * 1769 * The indexOffset determines whether to look for even or odd words in 1770 * the shuffle mask. This is based on the of the endianness of the target 1771 * machine. 1772 * - Little Endian: 1773 * - Use offset of 0 to check for odd elements 1774 * - Use offset of 4 to check for even elements 1775 * - Big Endian: 1776 * - Use offset of 0 to check for even elements 1777 * - Use offset of 4 to check for odd elements 1778 * A detailed description of the vector element ordering for little endian and 1779 * big endian can be found at 1780 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1781 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1782 * compiler differences mean to you 1783 * 1784 * The mask to the shuffle vector instruction specifies the indices of the 1785 * elements from the two input vectors to place in the result. The elements are 1786 * numbered in array-access order, starting with the first vector. These vectors 1787 * are always of type v16i8, thus each vector will contain 16 elements of size 1788 * 8. More info on the shuffle vector can be found in the 1789 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1790 * Language Reference. 1791 * 1792 * The RHSStartValue indicates whether the same input vectors are used (unary) 1793 * or two different input vectors are used, based on the following: 1794 * - If the instruction uses the same vector for both inputs, the range of the 1795 * indices will be 0 to 15. In this case, the RHSStart value passed should 1796 * be 0. 1797 * - If the instruction has two different vectors then the range of the 1798 * indices will be 0 to 31. In this case, the RHSStart value passed should 1799 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1800 * to 31 specify elements in the second vector). 1801 * 1802 * \param[in] N The shuffle vector SD Node to analyze 1803 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1804 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1805 * vector to the shuffle_vector instruction 1806 * \return true iff this shuffle vector represents an even or odd word merge 1807 */ 1808 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1809 unsigned RHSStartValue) { 1810 if (N->getValueType(0) != MVT::v16i8) 1811 return false; 1812 1813 for (unsigned i = 0; i < 2; ++i) 1814 for (unsigned j = 0; j < 4; ++j) 1815 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1816 i*RHSStartValue+j+IndexOffset) || 1817 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1818 i*RHSStartValue+j+IndexOffset+8)) 1819 return false; 1820 return true; 1821 } 1822 1823 /** 1824 * Determine if the specified shuffle mask is suitable for the vmrgew or 1825 * vmrgow instructions. 1826 * 1827 * \param[in] N The shuffle vector SD Node to analyze 1828 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1829 * \param[in] ShuffleKind Identify the type of merge: 1830 * - 0 = big-endian merge with two different inputs; 1831 * - 1 = either-endian merge with two identical inputs; 1832 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1833 * little-endian merges). 1834 * \param[in] DAG The current SelectionDAG 1835 * \return true iff this shuffle mask 1836 */ 1837 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1838 unsigned ShuffleKind, SelectionDAG &DAG) { 1839 if (DAG.getDataLayout().isLittleEndian()) { 1840 unsigned indexOffset = CheckEven ? 4 : 0; 1841 if (ShuffleKind == 1) // Unary 1842 return isVMerge(N, indexOffset, 0); 1843 else if (ShuffleKind == 2) // swapped 1844 return isVMerge(N, indexOffset, 16); 1845 else 1846 return false; 1847 } 1848 else { 1849 unsigned indexOffset = CheckEven ? 0 : 4; 1850 if (ShuffleKind == 1) // Unary 1851 return isVMerge(N, indexOffset, 0); 1852 else if (ShuffleKind == 0) // Normal 1853 return isVMerge(N, indexOffset, 16); 1854 else 1855 return false; 1856 } 1857 return false; 1858 } 1859 1860 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1861 /// amount, otherwise return -1. 1862 /// The ShuffleKind distinguishes between big-endian operations with two 1863 /// different inputs (0), either-endian operations with two identical inputs 1864 /// (1), and little-endian operations with two different inputs (2). For the 1865 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1866 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1867 SelectionDAG &DAG) { 1868 if (N->getValueType(0) != MVT::v16i8) 1869 return -1; 1870 1871 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1872 1873 // Find the first non-undef value in the shuffle mask. 1874 unsigned i; 1875 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1876 /*search*/; 1877 1878 if (i == 16) return -1; // all undef. 1879 1880 // Otherwise, check to see if the rest of the elements are consecutively 1881 // numbered from this value. 1882 unsigned ShiftAmt = SVOp->getMaskElt(i); 1883 if (ShiftAmt < i) return -1; 1884 1885 ShiftAmt -= i; 1886 bool isLE = DAG.getDataLayout().isLittleEndian(); 1887 1888 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1889 // Check the rest of the elements to see if they are consecutive. 1890 for (++i; i != 16; ++i) 1891 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1892 return -1; 1893 } else if (ShuffleKind == 1) { 1894 // Check the rest of the elements to see if they are consecutive. 1895 for (++i; i != 16; ++i) 1896 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1897 return -1; 1898 } else 1899 return -1; 1900 1901 if (isLE) 1902 ShiftAmt = 16 - ShiftAmt; 1903 1904 return ShiftAmt; 1905 } 1906 1907 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1908 /// specifies a splat of a single element that is suitable for input to 1909 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1910 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1911 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1912 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1913 1914 // The consecutive indices need to specify an element, not part of two 1915 // different elements. So abandon ship early if this isn't the case. 1916 if (N->getMaskElt(0) % EltSize != 0) 1917 return false; 1918 1919 // This is a splat operation if each element of the permute is the same, and 1920 // if the value doesn't reference the second vector. 1921 unsigned ElementBase = N->getMaskElt(0); 1922 1923 // FIXME: Handle UNDEF elements too! 1924 if (ElementBase >= 16) 1925 return false; 1926 1927 // Check that the indices are consecutive, in the case of a multi-byte element 1928 // splatted with a v16i8 mask. 1929 for (unsigned i = 1; i != EltSize; ++i) 1930 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1931 return false; 1932 1933 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1934 if (N->getMaskElt(i) < 0) continue; 1935 for (unsigned j = 0; j != EltSize; ++j) 1936 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1937 return false; 1938 } 1939 return true; 1940 } 1941 1942 /// Check that the mask is shuffling N byte elements. Within each N byte 1943 /// element of the mask, the indices could be either in increasing or 1944 /// decreasing order as long as they are consecutive. 1945 /// \param[in] N the shuffle vector SD Node to analyze 1946 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1947 /// Word/DoubleWord/QuadWord). 1948 /// \param[in] StepLen the delta indices number among the N byte element, if 1949 /// the mask is in increasing/decreasing order then it is 1/-1. 1950 /// \return true iff the mask is shuffling N byte elements. 1951 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1952 int StepLen) { 1953 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1954 "Unexpected element width."); 1955 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1956 1957 unsigned NumOfElem = 16 / Width; 1958 unsigned MaskVal[16]; // Width is never greater than 16 1959 for (unsigned i = 0; i < NumOfElem; ++i) { 1960 MaskVal[0] = N->getMaskElt(i * Width); 1961 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1962 return false; 1963 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1964 return false; 1965 } 1966 1967 for (unsigned int j = 1; j < Width; ++j) { 1968 MaskVal[j] = N->getMaskElt(i * Width + j); 1969 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1970 return false; 1971 } 1972 } 1973 } 1974 1975 return true; 1976 } 1977 1978 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1979 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1980 if (!isNByteElemShuffleMask(N, 4, 1)) 1981 return false; 1982 1983 // Now we look at mask elements 0,4,8,12 1984 unsigned M0 = N->getMaskElt(0) / 4; 1985 unsigned M1 = N->getMaskElt(4) / 4; 1986 unsigned M2 = N->getMaskElt(8) / 4; 1987 unsigned M3 = N->getMaskElt(12) / 4; 1988 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1989 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1990 1991 // Below, let H and L be arbitrary elements of the shuffle mask 1992 // where H is in the range [4,7] and L is in the range [0,3]. 1993 // H, 1, 2, 3 or L, 5, 6, 7 1994 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1995 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1996 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1997 InsertAtByte = IsLE ? 12 : 0; 1998 Swap = M0 < 4; 1999 return true; 2000 } 2001 // 0, H, 2, 3 or 4, L, 6, 7 2002 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2003 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2004 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2005 InsertAtByte = IsLE ? 8 : 4; 2006 Swap = M1 < 4; 2007 return true; 2008 } 2009 // 0, 1, H, 3 or 4, 5, L, 7 2010 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2011 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2012 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2013 InsertAtByte = IsLE ? 4 : 8; 2014 Swap = M2 < 4; 2015 return true; 2016 } 2017 // 0, 1, 2, H or 4, 5, 6, L 2018 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2019 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2020 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2021 InsertAtByte = IsLE ? 0 : 12; 2022 Swap = M3 < 4; 2023 return true; 2024 } 2025 2026 // If both vector operands for the shuffle are the same vector, the mask will 2027 // contain only elements from the first one and the second one will be undef. 2028 if (N->getOperand(1).isUndef()) { 2029 ShiftElts = 0; 2030 Swap = true; 2031 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2032 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2033 InsertAtByte = IsLE ? 12 : 0; 2034 return true; 2035 } 2036 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2037 InsertAtByte = IsLE ? 8 : 4; 2038 return true; 2039 } 2040 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2041 InsertAtByte = IsLE ? 4 : 8; 2042 return true; 2043 } 2044 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2045 InsertAtByte = IsLE ? 0 : 12; 2046 return true; 2047 } 2048 } 2049 2050 return false; 2051 } 2052 2053 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2054 bool &Swap, bool IsLE) { 2055 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2056 // Ensure each byte index of the word is consecutive. 2057 if (!isNByteElemShuffleMask(N, 4, 1)) 2058 return false; 2059 2060 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2061 unsigned M0 = N->getMaskElt(0) / 4; 2062 unsigned M1 = N->getMaskElt(4) / 4; 2063 unsigned M2 = N->getMaskElt(8) / 4; 2064 unsigned M3 = N->getMaskElt(12) / 4; 2065 2066 // If both vector operands for the shuffle are the same vector, the mask will 2067 // contain only elements from the first one and the second one will be undef. 2068 if (N->getOperand(1).isUndef()) { 2069 assert(M0 < 4 && "Indexing into an undef vector?"); 2070 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2071 return false; 2072 2073 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2074 Swap = false; 2075 return true; 2076 } 2077 2078 // Ensure each word index of the ShuffleVector Mask is consecutive. 2079 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2080 return false; 2081 2082 if (IsLE) { 2083 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2084 // Input vectors don't need to be swapped if the leading element 2085 // of the result is one of the 3 left elements of the second vector 2086 // (or if there is no shift to be done at all). 2087 Swap = false; 2088 ShiftElts = (8 - M0) % 8; 2089 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2090 // Input vectors need to be swapped if the leading element 2091 // of the result is one of the 3 left elements of the first vector 2092 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2093 Swap = true; 2094 ShiftElts = (4 - M0) % 4; 2095 } 2096 2097 return true; 2098 } else { // BE 2099 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2100 // Input vectors don't need to be swapped if the leading element 2101 // of the result is one of the 4 elements of the first vector. 2102 Swap = false; 2103 ShiftElts = M0; 2104 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2105 // Input vectors need to be swapped if the leading element 2106 // of the result is one of the 4 elements of the right vector. 2107 Swap = true; 2108 ShiftElts = M0 - 4; 2109 } 2110 2111 return true; 2112 } 2113 } 2114 2115 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2116 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2117 2118 if (!isNByteElemShuffleMask(N, Width, -1)) 2119 return false; 2120 2121 for (int i = 0; i < 16; i += Width) 2122 if (N->getMaskElt(i) != i + Width - 1) 2123 return false; 2124 2125 return true; 2126 } 2127 2128 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2129 return isXXBRShuffleMaskHelper(N, 2); 2130 } 2131 2132 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2133 return isXXBRShuffleMaskHelper(N, 4); 2134 } 2135 2136 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2137 return isXXBRShuffleMaskHelper(N, 8); 2138 } 2139 2140 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2141 return isXXBRShuffleMaskHelper(N, 16); 2142 } 2143 2144 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2145 /// if the inputs to the instruction should be swapped and set \p DM to the 2146 /// value for the immediate. 2147 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2148 /// AND element 0 of the result comes from the first input (LE) or second input 2149 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2150 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2151 /// mask. 2152 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2153 bool &Swap, bool IsLE) { 2154 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2155 2156 // Ensure each byte index of the double word is consecutive. 2157 if (!isNByteElemShuffleMask(N, 8, 1)) 2158 return false; 2159 2160 unsigned M0 = N->getMaskElt(0) / 8; 2161 unsigned M1 = N->getMaskElt(8) / 8; 2162 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2163 2164 // If both vector operands for the shuffle are the same vector, the mask will 2165 // contain only elements from the first one and the second one will be undef. 2166 if (N->getOperand(1).isUndef()) { 2167 if ((M0 | M1) < 2) { 2168 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2169 Swap = false; 2170 return true; 2171 } else 2172 return false; 2173 } 2174 2175 if (IsLE) { 2176 if (M0 > 1 && M1 < 2) { 2177 Swap = false; 2178 } else if (M0 < 2 && M1 > 1) { 2179 M0 = (M0 + 2) % 4; 2180 M1 = (M1 + 2) % 4; 2181 Swap = true; 2182 } else 2183 return false; 2184 2185 // Note: if control flow comes here that means Swap is already set above 2186 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2187 return true; 2188 } else { // BE 2189 if (M0 < 2 && M1 > 1) { 2190 Swap = false; 2191 } else if (M0 > 1 && M1 < 2) { 2192 M0 = (M0 + 2) % 4; 2193 M1 = (M1 + 2) % 4; 2194 Swap = true; 2195 } else 2196 return false; 2197 2198 // Note: if control flow comes here that means Swap is already set above 2199 DM = (M0 << 1) + (M1 & 1); 2200 return true; 2201 } 2202 } 2203 2204 2205 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2206 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2207 /// elements are counted from the left of the vector register). 2208 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2209 SelectionDAG &DAG) { 2210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2211 assert(isSplatShuffleMask(SVOp, EltSize)); 2212 if (DAG.getDataLayout().isLittleEndian()) 2213 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2214 else 2215 return SVOp->getMaskElt(0) / EltSize; 2216 } 2217 2218 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2219 /// by using a vspltis[bhw] instruction of the specified element size, return 2220 /// the constant being splatted. The ByteSize field indicates the number of 2221 /// bytes of each element [124] -> [bhw]. 2222 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2223 SDValue OpVal(nullptr, 0); 2224 2225 // If ByteSize of the splat is bigger than the element size of the 2226 // build_vector, then we have a case where we are checking for a splat where 2227 // multiple elements of the buildvector are folded together into a single 2228 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2229 unsigned EltSize = 16/N->getNumOperands(); 2230 if (EltSize < ByteSize) { 2231 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2232 SDValue UniquedVals[4]; 2233 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2234 2235 // See if all of the elements in the buildvector agree across. 2236 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2237 if (N->getOperand(i).isUndef()) continue; 2238 // If the element isn't a constant, bail fully out. 2239 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2240 2241 if (!UniquedVals[i&(Multiple-1)].getNode()) 2242 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2243 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2244 return SDValue(); // no match. 2245 } 2246 2247 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2248 // either constant or undef values that are identical for each chunk. See 2249 // if these chunks can form into a larger vspltis*. 2250 2251 // Check to see if all of the leading entries are either 0 or -1. If 2252 // neither, then this won't fit into the immediate field. 2253 bool LeadingZero = true; 2254 bool LeadingOnes = true; 2255 for (unsigned i = 0; i != Multiple-1; ++i) { 2256 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2257 2258 LeadingZero &= isNullConstant(UniquedVals[i]); 2259 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2260 } 2261 // Finally, check the least significant entry. 2262 if (LeadingZero) { 2263 if (!UniquedVals[Multiple-1].getNode()) 2264 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2265 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2266 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2267 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2268 } 2269 if (LeadingOnes) { 2270 if (!UniquedVals[Multiple-1].getNode()) 2271 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2272 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2273 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2274 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2275 } 2276 2277 return SDValue(); 2278 } 2279 2280 // Check to see if this buildvec has a single non-undef value in its elements. 2281 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2282 if (N->getOperand(i).isUndef()) continue; 2283 if (!OpVal.getNode()) 2284 OpVal = N->getOperand(i); 2285 else if (OpVal != N->getOperand(i)) 2286 return SDValue(); 2287 } 2288 2289 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2290 2291 unsigned ValSizeInBytes = EltSize; 2292 uint64_t Value = 0; 2293 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2294 Value = CN->getZExtValue(); 2295 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2296 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2297 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2298 } 2299 2300 // If the splat value is larger than the element value, then we can never do 2301 // this splat. The only case that we could fit the replicated bits into our 2302 // immediate field for would be zero, and we prefer to use vxor for it. 2303 if (ValSizeInBytes < ByteSize) return SDValue(); 2304 2305 // If the element value is larger than the splat value, check if it consists 2306 // of a repeated bit pattern of size ByteSize. 2307 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2308 return SDValue(); 2309 2310 // Properly sign extend the value. 2311 int MaskVal = SignExtend32(Value, ByteSize * 8); 2312 2313 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2314 if (MaskVal == 0) return SDValue(); 2315 2316 // Finally, if this value fits in a 5 bit sext field, return it 2317 if (SignExtend32<5>(MaskVal) == MaskVal) 2318 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2319 return SDValue(); 2320 } 2321 2322 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2323 /// amount, otherwise return -1. 2324 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2325 EVT VT = N->getValueType(0); 2326 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2327 return -1; 2328 2329 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2330 2331 // Find the first non-undef value in the shuffle mask. 2332 unsigned i; 2333 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2334 /*search*/; 2335 2336 if (i == 4) return -1; // all undef. 2337 2338 // Otherwise, check to see if the rest of the elements are consecutively 2339 // numbered from this value. 2340 unsigned ShiftAmt = SVOp->getMaskElt(i); 2341 if (ShiftAmt < i) return -1; 2342 ShiftAmt -= i; 2343 2344 // Check the rest of the elements to see if they are consecutive. 2345 for (++i; i != 4; ++i) 2346 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2347 return -1; 2348 2349 return ShiftAmt; 2350 } 2351 2352 //===----------------------------------------------------------------------===// 2353 // Addressing Mode Selection 2354 //===----------------------------------------------------------------------===// 2355 2356 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2357 /// or 64-bit immediate, and if the value can be accurately represented as a 2358 /// sign extension from a 16-bit value. If so, this returns true and the 2359 /// immediate. 2360 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2361 if (!isa<ConstantSDNode>(N)) 2362 return false; 2363 2364 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2365 if (N->getValueType(0) == MVT::i32) 2366 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2367 else 2368 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2369 } 2370 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2371 return isIntS16Immediate(Op.getNode(), Imm); 2372 } 2373 2374 2375 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2376 /// be represented as an indexed [r+r] operation. 2377 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2378 SDValue &Index, 2379 SelectionDAG &DAG) const { 2380 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2381 UI != E; ++UI) { 2382 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2383 if (Memop->getMemoryVT() == MVT::f64) { 2384 Base = N.getOperand(0); 2385 Index = N.getOperand(1); 2386 return true; 2387 } 2388 } 2389 } 2390 return false; 2391 } 2392 2393 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2394 /// can be represented as an indexed [r+r] operation. Returns false if it 2395 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2396 /// non-zero and N can be represented by a base register plus a signed 16-bit 2397 /// displacement, make a more precise judgement by checking (displacement % \p 2398 /// EncodingAlignment). 2399 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2400 SDValue &Index, SelectionDAG &DAG, 2401 unsigned EncodingAlignment) const { 2402 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2403 // a [pc+imm]. 2404 if (SelectAddressPCRel(N, Base)) 2405 return false; 2406 2407 int16_t imm = 0; 2408 if (N.getOpcode() == ISD::ADD) { 2409 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2410 // SPE load/store can only handle 8-bit offsets. 2411 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2412 return true; 2413 if (isIntS16Immediate(N.getOperand(1), imm) && 2414 (!EncodingAlignment || !(imm % EncodingAlignment))) 2415 return false; // r+i 2416 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2417 return false; // r+i 2418 2419 Base = N.getOperand(0); 2420 Index = N.getOperand(1); 2421 return true; 2422 } else if (N.getOpcode() == ISD::OR) { 2423 if (isIntS16Immediate(N.getOperand(1), imm) && 2424 (!EncodingAlignment || !(imm % EncodingAlignment))) 2425 return false; // r+i can fold it if we can. 2426 2427 // If this is an or of disjoint bitfields, we can codegen this as an add 2428 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2429 // disjoint. 2430 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2431 2432 if (LHSKnown.Zero.getBoolValue()) { 2433 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2434 // If all of the bits are known zero on the LHS or RHS, the add won't 2435 // carry. 2436 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2437 Base = N.getOperand(0); 2438 Index = N.getOperand(1); 2439 return true; 2440 } 2441 } 2442 } 2443 2444 return false; 2445 } 2446 2447 // If we happen to be doing an i64 load or store into a stack slot that has 2448 // less than a 4-byte alignment, then the frame-index elimination may need to 2449 // use an indexed load or store instruction (because the offset may not be a 2450 // multiple of 4). The extra register needed to hold the offset comes from the 2451 // register scavenger, and it is possible that the scavenger will need to use 2452 // an emergency spill slot. As a result, we need to make sure that a spill slot 2453 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2454 // stack slot. 2455 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2456 // FIXME: This does not handle the LWA case. 2457 if (VT != MVT::i64) 2458 return; 2459 2460 // NOTE: We'll exclude negative FIs here, which come from argument 2461 // lowering, because there are no known test cases triggering this problem 2462 // using packed structures (or similar). We can remove this exclusion if 2463 // we find such a test case. The reason why this is so test-case driven is 2464 // because this entire 'fixup' is only to prevent crashes (from the 2465 // register scavenger) on not-really-valid inputs. For example, if we have: 2466 // %a = alloca i1 2467 // %b = bitcast i1* %a to i64* 2468 // store i64* a, i64 b 2469 // then the store should really be marked as 'align 1', but is not. If it 2470 // were marked as 'align 1' then the indexed form would have been 2471 // instruction-selected initially, and the problem this 'fixup' is preventing 2472 // won't happen regardless. 2473 if (FrameIdx < 0) 2474 return; 2475 2476 MachineFunction &MF = DAG.getMachineFunction(); 2477 MachineFrameInfo &MFI = MF.getFrameInfo(); 2478 2479 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2480 return; 2481 2482 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2483 FuncInfo->setHasNonRISpills(); 2484 } 2485 2486 /// Returns true if the address N can be represented by a base register plus 2487 /// a signed 16-bit displacement [r+imm], and if it is not better 2488 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2489 /// displacements that are multiples of that value. 2490 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2491 SDValue &Base, 2492 SelectionDAG &DAG, 2493 unsigned EncodingAlignment) const { 2494 // FIXME dl should come from parent load or store, not from address 2495 SDLoc dl(N); 2496 2497 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2498 // a [pc+imm]. 2499 if (SelectAddressPCRel(N, Base)) 2500 return false; 2501 2502 // If this can be more profitably realized as r+r, fail. 2503 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2504 return false; 2505 2506 if (N.getOpcode() == ISD::ADD) { 2507 int16_t imm = 0; 2508 if (isIntS16Immediate(N.getOperand(1), imm) && 2509 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2510 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2511 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2512 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2513 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2514 } else { 2515 Base = N.getOperand(0); 2516 } 2517 return true; // [r+i] 2518 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2519 // Match LOAD (ADD (X, Lo(G))). 2520 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2521 && "Cannot handle constant offsets yet!"); 2522 Disp = N.getOperand(1).getOperand(0); // The global address. 2523 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2524 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2525 Disp.getOpcode() == ISD::TargetConstantPool || 2526 Disp.getOpcode() == ISD::TargetJumpTable); 2527 Base = N.getOperand(0); 2528 return true; // [&g+r] 2529 } 2530 } else if (N.getOpcode() == ISD::OR) { 2531 int16_t imm = 0; 2532 if (isIntS16Immediate(N.getOperand(1), imm) && 2533 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2534 // If this is an or of disjoint bitfields, we can codegen this as an add 2535 // (for better address arithmetic) if the LHS and RHS of the OR are 2536 // provably disjoint. 2537 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2538 2539 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2540 // If all of the bits are known zero on the LHS or RHS, the add won't 2541 // carry. 2542 if (FrameIndexSDNode *FI = 2543 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2544 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2545 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2546 } else { 2547 Base = N.getOperand(0); 2548 } 2549 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2550 return true; 2551 } 2552 } 2553 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2554 // Loading from a constant address. 2555 2556 // If this address fits entirely in a 16-bit sext immediate field, codegen 2557 // this as "d, 0" 2558 int16_t Imm; 2559 if (isIntS16Immediate(CN, Imm) && 2560 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2561 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2562 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2563 CN->getValueType(0)); 2564 return true; 2565 } 2566 2567 // Handle 32-bit sext immediates with LIS + addr mode. 2568 if ((CN->getValueType(0) == MVT::i32 || 2569 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2570 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2571 int Addr = (int)CN->getZExtValue(); 2572 2573 // Otherwise, break this down into an LIS + disp. 2574 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2575 2576 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2577 MVT::i32); 2578 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2579 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2580 return true; 2581 } 2582 } 2583 2584 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2585 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2586 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2587 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2588 } else 2589 Base = N; 2590 return true; // [r+0] 2591 } 2592 2593 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2594 /// represented as an indexed [r+r] operation. 2595 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2596 SDValue &Index, 2597 SelectionDAG &DAG) const { 2598 // Check to see if we can easily represent this as an [r+r] address. This 2599 // will fail if it thinks that the address is more profitably represented as 2600 // reg+imm, e.g. where imm = 0. 2601 if (SelectAddressRegReg(N, Base, Index, DAG)) 2602 return true; 2603 2604 // If the address is the result of an add, we will utilize the fact that the 2605 // address calculation includes an implicit add. However, we can reduce 2606 // register pressure if we do not materialize a constant just for use as the 2607 // index register. We only get rid of the add if it is not an add of a 2608 // value and a 16-bit signed constant and both have a single use. 2609 int16_t imm = 0; 2610 if (N.getOpcode() == ISD::ADD && 2611 (!isIntS16Immediate(N.getOperand(1), imm) || 2612 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2613 Base = N.getOperand(0); 2614 Index = N.getOperand(1); 2615 return true; 2616 } 2617 2618 // Otherwise, do it the hard way, using R0 as the base register. 2619 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2620 N.getValueType()); 2621 Index = N; 2622 return true; 2623 } 2624 2625 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2626 Ty *PCRelCand = dyn_cast<Ty>(N); 2627 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2628 } 2629 2630 /// Returns true if this address is a PC Relative address. 2631 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2632 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2633 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2634 // This is a materialize PC Relative node. Always select this as PC Relative. 2635 Base = N; 2636 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2637 return true; 2638 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2639 isValidPCRelNode<GlobalAddressSDNode>(N) || 2640 isValidPCRelNode<JumpTableSDNode>(N) || 2641 isValidPCRelNode<BlockAddressSDNode>(N)) 2642 return true; 2643 return false; 2644 } 2645 2646 /// Returns true if we should use a direct load into vector instruction 2647 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2648 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2649 2650 // If there are any other uses other than scalar to vector, then we should 2651 // keep it as a scalar load -> direct move pattern to prevent multiple 2652 // loads. 2653 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2654 if (!LD) 2655 return false; 2656 2657 EVT MemVT = LD->getMemoryVT(); 2658 if (!MemVT.isSimple()) 2659 return false; 2660 switch(MemVT.getSimpleVT().SimpleTy) { 2661 case MVT::i64: 2662 break; 2663 case MVT::i32: 2664 if (!ST.hasP8Vector()) 2665 return false; 2666 break; 2667 case MVT::i16: 2668 case MVT::i8: 2669 if (!ST.hasP9Vector()) 2670 return false; 2671 break; 2672 default: 2673 return false; 2674 } 2675 2676 SDValue LoadedVal(N, 0); 2677 if (!LoadedVal.hasOneUse()) 2678 return false; 2679 2680 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2681 UI != UE; ++UI) 2682 if (UI.getUse().get().getResNo() == 0 && 2683 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2684 return false; 2685 2686 return true; 2687 } 2688 2689 /// getPreIndexedAddressParts - returns true by value, base pointer and 2690 /// offset pointer and addressing mode by reference if the node's address 2691 /// can be legally represented as pre-indexed load / store address. 2692 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2693 SDValue &Offset, 2694 ISD::MemIndexedMode &AM, 2695 SelectionDAG &DAG) const { 2696 if (DisablePPCPreinc) return false; 2697 2698 bool isLoad = true; 2699 SDValue Ptr; 2700 EVT VT; 2701 unsigned Alignment; 2702 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2703 Ptr = LD->getBasePtr(); 2704 VT = LD->getMemoryVT(); 2705 Alignment = LD->getAlignment(); 2706 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2707 Ptr = ST->getBasePtr(); 2708 VT = ST->getMemoryVT(); 2709 Alignment = ST->getAlignment(); 2710 isLoad = false; 2711 } else 2712 return false; 2713 2714 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2715 // instructions because we can fold these into a more efficient instruction 2716 // instead, (such as LXSD). 2717 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2718 return false; 2719 } 2720 2721 // PowerPC doesn't have preinc load/store instructions for vectors (except 2722 // for QPX, which does have preinc r+r forms). 2723 if (VT.isVector()) { 2724 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2725 return false; 2726 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2727 AM = ISD::PRE_INC; 2728 return true; 2729 } 2730 } 2731 2732 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2733 // Common code will reject creating a pre-inc form if the base pointer 2734 // is a frame index, or if N is a store and the base pointer is either 2735 // the same as or a predecessor of the value being stored. Check for 2736 // those situations here, and try with swapped Base/Offset instead. 2737 bool Swap = false; 2738 2739 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2740 Swap = true; 2741 else if (!isLoad) { 2742 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2743 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2744 Swap = true; 2745 } 2746 2747 if (Swap) 2748 std::swap(Base, Offset); 2749 2750 AM = ISD::PRE_INC; 2751 return true; 2752 } 2753 2754 // LDU/STU can only handle immediates that are a multiple of 4. 2755 if (VT != MVT::i64) { 2756 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2757 return false; 2758 } else { 2759 // LDU/STU need an address with at least 4-byte alignment. 2760 if (Alignment < 4) 2761 return false; 2762 2763 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2764 return false; 2765 } 2766 2767 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2768 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2769 // sext i32 to i64 when addr mode is r+i. 2770 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2771 LD->getExtensionType() == ISD::SEXTLOAD && 2772 isa<ConstantSDNode>(Offset)) 2773 return false; 2774 } 2775 2776 AM = ISD::PRE_INC; 2777 return true; 2778 } 2779 2780 //===----------------------------------------------------------------------===// 2781 // LowerOperation implementation 2782 //===----------------------------------------------------------------------===// 2783 2784 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2785 /// and LoOpFlags to the target MO flags. 2786 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2787 unsigned &HiOpFlags, unsigned &LoOpFlags, 2788 const GlobalValue *GV = nullptr) { 2789 HiOpFlags = PPCII::MO_HA; 2790 LoOpFlags = PPCII::MO_LO; 2791 2792 // Don't use the pic base if not in PIC relocation model. 2793 if (IsPIC) { 2794 HiOpFlags |= PPCII::MO_PIC_FLAG; 2795 LoOpFlags |= PPCII::MO_PIC_FLAG; 2796 } 2797 } 2798 2799 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2800 SelectionDAG &DAG) { 2801 SDLoc DL(HiPart); 2802 EVT PtrVT = HiPart.getValueType(); 2803 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2804 2805 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2806 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2807 2808 // With PIC, the first instruction is actually "GR+hi(&G)". 2809 if (isPIC) 2810 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2811 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2812 2813 // Generate non-pic code that has direct accesses to the constant pool. 2814 // The address of the global is just (hi(&g)+lo(&g)). 2815 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2816 } 2817 2818 static void setUsesTOCBasePtr(MachineFunction &MF) { 2819 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2820 FuncInfo->setUsesTOCBasePtr(); 2821 } 2822 2823 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2824 setUsesTOCBasePtr(DAG.getMachineFunction()); 2825 } 2826 2827 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2828 SDValue GA) const { 2829 const bool Is64Bit = Subtarget.isPPC64(); 2830 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2831 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2832 : Subtarget.isAIXABI() 2833 ? DAG.getRegister(PPC::R2, VT) 2834 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2835 SDValue Ops[] = { GA, Reg }; 2836 return DAG.getMemIntrinsicNode( 2837 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2838 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2839 MachineMemOperand::MOLoad); 2840 } 2841 2842 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2843 SelectionDAG &DAG) const { 2844 EVT PtrVT = Op.getValueType(); 2845 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2846 const Constant *C = CP->getConstVal(); 2847 2848 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2849 // The actual address of the GlobalValue is stored in the TOC. 2850 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2851 if (Subtarget.isUsingPCRelativeCalls()) { 2852 SDLoc DL(CP); 2853 EVT Ty = getPointerTy(DAG.getDataLayout()); 2854 SDValue ConstPool = DAG.getTargetConstantPool( 2855 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2856 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2857 } 2858 setUsesTOCBasePtr(DAG); 2859 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2860 return getTOCEntry(DAG, SDLoc(CP), GA); 2861 } 2862 2863 unsigned MOHiFlag, MOLoFlag; 2864 bool IsPIC = isPositionIndependent(); 2865 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2866 2867 if (IsPIC && Subtarget.isSVR4ABI()) { 2868 SDValue GA = 2869 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2870 return getTOCEntry(DAG, SDLoc(CP), GA); 2871 } 2872 2873 SDValue CPIHi = 2874 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2875 SDValue CPILo = 2876 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2877 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2878 } 2879 2880 // For 64-bit PowerPC, prefer the more compact relative encodings. 2881 // This trades 32 bits per jump table entry for one or two instructions 2882 // on the jump site. 2883 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2884 if (isJumpTableRelative()) 2885 return MachineJumpTableInfo::EK_LabelDifference32; 2886 2887 return TargetLowering::getJumpTableEncoding(); 2888 } 2889 2890 bool PPCTargetLowering::isJumpTableRelative() const { 2891 if (UseAbsoluteJumpTables) 2892 return false; 2893 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2894 return true; 2895 return TargetLowering::isJumpTableRelative(); 2896 } 2897 2898 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2899 SelectionDAG &DAG) const { 2900 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2901 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2902 2903 switch (getTargetMachine().getCodeModel()) { 2904 case CodeModel::Small: 2905 case CodeModel::Medium: 2906 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2907 default: 2908 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2909 getPointerTy(DAG.getDataLayout())); 2910 } 2911 } 2912 2913 const MCExpr * 2914 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2915 unsigned JTI, 2916 MCContext &Ctx) const { 2917 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2918 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2919 2920 switch (getTargetMachine().getCodeModel()) { 2921 case CodeModel::Small: 2922 case CodeModel::Medium: 2923 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2924 default: 2925 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2926 } 2927 } 2928 2929 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2930 EVT PtrVT = Op.getValueType(); 2931 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2932 2933 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2934 if (Subtarget.isUsingPCRelativeCalls()) { 2935 SDLoc DL(JT); 2936 EVT Ty = getPointerTy(DAG.getDataLayout()); 2937 SDValue GA = 2938 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2939 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2940 return MatAddr; 2941 } 2942 2943 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2944 // The actual address of the GlobalValue is stored in the TOC. 2945 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2946 setUsesTOCBasePtr(DAG); 2947 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2948 return getTOCEntry(DAG, SDLoc(JT), GA); 2949 } 2950 2951 unsigned MOHiFlag, MOLoFlag; 2952 bool IsPIC = isPositionIndependent(); 2953 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2954 2955 if (IsPIC && Subtarget.isSVR4ABI()) { 2956 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2957 PPCII::MO_PIC_FLAG); 2958 return getTOCEntry(DAG, SDLoc(GA), GA); 2959 } 2960 2961 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2962 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2963 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2964 } 2965 2966 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2967 SelectionDAG &DAG) const { 2968 EVT PtrVT = Op.getValueType(); 2969 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2970 const BlockAddress *BA = BASDN->getBlockAddress(); 2971 2972 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2973 if (Subtarget.isUsingPCRelativeCalls()) { 2974 SDLoc DL(BASDN); 2975 EVT Ty = getPointerTy(DAG.getDataLayout()); 2976 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2977 PPCII::MO_PCREL_FLAG); 2978 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2979 return MatAddr; 2980 } 2981 2982 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2983 // The actual BlockAddress is stored in the TOC. 2984 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2985 setUsesTOCBasePtr(DAG); 2986 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2987 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2988 } 2989 2990 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2991 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2992 return getTOCEntry( 2993 DAG, SDLoc(BASDN), 2994 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2995 2996 unsigned MOHiFlag, MOLoFlag; 2997 bool IsPIC = isPositionIndependent(); 2998 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2999 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3000 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3001 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3002 } 3003 3004 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3005 SelectionDAG &DAG) const { 3006 // FIXME: TLS addresses currently use medium model code sequences, 3007 // which is the most useful form. Eventually support for small and 3008 // large models could be added if users need it, at the cost of 3009 // additional complexity. 3010 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3011 if (DAG.getTarget().useEmulatedTLS()) 3012 return LowerToTLSEmulatedModel(GA, DAG); 3013 3014 SDLoc dl(GA); 3015 const GlobalValue *GV = GA->getGlobal(); 3016 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3017 bool is64bit = Subtarget.isPPC64(); 3018 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3019 PICLevel::Level picLevel = M->getPICLevel(); 3020 3021 const TargetMachine &TM = getTargetMachine(); 3022 TLSModel::Model Model = TM.getTLSModel(GV); 3023 3024 if (Model == TLSModel::LocalExec) { 3025 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3026 PPCII::MO_TPREL_HA); 3027 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3028 PPCII::MO_TPREL_LO); 3029 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3030 : DAG.getRegister(PPC::R2, MVT::i32); 3031 3032 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3033 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3034 } 3035 3036 if (Model == TLSModel::InitialExec) { 3037 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3038 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3039 PPCII::MO_TLS); 3040 SDValue GOTPtr; 3041 if (is64bit) { 3042 setUsesTOCBasePtr(DAG); 3043 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3044 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3045 PtrVT, GOTReg, TGA); 3046 } else { 3047 if (!TM.isPositionIndependent()) 3048 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3049 else if (picLevel == PICLevel::SmallPIC) 3050 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3051 else 3052 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3053 } 3054 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3055 PtrVT, TGA, GOTPtr); 3056 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3057 } 3058 3059 if (Model == TLSModel::GeneralDynamic) { 3060 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3061 SDValue GOTPtr; 3062 if (is64bit) { 3063 setUsesTOCBasePtr(DAG); 3064 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3065 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3066 GOTReg, TGA); 3067 } else { 3068 if (picLevel == PICLevel::SmallPIC) 3069 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3070 else 3071 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3072 } 3073 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3074 GOTPtr, TGA, TGA); 3075 } 3076 3077 if (Model == TLSModel::LocalDynamic) { 3078 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3079 SDValue GOTPtr; 3080 if (is64bit) { 3081 setUsesTOCBasePtr(DAG); 3082 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3083 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3084 GOTReg, TGA); 3085 } else { 3086 if (picLevel == PICLevel::SmallPIC) 3087 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3088 else 3089 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3090 } 3091 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3092 PtrVT, GOTPtr, TGA, TGA); 3093 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3094 PtrVT, TLSAddr, TGA); 3095 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3096 } 3097 3098 llvm_unreachable("Unknown TLS model!"); 3099 } 3100 3101 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3102 SelectionDAG &DAG) const { 3103 EVT PtrVT = Op.getValueType(); 3104 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3105 SDLoc DL(GSDN); 3106 const GlobalValue *GV = GSDN->getGlobal(); 3107 3108 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3109 // The actual address of the GlobalValue is stored in the TOC. 3110 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3111 if (Subtarget.isUsingPCRelativeCalls()) { 3112 EVT Ty = getPointerTy(DAG.getDataLayout()); 3113 if (isAccessedAsGotIndirect(Op)) { 3114 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3115 PPCII::MO_PCREL_FLAG | 3116 PPCII::MO_GOT_FLAG); 3117 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3118 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3119 MachinePointerInfo()); 3120 return Load; 3121 } else { 3122 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3123 PPCII::MO_PCREL_FLAG); 3124 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3125 } 3126 } 3127 setUsesTOCBasePtr(DAG); 3128 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3129 return getTOCEntry(DAG, DL, GA); 3130 } 3131 3132 unsigned MOHiFlag, MOLoFlag; 3133 bool IsPIC = isPositionIndependent(); 3134 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3135 3136 if (IsPIC && Subtarget.isSVR4ABI()) { 3137 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3138 GSDN->getOffset(), 3139 PPCII::MO_PIC_FLAG); 3140 return getTOCEntry(DAG, DL, GA); 3141 } 3142 3143 SDValue GAHi = 3144 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3145 SDValue GALo = 3146 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3147 3148 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3149 } 3150 3151 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3152 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3153 SDLoc dl(Op); 3154 3155 if (Op.getValueType() == MVT::v2i64) { 3156 // When the operands themselves are v2i64 values, we need to do something 3157 // special because VSX has no underlying comparison operations for these. 3158 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3159 // Equality can be handled by casting to the legal type for Altivec 3160 // comparisons, everything else needs to be expanded. 3161 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3162 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3163 DAG.getSetCC(dl, MVT::v4i32, 3164 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3165 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3166 CC)); 3167 } 3168 3169 return SDValue(); 3170 } 3171 3172 // We handle most of these in the usual way. 3173 return Op; 3174 } 3175 3176 // If we're comparing for equality to zero, expose the fact that this is 3177 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3178 // fold the new nodes. 3179 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3180 return V; 3181 3182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3183 // Leave comparisons against 0 and -1 alone for now, since they're usually 3184 // optimized. FIXME: revisit this when we can custom lower all setcc 3185 // optimizations. 3186 if (C->isAllOnesValue() || C->isNullValue()) 3187 return SDValue(); 3188 } 3189 3190 // If we have an integer seteq/setne, turn it into a compare against zero 3191 // by xor'ing the rhs with the lhs, which is faster than setting a 3192 // condition register, reading it back out, and masking the correct bit. The 3193 // normal approach here uses sub to do this instead of xor. Using xor exposes 3194 // the result to other bit-twiddling opportunities. 3195 EVT LHSVT = Op.getOperand(0).getValueType(); 3196 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3197 EVT VT = Op.getValueType(); 3198 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3199 Op.getOperand(1)); 3200 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3201 } 3202 return SDValue(); 3203 } 3204 3205 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3206 SDNode *Node = Op.getNode(); 3207 EVT VT = Node->getValueType(0); 3208 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3209 SDValue InChain = Node->getOperand(0); 3210 SDValue VAListPtr = Node->getOperand(1); 3211 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3212 SDLoc dl(Node); 3213 3214 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3215 3216 // gpr_index 3217 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3218 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3219 InChain = GprIndex.getValue(1); 3220 3221 if (VT == MVT::i64) { 3222 // Check if GprIndex is even 3223 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3224 DAG.getConstant(1, dl, MVT::i32)); 3225 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3226 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3227 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3228 DAG.getConstant(1, dl, MVT::i32)); 3229 // Align GprIndex to be even if it isn't 3230 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3231 GprIndex); 3232 } 3233 3234 // fpr index is 1 byte after gpr 3235 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3236 DAG.getConstant(1, dl, MVT::i32)); 3237 3238 // fpr 3239 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3240 FprPtr, MachinePointerInfo(SV), MVT::i8); 3241 InChain = FprIndex.getValue(1); 3242 3243 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3244 DAG.getConstant(8, dl, MVT::i32)); 3245 3246 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3247 DAG.getConstant(4, dl, MVT::i32)); 3248 3249 // areas 3250 SDValue OverflowArea = 3251 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3252 InChain = OverflowArea.getValue(1); 3253 3254 SDValue RegSaveArea = 3255 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3256 InChain = RegSaveArea.getValue(1); 3257 3258 // select overflow_area if index > 8 3259 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3260 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3261 3262 // adjustment constant gpr_index * 4/8 3263 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3264 VT.isInteger() ? GprIndex : FprIndex, 3265 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3266 MVT::i32)); 3267 3268 // OurReg = RegSaveArea + RegConstant 3269 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3270 RegConstant); 3271 3272 // Floating types are 32 bytes into RegSaveArea 3273 if (VT.isFloatingPoint()) 3274 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3275 DAG.getConstant(32, dl, MVT::i32)); 3276 3277 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3278 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3279 VT.isInteger() ? GprIndex : FprIndex, 3280 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3281 MVT::i32)); 3282 3283 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3284 VT.isInteger() ? VAListPtr : FprPtr, 3285 MachinePointerInfo(SV), MVT::i8); 3286 3287 // determine if we should load from reg_save_area or overflow_area 3288 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3289 3290 // increase overflow_area by 4/8 if gpr/fpr > 8 3291 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3292 DAG.getConstant(VT.isInteger() ? 4 : 8, 3293 dl, MVT::i32)); 3294 3295 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3296 OverflowAreaPlusN); 3297 3298 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3299 MachinePointerInfo(), MVT::i32); 3300 3301 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3302 } 3303 3304 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3305 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3306 3307 // We have to copy the entire va_list struct: 3308 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3309 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3310 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3311 false, true, false, MachinePointerInfo(), 3312 MachinePointerInfo()); 3313 } 3314 3315 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3316 SelectionDAG &DAG) const { 3317 if (Subtarget.isAIXABI()) 3318 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3319 3320 return Op.getOperand(0); 3321 } 3322 3323 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3324 SelectionDAG &DAG) const { 3325 if (Subtarget.isAIXABI()) 3326 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3327 3328 SDValue Chain = Op.getOperand(0); 3329 SDValue Trmp = Op.getOperand(1); // trampoline 3330 SDValue FPtr = Op.getOperand(2); // nested function 3331 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3332 SDLoc dl(Op); 3333 3334 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3335 bool isPPC64 = (PtrVT == MVT::i64); 3336 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3337 3338 TargetLowering::ArgListTy Args; 3339 TargetLowering::ArgListEntry Entry; 3340 3341 Entry.Ty = IntPtrTy; 3342 Entry.Node = Trmp; Args.push_back(Entry); 3343 3344 // TrampSize == (isPPC64 ? 48 : 40); 3345 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3346 isPPC64 ? MVT::i64 : MVT::i32); 3347 Args.push_back(Entry); 3348 3349 Entry.Node = FPtr; Args.push_back(Entry); 3350 Entry.Node = Nest; Args.push_back(Entry); 3351 3352 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3353 TargetLowering::CallLoweringInfo CLI(DAG); 3354 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3355 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3356 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3357 3358 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3359 return CallResult.second; 3360 } 3361 3362 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3363 MachineFunction &MF = DAG.getMachineFunction(); 3364 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3365 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3366 3367 SDLoc dl(Op); 3368 3369 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3370 // vastart just stores the address of the VarArgsFrameIndex slot into the 3371 // memory location argument. 3372 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3373 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3374 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3375 MachinePointerInfo(SV)); 3376 } 3377 3378 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3379 // We suppose the given va_list is already allocated. 3380 // 3381 // typedef struct { 3382 // char gpr; /* index into the array of 8 GPRs 3383 // * stored in the register save area 3384 // * gpr=0 corresponds to r3, 3385 // * gpr=1 to r4, etc. 3386 // */ 3387 // char fpr; /* index into the array of 8 FPRs 3388 // * stored in the register save area 3389 // * fpr=0 corresponds to f1, 3390 // * fpr=1 to f2, etc. 3391 // */ 3392 // char *overflow_arg_area; 3393 // /* location on stack that holds 3394 // * the next overflow argument 3395 // */ 3396 // char *reg_save_area; 3397 // /* where r3:r10 and f1:f8 (if saved) 3398 // * are stored 3399 // */ 3400 // } va_list[1]; 3401 3402 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3403 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3404 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3405 PtrVT); 3406 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3407 PtrVT); 3408 3409 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3410 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3411 3412 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3413 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3414 3415 uint64_t FPROffset = 1; 3416 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3417 3418 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3419 3420 // Store first byte : number of int regs 3421 SDValue firstStore = 3422 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3423 MachinePointerInfo(SV), MVT::i8); 3424 uint64_t nextOffset = FPROffset; 3425 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3426 ConstFPROffset); 3427 3428 // Store second byte : number of float regs 3429 SDValue secondStore = 3430 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3431 MachinePointerInfo(SV, nextOffset), MVT::i8); 3432 nextOffset += StackOffset; 3433 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3434 3435 // Store second word : arguments given on stack 3436 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3437 MachinePointerInfo(SV, nextOffset)); 3438 nextOffset += FrameOffset; 3439 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3440 3441 // Store third word : arguments given in registers 3442 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3443 MachinePointerInfo(SV, nextOffset)); 3444 } 3445 3446 /// FPR - The set of FP registers that should be allocated for arguments 3447 /// on Darwin and AIX. 3448 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3449 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3450 PPC::F11, PPC::F12, PPC::F13}; 3451 3452 /// QFPR - The set of QPX registers that should be allocated for arguments. 3453 static const MCPhysReg QFPR[] = { 3454 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3455 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3456 3457 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3458 /// the stack. 3459 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3460 unsigned PtrByteSize) { 3461 unsigned ArgSize = ArgVT.getStoreSize(); 3462 if (Flags.isByVal()) 3463 ArgSize = Flags.getByValSize(); 3464 3465 // Round up to multiples of the pointer size, except for array members, 3466 // which are always packed. 3467 if (!Flags.isInConsecutiveRegs()) 3468 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3469 3470 return ArgSize; 3471 } 3472 3473 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3474 /// on the stack. 3475 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3476 ISD::ArgFlagsTy Flags, 3477 unsigned PtrByteSize) { 3478 Align Alignment(PtrByteSize); 3479 3480 // Altivec parameters are padded to a 16 byte boundary. 3481 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3482 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3483 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3484 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3485 Alignment = Align(16); 3486 // QPX vector types stored in double-precision are padded to a 32 byte 3487 // boundary. 3488 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3489 Alignment = Align(32); 3490 3491 // ByVal parameters are aligned as requested. 3492 if (Flags.isByVal()) { 3493 auto BVAlign = Flags.getNonZeroByValAlign(); 3494 if (BVAlign > PtrByteSize) { 3495 if (BVAlign.value() % PtrByteSize != 0) 3496 llvm_unreachable( 3497 "ByVal alignment is not a multiple of the pointer size"); 3498 3499 Alignment = BVAlign; 3500 } 3501 } 3502 3503 // Array members are always packed to their original alignment. 3504 if (Flags.isInConsecutiveRegs()) { 3505 // If the array member was split into multiple registers, the first 3506 // needs to be aligned to the size of the full type. (Except for 3507 // ppcf128, which is only aligned as its f64 components.) 3508 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3509 Alignment = Align(OrigVT.getStoreSize()); 3510 else 3511 Alignment = Align(ArgVT.getStoreSize()); 3512 } 3513 3514 return Alignment; 3515 } 3516 3517 /// CalculateStackSlotUsed - Return whether this argument will use its 3518 /// stack slot (instead of being passed in registers). ArgOffset, 3519 /// AvailableFPRs, and AvailableVRs must hold the current argument 3520 /// position, and will be updated to account for this argument. 3521 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3522 ISD::ArgFlagsTy Flags, 3523 unsigned PtrByteSize, 3524 unsigned LinkageSize, 3525 unsigned ParamAreaSize, 3526 unsigned &ArgOffset, 3527 unsigned &AvailableFPRs, 3528 unsigned &AvailableVRs, bool HasQPX) { 3529 bool UseMemory = false; 3530 3531 // Respect alignment of argument on the stack. 3532 Align Alignment = 3533 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3534 ArgOffset = alignTo(ArgOffset, Alignment); 3535 // If there's no space left in the argument save area, we must 3536 // use memory (this check also catches zero-sized arguments). 3537 if (ArgOffset >= LinkageSize + ParamAreaSize) 3538 UseMemory = true; 3539 3540 // Allocate argument on the stack. 3541 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3542 if (Flags.isInConsecutiveRegsLast()) 3543 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3544 // If we overran the argument save area, we must use memory 3545 // (this check catches arguments passed partially in memory) 3546 if (ArgOffset > LinkageSize + ParamAreaSize) 3547 UseMemory = true; 3548 3549 // However, if the argument is actually passed in an FPR or a VR, 3550 // we don't use memory after all. 3551 if (!Flags.isByVal()) { 3552 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3553 // QPX registers overlap with the scalar FP registers. 3554 (HasQPX && (ArgVT == MVT::v4f32 || 3555 ArgVT == MVT::v4f64 || 3556 ArgVT == MVT::v4i1))) 3557 if (AvailableFPRs > 0) { 3558 --AvailableFPRs; 3559 return false; 3560 } 3561 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3562 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3563 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3564 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3565 if (AvailableVRs > 0) { 3566 --AvailableVRs; 3567 return false; 3568 } 3569 } 3570 3571 return UseMemory; 3572 } 3573 3574 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3575 /// ensure minimum alignment required for target. 3576 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3577 unsigned NumBytes) { 3578 return alignTo(NumBytes, Lowering->getStackAlign()); 3579 } 3580 3581 SDValue PPCTargetLowering::LowerFormalArguments( 3582 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3583 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3584 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3585 if (Subtarget.isAIXABI()) 3586 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3587 InVals); 3588 if (Subtarget.is64BitELFABI()) 3589 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3590 InVals); 3591 if (Subtarget.is32BitELFABI()) 3592 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3593 InVals); 3594 3595 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3596 InVals); 3597 } 3598 3599 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3600 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3601 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3602 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3603 3604 // 32-bit SVR4 ABI Stack Frame Layout: 3605 // +-----------------------------------+ 3606 // +--> | Back chain | 3607 // | +-----------------------------------+ 3608 // | | Floating-point register save area | 3609 // | +-----------------------------------+ 3610 // | | General register save area | 3611 // | +-----------------------------------+ 3612 // | | CR save word | 3613 // | +-----------------------------------+ 3614 // | | VRSAVE save word | 3615 // | +-----------------------------------+ 3616 // | | Alignment padding | 3617 // | +-----------------------------------+ 3618 // | | Vector register save area | 3619 // | +-----------------------------------+ 3620 // | | Local variable space | 3621 // | +-----------------------------------+ 3622 // | | Parameter list area | 3623 // | +-----------------------------------+ 3624 // | | LR save word | 3625 // | +-----------------------------------+ 3626 // SP--> +--- | Back chain | 3627 // +-----------------------------------+ 3628 // 3629 // Specifications: 3630 // System V Application Binary Interface PowerPC Processor Supplement 3631 // AltiVec Technology Programming Interface Manual 3632 3633 MachineFunction &MF = DAG.getMachineFunction(); 3634 MachineFrameInfo &MFI = MF.getFrameInfo(); 3635 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3636 3637 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3638 // Potential tail calls could cause overwriting of argument stack slots. 3639 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3640 (CallConv == CallingConv::Fast)); 3641 unsigned PtrByteSize = 4; 3642 3643 // Assign locations to all of the incoming arguments. 3644 SmallVector<CCValAssign, 16> ArgLocs; 3645 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3646 *DAG.getContext()); 3647 3648 // Reserve space for the linkage area on the stack. 3649 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3650 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3651 if (useSoftFloat()) 3652 CCInfo.PreAnalyzeFormalArguments(Ins); 3653 3654 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3655 CCInfo.clearWasPPCF128(); 3656 3657 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3658 CCValAssign &VA = ArgLocs[i]; 3659 3660 // Arguments stored in registers. 3661 if (VA.isRegLoc()) { 3662 const TargetRegisterClass *RC; 3663 EVT ValVT = VA.getValVT(); 3664 3665 switch (ValVT.getSimpleVT().SimpleTy) { 3666 default: 3667 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3668 case MVT::i1: 3669 case MVT::i32: 3670 RC = &PPC::GPRCRegClass; 3671 break; 3672 case MVT::f32: 3673 if (Subtarget.hasP8Vector()) 3674 RC = &PPC::VSSRCRegClass; 3675 else if (Subtarget.hasSPE()) 3676 RC = &PPC::GPRCRegClass; 3677 else 3678 RC = &PPC::F4RCRegClass; 3679 break; 3680 case MVT::f64: 3681 if (Subtarget.hasVSX()) 3682 RC = &PPC::VSFRCRegClass; 3683 else if (Subtarget.hasSPE()) 3684 // SPE passes doubles in GPR pairs. 3685 RC = &PPC::GPRCRegClass; 3686 else 3687 RC = &PPC::F8RCRegClass; 3688 break; 3689 case MVT::v16i8: 3690 case MVT::v8i16: 3691 case MVT::v4i32: 3692 RC = &PPC::VRRCRegClass; 3693 break; 3694 case MVT::v4f32: 3695 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3696 break; 3697 case MVT::v2f64: 3698 case MVT::v2i64: 3699 RC = &PPC::VRRCRegClass; 3700 break; 3701 case MVT::v4f64: 3702 RC = &PPC::QFRCRegClass; 3703 break; 3704 case MVT::v4i1: 3705 RC = &PPC::QBRCRegClass; 3706 break; 3707 } 3708 3709 SDValue ArgValue; 3710 // Transform the arguments stored in physical registers into 3711 // virtual ones. 3712 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3713 assert(i + 1 < e && "No second half of double precision argument"); 3714 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3715 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3716 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3717 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3718 if (!Subtarget.isLittleEndian()) 3719 std::swap (ArgValueLo, ArgValueHi); 3720 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3721 ArgValueHi); 3722 } else { 3723 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3724 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3725 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3726 if (ValVT == MVT::i1) 3727 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3728 } 3729 3730 InVals.push_back(ArgValue); 3731 } else { 3732 // Argument stored in memory. 3733 assert(VA.isMemLoc()); 3734 3735 // Get the extended size of the argument type in stack 3736 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3737 // Get the actual size of the argument type 3738 unsigned ObjSize = VA.getValVT().getStoreSize(); 3739 unsigned ArgOffset = VA.getLocMemOffset(); 3740 // Stack objects in PPC32 are right justified. 3741 ArgOffset += ArgSize - ObjSize; 3742 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3743 3744 // Create load nodes to retrieve arguments from the stack. 3745 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3746 InVals.push_back( 3747 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3748 } 3749 } 3750 3751 // Assign locations to all of the incoming aggregate by value arguments. 3752 // Aggregates passed by value are stored in the local variable space of the 3753 // caller's stack frame, right above the parameter list area. 3754 SmallVector<CCValAssign, 16> ByValArgLocs; 3755 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3756 ByValArgLocs, *DAG.getContext()); 3757 3758 // Reserve stack space for the allocations in CCInfo. 3759 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3760 3761 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3762 3763 // Area that is at least reserved in the caller of this function. 3764 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3765 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3766 3767 // Set the size that is at least reserved in caller of this function. Tail 3768 // call optimized function's reserved stack space needs to be aligned so that 3769 // taking the difference between two stack areas will result in an aligned 3770 // stack. 3771 MinReservedArea = 3772 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3773 FuncInfo->setMinReservedArea(MinReservedArea); 3774 3775 SmallVector<SDValue, 8> MemOps; 3776 3777 // If the function takes variable number of arguments, make a frame index for 3778 // the start of the first vararg value... for expansion of llvm.va_start. 3779 if (isVarArg) { 3780 static const MCPhysReg GPArgRegs[] = { 3781 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3782 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3783 }; 3784 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3785 3786 static const MCPhysReg FPArgRegs[] = { 3787 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3788 PPC::F8 3789 }; 3790 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3791 3792 if (useSoftFloat() || hasSPE()) 3793 NumFPArgRegs = 0; 3794 3795 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3796 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3797 3798 // Make room for NumGPArgRegs and NumFPArgRegs. 3799 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3800 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3801 3802 FuncInfo->setVarArgsStackOffset( 3803 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3804 CCInfo.getNextStackOffset(), true)); 3805 3806 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3807 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3808 3809 // The fixed integer arguments of a variadic function are stored to the 3810 // VarArgsFrameIndex on the stack so that they may be loaded by 3811 // dereferencing the result of va_next. 3812 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3813 // Get an existing live-in vreg, or add a new one. 3814 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3815 if (!VReg) 3816 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3817 3818 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3819 SDValue Store = 3820 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3821 MemOps.push_back(Store); 3822 // Increment the address by four for the next argument to store 3823 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3824 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3825 } 3826 3827 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3828 // is set. 3829 // The double arguments are stored to the VarArgsFrameIndex 3830 // on the stack. 3831 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3832 // Get an existing live-in vreg, or add a new one. 3833 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3834 if (!VReg) 3835 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3836 3837 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3838 SDValue Store = 3839 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3840 MemOps.push_back(Store); 3841 // Increment the address by eight for the next argument to store 3842 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3843 PtrVT); 3844 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3845 } 3846 } 3847 3848 if (!MemOps.empty()) 3849 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3850 3851 return Chain; 3852 } 3853 3854 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3855 // value to MVT::i64 and then truncate to the correct register size. 3856 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3857 EVT ObjectVT, SelectionDAG &DAG, 3858 SDValue ArgVal, 3859 const SDLoc &dl) const { 3860 if (Flags.isSExt()) 3861 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3862 DAG.getValueType(ObjectVT)); 3863 else if (Flags.isZExt()) 3864 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3865 DAG.getValueType(ObjectVT)); 3866 3867 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3868 } 3869 3870 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3871 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3872 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3873 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3874 // TODO: add description of PPC stack frame format, or at least some docs. 3875 // 3876 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3877 bool isLittleEndian = Subtarget.isLittleEndian(); 3878 MachineFunction &MF = DAG.getMachineFunction(); 3879 MachineFrameInfo &MFI = MF.getFrameInfo(); 3880 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3881 3882 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3883 "fastcc not supported on varargs functions"); 3884 3885 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3886 // Potential tail calls could cause overwriting of argument stack slots. 3887 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3888 (CallConv == CallingConv::Fast)); 3889 unsigned PtrByteSize = 8; 3890 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3891 3892 static const MCPhysReg GPR[] = { 3893 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3894 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3895 }; 3896 static const MCPhysReg VR[] = { 3897 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3898 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3899 }; 3900 3901 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3902 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3903 const unsigned Num_VR_Regs = array_lengthof(VR); 3904 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3905 3906 // Do a first pass over the arguments to determine whether the ABI 3907 // guarantees that our caller has allocated the parameter save area 3908 // on its stack frame. In the ELFv1 ABI, this is always the case; 3909 // in the ELFv2 ABI, it is true if this is a vararg function or if 3910 // any parameter is located in a stack slot. 3911 3912 bool HasParameterArea = !isELFv2ABI || isVarArg; 3913 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3914 unsigned NumBytes = LinkageSize; 3915 unsigned AvailableFPRs = Num_FPR_Regs; 3916 unsigned AvailableVRs = Num_VR_Regs; 3917 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3918 if (Ins[i].Flags.isNest()) 3919 continue; 3920 3921 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3922 PtrByteSize, LinkageSize, ParamAreaSize, 3923 NumBytes, AvailableFPRs, AvailableVRs, 3924 Subtarget.hasQPX())) 3925 HasParameterArea = true; 3926 } 3927 3928 // Add DAG nodes to load the arguments or copy them out of registers. On 3929 // entry to a function on PPC, the arguments start after the linkage area, 3930 // although the first ones are often in registers. 3931 3932 unsigned ArgOffset = LinkageSize; 3933 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3934 unsigned &QFPR_idx = FPR_idx; 3935 SmallVector<SDValue, 8> MemOps; 3936 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3937 unsigned CurArgIdx = 0; 3938 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3939 SDValue ArgVal; 3940 bool needsLoad = false; 3941 EVT ObjectVT = Ins[ArgNo].VT; 3942 EVT OrigVT = Ins[ArgNo].ArgVT; 3943 unsigned ObjSize = ObjectVT.getStoreSize(); 3944 unsigned ArgSize = ObjSize; 3945 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3946 if (Ins[ArgNo].isOrigArg()) { 3947 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3948 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3949 } 3950 // We re-align the argument offset for each argument, except when using the 3951 // fast calling convention, when we need to make sure we do that only when 3952 // we'll actually use a stack slot. 3953 unsigned CurArgOffset; 3954 Align Alignment; 3955 auto ComputeArgOffset = [&]() { 3956 /* Respect alignment of argument on the stack. */ 3957 Alignment = 3958 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3959 ArgOffset = alignTo(ArgOffset, Alignment); 3960 CurArgOffset = ArgOffset; 3961 }; 3962 3963 if (CallConv != CallingConv::Fast) { 3964 ComputeArgOffset(); 3965 3966 /* Compute GPR index associated with argument offset. */ 3967 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3968 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3969 } 3970 3971 // FIXME the codegen can be much improved in some cases. 3972 // We do not have to keep everything in memory. 3973 if (Flags.isByVal()) { 3974 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3975 3976 if (CallConv == CallingConv::Fast) 3977 ComputeArgOffset(); 3978 3979 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3980 ObjSize = Flags.getByValSize(); 3981 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3982 // Empty aggregate parameters do not take up registers. Examples: 3983 // struct { } a; 3984 // union { } b; 3985 // int c[0]; 3986 // etc. However, we have to provide a place-holder in InVals, so 3987 // pretend we have an 8-byte item at the current address for that 3988 // purpose. 3989 if (!ObjSize) { 3990 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3991 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3992 InVals.push_back(FIN); 3993 continue; 3994 } 3995 3996 // Create a stack object covering all stack doublewords occupied 3997 // by the argument. If the argument is (fully or partially) on 3998 // the stack, or if the argument is fully in registers but the 3999 // caller has allocated the parameter save anyway, we can refer 4000 // directly to the caller's stack frame. Otherwise, create a 4001 // local copy in our own frame. 4002 int FI; 4003 if (HasParameterArea || 4004 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4005 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4006 else 4007 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4008 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4009 4010 // Handle aggregates smaller than 8 bytes. 4011 if (ObjSize < PtrByteSize) { 4012 // The value of the object is its address, which differs from the 4013 // address of the enclosing doubleword on big-endian systems. 4014 SDValue Arg = FIN; 4015 if (!isLittleEndian) { 4016 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4017 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4018 } 4019 InVals.push_back(Arg); 4020 4021 if (GPR_idx != Num_GPR_Regs) { 4022 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4023 FuncInfo->addLiveInAttr(VReg, Flags); 4024 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4025 SDValue Store; 4026 4027 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4028 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4029 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4030 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4031 MachinePointerInfo(&*FuncArg), ObjType); 4032 } else { 4033 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4034 // store the whole register as-is to the parameter save area 4035 // slot. 4036 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4037 MachinePointerInfo(&*FuncArg)); 4038 } 4039 4040 MemOps.push_back(Store); 4041 } 4042 // Whether we copied from a register or not, advance the offset 4043 // into the parameter save area by a full doubleword. 4044 ArgOffset += PtrByteSize; 4045 continue; 4046 } 4047 4048 // The value of the object is its address, which is the address of 4049 // its first stack doubleword. 4050 InVals.push_back(FIN); 4051 4052 // Store whatever pieces of the object are in registers to memory. 4053 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4054 if (GPR_idx == Num_GPR_Regs) 4055 break; 4056 4057 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4058 FuncInfo->addLiveInAttr(VReg, Flags); 4059 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4060 SDValue Addr = FIN; 4061 if (j) { 4062 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4063 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4064 } 4065 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4066 MachinePointerInfo(&*FuncArg, j)); 4067 MemOps.push_back(Store); 4068 ++GPR_idx; 4069 } 4070 ArgOffset += ArgSize; 4071 continue; 4072 } 4073 4074 switch (ObjectVT.getSimpleVT().SimpleTy) { 4075 default: llvm_unreachable("Unhandled argument type!"); 4076 case MVT::i1: 4077 case MVT::i32: 4078 case MVT::i64: 4079 if (Flags.isNest()) { 4080 // The 'nest' parameter, if any, is passed in R11. 4081 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4082 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4083 4084 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4085 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4086 4087 break; 4088 } 4089 4090 // These can be scalar arguments or elements of an integer array type 4091 // passed directly. Clang may use those instead of "byval" aggregate 4092 // types to avoid forcing arguments to memory unnecessarily. 4093 if (GPR_idx != Num_GPR_Regs) { 4094 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4095 FuncInfo->addLiveInAttr(VReg, Flags); 4096 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4097 4098 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4099 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4100 // value to MVT::i64 and then truncate to the correct register size. 4101 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4102 } else { 4103 if (CallConv == CallingConv::Fast) 4104 ComputeArgOffset(); 4105 4106 needsLoad = true; 4107 ArgSize = PtrByteSize; 4108 } 4109 if (CallConv != CallingConv::Fast || needsLoad) 4110 ArgOffset += 8; 4111 break; 4112 4113 case MVT::f32: 4114 case MVT::f64: 4115 // These can be scalar arguments or elements of a float array type 4116 // passed directly. The latter are used to implement ELFv2 homogenous 4117 // float aggregates. 4118 if (FPR_idx != Num_FPR_Regs) { 4119 unsigned VReg; 4120 4121 if (ObjectVT == MVT::f32) 4122 VReg = MF.addLiveIn(FPR[FPR_idx], 4123 Subtarget.hasP8Vector() 4124 ? &PPC::VSSRCRegClass 4125 : &PPC::F4RCRegClass); 4126 else 4127 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4128 ? &PPC::VSFRCRegClass 4129 : &PPC::F8RCRegClass); 4130 4131 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4132 ++FPR_idx; 4133 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4134 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4135 // once we support fp <-> gpr moves. 4136 4137 // This can only ever happen in the presence of f32 array types, 4138 // since otherwise we never run out of FPRs before running out 4139 // of GPRs. 4140 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4141 FuncInfo->addLiveInAttr(VReg, Flags); 4142 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4143 4144 if (ObjectVT == MVT::f32) { 4145 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4146 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4147 DAG.getConstant(32, dl, MVT::i32)); 4148 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4149 } 4150 4151 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4152 } else { 4153 if (CallConv == CallingConv::Fast) 4154 ComputeArgOffset(); 4155 4156 needsLoad = true; 4157 } 4158 4159 // When passing an array of floats, the array occupies consecutive 4160 // space in the argument area; only round up to the next doubleword 4161 // at the end of the array. Otherwise, each float takes 8 bytes. 4162 if (CallConv != CallingConv::Fast || needsLoad) { 4163 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4164 ArgOffset += ArgSize; 4165 if (Flags.isInConsecutiveRegsLast()) 4166 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4167 } 4168 break; 4169 case MVT::v4f32: 4170 case MVT::v4i32: 4171 case MVT::v8i16: 4172 case MVT::v16i8: 4173 case MVT::v2f64: 4174 case MVT::v2i64: 4175 case MVT::v1i128: 4176 case MVT::f128: 4177 if (!Subtarget.hasQPX()) { 4178 // These can be scalar arguments or elements of a vector array type 4179 // passed directly. The latter are used to implement ELFv2 homogenous 4180 // vector aggregates. 4181 if (VR_idx != Num_VR_Regs) { 4182 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4183 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4184 ++VR_idx; 4185 } else { 4186 if (CallConv == CallingConv::Fast) 4187 ComputeArgOffset(); 4188 needsLoad = true; 4189 } 4190 if (CallConv != CallingConv::Fast || needsLoad) 4191 ArgOffset += 16; 4192 break; 4193 } // not QPX 4194 4195 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4196 "Invalid QPX parameter type"); 4197 LLVM_FALLTHROUGH; 4198 4199 case MVT::v4f64: 4200 case MVT::v4i1: 4201 // QPX vectors are treated like their scalar floating-point subregisters 4202 // (except that they're larger). 4203 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4204 if (QFPR_idx != Num_QFPR_Regs) { 4205 const TargetRegisterClass *RC; 4206 switch (ObjectVT.getSimpleVT().SimpleTy) { 4207 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4208 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4209 default: RC = &PPC::QBRCRegClass; break; 4210 } 4211 4212 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4213 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4214 ++QFPR_idx; 4215 } else { 4216 if (CallConv == CallingConv::Fast) 4217 ComputeArgOffset(); 4218 needsLoad = true; 4219 } 4220 if (CallConv != CallingConv::Fast || needsLoad) 4221 ArgOffset += Sz; 4222 break; 4223 } 4224 4225 // We need to load the argument to a virtual register if we determined 4226 // above that we ran out of physical registers of the appropriate type. 4227 if (needsLoad) { 4228 if (ObjSize < ArgSize && !isLittleEndian) 4229 CurArgOffset += ArgSize - ObjSize; 4230 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4231 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4232 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4233 } 4234 4235 InVals.push_back(ArgVal); 4236 } 4237 4238 // Area that is at least reserved in the caller of this function. 4239 unsigned MinReservedArea; 4240 if (HasParameterArea) 4241 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4242 else 4243 MinReservedArea = LinkageSize; 4244 4245 // Set the size that is at least reserved in caller of this function. Tail 4246 // call optimized functions' reserved stack space needs to be aligned so that 4247 // taking the difference between two stack areas will result in an aligned 4248 // stack. 4249 MinReservedArea = 4250 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4251 FuncInfo->setMinReservedArea(MinReservedArea); 4252 4253 // If the function takes variable number of arguments, make a frame index for 4254 // the start of the first vararg value... for expansion of llvm.va_start. 4255 if (isVarArg) { 4256 int Depth = ArgOffset; 4257 4258 FuncInfo->setVarArgsFrameIndex( 4259 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4260 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4261 4262 // If this function is vararg, store any remaining integer argument regs 4263 // to their spots on the stack so that they may be loaded by dereferencing 4264 // the result of va_next. 4265 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4266 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4267 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4268 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4269 SDValue Store = 4270 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4271 MemOps.push_back(Store); 4272 // Increment the address by four for the next argument to store 4273 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4274 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4275 } 4276 } 4277 4278 if (!MemOps.empty()) 4279 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4280 4281 return Chain; 4282 } 4283 4284 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4285 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4286 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4287 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4288 // TODO: add description of PPC stack frame format, or at least some docs. 4289 // 4290 MachineFunction &MF = DAG.getMachineFunction(); 4291 MachineFrameInfo &MFI = MF.getFrameInfo(); 4292 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4293 4294 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4295 bool isPPC64 = PtrVT == MVT::i64; 4296 // Potential tail calls could cause overwriting of argument stack slots. 4297 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4298 (CallConv == CallingConv::Fast)); 4299 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4300 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4301 unsigned ArgOffset = LinkageSize; 4302 // Area that is at least reserved in caller of this function. 4303 unsigned MinReservedArea = ArgOffset; 4304 4305 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4306 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4307 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4308 }; 4309 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4310 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4311 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4312 }; 4313 static const MCPhysReg VR[] = { 4314 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4315 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4316 }; 4317 4318 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4319 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4320 const unsigned Num_VR_Regs = array_lengthof( VR); 4321 4322 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4323 4324 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4325 4326 // In 32-bit non-varargs functions, the stack space for vectors is after the 4327 // stack space for non-vectors. We do not use this space unless we have 4328 // too many vectors to fit in registers, something that only occurs in 4329 // constructed examples:), but we have to walk the arglist to figure 4330 // that out...for the pathological case, compute VecArgOffset as the 4331 // start of the vector parameter area. Computing VecArgOffset is the 4332 // entire point of the following loop. 4333 unsigned VecArgOffset = ArgOffset; 4334 if (!isVarArg && !isPPC64) { 4335 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4336 ++ArgNo) { 4337 EVT ObjectVT = Ins[ArgNo].VT; 4338 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4339 4340 if (Flags.isByVal()) { 4341 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4342 unsigned ObjSize = Flags.getByValSize(); 4343 unsigned ArgSize = 4344 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4345 VecArgOffset += ArgSize; 4346 continue; 4347 } 4348 4349 switch(ObjectVT.getSimpleVT().SimpleTy) { 4350 default: llvm_unreachable("Unhandled argument type!"); 4351 case MVT::i1: 4352 case MVT::i32: 4353 case MVT::f32: 4354 VecArgOffset += 4; 4355 break; 4356 case MVT::i64: // PPC64 4357 case MVT::f64: 4358 // FIXME: We are guaranteed to be !isPPC64 at this point. 4359 // Does MVT::i64 apply? 4360 VecArgOffset += 8; 4361 break; 4362 case MVT::v4f32: 4363 case MVT::v4i32: 4364 case MVT::v8i16: 4365 case MVT::v16i8: 4366 // Nothing to do, we're only looking at Nonvector args here. 4367 break; 4368 } 4369 } 4370 } 4371 // We've found where the vector parameter area in memory is. Skip the 4372 // first 12 parameters; these don't use that memory. 4373 VecArgOffset = ((VecArgOffset+15)/16)*16; 4374 VecArgOffset += 12*16; 4375 4376 // Add DAG nodes to load the arguments or copy them out of registers. On 4377 // entry to a function on PPC, the arguments start after the linkage area, 4378 // although the first ones are often in registers. 4379 4380 SmallVector<SDValue, 8> MemOps; 4381 unsigned nAltivecParamsAtEnd = 0; 4382 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4383 unsigned CurArgIdx = 0; 4384 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4385 SDValue ArgVal; 4386 bool needsLoad = false; 4387 EVT ObjectVT = Ins[ArgNo].VT; 4388 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4389 unsigned ArgSize = ObjSize; 4390 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4391 if (Ins[ArgNo].isOrigArg()) { 4392 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4393 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4394 } 4395 unsigned CurArgOffset = ArgOffset; 4396 4397 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4398 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4399 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4400 if (isVarArg || isPPC64) { 4401 MinReservedArea = ((MinReservedArea+15)/16)*16; 4402 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4403 Flags, 4404 PtrByteSize); 4405 } else nAltivecParamsAtEnd++; 4406 } else 4407 // Calculate min reserved area. 4408 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4409 Flags, 4410 PtrByteSize); 4411 4412 // FIXME the codegen can be much improved in some cases. 4413 // We do not have to keep everything in memory. 4414 if (Flags.isByVal()) { 4415 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4416 4417 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4418 ObjSize = Flags.getByValSize(); 4419 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4420 // Objects of size 1 and 2 are right justified, everything else is 4421 // left justified. This means the memory address is adjusted forwards. 4422 if (ObjSize==1 || ObjSize==2) { 4423 CurArgOffset = CurArgOffset + (4 - ObjSize); 4424 } 4425 // The value of the object is its address. 4426 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4427 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4428 InVals.push_back(FIN); 4429 if (ObjSize==1 || ObjSize==2) { 4430 if (GPR_idx != Num_GPR_Regs) { 4431 unsigned VReg; 4432 if (isPPC64) 4433 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4434 else 4435 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4436 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4437 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4438 SDValue Store = 4439 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4440 MachinePointerInfo(&*FuncArg), ObjType); 4441 MemOps.push_back(Store); 4442 ++GPR_idx; 4443 } 4444 4445 ArgOffset += PtrByteSize; 4446 4447 continue; 4448 } 4449 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4450 // Store whatever pieces of the object are in registers 4451 // to memory. ArgOffset will be the address of the beginning 4452 // of the object. 4453 if (GPR_idx != Num_GPR_Regs) { 4454 unsigned VReg; 4455 if (isPPC64) 4456 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4457 else 4458 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4459 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4460 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4461 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4462 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4463 MachinePointerInfo(&*FuncArg, j)); 4464 MemOps.push_back(Store); 4465 ++GPR_idx; 4466 ArgOffset += PtrByteSize; 4467 } else { 4468 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4469 break; 4470 } 4471 } 4472 continue; 4473 } 4474 4475 switch (ObjectVT.getSimpleVT().SimpleTy) { 4476 default: llvm_unreachable("Unhandled argument type!"); 4477 case MVT::i1: 4478 case MVT::i32: 4479 if (!isPPC64) { 4480 if (GPR_idx != Num_GPR_Regs) { 4481 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4482 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4483 4484 if (ObjectVT == MVT::i1) 4485 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4486 4487 ++GPR_idx; 4488 } else { 4489 needsLoad = true; 4490 ArgSize = PtrByteSize; 4491 } 4492 // All int arguments reserve stack space in the Darwin ABI. 4493 ArgOffset += PtrByteSize; 4494 break; 4495 } 4496 LLVM_FALLTHROUGH; 4497 case MVT::i64: // PPC64 4498 if (GPR_idx != Num_GPR_Regs) { 4499 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4500 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4501 4502 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4503 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4504 // value to MVT::i64 and then truncate to the correct register size. 4505 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4506 4507 ++GPR_idx; 4508 } else { 4509 needsLoad = true; 4510 ArgSize = PtrByteSize; 4511 } 4512 // All int arguments reserve stack space in the Darwin ABI. 4513 ArgOffset += 8; 4514 break; 4515 4516 case MVT::f32: 4517 case MVT::f64: 4518 // Every 4 bytes of argument space consumes one of the GPRs available for 4519 // argument passing. 4520 if (GPR_idx != Num_GPR_Regs) { 4521 ++GPR_idx; 4522 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4523 ++GPR_idx; 4524 } 4525 if (FPR_idx != Num_FPR_Regs) { 4526 unsigned VReg; 4527 4528 if (ObjectVT == MVT::f32) 4529 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4530 else 4531 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4532 4533 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4534 ++FPR_idx; 4535 } else { 4536 needsLoad = true; 4537 } 4538 4539 // All FP arguments reserve stack space in the Darwin ABI. 4540 ArgOffset += isPPC64 ? 8 : ObjSize; 4541 break; 4542 case MVT::v4f32: 4543 case MVT::v4i32: 4544 case MVT::v8i16: 4545 case MVT::v16i8: 4546 // Note that vector arguments in registers don't reserve stack space, 4547 // except in varargs functions. 4548 if (VR_idx != Num_VR_Regs) { 4549 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4550 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4551 if (isVarArg) { 4552 while ((ArgOffset % 16) != 0) { 4553 ArgOffset += PtrByteSize; 4554 if (GPR_idx != Num_GPR_Regs) 4555 GPR_idx++; 4556 } 4557 ArgOffset += 16; 4558 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4559 } 4560 ++VR_idx; 4561 } else { 4562 if (!isVarArg && !isPPC64) { 4563 // Vectors go after all the nonvectors. 4564 CurArgOffset = VecArgOffset; 4565 VecArgOffset += 16; 4566 } else { 4567 // Vectors are aligned. 4568 ArgOffset = ((ArgOffset+15)/16)*16; 4569 CurArgOffset = ArgOffset; 4570 ArgOffset += 16; 4571 } 4572 needsLoad = true; 4573 } 4574 break; 4575 } 4576 4577 // We need to load the argument to a virtual register if we determined above 4578 // that we ran out of physical registers of the appropriate type. 4579 if (needsLoad) { 4580 int FI = MFI.CreateFixedObject(ObjSize, 4581 CurArgOffset + (ArgSize - ObjSize), 4582 isImmutable); 4583 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4584 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4585 } 4586 4587 InVals.push_back(ArgVal); 4588 } 4589 4590 // Allow for Altivec parameters at the end, if needed. 4591 if (nAltivecParamsAtEnd) { 4592 MinReservedArea = ((MinReservedArea+15)/16)*16; 4593 MinReservedArea += 16*nAltivecParamsAtEnd; 4594 } 4595 4596 // Area that is at least reserved in the caller of this function. 4597 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4598 4599 // Set the size that is at least reserved in caller of this function. Tail 4600 // call optimized functions' reserved stack space needs to be aligned so that 4601 // taking the difference between two stack areas will result in an aligned 4602 // stack. 4603 MinReservedArea = 4604 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4605 FuncInfo->setMinReservedArea(MinReservedArea); 4606 4607 // If the function takes variable number of arguments, make a frame index for 4608 // the start of the first vararg value... for expansion of llvm.va_start. 4609 if (isVarArg) { 4610 int Depth = ArgOffset; 4611 4612 FuncInfo->setVarArgsFrameIndex( 4613 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4614 Depth, true)); 4615 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4616 4617 // If this function is vararg, store any remaining integer argument regs 4618 // to their spots on the stack so that they may be loaded by dereferencing 4619 // the result of va_next. 4620 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4621 unsigned VReg; 4622 4623 if (isPPC64) 4624 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4625 else 4626 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4627 4628 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4629 SDValue Store = 4630 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4631 MemOps.push_back(Store); 4632 // Increment the address by four for the next argument to store 4633 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4634 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4635 } 4636 } 4637 4638 if (!MemOps.empty()) 4639 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4640 4641 return Chain; 4642 } 4643 4644 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4645 /// adjusted to accommodate the arguments for the tailcall. 4646 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4647 unsigned ParamSize) { 4648 4649 if (!isTailCall) return 0; 4650 4651 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4652 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4653 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4654 // Remember only if the new adjustment is bigger. 4655 if (SPDiff < FI->getTailCallSPDelta()) 4656 FI->setTailCallSPDelta(SPDiff); 4657 4658 return SPDiff; 4659 } 4660 4661 static bool isFunctionGlobalAddress(SDValue Callee); 4662 4663 static bool 4664 callsShareTOCBase(const Function *Caller, SDValue Callee, 4665 const TargetMachine &TM) { 4666 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4667 // don't have enough information to determine if the caller and calle share 4668 // the same TOC base, so we have to pessimistically assume they don't for 4669 // correctness. 4670 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4671 if (!G) 4672 return false; 4673 4674 const GlobalValue *GV = G->getGlobal(); 4675 // The medium and large code models are expected to provide a sufficiently 4676 // large TOC to provide all data addressing needs of a module with a 4677 // single TOC. Since each module will be addressed with a single TOC then we 4678 // only need to check that caller and callee don't cross dso boundaries. 4679 if (CodeModel::Medium == TM.getCodeModel() || 4680 CodeModel::Large == TM.getCodeModel()) 4681 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4682 4683 // Otherwise we need to ensure callee and caller are in the same section, 4684 // since the linker may allocate multiple TOCs, and we don't know which 4685 // sections will belong to the same TOC base. 4686 4687 if (!GV->isStrongDefinitionForLinker()) 4688 return false; 4689 4690 // Any explicitly-specified sections and section prefixes must also match. 4691 // Also, if we're using -ffunction-sections, then each function is always in 4692 // a different section (the same is true for COMDAT functions). 4693 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4694 GV->getSection() != Caller->getSection()) 4695 return false; 4696 if (const auto *F = dyn_cast<Function>(GV)) { 4697 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4698 return false; 4699 } 4700 4701 // If the callee might be interposed, then we can't assume the ultimate call 4702 // target will be in the same section. Even in cases where we can assume that 4703 // interposition won't happen, in any case where the linker might insert a 4704 // stub to allow for interposition, we must generate code as though 4705 // interposition might occur. To understand why this matters, consider a 4706 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4707 // in the same section, but a is in a different module (i.e. has a different 4708 // TOC base pointer). If the linker allows for interposition between b and c, 4709 // then it will generate a stub for the call edge between b and c which will 4710 // save the TOC pointer into the designated stack slot allocated by b. If we 4711 // return true here, and therefore allow a tail call between b and c, that 4712 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4713 // pointer into the stack slot allocated by a (where the a -> b stub saved 4714 // a's TOC base pointer). If we're not considering a tail call, but rather, 4715 // whether a nop is needed after the call instruction in b, because the linker 4716 // will insert a stub, it might complain about a missing nop if we omit it 4717 // (although many don't complain in this case). 4718 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4719 return false; 4720 4721 return true; 4722 } 4723 4724 static bool 4725 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4726 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4727 assert(Subtarget.is64BitELFABI()); 4728 4729 const unsigned PtrByteSize = 8; 4730 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4731 4732 static const MCPhysReg GPR[] = { 4733 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4734 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4735 }; 4736 static const MCPhysReg VR[] = { 4737 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4738 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4739 }; 4740 4741 const unsigned NumGPRs = array_lengthof(GPR); 4742 const unsigned NumFPRs = 13; 4743 const unsigned NumVRs = array_lengthof(VR); 4744 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4745 4746 unsigned NumBytes = LinkageSize; 4747 unsigned AvailableFPRs = NumFPRs; 4748 unsigned AvailableVRs = NumVRs; 4749 4750 for (const ISD::OutputArg& Param : Outs) { 4751 if (Param.Flags.isNest()) continue; 4752 4753 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4754 PtrByteSize, LinkageSize, ParamAreaSize, 4755 NumBytes, AvailableFPRs, AvailableVRs, 4756 Subtarget.hasQPX())) 4757 return true; 4758 } 4759 return false; 4760 } 4761 4762 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4763 if (CB.arg_size() != CallerFn->arg_size()) 4764 return false; 4765 4766 auto CalleeArgIter = CB.arg_begin(); 4767 auto CalleeArgEnd = CB.arg_end(); 4768 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4769 4770 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4771 const Value* CalleeArg = *CalleeArgIter; 4772 const Value* CallerArg = &(*CallerArgIter); 4773 if (CalleeArg == CallerArg) 4774 continue; 4775 4776 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4777 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4778 // } 4779 // 1st argument of callee is undef and has the same type as caller. 4780 if (CalleeArg->getType() == CallerArg->getType() && 4781 isa<UndefValue>(CalleeArg)) 4782 continue; 4783 4784 return false; 4785 } 4786 4787 return true; 4788 } 4789 4790 // Returns true if TCO is possible between the callers and callees 4791 // calling conventions. 4792 static bool 4793 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4794 CallingConv::ID CalleeCC) { 4795 // Tail calls are possible with fastcc and ccc. 4796 auto isTailCallableCC = [] (CallingConv::ID CC){ 4797 return CC == CallingConv::C || CC == CallingConv::Fast; 4798 }; 4799 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4800 return false; 4801 4802 // We can safely tail call both fastcc and ccc callees from a c calling 4803 // convention caller. If the caller is fastcc, we may have less stack space 4804 // than a non-fastcc caller with the same signature so disable tail-calls in 4805 // that case. 4806 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4807 } 4808 4809 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4810 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4811 const SmallVectorImpl<ISD::OutputArg> &Outs, 4812 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4813 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4814 4815 if (DisableSCO && !TailCallOpt) return false; 4816 4817 // Variadic argument functions are not supported. 4818 if (isVarArg) return false; 4819 4820 auto &Caller = DAG.getMachineFunction().getFunction(); 4821 // Check that the calling conventions are compatible for tco. 4822 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4823 return false; 4824 4825 // Caller contains any byval parameter is not supported. 4826 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4827 return false; 4828 4829 // Callee contains any byval parameter is not supported, too. 4830 // Note: This is a quick work around, because in some cases, e.g. 4831 // caller's stack size > callee's stack size, we are still able to apply 4832 // sibling call optimization. For example, gcc is able to do SCO for caller1 4833 // in the following example, but not for caller2. 4834 // struct test { 4835 // long int a; 4836 // char ary[56]; 4837 // } gTest; 4838 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4839 // b->a = v.a; 4840 // return 0; 4841 // } 4842 // void caller1(struct test a, struct test c, struct test *b) { 4843 // callee(gTest, b); } 4844 // void caller2(struct test *b) { callee(gTest, b); } 4845 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4846 return false; 4847 4848 // If callee and caller use different calling conventions, we cannot pass 4849 // parameters on stack since offsets for the parameter area may be different. 4850 if (Caller.getCallingConv() != CalleeCC && 4851 needStackSlotPassParameters(Subtarget, Outs)) 4852 return false; 4853 4854 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4855 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4856 // callee potentially have different TOC bases then we cannot tail call since 4857 // we need to restore the TOC pointer after the call. 4858 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4859 // We cannot guarantee this for indirect calls or calls to external functions. 4860 // When PC-Relative addressing is used, the concept of the TOC is no longer 4861 // applicable so this check is not required. 4862 // Check first for indirect calls. 4863 if (!Subtarget.isUsingPCRelativeCalls() && 4864 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4865 return false; 4866 4867 // Check if we share the TOC base. 4868 if (!Subtarget.isUsingPCRelativeCalls() && 4869 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4870 return false; 4871 4872 // TCO allows altering callee ABI, so we don't have to check further. 4873 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4874 return true; 4875 4876 if (DisableSCO) return false; 4877 4878 // If callee use the same argument list that caller is using, then we can 4879 // apply SCO on this case. If it is not, then we need to check if callee needs 4880 // stack for passing arguments. 4881 // PC Relative tail calls may not have a CallBase. 4882 // If there is no CallBase we cannot verify if we have the same argument 4883 // list so assume that we don't have the same argument list. 4884 if (CB && !hasSameArgumentList(&Caller, *CB) && 4885 needStackSlotPassParameters(Subtarget, Outs)) 4886 return false; 4887 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4888 return false; 4889 4890 return true; 4891 } 4892 4893 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4894 /// for tail call optimization. Targets which want to do tail call 4895 /// optimization should implement this function. 4896 bool 4897 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4898 CallingConv::ID CalleeCC, 4899 bool isVarArg, 4900 const SmallVectorImpl<ISD::InputArg> &Ins, 4901 SelectionDAG& DAG) const { 4902 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4903 return false; 4904 4905 // Variable argument functions are not supported. 4906 if (isVarArg) 4907 return false; 4908 4909 MachineFunction &MF = DAG.getMachineFunction(); 4910 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4911 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4912 // Functions containing by val parameters are not supported. 4913 for (unsigned i = 0; i != Ins.size(); i++) { 4914 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4915 if (Flags.isByVal()) return false; 4916 } 4917 4918 // Non-PIC/GOT tail calls are supported. 4919 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4920 return true; 4921 4922 // At the moment we can only do local tail calls (in same module, hidden 4923 // or protected) if we are generating PIC. 4924 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4925 return G->getGlobal()->hasHiddenVisibility() 4926 || G->getGlobal()->hasProtectedVisibility(); 4927 } 4928 4929 return false; 4930 } 4931 4932 /// isCallCompatibleAddress - Return the immediate to use if the specified 4933 /// 32-bit value is representable in the immediate field of a BxA instruction. 4934 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4935 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4936 if (!C) return nullptr; 4937 4938 int Addr = C->getZExtValue(); 4939 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4940 SignExtend32<26>(Addr) != Addr) 4941 return nullptr; // Top 6 bits have to be sext of immediate. 4942 4943 return DAG 4944 .getConstant( 4945 (int)C->getZExtValue() >> 2, SDLoc(Op), 4946 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4947 .getNode(); 4948 } 4949 4950 namespace { 4951 4952 struct TailCallArgumentInfo { 4953 SDValue Arg; 4954 SDValue FrameIdxOp; 4955 int FrameIdx = 0; 4956 4957 TailCallArgumentInfo() = default; 4958 }; 4959 4960 } // end anonymous namespace 4961 4962 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4963 static void StoreTailCallArgumentsToStackSlot( 4964 SelectionDAG &DAG, SDValue Chain, 4965 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4966 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4967 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4968 SDValue Arg = TailCallArgs[i].Arg; 4969 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4970 int FI = TailCallArgs[i].FrameIdx; 4971 // Store relative to framepointer. 4972 MemOpChains.push_back(DAG.getStore( 4973 Chain, dl, Arg, FIN, 4974 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4975 } 4976 } 4977 4978 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4979 /// the appropriate stack slot for the tail call optimized function call. 4980 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4981 SDValue OldRetAddr, SDValue OldFP, 4982 int SPDiff, const SDLoc &dl) { 4983 if (SPDiff) { 4984 // Calculate the new stack slot for the return address. 4985 MachineFunction &MF = DAG.getMachineFunction(); 4986 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4987 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4988 bool isPPC64 = Subtarget.isPPC64(); 4989 int SlotSize = isPPC64 ? 8 : 4; 4990 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4991 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4992 NewRetAddrLoc, true); 4993 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4994 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4995 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4996 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4997 } 4998 return Chain; 4999 } 5000 5001 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5002 /// the position of the argument. 5003 static void 5004 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5005 SDValue Arg, int SPDiff, unsigned ArgOffset, 5006 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5007 int Offset = ArgOffset + SPDiff; 5008 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5009 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5010 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5011 SDValue FIN = DAG.getFrameIndex(FI, VT); 5012 TailCallArgumentInfo Info; 5013 Info.Arg = Arg; 5014 Info.FrameIdxOp = FIN; 5015 Info.FrameIdx = FI; 5016 TailCallArguments.push_back(Info); 5017 } 5018 5019 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5020 /// stack slot. Returns the chain as result and the loaded frame pointers in 5021 /// LROpOut/FPOpout. Used when tail calling. 5022 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5023 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5024 SDValue &FPOpOut, const SDLoc &dl) const { 5025 if (SPDiff) { 5026 // Load the LR and FP stack slot for later adjusting. 5027 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5028 LROpOut = getReturnAddrFrameIndex(DAG); 5029 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5030 Chain = SDValue(LROpOut.getNode(), 1); 5031 } 5032 return Chain; 5033 } 5034 5035 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5036 /// by "Src" to address "Dst" of size "Size". Alignment information is 5037 /// specified by the specific parameter attribute. The copy will be passed as 5038 /// a byval function parameter. 5039 /// Sometimes what we are copying is the end of a larger object, the part that 5040 /// does not fit in registers. 5041 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5042 SDValue Chain, ISD::ArgFlagsTy Flags, 5043 SelectionDAG &DAG, const SDLoc &dl) { 5044 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5045 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5046 Flags.getNonZeroByValAlign(), false, false, false, 5047 MachinePointerInfo(), MachinePointerInfo()); 5048 } 5049 5050 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5051 /// tail calls. 5052 static void LowerMemOpCallTo( 5053 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5054 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5055 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5056 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5057 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5058 if (!isTailCall) { 5059 if (isVector) { 5060 SDValue StackPtr; 5061 if (isPPC64) 5062 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5063 else 5064 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5065 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5066 DAG.getConstant(ArgOffset, dl, PtrVT)); 5067 } 5068 MemOpChains.push_back( 5069 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5070 // Calculate and remember argument location. 5071 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5072 TailCallArguments); 5073 } 5074 5075 static void 5076 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5077 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5078 SDValue FPOp, 5079 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5080 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5081 // might overwrite each other in case of tail call optimization. 5082 SmallVector<SDValue, 8> MemOpChains2; 5083 // Do not flag preceding copytoreg stuff together with the following stuff. 5084 InFlag = SDValue(); 5085 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5086 MemOpChains2, dl); 5087 if (!MemOpChains2.empty()) 5088 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5089 5090 // Store the return address to the appropriate stack slot. 5091 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5092 5093 // Emit callseq_end just before tailcall node. 5094 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5095 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5096 InFlag = Chain.getValue(1); 5097 } 5098 5099 // Is this global address that of a function that can be called by name? (as 5100 // opposed to something that must hold a descriptor for an indirect call). 5101 static bool isFunctionGlobalAddress(SDValue Callee) { 5102 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5103 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5104 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5105 return false; 5106 5107 return G->getGlobal()->getValueType()->isFunctionTy(); 5108 } 5109 5110 return false; 5111 } 5112 5113 SDValue PPCTargetLowering::LowerCallResult( 5114 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5115 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5116 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5117 SmallVector<CCValAssign, 16> RVLocs; 5118 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5119 *DAG.getContext()); 5120 5121 CCRetInfo.AnalyzeCallResult( 5122 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5123 ? RetCC_PPC_Cold 5124 : RetCC_PPC); 5125 5126 // Copy all of the result registers out of their specified physreg. 5127 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5128 CCValAssign &VA = RVLocs[i]; 5129 assert(VA.isRegLoc() && "Can only return in registers!"); 5130 5131 SDValue Val; 5132 5133 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5134 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5135 InFlag); 5136 Chain = Lo.getValue(1); 5137 InFlag = Lo.getValue(2); 5138 VA = RVLocs[++i]; // skip ahead to next loc 5139 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5140 InFlag); 5141 Chain = Hi.getValue(1); 5142 InFlag = Hi.getValue(2); 5143 if (!Subtarget.isLittleEndian()) 5144 std::swap (Lo, Hi); 5145 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5146 } else { 5147 Val = DAG.getCopyFromReg(Chain, dl, 5148 VA.getLocReg(), VA.getLocVT(), InFlag); 5149 Chain = Val.getValue(1); 5150 InFlag = Val.getValue(2); 5151 } 5152 5153 switch (VA.getLocInfo()) { 5154 default: llvm_unreachable("Unknown loc info!"); 5155 case CCValAssign::Full: break; 5156 case CCValAssign::AExt: 5157 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5158 break; 5159 case CCValAssign::ZExt: 5160 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5161 DAG.getValueType(VA.getValVT())); 5162 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5163 break; 5164 case CCValAssign::SExt: 5165 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5166 DAG.getValueType(VA.getValVT())); 5167 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5168 break; 5169 } 5170 5171 InVals.push_back(Val); 5172 } 5173 5174 return Chain; 5175 } 5176 5177 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5178 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5179 // PatchPoint calls are not indirect. 5180 if (isPatchPoint) 5181 return false; 5182 5183 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5184 return false; 5185 5186 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5187 // becuase the immediate function pointer points to a descriptor instead of 5188 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5189 // pointer immediate points to the global entry point, while the BLA would 5190 // need to jump to the local entry point (see rL211174). 5191 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5192 isBLACompatibleAddress(Callee, DAG)) 5193 return false; 5194 5195 return true; 5196 } 5197 5198 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5199 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5200 return Subtarget.isAIXABI() || 5201 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5202 } 5203 5204 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5205 const Function &Caller, 5206 const SDValue &Callee, 5207 const PPCSubtarget &Subtarget, 5208 const TargetMachine &TM) { 5209 if (CFlags.IsTailCall) 5210 return PPCISD::TC_RETURN; 5211 5212 // This is a call through a function pointer. 5213 if (CFlags.IsIndirect) { 5214 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5215 // indirect calls. The save of the caller's TOC pointer to the stack will be 5216 // inserted into the DAG as part of call lowering. The restore of the TOC 5217 // pointer is modeled by using a pseudo instruction for the call opcode that 5218 // represents the 2 instruction sequence of an indirect branch and link, 5219 // immediately followed by a load of the TOC pointer from the the stack save 5220 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5221 // as it is not saved or used. 5222 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5223 : PPCISD::BCTRL; 5224 } 5225 5226 if (Subtarget.isUsingPCRelativeCalls()) { 5227 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5228 return PPCISD::CALL_NOTOC; 5229 } 5230 5231 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5232 // immediately following the call instruction if the caller and callee may 5233 // have different TOC bases. At link time if the linker determines the calls 5234 // may not share a TOC base, the call is redirected to a trampoline inserted 5235 // by the linker. The trampoline will (among other things) save the callers 5236 // TOC pointer at an ABI designated offset in the linkage area and the linker 5237 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5238 // into gpr2. 5239 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5240 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5241 : PPCISD::CALL_NOP; 5242 5243 return PPCISD::CALL; 5244 } 5245 5246 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5247 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5248 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5249 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5250 return SDValue(Dest, 0); 5251 5252 // Returns true if the callee is local, and false otherwise. 5253 auto isLocalCallee = [&]() { 5254 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5255 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5256 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5257 5258 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5259 !dyn_cast_or_null<GlobalIFunc>(GV); 5260 }; 5261 5262 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5263 // a static relocation model causes some versions of GNU LD (2.17.50, at 5264 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5265 // built with secure-PLT. 5266 bool UsePlt = 5267 Subtarget.is32BitELFABI() && !isLocalCallee() && 5268 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5269 5270 // On AIX, direct function calls reference the symbol for the function's 5271 // entry point, which is named by prepending a "." before the function's 5272 // C-linkage name. 5273 const auto getAIXFuncEntryPointSymbolSDNode = 5274 [&](StringRef FuncName, bool IsDeclaration, 5275 const XCOFF::StorageClass &SC) { 5276 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5277 5278 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5279 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5280 5281 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5282 // On AIX, an undefined symbol needs to be associated with a 5283 // MCSectionXCOFF to get the correct storage mapping class. 5284 // In this case, XCOFF::XMC_PR. 5285 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5286 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5287 SectionKind::getMetadata()); 5288 S->setRepresentedCsect(Sec); 5289 } 5290 5291 MVT PtrVT = 5292 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5293 return DAG.getMCSymbol(S, PtrVT); 5294 }; 5295 5296 if (isFunctionGlobalAddress(Callee)) { 5297 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5298 const GlobalValue *GV = G->getGlobal(); 5299 5300 if (!Subtarget.isAIXABI()) 5301 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5302 UsePlt ? PPCII::MO_PLT : 0); 5303 5304 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5305 const GlobalObject *GO = cast<GlobalObject>(GV); 5306 const XCOFF::StorageClass SC = 5307 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5308 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5309 SC); 5310 } 5311 5312 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5313 const char *SymName = S->getSymbol(); 5314 if (!Subtarget.isAIXABI()) 5315 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5316 UsePlt ? PPCII::MO_PLT : 0); 5317 5318 // If there exists a user-declared function whose name is the same as the 5319 // ExternalSymbol's, then we pick up the user-declared version. 5320 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5321 if (const Function *F = 5322 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5323 const XCOFF::StorageClass SC = 5324 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5325 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5326 SC); 5327 } 5328 5329 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5330 } 5331 5332 // No transformation needed. 5333 assert(Callee.getNode() && "What no callee?"); 5334 return Callee; 5335 } 5336 5337 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5338 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5339 "Expected a CALLSEQ_STARTSDNode."); 5340 5341 // The last operand is the chain, except when the node has glue. If the node 5342 // has glue, then the last operand is the glue, and the chain is the second 5343 // last operand. 5344 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5345 if (LastValue.getValueType() != MVT::Glue) 5346 return LastValue; 5347 5348 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5349 } 5350 5351 // Creates the node that moves a functions address into the count register 5352 // to prepare for an indirect call instruction. 5353 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5354 SDValue &Glue, SDValue &Chain, 5355 const SDLoc &dl) { 5356 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5357 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5358 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5359 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5360 // The glue is the second value produced. 5361 Glue = Chain.getValue(1); 5362 } 5363 5364 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5365 SDValue &Glue, SDValue &Chain, 5366 SDValue CallSeqStart, 5367 const CallBase *CB, const SDLoc &dl, 5368 bool hasNest, 5369 const PPCSubtarget &Subtarget) { 5370 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5371 // entry point, but to the function descriptor (the function entry point 5372 // address is part of the function descriptor though). 5373 // The function descriptor is a three doubleword structure with the 5374 // following fields: function entry point, TOC base address and 5375 // environment pointer. 5376 // Thus for a call through a function pointer, the following actions need 5377 // to be performed: 5378 // 1. Save the TOC of the caller in the TOC save area of its stack 5379 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5380 // 2. Load the address of the function entry point from the function 5381 // descriptor. 5382 // 3. Load the TOC of the callee from the function descriptor into r2. 5383 // 4. Load the environment pointer from the function descriptor into 5384 // r11. 5385 // 5. Branch to the function entry point address. 5386 // 6. On return of the callee, the TOC of the caller needs to be 5387 // restored (this is done in FinishCall()). 5388 // 5389 // The loads are scheduled at the beginning of the call sequence, and the 5390 // register copies are flagged together to ensure that no other 5391 // operations can be scheduled in between. E.g. without flagging the 5392 // copies together, a TOC access in the caller could be scheduled between 5393 // the assignment of the callee TOC and the branch to the callee, which leads 5394 // to incorrect code. 5395 5396 // Start by loading the function address from the descriptor. 5397 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5398 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5399 ? (MachineMemOperand::MODereferenceable | 5400 MachineMemOperand::MOInvariant) 5401 : MachineMemOperand::MONone; 5402 5403 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5404 5405 // Registers used in building the DAG. 5406 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5407 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5408 5409 // Offsets of descriptor members. 5410 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5411 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5412 5413 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5414 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5415 5416 // One load for the functions entry point address. 5417 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5418 Alignment, MMOFlags); 5419 5420 // One for loading the TOC anchor for the module that contains the called 5421 // function. 5422 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5423 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5424 SDValue TOCPtr = 5425 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5426 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5427 5428 // One for loading the environment pointer. 5429 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5430 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5431 SDValue LoadEnvPtr = 5432 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5433 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5434 5435 5436 // Then copy the newly loaded TOC anchor to the TOC pointer. 5437 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5438 Chain = TOCVal.getValue(0); 5439 Glue = TOCVal.getValue(1); 5440 5441 // If the function call has an explicit 'nest' parameter, it takes the 5442 // place of the environment pointer. 5443 assert((!hasNest || !Subtarget.isAIXABI()) && 5444 "Nest parameter is not supported on AIX."); 5445 if (!hasNest) { 5446 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5447 Chain = EnvVal.getValue(0); 5448 Glue = EnvVal.getValue(1); 5449 } 5450 5451 // The rest of the indirect call sequence is the same as the non-descriptor 5452 // DAG. 5453 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5454 } 5455 5456 static void 5457 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5458 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5459 SelectionDAG &DAG, 5460 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5461 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5462 const PPCSubtarget &Subtarget) { 5463 const bool IsPPC64 = Subtarget.isPPC64(); 5464 // MVT for a general purpose register. 5465 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5466 5467 // First operand is always the chain. 5468 Ops.push_back(Chain); 5469 5470 // If it's a direct call pass the callee as the second operand. 5471 if (!CFlags.IsIndirect) 5472 Ops.push_back(Callee); 5473 else { 5474 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5475 5476 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5477 // on the stack (this would have been done in `LowerCall_64SVR4` or 5478 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5479 // represents both the indirect branch and a load that restores the TOC 5480 // pointer from the linkage area. The operand for the TOC restore is an add 5481 // of the TOC save offset to the stack pointer. This must be the second 5482 // operand: after the chain input but before any other variadic arguments. 5483 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5484 // saved or used. 5485 if (isTOCSaveRestoreRequired(Subtarget)) { 5486 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5487 5488 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5489 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5490 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5491 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5492 Ops.push_back(AddTOC); 5493 } 5494 5495 // Add the register used for the environment pointer. 5496 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5497 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5498 RegVT)); 5499 5500 5501 // Add CTR register as callee so a bctr can be emitted later. 5502 if (CFlags.IsTailCall) 5503 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5504 } 5505 5506 // If this is a tail call add stack pointer delta. 5507 if (CFlags.IsTailCall) 5508 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5509 5510 // Add argument registers to the end of the list so that they are known live 5511 // into the call. 5512 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5513 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5514 RegsToPass[i].second.getValueType())); 5515 5516 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5517 // no way to mark dependencies as implicit here. 5518 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5519 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5520 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5521 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5522 5523 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5524 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5525 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5526 5527 // Add a register mask operand representing the call-preserved registers. 5528 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5529 const uint32_t *Mask = 5530 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5531 assert(Mask && "Missing call preserved mask for calling convention"); 5532 Ops.push_back(DAG.getRegisterMask(Mask)); 5533 5534 // If the glue is valid, it is the last operand. 5535 if (Glue.getNode()) 5536 Ops.push_back(Glue); 5537 } 5538 5539 SDValue PPCTargetLowering::FinishCall( 5540 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5541 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5542 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5543 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5544 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5545 5546 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5547 Subtarget.isAIXABI()) 5548 setUsesTOCBasePtr(DAG); 5549 5550 unsigned CallOpc = 5551 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5552 Subtarget, DAG.getTarget()); 5553 5554 if (!CFlags.IsIndirect) 5555 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5556 else if (Subtarget.usesFunctionDescriptors()) 5557 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5558 dl, CFlags.HasNest, Subtarget); 5559 else 5560 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5561 5562 // Build the operand list for the call instruction. 5563 SmallVector<SDValue, 8> Ops; 5564 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5565 SPDiff, Subtarget); 5566 5567 // Emit tail call. 5568 if (CFlags.IsTailCall) { 5569 // Indirect tail call when using PC Relative calls do not have the same 5570 // constraints. 5571 assert(((Callee.getOpcode() == ISD::Register && 5572 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5573 Callee.getOpcode() == ISD::TargetExternalSymbol || 5574 Callee.getOpcode() == ISD::TargetGlobalAddress || 5575 isa<ConstantSDNode>(Callee) || 5576 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5577 "Expecting a global address, external symbol, absolute value, " 5578 "register or an indirect tail call when PC Relative calls are " 5579 "used."); 5580 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5581 assert(CallOpc == PPCISD::TC_RETURN && 5582 "Unexpected call opcode for a tail call."); 5583 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5584 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5585 } 5586 5587 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5588 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5589 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5590 Glue = Chain.getValue(1); 5591 5592 // When performing tail call optimization the callee pops its arguments off 5593 // the stack. Account for this here so these bytes can be pushed back on in 5594 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5595 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5596 getTargetMachine().Options.GuaranteedTailCallOpt) 5597 ? NumBytes 5598 : 0; 5599 5600 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5601 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5602 Glue, dl); 5603 Glue = Chain.getValue(1); 5604 5605 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5606 DAG, InVals); 5607 } 5608 5609 SDValue 5610 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5611 SmallVectorImpl<SDValue> &InVals) const { 5612 SelectionDAG &DAG = CLI.DAG; 5613 SDLoc &dl = CLI.DL; 5614 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5615 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5616 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5617 SDValue Chain = CLI.Chain; 5618 SDValue Callee = CLI.Callee; 5619 bool &isTailCall = CLI.IsTailCall; 5620 CallingConv::ID CallConv = CLI.CallConv; 5621 bool isVarArg = CLI.IsVarArg; 5622 bool isPatchPoint = CLI.IsPatchPoint; 5623 const CallBase *CB = CLI.CB; 5624 5625 if (isTailCall) { 5626 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5627 isTailCall = false; 5628 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5629 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5630 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5631 else 5632 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5633 Ins, DAG); 5634 if (isTailCall) { 5635 ++NumTailCalls; 5636 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5637 ++NumSiblingCalls; 5638 5639 // PC Relative calls no longer guarantee that the callee is a Global 5640 // Address Node. The callee could be an indirect tail call in which 5641 // case the SDValue for the callee could be a load (to load the address 5642 // of a function pointer) or it may be a register copy (to move the 5643 // address of the callee from a function parameter into a virtual 5644 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5645 assert((Subtarget.isUsingPCRelativeCalls() || 5646 isa<GlobalAddressSDNode>(Callee)) && 5647 "Callee should be an llvm::Function object."); 5648 5649 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5650 << "\nTCO callee: "); 5651 LLVM_DEBUG(Callee.dump()); 5652 } 5653 } 5654 5655 if (!isTailCall && CB && CB->isMustTailCall()) 5656 report_fatal_error("failed to perform tail call elimination on a call " 5657 "site marked musttail"); 5658 5659 // When long calls (i.e. indirect calls) are always used, calls are always 5660 // made via function pointer. If we have a function name, first translate it 5661 // into a pointer. 5662 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5663 !isTailCall) 5664 Callee = LowerGlobalAddress(Callee, DAG); 5665 5666 CallFlags CFlags( 5667 CallConv, isTailCall, isVarArg, isPatchPoint, 5668 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5669 // hasNest 5670 Subtarget.is64BitELFABI() && 5671 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5672 CLI.NoMerge); 5673 5674 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5675 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5676 InVals, CB); 5677 5678 if (Subtarget.isSVR4ABI()) 5679 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5680 InVals, CB); 5681 5682 if (Subtarget.isAIXABI()) 5683 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5684 InVals, CB); 5685 5686 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5687 InVals, CB); 5688 } 5689 5690 SDValue PPCTargetLowering::LowerCall_32SVR4( 5691 SDValue Chain, SDValue Callee, CallFlags CFlags, 5692 const SmallVectorImpl<ISD::OutputArg> &Outs, 5693 const SmallVectorImpl<SDValue> &OutVals, 5694 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5695 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5696 const CallBase *CB) const { 5697 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5698 // of the 32-bit SVR4 ABI stack frame layout. 5699 5700 const CallingConv::ID CallConv = CFlags.CallConv; 5701 const bool IsVarArg = CFlags.IsVarArg; 5702 const bool IsTailCall = CFlags.IsTailCall; 5703 5704 assert((CallConv == CallingConv::C || 5705 CallConv == CallingConv::Cold || 5706 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5707 5708 unsigned PtrByteSize = 4; 5709 5710 MachineFunction &MF = DAG.getMachineFunction(); 5711 5712 // Mark this function as potentially containing a function that contains a 5713 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5714 // and restoring the callers stack pointer in this functions epilog. This is 5715 // done because by tail calling the called function might overwrite the value 5716 // in this function's (MF) stack pointer stack slot 0(SP). 5717 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5718 CallConv == CallingConv::Fast) 5719 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5720 5721 // Count how many bytes are to be pushed on the stack, including the linkage 5722 // area, parameter list area and the part of the local variable space which 5723 // contains copies of aggregates which are passed by value. 5724 5725 // Assign locations to all of the outgoing arguments. 5726 SmallVector<CCValAssign, 16> ArgLocs; 5727 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5728 5729 // Reserve space for the linkage area on the stack. 5730 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5731 PtrByteSize); 5732 if (useSoftFloat()) 5733 CCInfo.PreAnalyzeCallOperands(Outs); 5734 5735 if (IsVarArg) { 5736 // Handle fixed and variable vector arguments differently. 5737 // Fixed vector arguments go into registers as long as registers are 5738 // available. Variable vector arguments always go into memory. 5739 unsigned NumArgs = Outs.size(); 5740 5741 for (unsigned i = 0; i != NumArgs; ++i) { 5742 MVT ArgVT = Outs[i].VT; 5743 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5744 bool Result; 5745 5746 if (Outs[i].IsFixed) { 5747 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5748 CCInfo); 5749 } else { 5750 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5751 ArgFlags, CCInfo); 5752 } 5753 5754 if (Result) { 5755 #ifndef NDEBUG 5756 errs() << "Call operand #" << i << " has unhandled type " 5757 << EVT(ArgVT).getEVTString() << "\n"; 5758 #endif 5759 llvm_unreachable(nullptr); 5760 } 5761 } 5762 } else { 5763 // All arguments are treated the same. 5764 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5765 } 5766 CCInfo.clearWasPPCF128(); 5767 5768 // Assign locations to all of the outgoing aggregate by value arguments. 5769 SmallVector<CCValAssign, 16> ByValArgLocs; 5770 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5771 5772 // Reserve stack space for the allocations in CCInfo. 5773 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5774 5775 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5776 5777 // Size of the linkage area, parameter list area and the part of the local 5778 // space variable where copies of aggregates which are passed by value are 5779 // stored. 5780 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5781 5782 // Calculate by how many bytes the stack has to be adjusted in case of tail 5783 // call optimization. 5784 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5785 5786 // Adjust the stack pointer for the new arguments... 5787 // These operations are automatically eliminated by the prolog/epilog pass 5788 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5789 SDValue CallSeqStart = Chain; 5790 5791 // Load the return address and frame pointer so it can be moved somewhere else 5792 // later. 5793 SDValue LROp, FPOp; 5794 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5795 5796 // Set up a copy of the stack pointer for use loading and storing any 5797 // arguments that may not fit in the registers available for argument 5798 // passing. 5799 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5800 5801 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5802 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5803 SmallVector<SDValue, 8> MemOpChains; 5804 5805 bool seenFloatArg = false; 5806 // Walk the register/memloc assignments, inserting copies/loads. 5807 // i - Tracks the index into the list of registers allocated for the call 5808 // RealArgIdx - Tracks the index into the list of actual function arguments 5809 // j - Tracks the index into the list of byval arguments 5810 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5811 i != e; 5812 ++i, ++RealArgIdx) { 5813 CCValAssign &VA = ArgLocs[i]; 5814 SDValue Arg = OutVals[RealArgIdx]; 5815 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5816 5817 if (Flags.isByVal()) { 5818 // Argument is an aggregate which is passed by value, thus we need to 5819 // create a copy of it in the local variable space of the current stack 5820 // frame (which is the stack frame of the caller) and pass the address of 5821 // this copy to the callee. 5822 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5823 CCValAssign &ByValVA = ByValArgLocs[j++]; 5824 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5825 5826 // Memory reserved in the local variable space of the callers stack frame. 5827 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5828 5829 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5830 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5831 StackPtr, PtrOff); 5832 5833 // Create a copy of the argument in the local area of the current 5834 // stack frame. 5835 SDValue MemcpyCall = 5836 CreateCopyOfByValArgument(Arg, PtrOff, 5837 CallSeqStart.getNode()->getOperand(0), 5838 Flags, DAG, dl); 5839 5840 // This must go outside the CALLSEQ_START..END. 5841 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5842 SDLoc(MemcpyCall)); 5843 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5844 NewCallSeqStart.getNode()); 5845 Chain = CallSeqStart = NewCallSeqStart; 5846 5847 // Pass the address of the aggregate copy on the stack either in a 5848 // physical register or in the parameter list area of the current stack 5849 // frame to the callee. 5850 Arg = PtrOff; 5851 } 5852 5853 // When useCRBits() is true, there can be i1 arguments. 5854 // It is because getRegisterType(MVT::i1) => MVT::i1, 5855 // and for other integer types getRegisterType() => MVT::i32. 5856 // Extend i1 and ensure callee will get i32. 5857 if (Arg.getValueType() == MVT::i1) 5858 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5859 dl, MVT::i32, Arg); 5860 5861 if (VA.isRegLoc()) { 5862 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5863 // Put argument in a physical register. 5864 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5865 bool IsLE = Subtarget.isLittleEndian(); 5866 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5867 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5868 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5869 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5870 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5871 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5872 SVal.getValue(0))); 5873 } else 5874 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5875 } else { 5876 // Put argument in the parameter list area of the current stack frame. 5877 assert(VA.isMemLoc()); 5878 unsigned LocMemOffset = VA.getLocMemOffset(); 5879 5880 if (!IsTailCall) { 5881 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5882 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5883 StackPtr, PtrOff); 5884 5885 MemOpChains.push_back( 5886 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5887 } else { 5888 // Calculate and remember argument location. 5889 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5890 TailCallArguments); 5891 } 5892 } 5893 } 5894 5895 if (!MemOpChains.empty()) 5896 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5897 5898 // Build a sequence of copy-to-reg nodes chained together with token chain 5899 // and flag operands which copy the outgoing args into the appropriate regs. 5900 SDValue InFlag; 5901 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5902 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5903 RegsToPass[i].second, InFlag); 5904 InFlag = Chain.getValue(1); 5905 } 5906 5907 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5908 // registers. 5909 if (IsVarArg) { 5910 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5911 SDValue Ops[] = { Chain, InFlag }; 5912 5913 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5914 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5915 5916 InFlag = Chain.getValue(1); 5917 } 5918 5919 if (IsTailCall) 5920 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5921 TailCallArguments); 5922 5923 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5924 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5925 } 5926 5927 // Copy an argument into memory, being careful to do this outside the 5928 // call sequence for the call to which the argument belongs. 5929 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5930 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5931 SelectionDAG &DAG, const SDLoc &dl) const { 5932 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5933 CallSeqStart.getNode()->getOperand(0), 5934 Flags, DAG, dl); 5935 // The MEMCPY must go outside the CALLSEQ_START..END. 5936 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5937 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5938 SDLoc(MemcpyCall)); 5939 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5940 NewCallSeqStart.getNode()); 5941 return NewCallSeqStart; 5942 } 5943 5944 SDValue PPCTargetLowering::LowerCall_64SVR4( 5945 SDValue Chain, SDValue Callee, CallFlags CFlags, 5946 const SmallVectorImpl<ISD::OutputArg> &Outs, 5947 const SmallVectorImpl<SDValue> &OutVals, 5948 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5949 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5950 const CallBase *CB) const { 5951 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5952 bool isLittleEndian = Subtarget.isLittleEndian(); 5953 unsigned NumOps = Outs.size(); 5954 bool IsSibCall = false; 5955 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5956 5957 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5958 unsigned PtrByteSize = 8; 5959 5960 MachineFunction &MF = DAG.getMachineFunction(); 5961 5962 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5963 IsSibCall = true; 5964 5965 // Mark this function as potentially containing a function that contains a 5966 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5967 // and restoring the callers stack pointer in this functions epilog. This is 5968 // done because by tail calling the called function might overwrite the value 5969 // in this function's (MF) stack pointer stack slot 0(SP). 5970 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5971 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5972 5973 assert(!(IsFastCall && CFlags.IsVarArg) && 5974 "fastcc not supported on varargs functions"); 5975 5976 // Count how many bytes are to be pushed on the stack, including the linkage 5977 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5978 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5979 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5980 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5981 unsigned NumBytes = LinkageSize; 5982 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5983 unsigned &QFPR_idx = FPR_idx; 5984 5985 static const MCPhysReg GPR[] = { 5986 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5987 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5988 }; 5989 static const MCPhysReg VR[] = { 5990 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5991 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5992 }; 5993 5994 const unsigned NumGPRs = array_lengthof(GPR); 5995 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5996 const unsigned NumVRs = array_lengthof(VR); 5997 const unsigned NumQFPRs = NumFPRs; 5998 5999 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6000 // can be passed to the callee in registers. 6001 // For the fast calling convention, there is another check below. 6002 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6003 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6004 if (!HasParameterArea) { 6005 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6006 unsigned AvailableFPRs = NumFPRs; 6007 unsigned AvailableVRs = NumVRs; 6008 unsigned NumBytesTmp = NumBytes; 6009 for (unsigned i = 0; i != NumOps; ++i) { 6010 if (Outs[i].Flags.isNest()) continue; 6011 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6012 PtrByteSize, LinkageSize, ParamAreaSize, 6013 NumBytesTmp, AvailableFPRs, AvailableVRs, 6014 Subtarget.hasQPX())) 6015 HasParameterArea = true; 6016 } 6017 } 6018 6019 // When using the fast calling convention, we don't provide backing for 6020 // arguments that will be in registers. 6021 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6022 6023 // Avoid allocating parameter area for fastcc functions if all the arguments 6024 // can be passed in the registers. 6025 if (IsFastCall) 6026 HasParameterArea = false; 6027 6028 // Add up all the space actually used. 6029 for (unsigned i = 0; i != NumOps; ++i) { 6030 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6031 EVT ArgVT = Outs[i].VT; 6032 EVT OrigVT = Outs[i].ArgVT; 6033 6034 if (Flags.isNest()) 6035 continue; 6036 6037 if (IsFastCall) { 6038 if (Flags.isByVal()) { 6039 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6040 if (NumGPRsUsed > NumGPRs) 6041 HasParameterArea = true; 6042 } else { 6043 switch (ArgVT.getSimpleVT().SimpleTy) { 6044 default: llvm_unreachable("Unexpected ValueType for argument!"); 6045 case MVT::i1: 6046 case MVT::i32: 6047 case MVT::i64: 6048 if (++NumGPRsUsed <= NumGPRs) 6049 continue; 6050 break; 6051 case MVT::v4i32: 6052 case MVT::v8i16: 6053 case MVT::v16i8: 6054 case MVT::v2f64: 6055 case MVT::v2i64: 6056 case MVT::v1i128: 6057 case MVT::f128: 6058 if (++NumVRsUsed <= NumVRs) 6059 continue; 6060 break; 6061 case MVT::v4f32: 6062 // When using QPX, this is handled like a FP register, otherwise, it 6063 // is an Altivec register. 6064 if (Subtarget.hasQPX()) { 6065 if (++NumFPRsUsed <= NumFPRs) 6066 continue; 6067 } else { 6068 if (++NumVRsUsed <= NumVRs) 6069 continue; 6070 } 6071 break; 6072 case MVT::f32: 6073 case MVT::f64: 6074 case MVT::v4f64: // QPX 6075 case MVT::v4i1: // QPX 6076 if (++NumFPRsUsed <= NumFPRs) 6077 continue; 6078 break; 6079 } 6080 HasParameterArea = true; 6081 } 6082 } 6083 6084 /* Respect alignment of argument on the stack. */ 6085 auto Alignement = 6086 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6087 NumBytes = alignTo(NumBytes, Alignement); 6088 6089 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6090 if (Flags.isInConsecutiveRegsLast()) 6091 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6092 } 6093 6094 unsigned NumBytesActuallyUsed = NumBytes; 6095 6096 // In the old ELFv1 ABI, 6097 // the prolog code of the callee may store up to 8 GPR argument registers to 6098 // the stack, allowing va_start to index over them in memory if its varargs. 6099 // Because we cannot tell if this is needed on the caller side, we have to 6100 // conservatively assume that it is needed. As such, make sure we have at 6101 // least enough stack space for the caller to store the 8 GPRs. 6102 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6103 // really requires memory operands, e.g. a vararg function. 6104 if (HasParameterArea) 6105 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6106 else 6107 NumBytes = LinkageSize; 6108 6109 // Tail call needs the stack to be aligned. 6110 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6111 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6112 6113 int SPDiff = 0; 6114 6115 // Calculate by how many bytes the stack has to be adjusted in case of tail 6116 // call optimization. 6117 if (!IsSibCall) 6118 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6119 6120 // To protect arguments on the stack from being clobbered in a tail call, 6121 // force all the loads to happen before doing any other lowering. 6122 if (CFlags.IsTailCall) 6123 Chain = DAG.getStackArgumentTokenFactor(Chain); 6124 6125 // Adjust the stack pointer for the new arguments... 6126 // These operations are automatically eliminated by the prolog/epilog pass 6127 if (!IsSibCall) 6128 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6129 SDValue CallSeqStart = Chain; 6130 6131 // Load the return address and frame pointer so it can be move somewhere else 6132 // later. 6133 SDValue LROp, FPOp; 6134 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6135 6136 // Set up a copy of the stack pointer for use loading and storing any 6137 // arguments that may not fit in the registers available for argument 6138 // passing. 6139 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6140 6141 // Figure out which arguments are going to go in registers, and which in 6142 // memory. Also, if this is a vararg function, floating point operations 6143 // must be stored to our stack, and loaded into integer regs as well, if 6144 // any integer regs are available for argument passing. 6145 unsigned ArgOffset = LinkageSize; 6146 6147 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6148 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6149 6150 SmallVector<SDValue, 8> MemOpChains; 6151 for (unsigned i = 0; i != NumOps; ++i) { 6152 SDValue Arg = OutVals[i]; 6153 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6154 EVT ArgVT = Outs[i].VT; 6155 EVT OrigVT = Outs[i].ArgVT; 6156 6157 // PtrOff will be used to store the current argument to the stack if a 6158 // register cannot be found for it. 6159 SDValue PtrOff; 6160 6161 // We re-align the argument offset for each argument, except when using the 6162 // fast calling convention, when we need to make sure we do that only when 6163 // we'll actually use a stack slot. 6164 auto ComputePtrOff = [&]() { 6165 /* Respect alignment of argument on the stack. */ 6166 auto Alignment = 6167 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6168 ArgOffset = alignTo(ArgOffset, Alignment); 6169 6170 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6171 6172 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6173 }; 6174 6175 if (!IsFastCall) { 6176 ComputePtrOff(); 6177 6178 /* Compute GPR index associated with argument offset. */ 6179 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6180 GPR_idx = std::min(GPR_idx, NumGPRs); 6181 } 6182 6183 // Promote integers to 64-bit values. 6184 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6185 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6186 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6187 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6188 } 6189 6190 // FIXME memcpy is used way more than necessary. Correctness first. 6191 // Note: "by value" is code for passing a structure by value, not 6192 // basic types. 6193 if (Flags.isByVal()) { 6194 // Note: Size includes alignment padding, so 6195 // struct x { short a; char b; } 6196 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6197 // These are the proper values we need for right-justifying the 6198 // aggregate in a parameter register. 6199 unsigned Size = Flags.getByValSize(); 6200 6201 // An empty aggregate parameter takes up no storage and no 6202 // registers. 6203 if (Size == 0) 6204 continue; 6205 6206 if (IsFastCall) 6207 ComputePtrOff(); 6208 6209 // All aggregates smaller than 8 bytes must be passed right-justified. 6210 if (Size==1 || Size==2 || Size==4) { 6211 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6212 if (GPR_idx != NumGPRs) { 6213 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6214 MachinePointerInfo(), VT); 6215 MemOpChains.push_back(Load.getValue(1)); 6216 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6217 6218 ArgOffset += PtrByteSize; 6219 continue; 6220 } 6221 } 6222 6223 if (GPR_idx == NumGPRs && Size < 8) { 6224 SDValue AddPtr = PtrOff; 6225 if (!isLittleEndian) { 6226 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6227 PtrOff.getValueType()); 6228 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6229 } 6230 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6231 CallSeqStart, 6232 Flags, DAG, dl); 6233 ArgOffset += PtrByteSize; 6234 continue; 6235 } 6236 // Copy entire object into memory. There are cases where gcc-generated 6237 // code assumes it is there, even if it could be put entirely into 6238 // registers. (This is not what the doc says.) 6239 6240 // FIXME: The above statement is likely due to a misunderstanding of the 6241 // documents. All arguments must be copied into the parameter area BY 6242 // THE CALLEE in the event that the callee takes the address of any 6243 // formal argument. That has not yet been implemented. However, it is 6244 // reasonable to use the stack area as a staging area for the register 6245 // load. 6246 6247 // Skip this for small aggregates, as we will use the same slot for a 6248 // right-justified copy, below. 6249 if (Size >= 8) 6250 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6251 CallSeqStart, 6252 Flags, DAG, dl); 6253 6254 // When a register is available, pass a small aggregate right-justified. 6255 if (Size < 8 && GPR_idx != NumGPRs) { 6256 // The easiest way to get this right-justified in a register 6257 // is to copy the structure into the rightmost portion of a 6258 // local variable slot, then load the whole slot into the 6259 // register. 6260 // FIXME: The memcpy seems to produce pretty awful code for 6261 // small aggregates, particularly for packed ones. 6262 // FIXME: It would be preferable to use the slot in the 6263 // parameter save area instead of a new local variable. 6264 SDValue AddPtr = PtrOff; 6265 if (!isLittleEndian) { 6266 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6267 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6268 } 6269 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6270 CallSeqStart, 6271 Flags, DAG, dl); 6272 6273 // Load the slot into the register. 6274 SDValue Load = 6275 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6276 MemOpChains.push_back(Load.getValue(1)); 6277 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6278 6279 // Done with this argument. 6280 ArgOffset += PtrByteSize; 6281 continue; 6282 } 6283 6284 // For aggregates larger than PtrByteSize, copy the pieces of the 6285 // object that fit into registers from the parameter save area. 6286 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6287 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6288 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6289 if (GPR_idx != NumGPRs) { 6290 SDValue Load = 6291 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6292 MemOpChains.push_back(Load.getValue(1)); 6293 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6294 ArgOffset += PtrByteSize; 6295 } else { 6296 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6297 break; 6298 } 6299 } 6300 continue; 6301 } 6302 6303 switch (Arg.getSimpleValueType().SimpleTy) { 6304 default: llvm_unreachable("Unexpected ValueType for argument!"); 6305 case MVT::i1: 6306 case MVT::i32: 6307 case MVT::i64: 6308 if (Flags.isNest()) { 6309 // The 'nest' parameter, if any, is passed in R11. 6310 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6311 break; 6312 } 6313 6314 // These can be scalar arguments or elements of an integer array type 6315 // passed directly. Clang may use those instead of "byval" aggregate 6316 // types to avoid forcing arguments to memory unnecessarily. 6317 if (GPR_idx != NumGPRs) { 6318 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6319 } else { 6320 if (IsFastCall) 6321 ComputePtrOff(); 6322 6323 assert(HasParameterArea && 6324 "Parameter area must exist to pass an argument in memory."); 6325 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6326 true, CFlags.IsTailCall, false, MemOpChains, 6327 TailCallArguments, dl); 6328 if (IsFastCall) 6329 ArgOffset += PtrByteSize; 6330 } 6331 if (!IsFastCall) 6332 ArgOffset += PtrByteSize; 6333 break; 6334 case MVT::f32: 6335 case MVT::f64: { 6336 // These can be scalar arguments or elements of a float array type 6337 // passed directly. The latter are used to implement ELFv2 homogenous 6338 // float aggregates. 6339 6340 // Named arguments go into FPRs first, and once they overflow, the 6341 // remaining arguments go into GPRs and then the parameter save area. 6342 // Unnamed arguments for vararg functions always go to GPRs and 6343 // then the parameter save area. For now, put all arguments to vararg 6344 // routines always in both locations (FPR *and* GPR or stack slot). 6345 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6346 bool NeededLoad = false; 6347 6348 // First load the argument into the next available FPR. 6349 if (FPR_idx != NumFPRs) 6350 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6351 6352 // Next, load the argument into GPR or stack slot if needed. 6353 if (!NeedGPROrStack) 6354 ; 6355 else if (GPR_idx != NumGPRs && !IsFastCall) { 6356 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6357 // once we support fp <-> gpr moves. 6358 6359 // In the non-vararg case, this can only ever happen in the 6360 // presence of f32 array types, since otherwise we never run 6361 // out of FPRs before running out of GPRs. 6362 SDValue ArgVal; 6363 6364 // Double values are always passed in a single GPR. 6365 if (Arg.getValueType() != MVT::f32) { 6366 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6367 6368 // Non-array float values are extended and passed in a GPR. 6369 } else if (!Flags.isInConsecutiveRegs()) { 6370 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6371 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6372 6373 // If we have an array of floats, we collect every odd element 6374 // together with its predecessor into one GPR. 6375 } else if (ArgOffset % PtrByteSize != 0) { 6376 SDValue Lo, Hi; 6377 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6378 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6379 if (!isLittleEndian) 6380 std::swap(Lo, Hi); 6381 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6382 6383 // The final element, if even, goes into the first half of a GPR. 6384 } else if (Flags.isInConsecutiveRegsLast()) { 6385 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6386 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6387 if (!isLittleEndian) 6388 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6389 DAG.getConstant(32, dl, MVT::i32)); 6390 6391 // Non-final even elements are skipped; they will be handled 6392 // together the with subsequent argument on the next go-around. 6393 } else 6394 ArgVal = SDValue(); 6395 6396 if (ArgVal.getNode()) 6397 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6398 } else { 6399 if (IsFastCall) 6400 ComputePtrOff(); 6401 6402 // Single-precision floating-point values are mapped to the 6403 // second (rightmost) word of the stack doubleword. 6404 if (Arg.getValueType() == MVT::f32 && 6405 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6406 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6407 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6408 } 6409 6410 assert(HasParameterArea && 6411 "Parameter area must exist to pass an argument in memory."); 6412 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6413 true, CFlags.IsTailCall, false, MemOpChains, 6414 TailCallArguments, dl); 6415 6416 NeededLoad = true; 6417 } 6418 // When passing an array of floats, the array occupies consecutive 6419 // space in the argument area; only round up to the next doubleword 6420 // at the end of the array. Otherwise, each float takes 8 bytes. 6421 if (!IsFastCall || NeededLoad) { 6422 ArgOffset += (Arg.getValueType() == MVT::f32 && 6423 Flags.isInConsecutiveRegs()) ? 4 : 8; 6424 if (Flags.isInConsecutiveRegsLast()) 6425 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6426 } 6427 break; 6428 } 6429 case MVT::v4f32: 6430 case MVT::v4i32: 6431 case MVT::v8i16: 6432 case MVT::v16i8: 6433 case MVT::v2f64: 6434 case MVT::v2i64: 6435 case MVT::v1i128: 6436 case MVT::f128: 6437 if (!Subtarget.hasQPX()) { 6438 // These can be scalar arguments or elements of a vector array type 6439 // passed directly. The latter are used to implement ELFv2 homogenous 6440 // vector aggregates. 6441 6442 // For a varargs call, named arguments go into VRs or on the stack as 6443 // usual; unnamed arguments always go to the stack or the corresponding 6444 // GPRs when within range. For now, we always put the value in both 6445 // locations (or even all three). 6446 if (CFlags.IsVarArg) { 6447 assert(HasParameterArea && 6448 "Parameter area must exist if we have a varargs call."); 6449 // We could elide this store in the case where the object fits 6450 // entirely in R registers. Maybe later. 6451 SDValue Store = 6452 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6453 MemOpChains.push_back(Store); 6454 if (VR_idx != NumVRs) { 6455 SDValue Load = 6456 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6457 MemOpChains.push_back(Load.getValue(1)); 6458 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6459 } 6460 ArgOffset += 16; 6461 for (unsigned i=0; i<16; i+=PtrByteSize) { 6462 if (GPR_idx == NumGPRs) 6463 break; 6464 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6465 DAG.getConstant(i, dl, PtrVT)); 6466 SDValue Load = 6467 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6468 MemOpChains.push_back(Load.getValue(1)); 6469 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6470 } 6471 break; 6472 } 6473 6474 // Non-varargs Altivec params go into VRs or on the stack. 6475 if (VR_idx != NumVRs) { 6476 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6477 } else { 6478 if (IsFastCall) 6479 ComputePtrOff(); 6480 6481 assert(HasParameterArea && 6482 "Parameter area must exist to pass an argument in memory."); 6483 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6484 true, CFlags.IsTailCall, true, MemOpChains, 6485 TailCallArguments, dl); 6486 if (IsFastCall) 6487 ArgOffset += 16; 6488 } 6489 6490 if (!IsFastCall) 6491 ArgOffset += 16; 6492 break; 6493 } // not QPX 6494 6495 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6496 "Invalid QPX parameter type"); 6497 6498 LLVM_FALLTHROUGH; 6499 case MVT::v4f64: 6500 case MVT::v4i1: { 6501 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6502 if (CFlags.IsVarArg) { 6503 assert(HasParameterArea && 6504 "Parameter area must exist if we have a varargs call."); 6505 // We could elide this store in the case where the object fits 6506 // entirely in R registers. Maybe later. 6507 SDValue Store = 6508 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6509 MemOpChains.push_back(Store); 6510 if (QFPR_idx != NumQFPRs) { 6511 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6512 PtrOff, MachinePointerInfo()); 6513 MemOpChains.push_back(Load.getValue(1)); 6514 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6515 } 6516 ArgOffset += (IsF32 ? 16 : 32); 6517 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6518 if (GPR_idx == NumGPRs) 6519 break; 6520 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6521 DAG.getConstant(i, dl, PtrVT)); 6522 SDValue Load = 6523 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6524 MemOpChains.push_back(Load.getValue(1)); 6525 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6526 } 6527 break; 6528 } 6529 6530 // Non-varargs QPX params go into registers or on the stack. 6531 if (QFPR_idx != NumQFPRs) { 6532 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6533 } else { 6534 if (IsFastCall) 6535 ComputePtrOff(); 6536 6537 assert(HasParameterArea && 6538 "Parameter area must exist to pass an argument in memory."); 6539 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6540 true, CFlags.IsTailCall, true, MemOpChains, 6541 TailCallArguments, dl); 6542 if (IsFastCall) 6543 ArgOffset += (IsF32 ? 16 : 32); 6544 } 6545 6546 if (!IsFastCall) 6547 ArgOffset += (IsF32 ? 16 : 32); 6548 break; 6549 } 6550 } 6551 } 6552 6553 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6554 "mismatch in size of parameter area"); 6555 (void)NumBytesActuallyUsed; 6556 6557 if (!MemOpChains.empty()) 6558 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6559 6560 // Check if this is an indirect call (MTCTR/BCTRL). 6561 // See prepareDescriptorIndirectCall and buildCallOperands for more 6562 // information about calls through function pointers in the 64-bit SVR4 ABI. 6563 if (CFlags.IsIndirect) { 6564 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6565 // caller in the TOC save area. 6566 if (isTOCSaveRestoreRequired(Subtarget)) { 6567 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6568 // Load r2 into a virtual register and store it to the TOC save area. 6569 setUsesTOCBasePtr(DAG); 6570 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6571 // TOC save area offset. 6572 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6573 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6574 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6575 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6576 MachinePointerInfo::getStack( 6577 DAG.getMachineFunction(), TOCSaveOffset)); 6578 } 6579 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6580 // This does not mean the MTCTR instruction must use R12; it's easier 6581 // to model this as an extra parameter, so do that. 6582 if (isELFv2ABI && !CFlags.IsPatchPoint) 6583 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6584 } 6585 6586 // Build a sequence of copy-to-reg nodes chained together with token chain 6587 // and flag operands which copy the outgoing args into the appropriate regs. 6588 SDValue InFlag; 6589 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6590 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6591 RegsToPass[i].second, InFlag); 6592 InFlag = Chain.getValue(1); 6593 } 6594 6595 if (CFlags.IsTailCall && !IsSibCall) 6596 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6597 TailCallArguments); 6598 6599 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6600 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6601 } 6602 6603 SDValue PPCTargetLowering::LowerCall_Darwin( 6604 SDValue Chain, SDValue Callee, CallFlags CFlags, 6605 const SmallVectorImpl<ISD::OutputArg> &Outs, 6606 const SmallVectorImpl<SDValue> &OutVals, 6607 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6608 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6609 const CallBase *CB) const { 6610 unsigned NumOps = Outs.size(); 6611 6612 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6613 bool isPPC64 = PtrVT == MVT::i64; 6614 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6615 6616 MachineFunction &MF = DAG.getMachineFunction(); 6617 6618 // Mark this function as potentially containing a function that contains a 6619 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6620 // and restoring the callers stack pointer in this functions epilog. This is 6621 // done because by tail calling the called function might overwrite the value 6622 // in this function's (MF) stack pointer stack slot 0(SP). 6623 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6624 CFlags.CallConv == CallingConv::Fast) 6625 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6626 6627 // Count how many bytes are to be pushed on the stack, including the linkage 6628 // area, and parameter passing area. We start with 24/48 bytes, which is 6629 // prereserved space for [SP][CR][LR][3 x unused]. 6630 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6631 unsigned NumBytes = LinkageSize; 6632 6633 // Add up all the space actually used. 6634 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6635 // they all go in registers, but we must reserve stack space for them for 6636 // possible use by the caller. In varargs or 64-bit calls, parameters are 6637 // assigned stack space in order, with padding so Altivec parameters are 6638 // 16-byte aligned. 6639 unsigned nAltivecParamsAtEnd = 0; 6640 for (unsigned i = 0; i != NumOps; ++i) { 6641 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6642 EVT ArgVT = Outs[i].VT; 6643 // Varargs Altivec parameters are padded to a 16 byte boundary. 6644 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6645 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6646 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6647 if (!CFlags.IsVarArg && !isPPC64) { 6648 // Non-varargs Altivec parameters go after all the non-Altivec 6649 // parameters; handle those later so we know how much padding we need. 6650 nAltivecParamsAtEnd++; 6651 continue; 6652 } 6653 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6654 NumBytes = ((NumBytes+15)/16)*16; 6655 } 6656 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6657 } 6658 6659 // Allow for Altivec parameters at the end, if needed. 6660 if (nAltivecParamsAtEnd) { 6661 NumBytes = ((NumBytes+15)/16)*16; 6662 NumBytes += 16*nAltivecParamsAtEnd; 6663 } 6664 6665 // The prolog code of the callee may store up to 8 GPR argument registers to 6666 // the stack, allowing va_start to index over them in memory if its varargs. 6667 // Because we cannot tell if this is needed on the caller side, we have to 6668 // conservatively assume that it is needed. As such, make sure we have at 6669 // least enough stack space for the caller to store the 8 GPRs. 6670 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6671 6672 // Tail call needs the stack to be aligned. 6673 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6674 CFlags.CallConv == CallingConv::Fast) 6675 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6676 6677 // Calculate by how many bytes the stack has to be adjusted in case of tail 6678 // call optimization. 6679 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6680 6681 // To protect arguments on the stack from being clobbered in a tail call, 6682 // force all the loads to happen before doing any other lowering. 6683 if (CFlags.IsTailCall) 6684 Chain = DAG.getStackArgumentTokenFactor(Chain); 6685 6686 // Adjust the stack pointer for the new arguments... 6687 // These operations are automatically eliminated by the prolog/epilog pass 6688 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6689 SDValue CallSeqStart = Chain; 6690 6691 // Load the return address and frame pointer so it can be move somewhere else 6692 // later. 6693 SDValue LROp, FPOp; 6694 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6695 6696 // Set up a copy of the stack pointer for use loading and storing any 6697 // arguments that may not fit in the registers available for argument 6698 // passing. 6699 SDValue StackPtr; 6700 if (isPPC64) 6701 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6702 else 6703 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6704 6705 // Figure out which arguments are going to go in registers, and which in 6706 // memory. Also, if this is a vararg function, floating point operations 6707 // must be stored to our stack, and loaded into integer regs as well, if 6708 // any integer regs are available for argument passing. 6709 unsigned ArgOffset = LinkageSize; 6710 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6711 6712 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6713 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6714 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6715 }; 6716 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6717 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6718 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6719 }; 6720 static const MCPhysReg VR[] = { 6721 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6722 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6723 }; 6724 const unsigned NumGPRs = array_lengthof(GPR_32); 6725 const unsigned NumFPRs = 13; 6726 const unsigned NumVRs = array_lengthof(VR); 6727 6728 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6729 6730 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6731 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6732 6733 SmallVector<SDValue, 8> MemOpChains; 6734 for (unsigned i = 0; i != NumOps; ++i) { 6735 SDValue Arg = OutVals[i]; 6736 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6737 6738 // PtrOff will be used to store the current argument to the stack if a 6739 // register cannot be found for it. 6740 SDValue PtrOff; 6741 6742 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6743 6744 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6745 6746 // On PPC64, promote integers to 64-bit values. 6747 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6748 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6749 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6750 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6751 } 6752 6753 // FIXME memcpy is used way more than necessary. Correctness first. 6754 // Note: "by value" is code for passing a structure by value, not 6755 // basic types. 6756 if (Flags.isByVal()) { 6757 unsigned Size = Flags.getByValSize(); 6758 // Very small objects are passed right-justified. Everything else is 6759 // passed left-justified. 6760 if (Size==1 || Size==2) { 6761 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6762 if (GPR_idx != NumGPRs) { 6763 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6764 MachinePointerInfo(), VT); 6765 MemOpChains.push_back(Load.getValue(1)); 6766 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6767 6768 ArgOffset += PtrByteSize; 6769 } else { 6770 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6771 PtrOff.getValueType()); 6772 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6773 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6774 CallSeqStart, 6775 Flags, DAG, dl); 6776 ArgOffset += PtrByteSize; 6777 } 6778 continue; 6779 } 6780 // Copy entire object into memory. There are cases where gcc-generated 6781 // code assumes it is there, even if it could be put entirely into 6782 // registers. (This is not what the doc says.) 6783 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6784 CallSeqStart, 6785 Flags, DAG, dl); 6786 6787 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6788 // copy the pieces of the object that fit into registers from the 6789 // parameter save area. 6790 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6791 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6792 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6793 if (GPR_idx != NumGPRs) { 6794 SDValue Load = 6795 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6796 MemOpChains.push_back(Load.getValue(1)); 6797 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6798 ArgOffset += PtrByteSize; 6799 } else { 6800 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6801 break; 6802 } 6803 } 6804 continue; 6805 } 6806 6807 switch (Arg.getSimpleValueType().SimpleTy) { 6808 default: llvm_unreachable("Unexpected ValueType for argument!"); 6809 case MVT::i1: 6810 case MVT::i32: 6811 case MVT::i64: 6812 if (GPR_idx != NumGPRs) { 6813 if (Arg.getValueType() == MVT::i1) 6814 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6815 6816 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6817 } else { 6818 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6819 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6820 TailCallArguments, dl); 6821 } 6822 ArgOffset += PtrByteSize; 6823 break; 6824 case MVT::f32: 6825 case MVT::f64: 6826 if (FPR_idx != NumFPRs) { 6827 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6828 6829 if (CFlags.IsVarArg) { 6830 SDValue Store = 6831 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6832 MemOpChains.push_back(Store); 6833 6834 // Float varargs are always shadowed in available integer registers 6835 if (GPR_idx != NumGPRs) { 6836 SDValue Load = 6837 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6838 MemOpChains.push_back(Load.getValue(1)); 6839 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6840 } 6841 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6842 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6843 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6844 SDValue Load = 6845 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6846 MemOpChains.push_back(Load.getValue(1)); 6847 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6848 } 6849 } else { 6850 // If we have any FPRs remaining, we may also have GPRs remaining. 6851 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6852 // GPRs. 6853 if (GPR_idx != NumGPRs) 6854 ++GPR_idx; 6855 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6856 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6857 ++GPR_idx; 6858 } 6859 } else 6860 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6861 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6862 TailCallArguments, dl); 6863 if (isPPC64) 6864 ArgOffset += 8; 6865 else 6866 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6867 break; 6868 case MVT::v4f32: 6869 case MVT::v4i32: 6870 case MVT::v8i16: 6871 case MVT::v16i8: 6872 if (CFlags.IsVarArg) { 6873 // These go aligned on the stack, or in the corresponding R registers 6874 // when within range. The Darwin PPC ABI doc claims they also go in 6875 // V registers; in fact gcc does this only for arguments that are 6876 // prototyped, not for those that match the ... We do it for all 6877 // arguments, seems to work. 6878 while (ArgOffset % 16 !=0) { 6879 ArgOffset += PtrByteSize; 6880 if (GPR_idx != NumGPRs) 6881 GPR_idx++; 6882 } 6883 // We could elide this store in the case where the object fits 6884 // entirely in R registers. Maybe later. 6885 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6886 DAG.getConstant(ArgOffset, dl, PtrVT)); 6887 SDValue Store = 6888 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6889 MemOpChains.push_back(Store); 6890 if (VR_idx != NumVRs) { 6891 SDValue Load = 6892 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6893 MemOpChains.push_back(Load.getValue(1)); 6894 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6895 } 6896 ArgOffset += 16; 6897 for (unsigned i=0; i<16; i+=PtrByteSize) { 6898 if (GPR_idx == NumGPRs) 6899 break; 6900 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6901 DAG.getConstant(i, dl, PtrVT)); 6902 SDValue Load = 6903 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6904 MemOpChains.push_back(Load.getValue(1)); 6905 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6906 } 6907 break; 6908 } 6909 6910 // Non-varargs Altivec params generally go in registers, but have 6911 // stack space allocated at the end. 6912 if (VR_idx != NumVRs) { 6913 // Doesn't have GPR space allocated. 6914 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6915 } else if (nAltivecParamsAtEnd==0) { 6916 // We are emitting Altivec params in order. 6917 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6918 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6919 TailCallArguments, dl); 6920 ArgOffset += 16; 6921 } 6922 break; 6923 } 6924 } 6925 // If all Altivec parameters fit in registers, as they usually do, 6926 // they get stack space following the non-Altivec parameters. We 6927 // don't track this here because nobody below needs it. 6928 // If there are more Altivec parameters than fit in registers emit 6929 // the stores here. 6930 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6931 unsigned j = 0; 6932 // Offset is aligned; skip 1st 12 params which go in V registers. 6933 ArgOffset = ((ArgOffset+15)/16)*16; 6934 ArgOffset += 12*16; 6935 for (unsigned i = 0; i != NumOps; ++i) { 6936 SDValue Arg = OutVals[i]; 6937 EVT ArgType = Outs[i].VT; 6938 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6939 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6940 if (++j > NumVRs) { 6941 SDValue PtrOff; 6942 // We are emitting Altivec params in order. 6943 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6944 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6945 TailCallArguments, dl); 6946 ArgOffset += 16; 6947 } 6948 } 6949 } 6950 } 6951 6952 if (!MemOpChains.empty()) 6953 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6954 6955 // On Darwin, R12 must contain the address of an indirect callee. This does 6956 // not mean the MTCTR instruction must use R12; it's easier to model this as 6957 // an extra parameter, so do that. 6958 if (CFlags.IsIndirect) { 6959 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6960 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6961 PPC::R12), Callee)); 6962 } 6963 6964 // Build a sequence of copy-to-reg nodes chained together with token chain 6965 // and flag operands which copy the outgoing args into the appropriate regs. 6966 SDValue InFlag; 6967 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6968 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6969 RegsToPass[i].second, InFlag); 6970 InFlag = Chain.getValue(1); 6971 } 6972 6973 if (CFlags.IsTailCall) 6974 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6975 TailCallArguments); 6976 6977 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6978 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6979 } 6980 6981 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6982 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6983 CCState &State) { 6984 6985 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6986 State.getMachineFunction().getSubtarget()); 6987 const bool IsPPC64 = Subtarget.isPPC64(); 6988 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6989 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6990 6991 assert((!ValVT.isInteger() || 6992 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6993 "Integer argument exceeds register size: should have been legalized"); 6994 6995 if (ValVT == MVT::f128) 6996 report_fatal_error("f128 is unimplemented on AIX."); 6997 6998 if (ArgFlags.isNest()) 6999 report_fatal_error("Nest arguments are unimplemented."); 7000 7001 if (ValVT.isVector() || LocVT.isVector()) 7002 report_fatal_error("Vector arguments are unimplemented on AIX."); 7003 7004 static const MCPhysReg GPR_32[] = {// 32-bit registers. 7005 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7006 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7007 static const MCPhysReg GPR_64[] = {// 64-bit registers. 7008 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7009 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7010 7011 if (ArgFlags.isByVal()) { 7012 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 7013 report_fatal_error("Pass-by-value arguments with alignment greater than " 7014 "register width are not supported."); 7015 7016 const unsigned ByValSize = ArgFlags.getByValSize(); 7017 7018 // An empty aggregate parameter takes up no storage and no registers, 7019 // but needs a MemLoc for a stack slot for the formal arguments side. 7020 if (ByValSize == 0) { 7021 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7022 State.getNextStackOffset(), RegVT, 7023 LocInfo)); 7024 return false; 7025 } 7026 7027 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 7028 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 7029 for (const unsigned E = Offset + StackSize; Offset < E; 7030 Offset += PtrByteSize) { 7031 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7032 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7033 else { 7034 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7035 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7036 LocInfo)); 7037 break; 7038 } 7039 } 7040 return false; 7041 } 7042 7043 // Arguments always reserve parameter save area. 7044 switch (ValVT.SimpleTy) { 7045 default: 7046 report_fatal_error("Unhandled value type for argument."); 7047 case MVT::i64: 7048 // i64 arguments should have been split to i32 for PPC32. 7049 assert(IsPPC64 && "PPC32 should have split i64 values."); 7050 LLVM_FALLTHROUGH; 7051 case MVT::i1: 7052 case MVT::i32: { 7053 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 7054 // AIX integer arguments are always passed in register width. 7055 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7056 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7057 : CCValAssign::LocInfo::ZExt; 7058 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7059 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7060 else 7061 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7062 7063 return false; 7064 } 7065 case MVT::f32: 7066 case MVT::f64: { 7067 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7068 const unsigned StoreSize = LocVT.getStoreSize(); 7069 // Floats are always 4-byte aligned in the PSA on AIX. 7070 // This includes f64 in 64-bit mode for ABI compatibility. 7071 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 7072 unsigned FReg = State.AllocateReg(FPR); 7073 if (FReg) 7074 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7075 7076 // Reserve and initialize GPRs or initialize the PSA as required. 7077 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 7078 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7079 assert(FReg && "An FPR should be available when a GPR is reserved."); 7080 if (State.isVarArg()) { 7081 // Successfully reserved GPRs are only initialized for vararg calls. 7082 // Custom handling is required for: 7083 // f64 in PPC32 needs to be split into 2 GPRs. 7084 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7085 State.addLoc( 7086 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7087 } 7088 } else { 7089 // If there are insufficient GPRs, the PSA needs to be initialized. 7090 // Initialization occurs even if an FPR was initialized for 7091 // compatibility with the AIX XL compiler. The full memory for the 7092 // argument will be initialized even if a prior word is saved in GPR. 7093 // A custom memLoc is used when the argument also passes in FPR so 7094 // that the callee handling can skip over it easily. 7095 State.addLoc( 7096 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7097 LocInfo) 7098 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7099 break; 7100 } 7101 } 7102 7103 return false; 7104 } 7105 } 7106 return true; 7107 } 7108 7109 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7110 bool IsPPC64) { 7111 assert((IsPPC64 || SVT != MVT::i64) && 7112 "i64 should have been split for 32-bit codegen."); 7113 7114 switch (SVT) { 7115 default: 7116 report_fatal_error("Unexpected value type for formal argument"); 7117 case MVT::i1: 7118 case MVT::i32: 7119 case MVT::i64: 7120 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7121 case MVT::f32: 7122 return &PPC::F4RCRegClass; 7123 case MVT::f64: 7124 return &PPC::F8RCRegClass; 7125 } 7126 } 7127 7128 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7129 SelectionDAG &DAG, SDValue ArgValue, 7130 MVT LocVT, const SDLoc &dl) { 7131 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7132 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7133 7134 if (Flags.isSExt()) 7135 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7136 DAG.getValueType(ValVT)); 7137 else if (Flags.isZExt()) 7138 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7139 DAG.getValueType(ValVT)); 7140 7141 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7142 } 7143 7144 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7145 const unsigned LASize = FL->getLinkageSize(); 7146 7147 if (PPC::GPRCRegClass.contains(Reg)) { 7148 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7149 "Reg must be a valid argument register!"); 7150 return LASize + 4 * (Reg - PPC::R3); 7151 } 7152 7153 if (PPC::G8RCRegClass.contains(Reg)) { 7154 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7155 "Reg must be a valid argument register!"); 7156 return LASize + 8 * (Reg - PPC::X3); 7157 } 7158 7159 llvm_unreachable("Only general purpose registers expected."); 7160 } 7161 7162 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7163 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7164 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7165 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7166 7167 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7168 CallConv == CallingConv::Fast) && 7169 "Unexpected calling convention!"); 7170 7171 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7172 report_fatal_error("Tail call support is unimplemented on AIX."); 7173 7174 if (useSoftFloat()) 7175 report_fatal_error("Soft float support is unimplemented on AIX."); 7176 7177 const PPCSubtarget &Subtarget = 7178 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7179 if (Subtarget.hasQPX()) 7180 report_fatal_error("QPX support is not supported on AIX."); 7181 7182 const bool IsPPC64 = Subtarget.isPPC64(); 7183 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7184 7185 // Assign locations to all of the incoming arguments. 7186 SmallVector<CCValAssign, 16> ArgLocs; 7187 MachineFunction &MF = DAG.getMachineFunction(); 7188 MachineFrameInfo &MFI = MF.getFrameInfo(); 7189 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7190 7191 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7192 // Reserve space for the linkage area on the stack. 7193 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7194 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7195 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7196 7197 SmallVector<SDValue, 8> MemOps; 7198 7199 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7200 CCValAssign &VA = ArgLocs[I++]; 7201 MVT LocVT = VA.getLocVT(); 7202 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7203 7204 // For compatibility with the AIX XL compiler, the float args in the 7205 // parameter save area are initialized even if the argument is available 7206 // in register. The caller is required to initialize both the register 7207 // and memory, however, the callee can choose to expect it in either. 7208 // The memloc is dismissed here because the argument is retrieved from 7209 // the register. 7210 if (VA.isMemLoc() && VA.needsCustom()) 7211 continue; 7212 7213 if (Flags.isByVal() && VA.isMemLoc()) { 7214 const unsigned Size = 7215 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7216 PtrByteSize); 7217 const int FI = MF.getFrameInfo().CreateFixedObject( 7218 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7219 /* IsAliased */ true); 7220 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7221 InVals.push_back(FIN); 7222 7223 continue; 7224 } 7225 7226 if (Flags.isByVal()) { 7227 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7228 7229 const MCPhysReg ArgReg = VA.getLocReg(); 7230 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7231 7232 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7233 report_fatal_error("Over aligned byvals not supported yet."); 7234 7235 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7236 const int FI = MF.getFrameInfo().CreateFixedObject( 7237 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7238 /* IsAliased */ true); 7239 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7240 InVals.push_back(FIN); 7241 7242 // Add live ins for all the RegLocs for the same ByVal. 7243 const TargetRegisterClass *RegClass = 7244 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7245 7246 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7247 unsigned Offset) { 7248 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7249 // Since the callers side has left justified the aggregate in the 7250 // register, we can simply store the entire register into the stack 7251 // slot. 7252 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7253 // The store to the fixedstack object is needed becuase accessing a 7254 // field of the ByVal will use a gep and load. Ideally we will optimize 7255 // to extracting the value from the register directly, and elide the 7256 // stores when the arguments address is not taken, but that will need to 7257 // be future work. 7258 SDValue Store = 7259 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7260 DAG.getObjectPtrOffset(dl, FIN, Offset), 7261 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7262 7263 MemOps.push_back(Store); 7264 }; 7265 7266 unsigned Offset = 0; 7267 HandleRegLoc(VA.getLocReg(), Offset); 7268 Offset += PtrByteSize; 7269 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7270 Offset += PtrByteSize) { 7271 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7272 "RegLocs should be for ByVal argument."); 7273 7274 const CCValAssign RL = ArgLocs[I++]; 7275 HandleRegLoc(RL.getLocReg(), Offset); 7276 } 7277 7278 if (Offset != StackSize) { 7279 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7280 "Expected MemLoc for remaining bytes."); 7281 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7282 // Consume the MemLoc.The InVal has already been emitted, so nothing 7283 // more needs to be done. 7284 ++I; 7285 } 7286 7287 continue; 7288 } 7289 7290 EVT ValVT = VA.getValVT(); 7291 if (VA.isRegLoc() && !VA.needsCustom()) { 7292 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7293 unsigned VReg = 7294 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7295 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7296 if (ValVT.isScalarInteger() && 7297 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7298 ArgValue = 7299 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7300 } 7301 InVals.push_back(ArgValue); 7302 continue; 7303 } 7304 if (VA.isMemLoc()) { 7305 const unsigned LocSize = LocVT.getStoreSize(); 7306 const unsigned ValSize = ValVT.getStoreSize(); 7307 assert((ValSize <= LocSize) && 7308 "Object size is larger than size of MemLoc"); 7309 int CurArgOffset = VA.getLocMemOffset(); 7310 // Objects are right-justified because AIX is big-endian. 7311 if (LocSize > ValSize) 7312 CurArgOffset += LocSize - ValSize; 7313 // Potential tail calls could cause overwriting of argument stack slots. 7314 const bool IsImmutable = 7315 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7316 (CallConv == CallingConv::Fast)); 7317 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7318 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7319 SDValue ArgValue = 7320 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7321 InVals.push_back(ArgValue); 7322 continue; 7323 } 7324 } 7325 7326 // On AIX a minimum of 8 words is saved to the parameter save area. 7327 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7328 // Area that is at least reserved in the caller of this function. 7329 unsigned CallerReservedArea = 7330 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7331 7332 // Set the size that is at least reserved in caller of this function. Tail 7333 // call optimized function's reserved stack space needs to be aligned so 7334 // that taking the difference between two stack areas will result in an 7335 // aligned stack. 7336 CallerReservedArea = 7337 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7338 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7339 FuncInfo->setMinReservedArea(CallerReservedArea); 7340 7341 if (isVarArg) { 7342 FuncInfo->setVarArgsFrameIndex( 7343 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7344 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7345 7346 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7347 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7348 7349 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7350 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7351 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7352 7353 // The fixed integer arguments of a variadic function are stored to the 7354 // VarArgsFrameIndex on the stack so that they may be loaded by 7355 // dereferencing the result of va_next. 7356 for (unsigned GPRIndex = 7357 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7358 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7359 7360 const unsigned VReg = 7361 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7362 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7363 7364 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7365 SDValue Store = 7366 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7367 MemOps.push_back(Store); 7368 // Increment the address for the next argument to store. 7369 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7370 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7371 } 7372 } 7373 7374 if (!MemOps.empty()) 7375 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7376 7377 return Chain; 7378 } 7379 7380 SDValue PPCTargetLowering::LowerCall_AIX( 7381 SDValue Chain, SDValue Callee, CallFlags CFlags, 7382 const SmallVectorImpl<ISD::OutputArg> &Outs, 7383 const SmallVectorImpl<SDValue> &OutVals, 7384 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7385 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7386 const CallBase *CB) const { 7387 7388 assert((CFlags.CallConv == CallingConv::C || 7389 CFlags.CallConv == CallingConv::Cold || 7390 CFlags.CallConv == CallingConv::Fast) && 7391 "Unexpected calling convention!"); 7392 7393 if (CFlags.IsPatchPoint) 7394 report_fatal_error("This call type is unimplemented on AIX."); 7395 7396 const PPCSubtarget& Subtarget = 7397 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7398 if (Subtarget.hasQPX()) 7399 report_fatal_error("QPX is not supported on AIX."); 7400 if (Subtarget.hasAltivec()) 7401 report_fatal_error("Altivec support is unimplemented on AIX."); 7402 7403 MachineFunction &MF = DAG.getMachineFunction(); 7404 SmallVector<CCValAssign, 16> ArgLocs; 7405 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7406 *DAG.getContext()); 7407 7408 // Reserve space for the linkage save area (LSA) on the stack. 7409 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7410 // [SP][CR][LR][2 x reserved][TOC]. 7411 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7412 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7413 const bool IsPPC64 = Subtarget.isPPC64(); 7414 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7415 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7416 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7417 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7418 7419 // The prolog code of the callee may store up to 8 GPR argument registers to 7420 // the stack, allowing va_start to index over them in memory if the callee 7421 // is variadic. 7422 // Because we cannot tell if this is needed on the caller side, we have to 7423 // conservatively assume that it is needed. As such, make sure we have at 7424 // least enough stack space for the caller to store the 8 GPRs. 7425 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7426 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7427 CCInfo.getNextStackOffset()); 7428 7429 // Adjust the stack pointer for the new arguments... 7430 // These operations are automatically eliminated by the prolog/epilog pass. 7431 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7432 SDValue CallSeqStart = Chain; 7433 7434 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7435 SmallVector<SDValue, 8> MemOpChains; 7436 7437 // Set up a copy of the stack pointer for loading and storing any 7438 // arguments that may not fit in the registers available for argument 7439 // passing. 7440 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7441 : DAG.getRegister(PPC::R1, MVT::i32); 7442 7443 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7444 const unsigned ValNo = ArgLocs[I].getValNo(); 7445 SDValue Arg = OutVals[ValNo]; 7446 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7447 7448 if (Flags.isByVal()) { 7449 const unsigned ByValSize = Flags.getByValSize(); 7450 7451 // Nothing to do for zero-sized ByVals on the caller side. 7452 if (!ByValSize) { 7453 ++I; 7454 continue; 7455 } 7456 7457 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7458 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7459 (LoadOffset != 0) 7460 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7461 : Arg, 7462 MachinePointerInfo(), VT); 7463 }; 7464 7465 unsigned LoadOffset = 0; 7466 7467 // Initialize registers, which are fully occupied by the by-val argument. 7468 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7469 SDValue Load = GetLoad(PtrVT, LoadOffset); 7470 MemOpChains.push_back(Load.getValue(1)); 7471 LoadOffset += PtrByteSize; 7472 const CCValAssign &ByValVA = ArgLocs[I++]; 7473 assert(ByValVA.getValNo() == ValNo && 7474 "Unexpected location for pass-by-value argument."); 7475 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7476 } 7477 7478 if (LoadOffset == ByValSize) 7479 continue; 7480 7481 // There must be one more loc to handle the remainder. 7482 assert(ArgLocs[I].getValNo() == ValNo && 7483 "Expected additional location for by-value argument."); 7484 7485 if (ArgLocs[I].isMemLoc()) { 7486 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7487 const CCValAssign &ByValVA = ArgLocs[I++]; 7488 ISD::ArgFlagsTy MemcpyFlags = Flags; 7489 // Only memcpy the bytes that don't pass in register. 7490 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7491 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7492 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7493 : Arg, 7494 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7495 CallSeqStart, MemcpyFlags, DAG, dl); 7496 continue; 7497 } 7498 7499 // Initialize the final register residue. 7500 // Any residue that occupies the final by-val arg register must be 7501 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7502 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7503 // 2 and 1 byte loads. 7504 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7505 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7506 "Unexpected register residue for by-value argument."); 7507 SDValue ResidueVal; 7508 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7509 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7510 const MVT VT = 7511 N == 1 ? MVT::i8 7512 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7513 SDValue Load = GetLoad(VT, LoadOffset); 7514 MemOpChains.push_back(Load.getValue(1)); 7515 LoadOffset += N; 7516 Bytes += N; 7517 7518 // By-val arguments are passed left-justfied in register. 7519 // Every load here needs to be shifted, otherwise a full register load 7520 // should have been used. 7521 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7522 "Unexpected load emitted during handling of pass-by-value " 7523 "argument."); 7524 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7525 EVT ShiftAmountTy = 7526 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7527 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7528 SDValue ShiftedLoad = 7529 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7530 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7531 ShiftedLoad) 7532 : ShiftedLoad; 7533 } 7534 7535 const CCValAssign &ByValVA = ArgLocs[I++]; 7536 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7537 continue; 7538 } 7539 7540 CCValAssign &VA = ArgLocs[I++]; 7541 const MVT LocVT = VA.getLocVT(); 7542 const MVT ValVT = VA.getValVT(); 7543 7544 switch (VA.getLocInfo()) { 7545 default: 7546 report_fatal_error("Unexpected argument extension type."); 7547 case CCValAssign::Full: 7548 break; 7549 case CCValAssign::ZExt: 7550 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7551 break; 7552 case CCValAssign::SExt: 7553 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7554 break; 7555 } 7556 7557 if (VA.isRegLoc() && !VA.needsCustom()) { 7558 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7559 continue; 7560 } 7561 7562 if (VA.isMemLoc()) { 7563 SDValue PtrOff = 7564 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7565 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7566 MemOpChains.push_back( 7567 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7568 7569 continue; 7570 } 7571 7572 // Custom handling is used for GPR initializations for vararg float 7573 // arguments. 7574 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7575 ValVT.isFloatingPoint() && LocVT.isInteger() && 7576 "Unexpected register handling for calling convention."); 7577 7578 SDValue ArgAsInt = 7579 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7580 7581 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7582 // f32 in 32-bit GPR 7583 // f64 in 64-bit GPR 7584 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7585 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7586 // f32 in 64-bit GPR. 7587 RegsToPass.push_back(std::make_pair( 7588 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7589 else { 7590 // f64 in two 32-bit GPRs 7591 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7592 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7593 "Unexpected custom register for argument!"); 7594 CCValAssign &GPR1 = VA; 7595 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7596 DAG.getConstant(32, dl, MVT::i8)); 7597 RegsToPass.push_back(std::make_pair( 7598 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7599 7600 if (I != E) { 7601 // If only 1 GPR was available, there will only be one custom GPR and 7602 // the argument will also pass in memory. 7603 CCValAssign &PeekArg = ArgLocs[I]; 7604 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7605 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7606 CCValAssign &GPR2 = ArgLocs[I++]; 7607 RegsToPass.push_back(std::make_pair( 7608 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7609 } 7610 } 7611 } 7612 } 7613 7614 if (!MemOpChains.empty()) 7615 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7616 7617 // For indirect calls, we need to save the TOC base to the stack for 7618 // restoration after the call. 7619 if (CFlags.IsIndirect) { 7620 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7621 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7622 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7623 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7624 const unsigned TOCSaveOffset = 7625 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7626 7627 setUsesTOCBasePtr(DAG); 7628 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7629 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7630 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7631 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7632 Chain = DAG.getStore( 7633 Val.getValue(1), dl, Val, AddPtr, 7634 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7635 } 7636 7637 // Build a sequence of copy-to-reg nodes chained together with token chain 7638 // and flag operands which copy the outgoing args into the appropriate regs. 7639 SDValue InFlag; 7640 for (auto Reg : RegsToPass) { 7641 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7642 InFlag = Chain.getValue(1); 7643 } 7644 7645 const int SPDiff = 0; 7646 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7647 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7648 } 7649 7650 bool 7651 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7652 MachineFunction &MF, bool isVarArg, 7653 const SmallVectorImpl<ISD::OutputArg> &Outs, 7654 LLVMContext &Context) const { 7655 SmallVector<CCValAssign, 16> RVLocs; 7656 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7657 return CCInfo.CheckReturn( 7658 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7659 ? RetCC_PPC_Cold 7660 : RetCC_PPC); 7661 } 7662 7663 SDValue 7664 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7665 bool isVarArg, 7666 const SmallVectorImpl<ISD::OutputArg> &Outs, 7667 const SmallVectorImpl<SDValue> &OutVals, 7668 const SDLoc &dl, SelectionDAG &DAG) const { 7669 SmallVector<CCValAssign, 16> RVLocs; 7670 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7671 *DAG.getContext()); 7672 CCInfo.AnalyzeReturn(Outs, 7673 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7674 ? RetCC_PPC_Cold 7675 : RetCC_PPC); 7676 7677 SDValue Flag; 7678 SmallVector<SDValue, 4> RetOps(1, Chain); 7679 7680 // Copy the result values into the output registers. 7681 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7682 CCValAssign &VA = RVLocs[i]; 7683 assert(VA.isRegLoc() && "Can only return in registers!"); 7684 7685 SDValue Arg = OutVals[RealResIdx]; 7686 7687 switch (VA.getLocInfo()) { 7688 default: llvm_unreachable("Unknown loc info!"); 7689 case CCValAssign::Full: break; 7690 case CCValAssign::AExt: 7691 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7692 break; 7693 case CCValAssign::ZExt: 7694 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7695 break; 7696 case CCValAssign::SExt: 7697 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7698 break; 7699 } 7700 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7701 bool isLittleEndian = Subtarget.isLittleEndian(); 7702 // Legalize ret f64 -> ret 2 x i32. 7703 SDValue SVal = 7704 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7705 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7706 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7707 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7708 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7709 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7710 Flag = Chain.getValue(1); 7711 VA = RVLocs[++i]; // skip ahead to next loc 7712 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7713 } else 7714 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7715 Flag = Chain.getValue(1); 7716 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7717 } 7718 7719 RetOps[0] = Chain; // Update chain. 7720 7721 // Add the flag if we have it. 7722 if (Flag.getNode()) 7723 RetOps.push_back(Flag); 7724 7725 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7726 } 7727 7728 SDValue 7729 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7730 SelectionDAG &DAG) const { 7731 SDLoc dl(Op); 7732 7733 // Get the correct type for integers. 7734 EVT IntVT = Op.getValueType(); 7735 7736 // Get the inputs. 7737 SDValue Chain = Op.getOperand(0); 7738 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7739 // Build a DYNAREAOFFSET node. 7740 SDValue Ops[2] = {Chain, FPSIdx}; 7741 SDVTList VTs = DAG.getVTList(IntVT); 7742 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7743 } 7744 7745 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7746 SelectionDAG &DAG) const { 7747 // When we pop the dynamic allocation we need to restore the SP link. 7748 SDLoc dl(Op); 7749 7750 // Get the correct type for pointers. 7751 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7752 7753 // Construct the stack pointer operand. 7754 bool isPPC64 = Subtarget.isPPC64(); 7755 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7756 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7757 7758 // Get the operands for the STACKRESTORE. 7759 SDValue Chain = Op.getOperand(0); 7760 SDValue SaveSP = Op.getOperand(1); 7761 7762 // Load the old link SP. 7763 SDValue LoadLinkSP = 7764 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7765 7766 // Restore the stack pointer. 7767 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7768 7769 // Store the old link SP. 7770 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7771 } 7772 7773 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7774 MachineFunction &MF = DAG.getMachineFunction(); 7775 bool isPPC64 = Subtarget.isPPC64(); 7776 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7777 7778 // Get current frame pointer save index. The users of this index will be 7779 // primarily DYNALLOC instructions. 7780 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7781 int RASI = FI->getReturnAddrSaveIndex(); 7782 7783 // If the frame pointer save index hasn't been defined yet. 7784 if (!RASI) { 7785 // Find out what the fix offset of the frame pointer save area. 7786 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7787 // Allocate the frame index for frame pointer save area. 7788 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7789 // Save the result. 7790 FI->setReturnAddrSaveIndex(RASI); 7791 } 7792 return DAG.getFrameIndex(RASI, PtrVT); 7793 } 7794 7795 SDValue 7796 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7797 MachineFunction &MF = DAG.getMachineFunction(); 7798 bool isPPC64 = Subtarget.isPPC64(); 7799 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7800 7801 // Get current frame pointer save index. The users of this index will be 7802 // primarily DYNALLOC instructions. 7803 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7804 int FPSI = FI->getFramePointerSaveIndex(); 7805 7806 // If the frame pointer save index hasn't been defined yet. 7807 if (!FPSI) { 7808 // Find out what the fix offset of the frame pointer save area. 7809 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7810 // Allocate the frame index for frame pointer save area. 7811 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7812 // Save the result. 7813 FI->setFramePointerSaveIndex(FPSI); 7814 } 7815 return DAG.getFrameIndex(FPSI, PtrVT); 7816 } 7817 7818 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7819 SelectionDAG &DAG) const { 7820 // Get the inputs. 7821 SDValue Chain = Op.getOperand(0); 7822 SDValue Size = Op.getOperand(1); 7823 SDLoc dl(Op); 7824 7825 // Get the correct type for pointers. 7826 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7827 // Negate the size. 7828 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7829 DAG.getConstant(0, dl, PtrVT), Size); 7830 // Construct a node for the frame pointer save index. 7831 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7832 // Build a DYNALLOC node. 7833 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7834 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7835 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7836 } 7837 7838 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7839 SelectionDAG &DAG) const { 7840 MachineFunction &MF = DAG.getMachineFunction(); 7841 7842 bool isPPC64 = Subtarget.isPPC64(); 7843 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7844 7845 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7846 return DAG.getFrameIndex(FI, PtrVT); 7847 } 7848 7849 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7850 SelectionDAG &DAG) const { 7851 SDLoc DL(Op); 7852 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7853 DAG.getVTList(MVT::i32, MVT::Other), 7854 Op.getOperand(0), Op.getOperand(1)); 7855 } 7856 7857 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7858 SelectionDAG &DAG) const { 7859 SDLoc DL(Op); 7860 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7861 Op.getOperand(0), Op.getOperand(1)); 7862 } 7863 7864 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7865 if (Op.getValueType().isVector()) 7866 return LowerVectorLoad(Op, DAG); 7867 7868 assert(Op.getValueType() == MVT::i1 && 7869 "Custom lowering only for i1 loads"); 7870 7871 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7872 7873 SDLoc dl(Op); 7874 LoadSDNode *LD = cast<LoadSDNode>(Op); 7875 7876 SDValue Chain = LD->getChain(); 7877 SDValue BasePtr = LD->getBasePtr(); 7878 MachineMemOperand *MMO = LD->getMemOperand(); 7879 7880 SDValue NewLD = 7881 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7882 BasePtr, MVT::i8, MMO); 7883 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7884 7885 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7886 return DAG.getMergeValues(Ops, dl); 7887 } 7888 7889 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7890 if (Op.getOperand(1).getValueType().isVector()) 7891 return LowerVectorStore(Op, DAG); 7892 7893 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7894 "Custom lowering only for i1 stores"); 7895 7896 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7897 7898 SDLoc dl(Op); 7899 StoreSDNode *ST = cast<StoreSDNode>(Op); 7900 7901 SDValue Chain = ST->getChain(); 7902 SDValue BasePtr = ST->getBasePtr(); 7903 SDValue Value = ST->getValue(); 7904 MachineMemOperand *MMO = ST->getMemOperand(); 7905 7906 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7907 Value); 7908 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7909 } 7910 7911 // FIXME: Remove this once the ANDI glue bug is fixed: 7912 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7913 assert(Op.getValueType() == MVT::i1 && 7914 "Custom lowering only for i1 results"); 7915 7916 SDLoc DL(Op); 7917 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7918 } 7919 7920 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7921 SelectionDAG &DAG) const { 7922 7923 // Implements a vector truncate that fits in a vector register as a shuffle. 7924 // We want to legalize vector truncates down to where the source fits in 7925 // a vector register (and target is therefore smaller than vector register 7926 // size). At that point legalization will try to custom lower the sub-legal 7927 // result and get here - where we can contain the truncate as a single target 7928 // operation. 7929 7930 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7931 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7932 // 7933 // We will implement it for big-endian ordering as this (where x denotes 7934 // undefined): 7935 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7936 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7937 // 7938 // The same operation in little-endian ordering will be: 7939 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7940 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7941 7942 assert(Op.getValueType().isVector() && "Vector type expected."); 7943 7944 SDLoc DL(Op); 7945 SDValue N1 = Op.getOperand(0); 7946 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7947 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7948 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7949 7950 EVT TrgVT = Op.getValueType(); 7951 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7952 EVT EltVT = TrgVT.getVectorElementType(); 7953 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7954 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7955 7956 // First list the elements we want to keep. 7957 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7958 SmallVector<int, 16> ShuffV; 7959 if (Subtarget.isLittleEndian()) 7960 for (unsigned i = 0; i < TrgNumElts; ++i) 7961 ShuffV.push_back(i * SizeMult); 7962 else 7963 for (unsigned i = 1; i <= TrgNumElts; ++i) 7964 ShuffV.push_back(i * SizeMult - 1); 7965 7966 // Populate the remaining elements with undefs. 7967 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7968 // ShuffV.push_back(i + WideNumElts); 7969 ShuffV.push_back(WideNumElts + 1); 7970 7971 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7972 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7973 } 7974 7975 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7976 /// possible. 7977 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7978 // Not FP? Not a fsel. 7979 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7980 !Op.getOperand(2).getValueType().isFloatingPoint()) 7981 return Op; 7982 7983 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7984 7985 EVT ResVT = Op.getValueType(); 7986 EVT CmpVT = Op.getOperand(0).getValueType(); 7987 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7988 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7989 SDLoc dl(Op); 7990 SDNodeFlags Flags = Op.getNode()->getFlags(); 7991 7992 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7993 // presence of infinities. 7994 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7995 switch (CC) { 7996 default: 7997 break; 7998 case ISD::SETOGT: 7999 case ISD::SETGT: 8000 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8001 case ISD::SETOLT: 8002 case ISD::SETLT: 8003 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8004 } 8005 } 8006 8007 // We might be able to do better than this under some circumstances, but in 8008 // general, fsel-based lowering of select is a finite-math-only optimization. 8009 // For more information, see section F.3 of the 2.06 ISA specification. 8010 // With ISA 3.0 8011 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8012 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8013 return Op; 8014 8015 // If the RHS of the comparison is a 0.0, we don't need to do the 8016 // subtraction at all. 8017 SDValue Sel1; 8018 if (isFloatingPointZero(RHS)) 8019 switch (CC) { 8020 default: break; // SETUO etc aren't handled by fsel. 8021 case ISD::SETNE: 8022 std::swap(TV, FV); 8023 LLVM_FALLTHROUGH; 8024 case ISD::SETEQ: 8025 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8026 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8027 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8028 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8029 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8030 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8031 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8032 case ISD::SETULT: 8033 case ISD::SETLT: 8034 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8035 LLVM_FALLTHROUGH; 8036 case ISD::SETOGE: 8037 case ISD::SETGE: 8038 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8039 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8040 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8041 case ISD::SETUGT: 8042 case ISD::SETGT: 8043 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8044 LLVM_FALLTHROUGH; 8045 case ISD::SETOLE: 8046 case ISD::SETLE: 8047 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8048 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8049 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8050 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8051 } 8052 8053 SDValue Cmp; 8054 switch (CC) { 8055 default: break; // SETUO etc aren't handled by fsel. 8056 case ISD::SETNE: 8057 std::swap(TV, FV); 8058 LLVM_FALLTHROUGH; 8059 case ISD::SETEQ: 8060 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8061 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8062 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8063 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8064 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8065 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8066 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8067 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8068 case ISD::SETULT: 8069 case ISD::SETLT: 8070 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8071 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8072 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8073 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8074 case ISD::SETOGE: 8075 case ISD::SETGE: 8076 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8077 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8078 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8079 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8080 case ISD::SETUGT: 8081 case ISD::SETGT: 8082 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8083 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8084 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8085 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8086 case ISD::SETOLE: 8087 case ISD::SETLE: 8088 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8089 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8090 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8091 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8092 } 8093 return Op; 8094 } 8095 8096 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8097 SelectionDAG &DAG, 8098 const SDLoc &dl) const { 8099 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8100 SDValue Src = Op.getOperand(0); 8101 if (Src.getValueType() == MVT::f32) 8102 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8103 8104 SDValue Tmp; 8105 switch (Op.getSimpleValueType().SimpleTy) { 8106 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8107 case MVT::i32: 8108 Tmp = DAG.getNode( 8109 Op.getOpcode() == ISD::FP_TO_SINT 8110 ? PPCISD::FCTIWZ 8111 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8112 dl, MVT::f64, Src); 8113 break; 8114 case MVT::i64: 8115 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8116 "i64 FP_TO_UINT is supported only with FPCVT"); 8117 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8118 PPCISD::FCTIDUZ, 8119 dl, MVT::f64, Src); 8120 break; 8121 } 8122 8123 // Convert the FP value to an int value through memory. 8124 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8125 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8126 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8127 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8128 MachinePointerInfo MPI = 8129 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8130 8131 // Emit a store to the stack slot. 8132 SDValue Chain; 8133 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8134 if (i32Stack) { 8135 MachineFunction &MF = DAG.getMachineFunction(); 8136 Alignment = Align(4); 8137 MachineMemOperand *MMO = 8138 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8139 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8140 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8141 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8142 } else 8143 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8144 8145 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8146 // add in a bias on big endian. 8147 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8148 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8149 DAG.getConstant(4, dl, FIPtr.getValueType())); 8150 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8151 } 8152 8153 RLI.Chain = Chain; 8154 RLI.Ptr = FIPtr; 8155 RLI.MPI = MPI; 8156 RLI.Alignment = Alignment; 8157 } 8158 8159 /// Custom lowers floating point to integer conversions to use 8160 /// the direct move instructions available in ISA 2.07 to avoid the 8161 /// need for load/store combinations. 8162 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8163 SelectionDAG &DAG, 8164 const SDLoc &dl) const { 8165 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8166 SDValue Src = Op.getOperand(0); 8167 8168 if (Src.getValueType() == MVT::f32) 8169 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8170 8171 SDValue Tmp; 8172 switch (Op.getSimpleValueType().SimpleTy) { 8173 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8174 case MVT::i32: 8175 Tmp = DAG.getNode( 8176 Op.getOpcode() == ISD::FP_TO_SINT 8177 ? PPCISD::FCTIWZ 8178 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8179 dl, MVT::f64, Src); 8180 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8181 break; 8182 case MVT::i64: 8183 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8184 "i64 FP_TO_UINT is supported only with FPCVT"); 8185 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8186 PPCISD::FCTIDUZ, 8187 dl, MVT::f64, Src); 8188 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8189 break; 8190 } 8191 return Tmp; 8192 } 8193 8194 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8195 const SDLoc &dl) const { 8196 8197 // FP to INT conversions are legal for f128. 8198 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8199 return Op; 8200 8201 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8202 // PPC (the libcall is not available). 8203 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8204 if (Op.getValueType() == MVT::i32) { 8205 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8206 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8207 MVT::f64, Op.getOperand(0), 8208 DAG.getIntPtrConstant(0, dl)); 8209 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8210 MVT::f64, Op.getOperand(0), 8211 DAG.getIntPtrConstant(1, dl)); 8212 8213 // Add the two halves of the long double in round-to-zero mode. 8214 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8215 8216 // Now use a smaller FP_TO_SINT. 8217 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8218 } 8219 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8220 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8221 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8222 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8223 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8224 // FIXME: generated code sucks. 8225 // TODO: Are there fast-math-flags to propagate to this FSUB? 8226 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8227 Op.getOperand(0), Tmp); 8228 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8229 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8230 DAG.getConstant(0x80000000, dl, MVT::i32)); 8231 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8232 Op.getOperand(0)); 8233 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8234 ISD::SETGE); 8235 } 8236 } 8237 8238 return SDValue(); 8239 } 8240 8241 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8242 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8243 8244 ReuseLoadInfo RLI; 8245 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8246 8247 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8248 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8249 } 8250 8251 // We're trying to insert a regular store, S, and then a load, L. If the 8252 // incoming value, O, is a load, we might just be able to have our load use the 8253 // address used by O. However, we don't know if anything else will store to 8254 // that address before we can load from it. To prevent this situation, we need 8255 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8256 // the same chain operand as O, we create a token factor from the chain results 8257 // of O and L, and we replace all uses of O's chain result with that token 8258 // factor (see spliceIntoChain below for this last part). 8259 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8260 ReuseLoadInfo &RLI, 8261 SelectionDAG &DAG, 8262 ISD::LoadExtType ET) const { 8263 SDLoc dl(Op); 8264 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8265 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8266 if (ET == ISD::NON_EXTLOAD && 8267 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8268 isOperationLegalOrCustom(Op.getOpcode(), 8269 Op.getOperand(0).getValueType())) { 8270 8271 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8272 return true; 8273 } 8274 8275 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8276 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8277 LD->isNonTemporal()) 8278 return false; 8279 if (LD->getMemoryVT() != MemVT) 8280 return false; 8281 8282 RLI.Ptr = LD->getBasePtr(); 8283 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8284 assert(LD->getAddressingMode() == ISD::PRE_INC && 8285 "Non-pre-inc AM on PPC?"); 8286 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8287 LD->getOffset()); 8288 } 8289 8290 RLI.Chain = LD->getChain(); 8291 RLI.MPI = LD->getPointerInfo(); 8292 RLI.IsDereferenceable = LD->isDereferenceable(); 8293 RLI.IsInvariant = LD->isInvariant(); 8294 RLI.Alignment = LD->getAlign(); 8295 RLI.AAInfo = LD->getAAInfo(); 8296 RLI.Ranges = LD->getRanges(); 8297 8298 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8299 return true; 8300 } 8301 8302 // Given the head of the old chain, ResChain, insert a token factor containing 8303 // it and NewResChain, and make users of ResChain now be users of that token 8304 // factor. 8305 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8306 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8307 SDValue NewResChain, 8308 SelectionDAG &DAG) const { 8309 if (!ResChain) 8310 return; 8311 8312 SDLoc dl(NewResChain); 8313 8314 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8315 NewResChain, DAG.getUNDEF(MVT::Other)); 8316 assert(TF.getNode() != NewResChain.getNode() && 8317 "A new TF really is required here"); 8318 8319 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8320 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8321 } 8322 8323 /// Analyze profitability of direct move 8324 /// prefer float load to int load plus direct move 8325 /// when there is no integer use of int load 8326 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8327 SDNode *Origin = Op.getOperand(0).getNode(); 8328 if (Origin->getOpcode() != ISD::LOAD) 8329 return true; 8330 8331 // If there is no LXSIBZX/LXSIHZX, like Power8, 8332 // prefer direct move if the memory size is 1 or 2 bytes. 8333 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8334 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8335 return true; 8336 8337 for (SDNode::use_iterator UI = Origin->use_begin(), 8338 UE = Origin->use_end(); 8339 UI != UE; ++UI) { 8340 8341 // Only look at the users of the loaded value. 8342 if (UI.getUse().get().getResNo() != 0) 8343 continue; 8344 8345 if (UI->getOpcode() != ISD::SINT_TO_FP && 8346 UI->getOpcode() != ISD::UINT_TO_FP) 8347 return true; 8348 } 8349 8350 return false; 8351 } 8352 8353 /// Custom lowers integer to floating point conversions to use 8354 /// the direct move instructions available in ISA 2.07 to avoid the 8355 /// need for load/store combinations. 8356 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8357 SelectionDAG &DAG, 8358 const SDLoc &dl) const { 8359 assert((Op.getValueType() == MVT::f32 || 8360 Op.getValueType() == MVT::f64) && 8361 "Invalid floating point type as target of conversion"); 8362 assert(Subtarget.hasFPCVT() && 8363 "Int to FP conversions with direct moves require FPCVT"); 8364 SDValue FP; 8365 SDValue Src = Op.getOperand(0); 8366 bool SinglePrec = Op.getValueType() == MVT::f32; 8367 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8368 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8369 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8370 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8371 8372 if (WordInt) { 8373 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8374 dl, MVT::f64, Src); 8375 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8376 } 8377 else { 8378 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8379 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8380 } 8381 8382 return FP; 8383 } 8384 8385 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8386 8387 EVT VecVT = Vec.getValueType(); 8388 assert(VecVT.isVector() && "Expected a vector type."); 8389 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8390 8391 EVT EltVT = VecVT.getVectorElementType(); 8392 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8393 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8394 8395 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8396 SmallVector<SDValue, 16> Ops(NumConcat); 8397 Ops[0] = Vec; 8398 SDValue UndefVec = DAG.getUNDEF(VecVT); 8399 for (unsigned i = 1; i < NumConcat; ++i) 8400 Ops[i] = UndefVec; 8401 8402 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8403 } 8404 8405 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8406 const SDLoc &dl) const { 8407 8408 unsigned Opc = Op.getOpcode(); 8409 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8410 "Unexpected conversion type"); 8411 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8412 "Supports conversions to v2f64/v4f32 only."); 8413 8414 bool SignedConv = Opc == ISD::SINT_TO_FP; 8415 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8416 8417 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8418 EVT WideVT = Wide.getValueType(); 8419 unsigned WideNumElts = WideVT.getVectorNumElements(); 8420 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8421 8422 SmallVector<int, 16> ShuffV; 8423 for (unsigned i = 0; i < WideNumElts; ++i) 8424 ShuffV.push_back(i + WideNumElts); 8425 8426 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8427 int SaveElts = FourEltRes ? 4 : 2; 8428 if (Subtarget.isLittleEndian()) 8429 for (int i = 0; i < SaveElts; i++) 8430 ShuffV[i * Stride] = i; 8431 else 8432 for (int i = 1; i <= SaveElts; i++) 8433 ShuffV[i * Stride - 1] = i - 1; 8434 8435 SDValue ShuffleSrc2 = 8436 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8437 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8438 8439 SDValue Extend; 8440 if (SignedConv) { 8441 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8442 EVT ExtVT = Op.getOperand(0).getValueType(); 8443 if (Subtarget.hasP9Altivec()) 8444 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8445 IntermediateVT.getVectorNumElements()); 8446 8447 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8448 DAG.getValueType(ExtVT)); 8449 } else 8450 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8451 8452 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8453 } 8454 8455 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8456 SelectionDAG &DAG) const { 8457 SDLoc dl(Op); 8458 8459 EVT InVT = Op.getOperand(0).getValueType(); 8460 EVT OutVT = Op.getValueType(); 8461 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8462 isOperationCustom(Op.getOpcode(), InVT)) 8463 return LowerINT_TO_FPVector(Op, DAG, dl); 8464 8465 // Conversions to f128 are legal. 8466 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8467 return Op; 8468 8469 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8470 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8471 return SDValue(); 8472 8473 SDValue Value = Op.getOperand(0); 8474 // The values are now known to be -1 (false) or 1 (true). To convert this 8475 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8476 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8477 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8478 8479 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8480 8481 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8482 8483 if (Op.getValueType() != MVT::v4f64) 8484 Value = DAG.getNode(ISD::FP_ROUND, dl, 8485 Op.getValueType(), Value, 8486 DAG.getIntPtrConstant(1, dl)); 8487 return Value; 8488 } 8489 8490 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8491 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8492 return SDValue(); 8493 8494 if (Op.getOperand(0).getValueType() == MVT::i1) 8495 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8496 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8497 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8498 8499 // If we have direct moves, we can do all the conversion, skip the store/load 8500 // however, without FPCVT we can't do most conversions. 8501 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8502 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8503 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8504 8505 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8506 "UINT_TO_FP is supported only with FPCVT"); 8507 8508 // If we have FCFIDS, then use it when converting to single-precision. 8509 // Otherwise, convert to double-precision and then round. 8510 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8511 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8512 : PPCISD::FCFIDS) 8513 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8514 : PPCISD::FCFID); 8515 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8516 ? MVT::f32 8517 : MVT::f64; 8518 8519 if (Op.getOperand(0).getValueType() == MVT::i64) { 8520 SDValue SINT = Op.getOperand(0); 8521 // When converting to single-precision, we actually need to convert 8522 // to double-precision first and then round to single-precision. 8523 // To avoid double-rounding effects during that operation, we have 8524 // to prepare the input operand. Bits that might be truncated when 8525 // converting to double-precision are replaced by a bit that won't 8526 // be lost at this stage, but is below the single-precision rounding 8527 // position. 8528 // 8529 // However, if -enable-unsafe-fp-math is in effect, accept double 8530 // rounding to avoid the extra overhead. 8531 if (Op.getValueType() == MVT::f32 && 8532 !Subtarget.hasFPCVT() && 8533 !DAG.getTarget().Options.UnsafeFPMath) { 8534 8535 // Twiddle input to make sure the low 11 bits are zero. (If this 8536 // is the case, we are guaranteed the value will fit into the 53 bit 8537 // mantissa of an IEEE double-precision value without rounding.) 8538 // If any of those low 11 bits were not zero originally, make sure 8539 // bit 12 (value 2048) is set instead, so that the final rounding 8540 // to single-precision gets the correct result. 8541 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8542 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8543 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8544 Round, DAG.getConstant(2047, dl, MVT::i64)); 8545 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8546 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8547 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8548 8549 // However, we cannot use that value unconditionally: if the magnitude 8550 // of the input value is small, the bit-twiddling we did above might 8551 // end up visibly changing the output. Fortunately, in that case, we 8552 // don't need to twiddle bits since the original input will convert 8553 // exactly to double-precision floating-point already. Therefore, 8554 // construct a conditional to use the original value if the top 11 8555 // bits are all sign-bit copies, and use the rounded value computed 8556 // above otherwise. 8557 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8558 SINT, DAG.getConstant(53, dl, MVT::i32)); 8559 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8560 Cond, DAG.getConstant(1, dl, MVT::i64)); 8561 Cond = DAG.getSetCC( 8562 dl, 8563 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8564 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8565 8566 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8567 } 8568 8569 ReuseLoadInfo RLI; 8570 SDValue Bits; 8571 8572 MachineFunction &MF = DAG.getMachineFunction(); 8573 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8574 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8575 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8576 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8577 } else if (Subtarget.hasLFIWAX() && 8578 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8579 MachineMemOperand *MMO = 8580 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8581 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8582 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8583 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8584 DAG.getVTList(MVT::f64, MVT::Other), 8585 Ops, MVT::i32, MMO); 8586 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8587 } else if (Subtarget.hasFPCVT() && 8588 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8589 MachineMemOperand *MMO = 8590 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8591 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8592 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8593 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8594 DAG.getVTList(MVT::f64, MVT::Other), 8595 Ops, MVT::i32, MMO); 8596 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8597 } else if (((Subtarget.hasLFIWAX() && 8598 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8599 (Subtarget.hasFPCVT() && 8600 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8601 SINT.getOperand(0).getValueType() == MVT::i32) { 8602 MachineFrameInfo &MFI = MF.getFrameInfo(); 8603 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8604 8605 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8606 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8607 8608 SDValue Store = 8609 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8610 MachinePointerInfo::getFixedStack( 8611 DAG.getMachineFunction(), FrameIdx)); 8612 8613 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8614 "Expected an i32 store"); 8615 8616 RLI.Ptr = FIdx; 8617 RLI.Chain = Store; 8618 RLI.MPI = 8619 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8620 RLI.Alignment = Align(4); 8621 8622 MachineMemOperand *MMO = 8623 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8624 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8625 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8626 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8627 PPCISD::LFIWZX : PPCISD::LFIWAX, 8628 dl, DAG.getVTList(MVT::f64, MVT::Other), 8629 Ops, MVT::i32, MMO); 8630 } else 8631 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8632 8633 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8634 8635 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8636 FP = DAG.getNode(ISD::FP_ROUND, dl, 8637 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8638 return FP; 8639 } 8640 8641 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8642 "Unhandled INT_TO_FP type in custom expander!"); 8643 // Since we only generate this in 64-bit mode, we can take advantage of 8644 // 64-bit registers. In particular, sign extend the input value into the 8645 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8646 // then lfd it and fcfid it. 8647 MachineFunction &MF = DAG.getMachineFunction(); 8648 MachineFrameInfo &MFI = MF.getFrameInfo(); 8649 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8650 8651 SDValue Ld; 8652 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8653 ReuseLoadInfo RLI; 8654 bool ReusingLoad; 8655 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8656 DAG))) { 8657 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8658 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8659 8660 SDValue Store = 8661 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8662 MachinePointerInfo::getFixedStack( 8663 DAG.getMachineFunction(), FrameIdx)); 8664 8665 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8666 "Expected an i32 store"); 8667 8668 RLI.Ptr = FIdx; 8669 RLI.Chain = Store; 8670 RLI.MPI = 8671 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8672 RLI.Alignment = Align(4); 8673 } 8674 8675 MachineMemOperand *MMO = 8676 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8677 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8678 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8679 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8680 PPCISD::LFIWZX : PPCISD::LFIWAX, 8681 dl, DAG.getVTList(MVT::f64, MVT::Other), 8682 Ops, MVT::i32, MMO); 8683 if (ReusingLoad) 8684 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8685 } else { 8686 assert(Subtarget.isPPC64() && 8687 "i32->FP without LFIWAX supported only on PPC64"); 8688 8689 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8690 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8691 8692 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8693 Op.getOperand(0)); 8694 8695 // STD the extended value into the stack slot. 8696 SDValue Store = DAG.getStore( 8697 DAG.getEntryNode(), dl, Ext64, FIdx, 8698 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8699 8700 // Load the value as a double. 8701 Ld = DAG.getLoad( 8702 MVT::f64, dl, Store, FIdx, 8703 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8704 } 8705 8706 // FCFID it and return it. 8707 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8708 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8709 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8710 DAG.getIntPtrConstant(0, dl)); 8711 return FP; 8712 } 8713 8714 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8715 SelectionDAG &DAG) const { 8716 SDLoc dl(Op); 8717 /* 8718 The rounding mode is in bits 30:31 of FPSR, and has the following 8719 settings: 8720 00 Round to nearest 8721 01 Round to 0 8722 10 Round to +inf 8723 11 Round to -inf 8724 8725 FLT_ROUNDS, on the other hand, expects the following: 8726 -1 Undefined 8727 0 Round to 0 8728 1 Round to nearest 8729 2 Round to +inf 8730 3 Round to -inf 8731 8732 To perform the conversion, we do: 8733 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8734 */ 8735 8736 MachineFunction &MF = DAG.getMachineFunction(); 8737 EVT VT = Op.getValueType(); 8738 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8739 8740 // Save FP Control Word to register 8741 SDValue Chain = Op.getOperand(0); 8742 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8743 Chain = MFFS.getValue(1); 8744 8745 // Save FP register to stack slot 8746 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8747 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8748 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8749 8750 // Load FP Control Word from low 32 bits of stack slot. 8751 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8752 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8753 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8754 Chain = CWD.getValue(1); 8755 8756 // Transform as necessary 8757 SDValue CWD1 = 8758 DAG.getNode(ISD::AND, dl, MVT::i32, 8759 CWD, DAG.getConstant(3, dl, MVT::i32)); 8760 SDValue CWD2 = 8761 DAG.getNode(ISD::SRL, dl, MVT::i32, 8762 DAG.getNode(ISD::AND, dl, MVT::i32, 8763 DAG.getNode(ISD::XOR, dl, MVT::i32, 8764 CWD, DAG.getConstant(3, dl, MVT::i32)), 8765 DAG.getConstant(3, dl, MVT::i32)), 8766 DAG.getConstant(1, dl, MVT::i32)); 8767 8768 SDValue RetVal = 8769 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8770 8771 RetVal = 8772 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8773 dl, VT, RetVal); 8774 8775 return DAG.getMergeValues({RetVal, Chain}, dl); 8776 } 8777 8778 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8779 EVT VT = Op.getValueType(); 8780 unsigned BitWidth = VT.getSizeInBits(); 8781 SDLoc dl(Op); 8782 assert(Op.getNumOperands() == 3 && 8783 VT == Op.getOperand(1).getValueType() && 8784 "Unexpected SHL!"); 8785 8786 // Expand into a bunch of logical ops. Note that these ops 8787 // depend on the PPC behavior for oversized shift amounts. 8788 SDValue Lo = Op.getOperand(0); 8789 SDValue Hi = Op.getOperand(1); 8790 SDValue Amt = Op.getOperand(2); 8791 EVT AmtVT = Amt.getValueType(); 8792 8793 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8794 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8795 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8796 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8797 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8798 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8799 DAG.getConstant(-BitWidth, dl, AmtVT)); 8800 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8801 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8802 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8803 SDValue OutOps[] = { OutLo, OutHi }; 8804 return DAG.getMergeValues(OutOps, dl); 8805 } 8806 8807 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8808 EVT VT = Op.getValueType(); 8809 SDLoc dl(Op); 8810 unsigned BitWidth = VT.getSizeInBits(); 8811 assert(Op.getNumOperands() == 3 && 8812 VT == Op.getOperand(1).getValueType() && 8813 "Unexpected SRL!"); 8814 8815 // Expand into a bunch of logical ops. Note that these ops 8816 // depend on the PPC behavior for oversized shift amounts. 8817 SDValue Lo = Op.getOperand(0); 8818 SDValue Hi = Op.getOperand(1); 8819 SDValue Amt = Op.getOperand(2); 8820 EVT AmtVT = Amt.getValueType(); 8821 8822 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8823 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8824 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8825 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8826 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8827 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8828 DAG.getConstant(-BitWidth, dl, AmtVT)); 8829 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8830 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8831 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8832 SDValue OutOps[] = { OutLo, OutHi }; 8833 return DAG.getMergeValues(OutOps, dl); 8834 } 8835 8836 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8837 SDLoc dl(Op); 8838 EVT VT = Op.getValueType(); 8839 unsigned BitWidth = VT.getSizeInBits(); 8840 assert(Op.getNumOperands() == 3 && 8841 VT == Op.getOperand(1).getValueType() && 8842 "Unexpected SRA!"); 8843 8844 // Expand into a bunch of logical ops, followed by a select_cc. 8845 SDValue Lo = Op.getOperand(0); 8846 SDValue Hi = Op.getOperand(1); 8847 SDValue Amt = Op.getOperand(2); 8848 EVT AmtVT = Amt.getValueType(); 8849 8850 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8851 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8852 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8853 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8854 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8855 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8856 DAG.getConstant(-BitWidth, dl, AmtVT)); 8857 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8858 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8859 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8860 Tmp4, Tmp6, ISD::SETLE); 8861 SDValue OutOps[] = { OutLo, OutHi }; 8862 return DAG.getMergeValues(OutOps, dl); 8863 } 8864 8865 //===----------------------------------------------------------------------===// 8866 // Vector related lowering. 8867 // 8868 8869 /// BuildSplatI - Build a canonical splati of Val with an element size of 8870 /// SplatSize. Cast the result to VT. 8871 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8872 SelectionDAG &DAG, const SDLoc &dl) { 8873 static const MVT VTys[] = { // canonical VT to use for each size. 8874 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8875 }; 8876 8877 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8878 8879 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8880 if (Val == -1) 8881 SplatSize = 1; 8882 8883 EVT CanonicalVT = VTys[SplatSize-1]; 8884 8885 // Build a canonical splat for this value. 8886 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8887 } 8888 8889 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8890 /// specified intrinsic ID. 8891 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8892 const SDLoc &dl, EVT DestVT = MVT::Other) { 8893 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8894 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8895 DAG.getConstant(IID, dl, MVT::i32), Op); 8896 } 8897 8898 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8899 /// specified intrinsic ID. 8900 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8901 SelectionDAG &DAG, const SDLoc &dl, 8902 EVT DestVT = MVT::Other) { 8903 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8904 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8905 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8906 } 8907 8908 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8909 /// specified intrinsic ID. 8910 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8911 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8912 EVT DestVT = MVT::Other) { 8913 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8914 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8915 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8916 } 8917 8918 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8919 /// amount. The result has the specified value type. 8920 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8921 SelectionDAG &DAG, const SDLoc &dl) { 8922 // Force LHS/RHS to be the right type. 8923 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8924 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8925 8926 int Ops[16]; 8927 for (unsigned i = 0; i != 16; ++i) 8928 Ops[i] = i + Amt; 8929 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8930 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8931 } 8932 8933 /// Do we have an efficient pattern in a .td file for this node? 8934 /// 8935 /// \param V - pointer to the BuildVectorSDNode being matched 8936 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8937 /// 8938 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8939 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8940 /// the opposite is true (expansion is beneficial) are: 8941 /// - The node builds a vector out of integers that are not 32 or 64-bits 8942 /// - The node builds a vector out of constants 8943 /// - The node is a "load-and-splat" 8944 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8945 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8946 bool HasDirectMove, 8947 bool HasP8Vector) { 8948 EVT VecVT = V->getValueType(0); 8949 bool RightType = VecVT == MVT::v2f64 || 8950 (HasP8Vector && VecVT == MVT::v4f32) || 8951 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8952 if (!RightType) 8953 return false; 8954 8955 bool IsSplat = true; 8956 bool IsLoad = false; 8957 SDValue Op0 = V->getOperand(0); 8958 8959 // This function is called in a block that confirms the node is not a constant 8960 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8961 // different constants. 8962 if (V->isConstant()) 8963 return false; 8964 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8965 if (V->getOperand(i).isUndef()) 8966 return false; 8967 // We want to expand nodes that represent load-and-splat even if the 8968 // loaded value is a floating point truncation or conversion to int. 8969 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8970 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8971 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8972 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8973 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8974 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8975 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8976 IsLoad = true; 8977 // If the operands are different or the input is not a load and has more 8978 // uses than just this BV node, then it isn't a splat. 8979 if (V->getOperand(i) != Op0 || 8980 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8981 IsSplat = false; 8982 } 8983 return !(IsSplat && IsLoad); 8984 } 8985 8986 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8987 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8988 8989 SDLoc dl(Op); 8990 SDValue Op0 = Op->getOperand(0); 8991 8992 if (!EnableQuadPrecision || 8993 (Op.getValueType() != MVT::f128 ) || 8994 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8995 (Op0.getOperand(0).getValueType() != MVT::i64) || 8996 (Op0.getOperand(1).getValueType() != MVT::i64)) 8997 return SDValue(); 8998 8999 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9000 Op0.getOperand(1)); 9001 } 9002 9003 static const SDValue *getNormalLoadInput(const SDValue &Op) { 9004 const SDValue *InputLoad = &Op; 9005 if (InputLoad->getOpcode() == ISD::BITCAST) 9006 InputLoad = &InputLoad->getOperand(0); 9007 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 9008 InputLoad = &InputLoad->getOperand(0); 9009 if (InputLoad->getOpcode() != ISD::LOAD) 9010 return nullptr; 9011 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9012 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9013 } 9014 9015 // If this is a case we can't handle, return null and let the default 9016 // expansion code take care of it. If we CAN select this case, and if it 9017 // selects to a single instruction, return Op. Otherwise, if we can codegen 9018 // this case more efficiently than a constant pool load, lower it to the 9019 // sequence of ops that should be used. 9020 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9021 SelectionDAG &DAG) const { 9022 SDLoc dl(Op); 9023 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9024 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9025 9026 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9027 // We first build an i32 vector, load it into a QPX register, 9028 // then convert it to a floating-point vector and compare it 9029 // to a zero vector to get the boolean result. 9030 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9031 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9032 MachinePointerInfo PtrInfo = 9033 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9034 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9035 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9036 9037 assert(BVN->getNumOperands() == 4 && 9038 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9039 9040 bool IsConst = true; 9041 for (unsigned i = 0; i < 4; ++i) { 9042 if (BVN->getOperand(i).isUndef()) continue; 9043 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9044 IsConst = false; 9045 break; 9046 } 9047 } 9048 9049 if (IsConst) { 9050 Constant *One = 9051 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9052 Constant *NegOne = 9053 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9054 9055 Constant *CV[4]; 9056 for (unsigned i = 0; i < 4; ++i) { 9057 if (BVN->getOperand(i).isUndef()) 9058 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9059 else if (isNullConstant(BVN->getOperand(i))) 9060 CV[i] = NegOne; 9061 else 9062 CV[i] = One; 9063 } 9064 9065 Constant *CP = ConstantVector::get(CV); 9066 SDValue CPIdx = 9067 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9068 9069 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9070 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9071 return DAG.getMemIntrinsicNode( 9072 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9073 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9074 } 9075 9076 SmallVector<SDValue, 4> Stores; 9077 for (unsigned i = 0; i < 4; ++i) { 9078 if (BVN->getOperand(i).isUndef()) continue; 9079 9080 unsigned Offset = 4*i; 9081 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9082 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9083 9084 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9085 if (StoreSize > 4) { 9086 Stores.push_back( 9087 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9088 PtrInfo.getWithOffset(Offset), MVT::i32)); 9089 } else { 9090 SDValue StoreValue = BVN->getOperand(i); 9091 if (StoreSize < 4) 9092 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9093 9094 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9095 PtrInfo.getWithOffset(Offset))); 9096 } 9097 } 9098 9099 SDValue StoreChain; 9100 if (!Stores.empty()) 9101 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9102 else 9103 StoreChain = DAG.getEntryNode(); 9104 9105 // Now load from v4i32 into the QPX register; this will extend it to 9106 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9107 // is typed as v4f64 because the QPX register integer states are not 9108 // explicitly represented. 9109 9110 SDValue Ops[] = {StoreChain, 9111 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9112 FIdx}; 9113 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9114 9115 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9116 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9117 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9118 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9119 LoadedVect); 9120 9121 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9122 9123 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9124 } 9125 9126 // All other QPX vectors are handled by generic code. 9127 if (Subtarget.hasQPX()) 9128 return SDValue(); 9129 9130 // Check if this is a splat of a constant value. 9131 APInt APSplatBits, APSplatUndef; 9132 unsigned SplatBitSize; 9133 bool HasAnyUndefs; 9134 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9135 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9136 SplatBitSize > 32) { 9137 9138 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9139 // Handle load-and-splat patterns as we have instructions that will do this 9140 // in one go. 9141 if (InputLoad && DAG.isSplatValue(Op, true)) { 9142 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9143 9144 // We have handling for 4 and 8 byte elements. 9145 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9146 9147 // Checking for a single use of this load, we have to check for vector 9148 // width (128 bits) / ElementSize uses (since each operand of the 9149 // BUILD_VECTOR is a separate use of the value. 9150 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9151 ((Subtarget.hasVSX() && ElementSize == 64) || 9152 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9153 SDValue Ops[] = { 9154 LD->getChain(), // Chain 9155 LD->getBasePtr(), // Ptr 9156 DAG.getValueType(Op.getValueType()) // VT 9157 }; 9158 return 9159 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9160 DAG.getVTList(Op.getValueType(), MVT::Other), 9161 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9162 } 9163 } 9164 9165 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9166 // lowered to VSX instructions under certain conditions. 9167 // Without VSX, there is no pattern more efficient than expanding the node. 9168 if (Subtarget.hasVSX() && 9169 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9170 Subtarget.hasP8Vector())) 9171 return Op; 9172 return SDValue(); 9173 } 9174 9175 unsigned SplatBits = APSplatBits.getZExtValue(); 9176 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9177 unsigned SplatSize = SplatBitSize / 8; 9178 9179 // First, handle single instruction cases. 9180 9181 // All zeros? 9182 if (SplatBits == 0) { 9183 // Canonicalize all zero vectors to be v4i32. 9184 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9185 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9186 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9187 } 9188 return Op; 9189 } 9190 9191 // We have XXSPLTIB for constant splats one byte wide 9192 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9193 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9194 if (Subtarget.hasP9Vector() && SplatSize == 1) 9195 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9196 9197 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9198 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9199 (32-SplatBitSize)); 9200 if (SextVal >= -16 && SextVal <= 15) 9201 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9202 9203 // Two instruction sequences. 9204 9205 // If this value is in the range [-32,30] and is even, use: 9206 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9207 // If this value is in the range [17,31] and is odd, use: 9208 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9209 // If this value is in the range [-31,-17] and is odd, use: 9210 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9211 // Note the last two are three-instruction sequences. 9212 if (SextVal >= -32 && SextVal <= 31) { 9213 // To avoid having these optimizations undone by constant folding, 9214 // we convert to a pseudo that will be expanded later into one of 9215 // the above forms. 9216 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9217 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9218 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9219 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9220 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9221 if (VT == Op.getValueType()) 9222 return RetVal; 9223 else 9224 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9225 } 9226 9227 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9228 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9229 // for fneg/fabs. 9230 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9231 // Make -1 and vspltisw -1: 9232 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9233 9234 // Make the VSLW intrinsic, computing 0x8000_0000. 9235 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9236 OnesV, DAG, dl); 9237 9238 // xor by OnesV to invert it. 9239 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9240 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9241 } 9242 9243 // Check to see if this is a wide variety of vsplti*, binop self cases. 9244 static const signed char SplatCsts[] = { 9245 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9246 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9247 }; 9248 9249 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9250 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9251 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9252 int i = SplatCsts[idx]; 9253 9254 // Figure out what shift amount will be used by altivec if shifted by i in 9255 // this splat size. 9256 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9257 9258 // vsplti + shl self. 9259 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9260 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9261 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9262 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9263 Intrinsic::ppc_altivec_vslw 9264 }; 9265 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9266 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9267 } 9268 9269 // vsplti + srl self. 9270 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9271 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9272 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9273 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9274 Intrinsic::ppc_altivec_vsrw 9275 }; 9276 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9277 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9278 } 9279 9280 // vsplti + sra self. 9281 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9282 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9283 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9284 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9285 Intrinsic::ppc_altivec_vsraw 9286 }; 9287 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9288 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9289 } 9290 9291 // vsplti + rol self. 9292 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9293 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9294 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9295 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9296 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9297 Intrinsic::ppc_altivec_vrlw 9298 }; 9299 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9300 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9301 } 9302 9303 // t = vsplti c, result = vsldoi t, t, 1 9304 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9305 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9306 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9307 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9308 } 9309 // t = vsplti c, result = vsldoi t, t, 2 9310 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9311 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9312 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9313 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9314 } 9315 // t = vsplti c, result = vsldoi t, t, 3 9316 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9317 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9318 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9319 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9320 } 9321 } 9322 9323 return SDValue(); 9324 } 9325 9326 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9327 /// the specified operations to build the shuffle. 9328 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9329 SDValue RHS, SelectionDAG &DAG, 9330 const SDLoc &dl) { 9331 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9332 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9333 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9334 9335 enum { 9336 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9337 OP_VMRGHW, 9338 OP_VMRGLW, 9339 OP_VSPLTISW0, 9340 OP_VSPLTISW1, 9341 OP_VSPLTISW2, 9342 OP_VSPLTISW3, 9343 OP_VSLDOI4, 9344 OP_VSLDOI8, 9345 OP_VSLDOI12 9346 }; 9347 9348 if (OpNum == OP_COPY) { 9349 if (LHSID == (1*9+2)*9+3) return LHS; 9350 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9351 return RHS; 9352 } 9353 9354 SDValue OpLHS, OpRHS; 9355 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9356 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9357 9358 int ShufIdxs[16]; 9359 switch (OpNum) { 9360 default: llvm_unreachable("Unknown i32 permute!"); 9361 case OP_VMRGHW: 9362 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9363 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9364 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9365 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9366 break; 9367 case OP_VMRGLW: 9368 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9369 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9370 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9371 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9372 break; 9373 case OP_VSPLTISW0: 9374 for (unsigned i = 0; i != 16; ++i) 9375 ShufIdxs[i] = (i&3)+0; 9376 break; 9377 case OP_VSPLTISW1: 9378 for (unsigned i = 0; i != 16; ++i) 9379 ShufIdxs[i] = (i&3)+4; 9380 break; 9381 case OP_VSPLTISW2: 9382 for (unsigned i = 0; i != 16; ++i) 9383 ShufIdxs[i] = (i&3)+8; 9384 break; 9385 case OP_VSPLTISW3: 9386 for (unsigned i = 0; i != 16; ++i) 9387 ShufIdxs[i] = (i&3)+12; 9388 break; 9389 case OP_VSLDOI4: 9390 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9391 case OP_VSLDOI8: 9392 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9393 case OP_VSLDOI12: 9394 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9395 } 9396 EVT VT = OpLHS.getValueType(); 9397 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9398 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9399 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9400 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9401 } 9402 9403 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9404 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9405 /// SDValue. 9406 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9407 SelectionDAG &DAG) const { 9408 const unsigned BytesInVector = 16; 9409 bool IsLE = Subtarget.isLittleEndian(); 9410 SDLoc dl(N); 9411 SDValue V1 = N->getOperand(0); 9412 SDValue V2 = N->getOperand(1); 9413 unsigned ShiftElts = 0, InsertAtByte = 0; 9414 bool Swap = false; 9415 9416 // Shifts required to get the byte we want at element 7. 9417 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9418 0, 15, 14, 13, 12, 11, 10, 9}; 9419 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9420 1, 2, 3, 4, 5, 6, 7, 8}; 9421 9422 ArrayRef<int> Mask = N->getMask(); 9423 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9424 9425 // For each mask element, find out if we're just inserting something 9426 // from V2 into V1 or vice versa. 9427 // Possible permutations inserting an element from V2 into V1: 9428 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9429 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9430 // ... 9431 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9432 // Inserting from V1 into V2 will be similar, except mask range will be 9433 // [16,31]. 9434 9435 bool FoundCandidate = false; 9436 // If both vector operands for the shuffle are the same vector, the mask 9437 // will contain only elements from the first one and the second one will be 9438 // undef. 9439 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9440 // Go through the mask of half-words to find an element that's being moved 9441 // from one vector to the other. 9442 for (unsigned i = 0; i < BytesInVector; ++i) { 9443 unsigned CurrentElement = Mask[i]; 9444 // If 2nd operand is undefined, we should only look for element 7 in the 9445 // Mask. 9446 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9447 continue; 9448 9449 bool OtherElementsInOrder = true; 9450 // Examine the other elements in the Mask to see if they're in original 9451 // order. 9452 for (unsigned j = 0; j < BytesInVector; ++j) { 9453 if (j == i) 9454 continue; 9455 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9456 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9457 // in which we always assume we're always picking from the 1st operand. 9458 int MaskOffset = 9459 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9460 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9461 OtherElementsInOrder = false; 9462 break; 9463 } 9464 } 9465 // If other elements are in original order, we record the number of shifts 9466 // we need to get the element we want into element 7. Also record which byte 9467 // in the vector we should insert into. 9468 if (OtherElementsInOrder) { 9469 // If 2nd operand is undefined, we assume no shifts and no swapping. 9470 if (V2.isUndef()) { 9471 ShiftElts = 0; 9472 Swap = false; 9473 } else { 9474 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9475 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9476 : BigEndianShifts[CurrentElement & 0xF]; 9477 Swap = CurrentElement < BytesInVector; 9478 } 9479 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9480 FoundCandidate = true; 9481 break; 9482 } 9483 } 9484 9485 if (!FoundCandidate) 9486 return SDValue(); 9487 9488 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9489 // optionally with VECSHL if shift is required. 9490 if (Swap) 9491 std::swap(V1, V2); 9492 if (V2.isUndef()) 9493 V2 = V1; 9494 if (ShiftElts) { 9495 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9496 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9497 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9498 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9499 } 9500 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9501 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9502 } 9503 9504 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9505 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9506 /// SDValue. 9507 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9508 SelectionDAG &DAG) const { 9509 const unsigned NumHalfWords = 8; 9510 const unsigned BytesInVector = NumHalfWords * 2; 9511 // Check that the shuffle is on half-words. 9512 if (!isNByteElemShuffleMask(N, 2, 1)) 9513 return SDValue(); 9514 9515 bool IsLE = Subtarget.isLittleEndian(); 9516 SDLoc dl(N); 9517 SDValue V1 = N->getOperand(0); 9518 SDValue V2 = N->getOperand(1); 9519 unsigned ShiftElts = 0, InsertAtByte = 0; 9520 bool Swap = false; 9521 9522 // Shifts required to get the half-word we want at element 3. 9523 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9524 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9525 9526 uint32_t Mask = 0; 9527 uint32_t OriginalOrderLow = 0x1234567; 9528 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9529 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9530 // 32-bit space, only need 4-bit nibbles per element. 9531 for (unsigned i = 0; i < NumHalfWords; ++i) { 9532 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9533 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9534 } 9535 9536 // For each mask element, find out if we're just inserting something 9537 // from V2 into V1 or vice versa. Possible permutations inserting an element 9538 // from V2 into V1: 9539 // X, 1, 2, 3, 4, 5, 6, 7 9540 // 0, X, 2, 3, 4, 5, 6, 7 9541 // 0, 1, X, 3, 4, 5, 6, 7 9542 // 0, 1, 2, X, 4, 5, 6, 7 9543 // 0, 1, 2, 3, X, 5, 6, 7 9544 // 0, 1, 2, 3, 4, X, 6, 7 9545 // 0, 1, 2, 3, 4, 5, X, 7 9546 // 0, 1, 2, 3, 4, 5, 6, X 9547 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9548 9549 bool FoundCandidate = false; 9550 // Go through the mask of half-words to find an element that's being moved 9551 // from one vector to the other. 9552 for (unsigned i = 0; i < NumHalfWords; ++i) { 9553 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9554 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9555 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9556 uint32_t TargetOrder = 0x0; 9557 9558 // If both vector operands for the shuffle are the same vector, the mask 9559 // will contain only elements from the first one and the second one will be 9560 // undef. 9561 if (V2.isUndef()) { 9562 ShiftElts = 0; 9563 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9564 TargetOrder = OriginalOrderLow; 9565 Swap = false; 9566 // Skip if not the correct element or mask of other elements don't equal 9567 // to our expected order. 9568 if (MaskOneElt == VINSERTHSrcElem && 9569 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9570 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9571 FoundCandidate = true; 9572 break; 9573 } 9574 } else { // If both operands are defined. 9575 // Target order is [8,15] if the current mask is between [0,7]. 9576 TargetOrder = 9577 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9578 // Skip if mask of other elements don't equal our expected order. 9579 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9580 // We only need the last 3 bits for the number of shifts. 9581 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9582 : BigEndianShifts[MaskOneElt & 0x7]; 9583 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9584 Swap = MaskOneElt < NumHalfWords; 9585 FoundCandidate = true; 9586 break; 9587 } 9588 } 9589 } 9590 9591 if (!FoundCandidate) 9592 return SDValue(); 9593 9594 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9595 // optionally with VECSHL if shift is required. 9596 if (Swap) 9597 std::swap(V1, V2); 9598 if (V2.isUndef()) 9599 V2 = V1; 9600 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9601 if (ShiftElts) { 9602 // Double ShiftElts because we're left shifting on v16i8 type. 9603 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9604 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9605 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9606 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9607 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9608 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9609 } 9610 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9611 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9612 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9613 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9614 } 9615 9616 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9617 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9618 /// return the code it can be lowered into. Worst case, it can always be 9619 /// lowered into a vperm. 9620 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9621 SelectionDAG &DAG) const { 9622 SDLoc dl(Op); 9623 SDValue V1 = Op.getOperand(0); 9624 SDValue V2 = Op.getOperand(1); 9625 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9626 EVT VT = Op.getValueType(); 9627 bool isLittleEndian = Subtarget.isLittleEndian(); 9628 9629 unsigned ShiftElts, InsertAtByte; 9630 bool Swap = false; 9631 9632 // If this is a load-and-splat, we can do that with a single instruction 9633 // in some cases. However if the load has multiple uses, we don't want to 9634 // combine it because that will just produce multiple loads. 9635 const SDValue *InputLoad = getNormalLoadInput(V1); 9636 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9637 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9638 InputLoad->hasOneUse()) { 9639 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9640 int SplatIdx = 9641 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9642 9643 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9644 // For 4-byte load-and-splat, we need Power9. 9645 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9646 uint64_t Offset = 0; 9647 if (IsFourByte) 9648 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9649 else 9650 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9651 SDValue BasePtr = LD->getBasePtr(); 9652 if (Offset != 0) 9653 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9654 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9655 SDValue Ops[] = { 9656 LD->getChain(), // Chain 9657 BasePtr, // BasePtr 9658 DAG.getValueType(Op.getValueType()) // VT 9659 }; 9660 SDVTList VTL = 9661 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9662 SDValue LdSplt = 9663 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9664 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9665 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9666 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9667 return LdSplt; 9668 } 9669 } 9670 if (Subtarget.hasP9Vector() && 9671 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9672 isLittleEndian)) { 9673 if (Swap) 9674 std::swap(V1, V2); 9675 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9676 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9677 if (ShiftElts) { 9678 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9679 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9680 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9681 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9682 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9683 } 9684 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9685 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9686 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9687 } 9688 9689 if (Subtarget.hasP9Altivec()) { 9690 SDValue NewISDNode; 9691 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9692 return NewISDNode; 9693 9694 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9695 return NewISDNode; 9696 } 9697 9698 if (Subtarget.hasVSX() && 9699 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9700 if (Swap) 9701 std::swap(V1, V2); 9702 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9703 SDValue Conv2 = 9704 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9705 9706 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9707 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9708 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9709 } 9710 9711 if (Subtarget.hasVSX() && 9712 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9713 if (Swap) 9714 std::swap(V1, V2); 9715 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9716 SDValue Conv2 = 9717 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9718 9719 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9720 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9721 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9722 } 9723 9724 if (Subtarget.hasP9Vector()) { 9725 if (PPC::isXXBRHShuffleMask(SVOp)) { 9726 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9727 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9728 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9729 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9730 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9731 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9732 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9733 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9734 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9735 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9736 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9737 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9738 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9739 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9740 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9741 } 9742 } 9743 9744 if (Subtarget.hasVSX()) { 9745 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9746 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9747 9748 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9749 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9750 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9751 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9752 } 9753 9754 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9755 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9756 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9757 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9758 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9759 } 9760 } 9761 9762 if (Subtarget.hasQPX()) { 9763 if (VT.getVectorNumElements() != 4) 9764 return SDValue(); 9765 9766 if (V2.isUndef()) V2 = V1; 9767 9768 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9769 if (AlignIdx != -1) { 9770 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9771 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9772 } else if (SVOp->isSplat()) { 9773 int SplatIdx = SVOp->getSplatIndex(); 9774 if (SplatIdx >= 4) { 9775 std::swap(V1, V2); 9776 SplatIdx -= 4; 9777 } 9778 9779 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9780 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9781 } 9782 9783 // Lower this into a qvgpci/qvfperm pair. 9784 9785 // Compute the qvgpci literal 9786 unsigned idx = 0; 9787 for (unsigned i = 0; i < 4; ++i) { 9788 int m = SVOp->getMaskElt(i); 9789 unsigned mm = m >= 0 ? (unsigned) m : i; 9790 idx |= mm << (3-i)*3; 9791 } 9792 9793 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9794 DAG.getConstant(idx, dl, MVT::i32)); 9795 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9796 } 9797 9798 // Cases that are handled by instructions that take permute immediates 9799 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9800 // selected by the instruction selector. 9801 if (V2.isUndef()) { 9802 if (PPC::isSplatShuffleMask(SVOp, 1) || 9803 PPC::isSplatShuffleMask(SVOp, 2) || 9804 PPC::isSplatShuffleMask(SVOp, 4) || 9805 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9806 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9807 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9808 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9809 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9810 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9811 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9812 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9813 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9814 (Subtarget.hasP8Altivec() && ( 9815 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9816 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9817 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9818 return Op; 9819 } 9820 } 9821 9822 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9823 // and produce a fixed permutation. If any of these match, do not lower to 9824 // VPERM. 9825 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9826 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9827 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9828 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9829 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9830 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9831 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9832 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9833 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9834 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9835 (Subtarget.hasP8Altivec() && ( 9836 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9837 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9838 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9839 return Op; 9840 9841 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9842 // perfect shuffle table to emit an optimal matching sequence. 9843 ArrayRef<int> PermMask = SVOp->getMask(); 9844 9845 unsigned PFIndexes[4]; 9846 bool isFourElementShuffle = true; 9847 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9848 unsigned EltNo = 8; // Start out undef. 9849 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9850 if (PermMask[i*4+j] < 0) 9851 continue; // Undef, ignore it. 9852 9853 unsigned ByteSource = PermMask[i*4+j]; 9854 if ((ByteSource & 3) != j) { 9855 isFourElementShuffle = false; 9856 break; 9857 } 9858 9859 if (EltNo == 8) { 9860 EltNo = ByteSource/4; 9861 } else if (EltNo != ByteSource/4) { 9862 isFourElementShuffle = false; 9863 break; 9864 } 9865 } 9866 PFIndexes[i] = EltNo; 9867 } 9868 9869 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9870 // perfect shuffle vector to determine if it is cost effective to do this as 9871 // discrete instructions, or whether we should use a vperm. 9872 // For now, we skip this for little endian until such time as we have a 9873 // little-endian perfect shuffle table. 9874 if (isFourElementShuffle && !isLittleEndian) { 9875 // Compute the index in the perfect shuffle table. 9876 unsigned PFTableIndex = 9877 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9878 9879 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9880 unsigned Cost = (PFEntry >> 30); 9881 9882 // Determining when to avoid vperm is tricky. Many things affect the cost 9883 // of vperm, particularly how many times the perm mask needs to be computed. 9884 // For example, if the perm mask can be hoisted out of a loop or is already 9885 // used (perhaps because there are multiple permutes with the same shuffle 9886 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9887 // the loop requires an extra register. 9888 // 9889 // As a compromise, we only emit discrete instructions if the shuffle can be 9890 // generated in 3 or fewer operations. When we have loop information 9891 // available, if this block is within a loop, we should avoid using vperm 9892 // for 3-operation perms and use a constant pool load instead. 9893 if (Cost < 3) 9894 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9895 } 9896 9897 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9898 // vector that will get spilled to the constant pool. 9899 if (V2.isUndef()) V2 = V1; 9900 9901 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9902 // that it is in input element units, not in bytes. Convert now. 9903 9904 // For little endian, the order of the input vectors is reversed, and 9905 // the permutation mask is complemented with respect to 31. This is 9906 // necessary to produce proper semantics with the big-endian-biased vperm 9907 // instruction. 9908 EVT EltVT = V1.getValueType().getVectorElementType(); 9909 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9910 9911 SmallVector<SDValue, 16> ResultMask; 9912 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9913 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9914 9915 for (unsigned j = 0; j != BytesPerElement; ++j) 9916 if (isLittleEndian) 9917 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9918 dl, MVT::i32)); 9919 else 9920 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9921 MVT::i32)); 9922 } 9923 9924 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9925 if (isLittleEndian) 9926 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9927 V2, V1, VPermMask); 9928 else 9929 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9930 V1, V2, VPermMask); 9931 } 9932 9933 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9934 /// vector comparison. If it is, return true and fill in Opc/isDot with 9935 /// information about the intrinsic. 9936 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9937 bool &isDot, const PPCSubtarget &Subtarget) { 9938 unsigned IntrinsicID = 9939 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9940 CompareOpc = -1; 9941 isDot = false; 9942 switch (IntrinsicID) { 9943 default: 9944 return false; 9945 // Comparison predicates. 9946 case Intrinsic::ppc_altivec_vcmpbfp_p: 9947 CompareOpc = 966; 9948 isDot = true; 9949 break; 9950 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9951 CompareOpc = 198; 9952 isDot = true; 9953 break; 9954 case Intrinsic::ppc_altivec_vcmpequb_p: 9955 CompareOpc = 6; 9956 isDot = true; 9957 break; 9958 case Intrinsic::ppc_altivec_vcmpequh_p: 9959 CompareOpc = 70; 9960 isDot = true; 9961 break; 9962 case Intrinsic::ppc_altivec_vcmpequw_p: 9963 CompareOpc = 134; 9964 isDot = true; 9965 break; 9966 case Intrinsic::ppc_altivec_vcmpequd_p: 9967 if (Subtarget.hasP8Altivec()) { 9968 CompareOpc = 199; 9969 isDot = true; 9970 } else 9971 return false; 9972 break; 9973 case Intrinsic::ppc_altivec_vcmpneb_p: 9974 case Intrinsic::ppc_altivec_vcmpneh_p: 9975 case Intrinsic::ppc_altivec_vcmpnew_p: 9976 case Intrinsic::ppc_altivec_vcmpnezb_p: 9977 case Intrinsic::ppc_altivec_vcmpnezh_p: 9978 case Intrinsic::ppc_altivec_vcmpnezw_p: 9979 if (Subtarget.hasP9Altivec()) { 9980 switch (IntrinsicID) { 9981 default: 9982 llvm_unreachable("Unknown comparison intrinsic."); 9983 case Intrinsic::ppc_altivec_vcmpneb_p: 9984 CompareOpc = 7; 9985 break; 9986 case Intrinsic::ppc_altivec_vcmpneh_p: 9987 CompareOpc = 71; 9988 break; 9989 case Intrinsic::ppc_altivec_vcmpnew_p: 9990 CompareOpc = 135; 9991 break; 9992 case Intrinsic::ppc_altivec_vcmpnezb_p: 9993 CompareOpc = 263; 9994 break; 9995 case Intrinsic::ppc_altivec_vcmpnezh_p: 9996 CompareOpc = 327; 9997 break; 9998 case Intrinsic::ppc_altivec_vcmpnezw_p: 9999 CompareOpc = 391; 10000 break; 10001 } 10002 isDot = true; 10003 } else 10004 return false; 10005 break; 10006 case Intrinsic::ppc_altivec_vcmpgefp_p: 10007 CompareOpc = 454; 10008 isDot = true; 10009 break; 10010 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10011 CompareOpc = 710; 10012 isDot = true; 10013 break; 10014 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10015 CompareOpc = 774; 10016 isDot = true; 10017 break; 10018 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10019 CompareOpc = 838; 10020 isDot = true; 10021 break; 10022 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10023 CompareOpc = 902; 10024 isDot = true; 10025 break; 10026 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10027 if (Subtarget.hasP8Altivec()) { 10028 CompareOpc = 967; 10029 isDot = true; 10030 } else 10031 return false; 10032 break; 10033 case Intrinsic::ppc_altivec_vcmpgtub_p: 10034 CompareOpc = 518; 10035 isDot = true; 10036 break; 10037 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10038 CompareOpc = 582; 10039 isDot = true; 10040 break; 10041 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10042 CompareOpc = 646; 10043 isDot = true; 10044 break; 10045 case Intrinsic::ppc_altivec_vcmpgtud_p: 10046 if (Subtarget.hasP8Altivec()) { 10047 CompareOpc = 711; 10048 isDot = true; 10049 } else 10050 return false; 10051 break; 10052 10053 // VSX predicate comparisons use the same infrastructure 10054 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10055 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10056 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10057 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10058 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10059 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10060 if (Subtarget.hasVSX()) { 10061 switch (IntrinsicID) { 10062 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10063 CompareOpc = 99; 10064 break; 10065 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10066 CompareOpc = 115; 10067 break; 10068 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10069 CompareOpc = 107; 10070 break; 10071 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10072 CompareOpc = 67; 10073 break; 10074 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10075 CompareOpc = 83; 10076 break; 10077 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10078 CompareOpc = 75; 10079 break; 10080 } 10081 isDot = true; 10082 } else 10083 return false; 10084 break; 10085 10086 // Normal Comparisons. 10087 case Intrinsic::ppc_altivec_vcmpbfp: 10088 CompareOpc = 966; 10089 break; 10090 case Intrinsic::ppc_altivec_vcmpeqfp: 10091 CompareOpc = 198; 10092 break; 10093 case Intrinsic::ppc_altivec_vcmpequb: 10094 CompareOpc = 6; 10095 break; 10096 case Intrinsic::ppc_altivec_vcmpequh: 10097 CompareOpc = 70; 10098 break; 10099 case Intrinsic::ppc_altivec_vcmpequw: 10100 CompareOpc = 134; 10101 break; 10102 case Intrinsic::ppc_altivec_vcmpequd: 10103 if (Subtarget.hasP8Altivec()) 10104 CompareOpc = 199; 10105 else 10106 return false; 10107 break; 10108 case Intrinsic::ppc_altivec_vcmpneb: 10109 case Intrinsic::ppc_altivec_vcmpneh: 10110 case Intrinsic::ppc_altivec_vcmpnew: 10111 case Intrinsic::ppc_altivec_vcmpnezb: 10112 case Intrinsic::ppc_altivec_vcmpnezh: 10113 case Intrinsic::ppc_altivec_vcmpnezw: 10114 if (Subtarget.hasP9Altivec()) 10115 switch (IntrinsicID) { 10116 default: 10117 llvm_unreachable("Unknown comparison intrinsic."); 10118 case Intrinsic::ppc_altivec_vcmpneb: 10119 CompareOpc = 7; 10120 break; 10121 case Intrinsic::ppc_altivec_vcmpneh: 10122 CompareOpc = 71; 10123 break; 10124 case Intrinsic::ppc_altivec_vcmpnew: 10125 CompareOpc = 135; 10126 break; 10127 case Intrinsic::ppc_altivec_vcmpnezb: 10128 CompareOpc = 263; 10129 break; 10130 case Intrinsic::ppc_altivec_vcmpnezh: 10131 CompareOpc = 327; 10132 break; 10133 case Intrinsic::ppc_altivec_vcmpnezw: 10134 CompareOpc = 391; 10135 break; 10136 } 10137 else 10138 return false; 10139 break; 10140 case Intrinsic::ppc_altivec_vcmpgefp: 10141 CompareOpc = 454; 10142 break; 10143 case Intrinsic::ppc_altivec_vcmpgtfp: 10144 CompareOpc = 710; 10145 break; 10146 case Intrinsic::ppc_altivec_vcmpgtsb: 10147 CompareOpc = 774; 10148 break; 10149 case Intrinsic::ppc_altivec_vcmpgtsh: 10150 CompareOpc = 838; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpgtsw: 10153 CompareOpc = 902; 10154 break; 10155 case Intrinsic::ppc_altivec_vcmpgtsd: 10156 if (Subtarget.hasP8Altivec()) 10157 CompareOpc = 967; 10158 else 10159 return false; 10160 break; 10161 case Intrinsic::ppc_altivec_vcmpgtub: 10162 CompareOpc = 518; 10163 break; 10164 case Intrinsic::ppc_altivec_vcmpgtuh: 10165 CompareOpc = 582; 10166 break; 10167 case Intrinsic::ppc_altivec_vcmpgtuw: 10168 CompareOpc = 646; 10169 break; 10170 case Intrinsic::ppc_altivec_vcmpgtud: 10171 if (Subtarget.hasP8Altivec()) 10172 CompareOpc = 711; 10173 else 10174 return false; 10175 break; 10176 } 10177 return true; 10178 } 10179 10180 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10181 /// lower, do it, otherwise return null. 10182 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10183 SelectionDAG &DAG) const { 10184 unsigned IntrinsicID = 10185 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10186 10187 SDLoc dl(Op); 10188 10189 if (IntrinsicID == Intrinsic::thread_pointer) { 10190 // Reads the thread pointer register, used for __builtin_thread_pointer. 10191 if (Subtarget.isPPC64()) 10192 return DAG.getRegister(PPC::X13, MVT::i64); 10193 return DAG.getRegister(PPC::R2, MVT::i32); 10194 } 10195 10196 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10197 // opcode number of the comparison. 10198 int CompareOpc; 10199 bool isDot; 10200 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10201 return SDValue(); // Don't custom lower most intrinsics. 10202 10203 // If this is a non-dot comparison, make the VCMP node and we are done. 10204 if (!isDot) { 10205 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10206 Op.getOperand(1), Op.getOperand(2), 10207 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10208 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10209 } 10210 10211 // Create the PPCISD altivec 'dot' comparison node. 10212 SDValue Ops[] = { 10213 Op.getOperand(2), // LHS 10214 Op.getOperand(3), // RHS 10215 DAG.getConstant(CompareOpc, dl, MVT::i32) 10216 }; 10217 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10218 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10219 10220 // Now that we have the comparison, emit a copy from the CR to a GPR. 10221 // This is flagged to the above dot comparison. 10222 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10223 DAG.getRegister(PPC::CR6, MVT::i32), 10224 CompNode.getValue(1)); 10225 10226 // Unpack the result based on how the target uses it. 10227 unsigned BitNo; // Bit # of CR6. 10228 bool InvertBit; // Invert result? 10229 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10230 default: // Can't happen, don't crash on invalid number though. 10231 case 0: // Return the value of the EQ bit of CR6. 10232 BitNo = 0; InvertBit = false; 10233 break; 10234 case 1: // Return the inverted value of the EQ bit of CR6. 10235 BitNo = 0; InvertBit = true; 10236 break; 10237 case 2: // Return the value of the LT bit of CR6. 10238 BitNo = 2; InvertBit = false; 10239 break; 10240 case 3: // Return the inverted value of the LT bit of CR6. 10241 BitNo = 2; InvertBit = true; 10242 break; 10243 } 10244 10245 // Shift the bit into the low position. 10246 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10247 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10248 // Isolate the bit. 10249 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10250 DAG.getConstant(1, dl, MVT::i32)); 10251 10252 // If we are supposed to, toggle the bit. 10253 if (InvertBit) 10254 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10255 DAG.getConstant(1, dl, MVT::i32)); 10256 return Flags; 10257 } 10258 10259 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10260 SelectionDAG &DAG) const { 10261 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10262 // the beginning of the argument list. 10263 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10264 SDLoc DL(Op); 10265 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10266 case Intrinsic::ppc_cfence: { 10267 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10268 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10269 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10270 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10271 Op.getOperand(ArgStart + 1)), 10272 Op.getOperand(0)), 10273 0); 10274 } 10275 default: 10276 break; 10277 } 10278 return SDValue(); 10279 } 10280 10281 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10282 // Check for a DIV with the same operands as this REM. 10283 for (auto UI : Op.getOperand(1)->uses()) { 10284 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10285 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10286 if (UI->getOperand(0) == Op.getOperand(0) && 10287 UI->getOperand(1) == Op.getOperand(1)) 10288 return SDValue(); 10289 } 10290 return Op; 10291 } 10292 10293 // Lower scalar BSWAP64 to xxbrd. 10294 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10295 SDLoc dl(Op); 10296 // MTVSRDD 10297 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10298 Op.getOperand(0)); 10299 // XXBRD 10300 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10301 // MFVSRD 10302 int VectorIndex = 0; 10303 if (Subtarget.isLittleEndian()) 10304 VectorIndex = 1; 10305 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10306 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10307 return Op; 10308 } 10309 10310 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10311 // compared to a value that is atomically loaded (atomic loads zero-extend). 10312 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10313 SelectionDAG &DAG) const { 10314 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10315 "Expecting an atomic compare-and-swap here."); 10316 SDLoc dl(Op); 10317 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10318 EVT MemVT = AtomicNode->getMemoryVT(); 10319 if (MemVT.getSizeInBits() >= 32) 10320 return Op; 10321 10322 SDValue CmpOp = Op.getOperand(2); 10323 // If this is already correctly zero-extended, leave it alone. 10324 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10325 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10326 return Op; 10327 10328 // Clear the high bits of the compare operand. 10329 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10330 SDValue NewCmpOp = 10331 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10332 DAG.getConstant(MaskVal, dl, MVT::i32)); 10333 10334 // Replace the existing compare operand with the properly zero-extended one. 10335 SmallVector<SDValue, 4> Ops; 10336 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10337 Ops.push_back(AtomicNode->getOperand(i)); 10338 Ops[2] = NewCmpOp; 10339 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10340 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10341 auto NodeTy = 10342 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10343 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10344 } 10345 10346 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10347 SelectionDAG &DAG) const { 10348 SDLoc dl(Op); 10349 // Create a stack slot that is 16-byte aligned. 10350 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10351 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10352 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10353 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10354 10355 // Store the input value into Value#0 of the stack slot. 10356 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10357 MachinePointerInfo()); 10358 // Load it out. 10359 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10360 } 10361 10362 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10363 SelectionDAG &DAG) const { 10364 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10365 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10366 10367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10368 // We have legal lowering for constant indices but not for variable ones. 10369 if (!C) 10370 return SDValue(); 10371 10372 EVT VT = Op.getValueType(); 10373 SDLoc dl(Op); 10374 SDValue V1 = Op.getOperand(0); 10375 SDValue V2 = Op.getOperand(1); 10376 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10377 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10378 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10379 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10380 unsigned InsertAtElement = C->getZExtValue(); 10381 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10382 if (Subtarget.isLittleEndian()) { 10383 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10384 } 10385 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10386 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10387 } 10388 return Op; 10389 } 10390 10391 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10392 SelectionDAG &DAG) const { 10393 SDLoc dl(Op); 10394 SDNode *N = Op.getNode(); 10395 10396 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10397 "Unknown extract_vector_elt type"); 10398 10399 SDValue Value = N->getOperand(0); 10400 10401 // The first part of this is like the store lowering except that we don't 10402 // need to track the chain. 10403 10404 // The values are now known to be -1 (false) or 1 (true). To convert this 10405 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10406 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10407 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10408 10409 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10410 // understand how to form the extending load. 10411 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10412 10413 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10414 10415 // Now convert to an integer and store. 10416 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10417 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10418 Value); 10419 10420 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10421 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10422 MachinePointerInfo PtrInfo = 10423 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10424 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10425 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10426 10427 SDValue StoreChain = DAG.getEntryNode(); 10428 SDValue Ops[] = {StoreChain, 10429 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10430 Value, FIdx}; 10431 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10432 10433 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10434 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10435 10436 // Extract the value requested. 10437 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10438 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10439 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10440 10441 SDValue IntVal = 10442 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10443 10444 if (!Subtarget.useCRBits()) 10445 return IntVal; 10446 10447 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10448 } 10449 10450 /// Lowering for QPX v4i1 loads 10451 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10452 SelectionDAG &DAG) const { 10453 SDLoc dl(Op); 10454 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10455 SDValue LoadChain = LN->getChain(); 10456 SDValue BasePtr = LN->getBasePtr(); 10457 10458 if (Op.getValueType() == MVT::v4f64 || 10459 Op.getValueType() == MVT::v4f32) { 10460 EVT MemVT = LN->getMemoryVT(); 10461 unsigned Alignment = LN->getAlignment(); 10462 10463 // If this load is properly aligned, then it is legal. 10464 if (Alignment >= MemVT.getStoreSize()) 10465 return Op; 10466 10467 EVT ScalarVT = Op.getValueType().getScalarType(), 10468 ScalarMemVT = MemVT.getScalarType(); 10469 unsigned Stride = ScalarMemVT.getStoreSize(); 10470 10471 SDValue Vals[4], LoadChains[4]; 10472 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10473 SDValue Load; 10474 if (ScalarVT != ScalarMemVT) 10475 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10476 BasePtr, 10477 LN->getPointerInfo().getWithOffset(Idx * Stride), 10478 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10479 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10480 else 10481 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10482 LN->getPointerInfo().getWithOffset(Idx * Stride), 10483 MinAlign(Alignment, Idx * Stride), 10484 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10485 10486 if (Idx == 0 && LN->isIndexed()) { 10487 assert(LN->getAddressingMode() == ISD::PRE_INC && 10488 "Unknown addressing mode on vector load"); 10489 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10490 LN->getAddressingMode()); 10491 } 10492 10493 Vals[Idx] = Load; 10494 LoadChains[Idx] = Load.getValue(1); 10495 10496 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10497 DAG.getConstant(Stride, dl, 10498 BasePtr.getValueType())); 10499 } 10500 10501 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10502 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10503 10504 if (LN->isIndexed()) { 10505 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10506 return DAG.getMergeValues(RetOps, dl); 10507 } 10508 10509 SDValue RetOps[] = { Value, TF }; 10510 return DAG.getMergeValues(RetOps, dl); 10511 } 10512 10513 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10514 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10515 10516 // To lower v4i1 from a byte array, we load the byte elements of the 10517 // vector and then reuse the BUILD_VECTOR logic. 10518 10519 SDValue VectElmts[4], VectElmtChains[4]; 10520 for (unsigned i = 0; i < 4; ++i) { 10521 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10522 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10523 10524 VectElmts[i] = DAG.getExtLoad( 10525 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10526 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10527 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10528 VectElmtChains[i] = VectElmts[i].getValue(1); 10529 } 10530 10531 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10532 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10533 10534 SDValue RVals[] = { Value, LoadChain }; 10535 return DAG.getMergeValues(RVals, dl); 10536 } 10537 10538 /// Lowering for QPX v4i1 stores 10539 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10540 SelectionDAG &DAG) const { 10541 SDLoc dl(Op); 10542 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10543 SDValue StoreChain = SN->getChain(); 10544 SDValue BasePtr = SN->getBasePtr(); 10545 SDValue Value = SN->getValue(); 10546 10547 if (Value.getValueType() == MVT::v4f64 || 10548 Value.getValueType() == MVT::v4f32) { 10549 EVT MemVT = SN->getMemoryVT(); 10550 unsigned Alignment = SN->getAlignment(); 10551 10552 // If this store is properly aligned, then it is legal. 10553 if (Alignment >= MemVT.getStoreSize()) 10554 return Op; 10555 10556 EVT ScalarVT = Value.getValueType().getScalarType(), 10557 ScalarMemVT = MemVT.getScalarType(); 10558 unsigned Stride = ScalarMemVT.getStoreSize(); 10559 10560 SDValue Stores[4]; 10561 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10562 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10563 DAG.getVectorIdxConstant(Idx, dl)); 10564 SDValue Store; 10565 if (ScalarVT != ScalarMemVT) 10566 Store = 10567 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10568 SN->getPointerInfo().getWithOffset(Idx * Stride), 10569 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10570 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10571 else 10572 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10573 SN->getPointerInfo().getWithOffset(Idx * Stride), 10574 MinAlign(Alignment, Idx * Stride), 10575 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10576 10577 if (Idx == 0 && SN->isIndexed()) { 10578 assert(SN->getAddressingMode() == ISD::PRE_INC && 10579 "Unknown addressing mode on vector store"); 10580 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10581 SN->getAddressingMode()); 10582 } 10583 10584 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10585 DAG.getConstant(Stride, dl, 10586 BasePtr.getValueType())); 10587 Stores[Idx] = Store; 10588 } 10589 10590 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10591 10592 if (SN->isIndexed()) { 10593 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10594 return DAG.getMergeValues(RetOps, dl); 10595 } 10596 10597 return TF; 10598 } 10599 10600 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10601 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10602 10603 // The values are now known to be -1 (false) or 1 (true). To convert this 10604 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10605 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10606 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10607 10608 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10609 // understand how to form the extending load. 10610 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10611 10612 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10613 10614 // Now convert to an integer and store. 10615 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10616 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10617 Value); 10618 10619 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10620 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10621 MachinePointerInfo PtrInfo = 10622 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10623 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10624 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10625 10626 SDValue Ops[] = {StoreChain, 10627 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10628 Value, FIdx}; 10629 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10630 10631 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10632 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10633 10634 // Move data into the byte array. 10635 SDValue Loads[4], LoadChains[4]; 10636 for (unsigned i = 0; i < 4; ++i) { 10637 unsigned Offset = 4*i; 10638 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10639 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10640 10641 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10642 PtrInfo.getWithOffset(Offset)); 10643 LoadChains[i] = Loads[i].getValue(1); 10644 } 10645 10646 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10647 10648 SDValue Stores[4]; 10649 for (unsigned i = 0; i < 4; ++i) { 10650 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10651 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10652 10653 Stores[i] = DAG.getTruncStore( 10654 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10655 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10656 SN->getAAInfo()); 10657 } 10658 10659 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10660 10661 return StoreChain; 10662 } 10663 10664 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10665 SDLoc dl(Op); 10666 if (Op.getValueType() == MVT::v4i32) { 10667 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10668 10669 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10670 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10671 10672 SDValue RHSSwap = // = vrlw RHS, 16 10673 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10674 10675 // Shrinkify inputs to v8i16. 10676 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10677 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10678 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10679 10680 // Low parts multiplied together, generating 32-bit results (we ignore the 10681 // top parts). 10682 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10683 LHS, RHS, DAG, dl, MVT::v4i32); 10684 10685 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10686 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10687 // Shift the high parts up 16 bits. 10688 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10689 Neg16, DAG, dl); 10690 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10691 } else if (Op.getValueType() == MVT::v16i8) { 10692 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10693 bool isLittleEndian = Subtarget.isLittleEndian(); 10694 10695 // Multiply the even 8-bit parts, producing 16-bit sums. 10696 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10697 LHS, RHS, DAG, dl, MVT::v8i16); 10698 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10699 10700 // Multiply the odd 8-bit parts, producing 16-bit sums. 10701 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10702 LHS, RHS, DAG, dl, MVT::v8i16); 10703 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10704 10705 // Merge the results together. Because vmuleub and vmuloub are 10706 // instructions with a big-endian bias, we must reverse the 10707 // element numbering and reverse the meaning of "odd" and "even" 10708 // when generating little endian code. 10709 int Ops[16]; 10710 for (unsigned i = 0; i != 8; ++i) { 10711 if (isLittleEndian) { 10712 Ops[i*2 ] = 2*i; 10713 Ops[i*2+1] = 2*i+16; 10714 } else { 10715 Ops[i*2 ] = 2*i+1; 10716 Ops[i*2+1] = 2*i+1+16; 10717 } 10718 } 10719 if (isLittleEndian) 10720 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10721 else 10722 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10723 } else { 10724 llvm_unreachable("Unknown mul to lower!"); 10725 } 10726 } 10727 10728 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10729 10730 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10731 10732 EVT VT = Op.getValueType(); 10733 assert(VT.isVector() && 10734 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10735 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10736 VT == MVT::v16i8) && 10737 "Unexpected vector element type!"); 10738 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10739 "Current subtarget doesn't support smax v2i64!"); 10740 10741 // For vector abs, it can be lowered to: 10742 // abs x 10743 // ==> 10744 // y = -x 10745 // smax(x, y) 10746 10747 SDLoc dl(Op); 10748 SDValue X = Op.getOperand(0); 10749 SDValue Zero = DAG.getConstant(0, dl, VT); 10750 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10751 10752 // SMAX patch https://reviews.llvm.org/D47332 10753 // hasn't landed yet, so use intrinsic first here. 10754 // TODO: Should use SMAX directly once SMAX patch landed 10755 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10756 if (VT == MVT::v2i64) 10757 BifID = Intrinsic::ppc_altivec_vmaxsd; 10758 else if (VT == MVT::v8i16) 10759 BifID = Intrinsic::ppc_altivec_vmaxsh; 10760 else if (VT == MVT::v16i8) 10761 BifID = Intrinsic::ppc_altivec_vmaxsb; 10762 10763 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10764 } 10765 10766 // Custom lowering for fpext vf32 to v2f64 10767 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10768 10769 assert(Op.getOpcode() == ISD::FP_EXTEND && 10770 "Should only be called for ISD::FP_EXTEND"); 10771 10772 // FIXME: handle extends from half precision float vectors on P9. 10773 // We only want to custom lower an extend from v2f32 to v2f64. 10774 if (Op.getValueType() != MVT::v2f64 || 10775 Op.getOperand(0).getValueType() != MVT::v2f32) 10776 return SDValue(); 10777 10778 SDLoc dl(Op); 10779 SDValue Op0 = Op.getOperand(0); 10780 10781 switch (Op0.getOpcode()) { 10782 default: 10783 return SDValue(); 10784 case ISD::EXTRACT_SUBVECTOR: { 10785 assert(Op0.getNumOperands() == 2 && 10786 isa<ConstantSDNode>(Op0->getOperand(1)) && 10787 "Node should have 2 operands with second one being a constant!"); 10788 10789 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10790 return SDValue(); 10791 10792 // Custom lower is only done for high or low doubleword. 10793 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10794 if (Idx % 2 != 0) 10795 return SDValue(); 10796 10797 // Since input is v4f32, at this point Idx is either 0 or 2. 10798 // Shift to get the doubleword position we want. 10799 int DWord = Idx >> 1; 10800 10801 // High and low word positions are different on little endian. 10802 if (Subtarget.isLittleEndian()) 10803 DWord ^= 0x1; 10804 10805 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10806 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10807 } 10808 case ISD::FADD: 10809 case ISD::FMUL: 10810 case ISD::FSUB: { 10811 SDValue NewLoad[2]; 10812 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10813 // Ensure both input are loads. 10814 SDValue LdOp = Op0.getOperand(i); 10815 if (LdOp.getOpcode() != ISD::LOAD) 10816 return SDValue(); 10817 // Generate new load node. 10818 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10819 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10820 NewLoad[i] = DAG.getMemIntrinsicNode( 10821 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10822 LD->getMemoryVT(), LD->getMemOperand()); 10823 } 10824 SDValue NewOp = 10825 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10826 NewLoad[1], Op0.getNode()->getFlags()); 10827 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10828 DAG.getConstant(0, dl, MVT::i32)); 10829 } 10830 case ISD::LOAD: { 10831 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10832 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10833 SDValue NewLd = DAG.getMemIntrinsicNode( 10834 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10835 LD->getMemoryVT(), LD->getMemOperand()); 10836 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10837 DAG.getConstant(0, dl, MVT::i32)); 10838 } 10839 } 10840 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10841 } 10842 10843 /// LowerOperation - Provide custom lowering hooks for some operations. 10844 /// 10845 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10846 switch (Op.getOpcode()) { 10847 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10848 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10849 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10850 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10851 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10852 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10853 case ISD::SETCC: return LowerSETCC(Op, DAG); 10854 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10855 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10856 10857 // Variable argument lowering. 10858 case ISD::VASTART: return LowerVASTART(Op, DAG); 10859 case ISD::VAARG: return LowerVAARG(Op, DAG); 10860 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10861 10862 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10863 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10864 case ISD::GET_DYNAMIC_AREA_OFFSET: 10865 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10866 10867 // Exception handling lowering. 10868 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10869 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10870 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10871 10872 case ISD::LOAD: return LowerLOAD(Op, DAG); 10873 case ISD::STORE: return LowerSTORE(Op, DAG); 10874 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10875 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10876 case ISD::FP_TO_UINT: 10877 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10878 case ISD::UINT_TO_FP: 10879 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10880 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10881 10882 // Lower 64-bit shifts. 10883 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10884 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10885 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10886 10887 // Vector-related lowering. 10888 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10889 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10890 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10891 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10892 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10893 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10894 case ISD::MUL: return LowerMUL(Op, DAG); 10895 case ISD::ABS: return LowerABS(Op, DAG); 10896 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10897 10898 // For counter-based loop handling. 10899 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10900 10901 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10902 10903 // Frame & Return address. 10904 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10905 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10906 10907 case ISD::INTRINSIC_VOID: 10908 return LowerINTRINSIC_VOID(Op, DAG); 10909 case ISD::SREM: 10910 case ISD::UREM: 10911 return LowerREM(Op, DAG); 10912 case ISD::BSWAP: 10913 return LowerBSWAP(Op, DAG); 10914 case ISD::ATOMIC_CMP_SWAP: 10915 return LowerATOMIC_CMP_SWAP(Op, DAG); 10916 } 10917 } 10918 10919 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10920 SmallVectorImpl<SDValue>&Results, 10921 SelectionDAG &DAG) const { 10922 SDLoc dl(N); 10923 switch (N->getOpcode()) { 10924 default: 10925 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10926 case ISD::READCYCLECOUNTER: { 10927 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10928 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10929 10930 Results.push_back( 10931 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10932 Results.push_back(RTB.getValue(2)); 10933 break; 10934 } 10935 case ISD::INTRINSIC_W_CHAIN: { 10936 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10937 Intrinsic::loop_decrement) 10938 break; 10939 10940 assert(N->getValueType(0) == MVT::i1 && 10941 "Unexpected result type for CTR decrement intrinsic"); 10942 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10943 N->getValueType(0)); 10944 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10945 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10946 N->getOperand(1)); 10947 10948 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10949 Results.push_back(NewInt.getValue(1)); 10950 break; 10951 } 10952 case ISD::VAARG: { 10953 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10954 return; 10955 10956 EVT VT = N->getValueType(0); 10957 10958 if (VT == MVT::i64) { 10959 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10960 10961 Results.push_back(NewNode); 10962 Results.push_back(NewNode.getValue(1)); 10963 } 10964 return; 10965 } 10966 case ISD::FP_TO_SINT: 10967 case ISD::FP_TO_UINT: 10968 // LowerFP_TO_INT() can only handle f32 and f64. 10969 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10970 return; 10971 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10972 return; 10973 case ISD::TRUNCATE: { 10974 EVT TrgVT = N->getValueType(0); 10975 EVT OpVT = N->getOperand(0).getValueType(); 10976 if (TrgVT.isVector() && 10977 isOperationCustom(N->getOpcode(), TrgVT) && 10978 OpVT.getSizeInBits() <= 128 && 10979 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10980 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10981 return; 10982 } 10983 case ISD::BITCAST: 10984 // Don't handle bitcast here. 10985 return; 10986 case ISD::FP_EXTEND: 10987 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10988 if (Lowered) 10989 Results.push_back(Lowered); 10990 return; 10991 } 10992 } 10993 10994 //===----------------------------------------------------------------------===// 10995 // Other Lowering Code 10996 //===----------------------------------------------------------------------===// 10997 10998 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10999 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11000 Function *Func = Intrinsic::getDeclaration(M, Id); 11001 return Builder.CreateCall(Func, {}); 11002 } 11003 11004 // The mappings for emitLeading/TrailingFence is taken from 11005 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11006 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11007 Instruction *Inst, 11008 AtomicOrdering Ord) const { 11009 if (Ord == AtomicOrdering::SequentiallyConsistent) 11010 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11011 if (isReleaseOrStronger(Ord)) 11012 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11013 return nullptr; 11014 } 11015 11016 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11017 Instruction *Inst, 11018 AtomicOrdering Ord) const { 11019 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11020 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11021 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11022 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11023 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11024 return Builder.CreateCall( 11025 Intrinsic::getDeclaration( 11026 Builder.GetInsertBlock()->getParent()->getParent(), 11027 Intrinsic::ppc_cfence, {Inst->getType()}), 11028 {Inst}); 11029 // FIXME: Can use isync for rmw operation. 11030 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11031 } 11032 return nullptr; 11033 } 11034 11035 MachineBasicBlock * 11036 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11037 unsigned AtomicSize, 11038 unsigned BinOpcode, 11039 unsigned CmpOpcode, 11040 unsigned CmpPred) const { 11041 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11042 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11043 11044 auto LoadMnemonic = PPC::LDARX; 11045 auto StoreMnemonic = PPC::STDCX; 11046 switch (AtomicSize) { 11047 default: 11048 llvm_unreachable("Unexpected size of atomic entity"); 11049 case 1: 11050 LoadMnemonic = PPC::LBARX; 11051 StoreMnemonic = PPC::STBCX; 11052 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11053 break; 11054 case 2: 11055 LoadMnemonic = PPC::LHARX; 11056 StoreMnemonic = PPC::STHCX; 11057 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11058 break; 11059 case 4: 11060 LoadMnemonic = PPC::LWARX; 11061 StoreMnemonic = PPC::STWCX; 11062 break; 11063 case 8: 11064 LoadMnemonic = PPC::LDARX; 11065 StoreMnemonic = PPC::STDCX; 11066 break; 11067 } 11068 11069 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11070 MachineFunction *F = BB->getParent(); 11071 MachineFunction::iterator It = ++BB->getIterator(); 11072 11073 Register dest = MI.getOperand(0).getReg(); 11074 Register ptrA = MI.getOperand(1).getReg(); 11075 Register ptrB = MI.getOperand(2).getReg(); 11076 Register incr = MI.getOperand(3).getReg(); 11077 DebugLoc dl = MI.getDebugLoc(); 11078 11079 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11080 MachineBasicBlock *loop2MBB = 11081 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11082 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11083 F->insert(It, loopMBB); 11084 if (CmpOpcode) 11085 F->insert(It, loop2MBB); 11086 F->insert(It, exitMBB); 11087 exitMBB->splice(exitMBB->begin(), BB, 11088 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11089 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11090 11091 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11092 Register TmpReg = (!BinOpcode) ? incr : 11093 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11094 : &PPC::GPRCRegClass); 11095 11096 // thisMBB: 11097 // ... 11098 // fallthrough --> loopMBB 11099 BB->addSuccessor(loopMBB); 11100 11101 // loopMBB: 11102 // l[wd]arx dest, ptr 11103 // add r0, dest, incr 11104 // st[wd]cx. r0, ptr 11105 // bne- loopMBB 11106 // fallthrough --> exitMBB 11107 11108 // For max/min... 11109 // loopMBB: 11110 // l[wd]arx dest, ptr 11111 // cmpl?[wd] incr, dest 11112 // bgt exitMBB 11113 // loop2MBB: 11114 // st[wd]cx. dest, ptr 11115 // bne- loopMBB 11116 // fallthrough --> exitMBB 11117 11118 BB = loopMBB; 11119 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11120 .addReg(ptrA).addReg(ptrB); 11121 if (BinOpcode) 11122 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11123 if (CmpOpcode) { 11124 // Signed comparisons of byte or halfword values must be sign-extended. 11125 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11126 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11127 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11128 ExtReg).addReg(dest); 11129 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11130 .addReg(incr).addReg(ExtReg); 11131 } else 11132 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11133 .addReg(incr).addReg(dest); 11134 11135 BuildMI(BB, dl, TII->get(PPC::BCC)) 11136 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11137 BB->addSuccessor(loop2MBB); 11138 BB->addSuccessor(exitMBB); 11139 BB = loop2MBB; 11140 } 11141 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11142 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11143 BuildMI(BB, dl, TII->get(PPC::BCC)) 11144 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11145 BB->addSuccessor(loopMBB); 11146 BB->addSuccessor(exitMBB); 11147 11148 // exitMBB: 11149 // ... 11150 BB = exitMBB; 11151 return BB; 11152 } 11153 11154 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11155 MachineInstr &MI, MachineBasicBlock *BB, 11156 bool is8bit, // operation 11157 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11158 // If we support part-word atomic mnemonics, just use them 11159 if (Subtarget.hasPartwordAtomics()) 11160 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11161 CmpPred); 11162 11163 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11164 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11165 // In 64 bit mode we have to use 64 bits for addresses, even though the 11166 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11167 // registers without caring whether they're 32 or 64, but here we're 11168 // doing actual arithmetic on the addresses. 11169 bool is64bit = Subtarget.isPPC64(); 11170 bool isLittleEndian = Subtarget.isLittleEndian(); 11171 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11172 11173 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11174 MachineFunction *F = BB->getParent(); 11175 MachineFunction::iterator It = ++BB->getIterator(); 11176 11177 Register dest = MI.getOperand(0).getReg(); 11178 Register ptrA = MI.getOperand(1).getReg(); 11179 Register ptrB = MI.getOperand(2).getReg(); 11180 Register incr = MI.getOperand(3).getReg(); 11181 DebugLoc dl = MI.getDebugLoc(); 11182 11183 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11184 MachineBasicBlock *loop2MBB = 11185 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11186 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11187 F->insert(It, loopMBB); 11188 if (CmpOpcode) 11189 F->insert(It, loop2MBB); 11190 F->insert(It, exitMBB); 11191 exitMBB->splice(exitMBB->begin(), BB, 11192 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11193 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11194 11195 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11196 const TargetRegisterClass *RC = 11197 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11198 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11199 11200 Register PtrReg = RegInfo.createVirtualRegister(RC); 11201 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11202 Register ShiftReg = 11203 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11204 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11205 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11206 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11207 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11208 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11209 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11210 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11211 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11212 Register Ptr1Reg; 11213 Register TmpReg = 11214 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11215 11216 // thisMBB: 11217 // ... 11218 // fallthrough --> loopMBB 11219 BB->addSuccessor(loopMBB); 11220 11221 // The 4-byte load must be aligned, while a char or short may be 11222 // anywhere in the word. Hence all this nasty bookkeeping code. 11223 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11224 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11225 // xori shift, shift1, 24 [16] 11226 // rlwinm ptr, ptr1, 0, 0, 29 11227 // slw incr2, incr, shift 11228 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11229 // slw mask, mask2, shift 11230 // loopMBB: 11231 // lwarx tmpDest, ptr 11232 // add tmp, tmpDest, incr2 11233 // andc tmp2, tmpDest, mask 11234 // and tmp3, tmp, mask 11235 // or tmp4, tmp3, tmp2 11236 // stwcx. tmp4, ptr 11237 // bne- loopMBB 11238 // fallthrough --> exitMBB 11239 // srw dest, tmpDest, shift 11240 if (ptrA != ZeroReg) { 11241 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11242 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11243 .addReg(ptrA) 11244 .addReg(ptrB); 11245 } else { 11246 Ptr1Reg = ptrB; 11247 } 11248 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11249 // mode. 11250 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11251 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11252 .addImm(3) 11253 .addImm(27) 11254 .addImm(is8bit ? 28 : 27); 11255 if (!isLittleEndian) 11256 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11257 .addReg(Shift1Reg) 11258 .addImm(is8bit ? 24 : 16); 11259 if (is64bit) 11260 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11261 .addReg(Ptr1Reg) 11262 .addImm(0) 11263 .addImm(61); 11264 else 11265 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11266 .addReg(Ptr1Reg) 11267 .addImm(0) 11268 .addImm(0) 11269 .addImm(29); 11270 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11271 if (is8bit) 11272 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11273 else { 11274 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11275 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11276 .addReg(Mask3Reg) 11277 .addImm(65535); 11278 } 11279 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11280 .addReg(Mask2Reg) 11281 .addReg(ShiftReg); 11282 11283 BB = loopMBB; 11284 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11285 .addReg(ZeroReg) 11286 .addReg(PtrReg); 11287 if (BinOpcode) 11288 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11289 .addReg(Incr2Reg) 11290 .addReg(TmpDestReg); 11291 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11292 .addReg(TmpDestReg) 11293 .addReg(MaskReg); 11294 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11295 if (CmpOpcode) { 11296 // For unsigned comparisons, we can directly compare the shifted values. 11297 // For signed comparisons we shift and sign extend. 11298 Register SReg = RegInfo.createVirtualRegister(GPRC); 11299 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11300 .addReg(TmpDestReg) 11301 .addReg(MaskReg); 11302 unsigned ValueReg = SReg; 11303 unsigned CmpReg = Incr2Reg; 11304 if (CmpOpcode == PPC::CMPW) { 11305 ValueReg = RegInfo.createVirtualRegister(GPRC); 11306 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11307 .addReg(SReg) 11308 .addReg(ShiftReg); 11309 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11310 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11311 .addReg(ValueReg); 11312 ValueReg = ValueSReg; 11313 CmpReg = incr; 11314 } 11315 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11316 .addReg(CmpReg) 11317 .addReg(ValueReg); 11318 BuildMI(BB, dl, TII->get(PPC::BCC)) 11319 .addImm(CmpPred) 11320 .addReg(PPC::CR0) 11321 .addMBB(exitMBB); 11322 BB->addSuccessor(loop2MBB); 11323 BB->addSuccessor(exitMBB); 11324 BB = loop2MBB; 11325 } 11326 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11327 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11328 .addReg(Tmp4Reg) 11329 .addReg(ZeroReg) 11330 .addReg(PtrReg); 11331 BuildMI(BB, dl, TII->get(PPC::BCC)) 11332 .addImm(PPC::PRED_NE) 11333 .addReg(PPC::CR0) 11334 .addMBB(loopMBB); 11335 BB->addSuccessor(loopMBB); 11336 BB->addSuccessor(exitMBB); 11337 11338 // exitMBB: 11339 // ... 11340 BB = exitMBB; 11341 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11342 .addReg(TmpDestReg) 11343 .addReg(ShiftReg); 11344 return BB; 11345 } 11346 11347 llvm::MachineBasicBlock * 11348 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11349 MachineBasicBlock *MBB) const { 11350 DebugLoc DL = MI.getDebugLoc(); 11351 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11352 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11353 11354 MachineFunction *MF = MBB->getParent(); 11355 MachineRegisterInfo &MRI = MF->getRegInfo(); 11356 11357 const BasicBlock *BB = MBB->getBasicBlock(); 11358 MachineFunction::iterator I = ++MBB->getIterator(); 11359 11360 Register DstReg = MI.getOperand(0).getReg(); 11361 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11362 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11363 Register mainDstReg = MRI.createVirtualRegister(RC); 11364 Register restoreDstReg = MRI.createVirtualRegister(RC); 11365 11366 MVT PVT = getPointerTy(MF->getDataLayout()); 11367 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11368 "Invalid Pointer Size!"); 11369 // For v = setjmp(buf), we generate 11370 // 11371 // thisMBB: 11372 // SjLjSetup mainMBB 11373 // bl mainMBB 11374 // v_restore = 1 11375 // b sinkMBB 11376 // 11377 // mainMBB: 11378 // buf[LabelOffset] = LR 11379 // v_main = 0 11380 // 11381 // sinkMBB: 11382 // v = phi(main, restore) 11383 // 11384 11385 MachineBasicBlock *thisMBB = MBB; 11386 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11387 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11388 MF->insert(I, mainMBB); 11389 MF->insert(I, sinkMBB); 11390 11391 MachineInstrBuilder MIB; 11392 11393 // Transfer the remainder of BB and its successor edges to sinkMBB. 11394 sinkMBB->splice(sinkMBB->begin(), MBB, 11395 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11396 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11397 11398 // Note that the structure of the jmp_buf used here is not compatible 11399 // with that used by libc, and is not designed to be. Specifically, it 11400 // stores only those 'reserved' registers that LLVM does not otherwise 11401 // understand how to spill. Also, by convention, by the time this 11402 // intrinsic is called, Clang has already stored the frame address in the 11403 // first slot of the buffer and stack address in the third. Following the 11404 // X86 target code, we'll store the jump address in the second slot. We also 11405 // need to save the TOC pointer (R2) to handle jumps between shared 11406 // libraries, and that will be stored in the fourth slot. The thread 11407 // identifier (R13) is not affected. 11408 11409 // thisMBB: 11410 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11411 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11412 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11413 11414 // Prepare IP either in reg. 11415 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11416 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11417 Register BufReg = MI.getOperand(1).getReg(); 11418 11419 if (Subtarget.is64BitELFABI()) { 11420 setUsesTOCBasePtr(*MBB->getParent()); 11421 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11422 .addReg(PPC::X2) 11423 .addImm(TOCOffset) 11424 .addReg(BufReg) 11425 .cloneMemRefs(MI); 11426 } 11427 11428 // Naked functions never have a base pointer, and so we use r1. For all 11429 // other functions, this decision must be delayed until during PEI. 11430 unsigned BaseReg; 11431 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11432 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11433 else 11434 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11435 11436 MIB = BuildMI(*thisMBB, MI, DL, 11437 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11438 .addReg(BaseReg) 11439 .addImm(BPOffset) 11440 .addReg(BufReg) 11441 .cloneMemRefs(MI); 11442 11443 // Setup 11444 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11445 MIB.addRegMask(TRI->getNoPreservedMask()); 11446 11447 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11448 11449 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11450 .addMBB(mainMBB); 11451 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11452 11453 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11454 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11455 11456 // mainMBB: 11457 // mainDstReg = 0 11458 MIB = 11459 BuildMI(mainMBB, DL, 11460 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11461 11462 // Store IP 11463 if (Subtarget.isPPC64()) { 11464 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11465 .addReg(LabelReg) 11466 .addImm(LabelOffset) 11467 .addReg(BufReg); 11468 } else { 11469 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11470 .addReg(LabelReg) 11471 .addImm(LabelOffset) 11472 .addReg(BufReg); 11473 } 11474 MIB.cloneMemRefs(MI); 11475 11476 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11477 mainMBB->addSuccessor(sinkMBB); 11478 11479 // sinkMBB: 11480 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11481 TII->get(PPC::PHI), DstReg) 11482 .addReg(mainDstReg).addMBB(mainMBB) 11483 .addReg(restoreDstReg).addMBB(thisMBB); 11484 11485 MI.eraseFromParent(); 11486 return sinkMBB; 11487 } 11488 11489 MachineBasicBlock * 11490 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11491 MachineBasicBlock *MBB) const { 11492 DebugLoc DL = MI.getDebugLoc(); 11493 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11494 11495 MachineFunction *MF = MBB->getParent(); 11496 MachineRegisterInfo &MRI = MF->getRegInfo(); 11497 11498 MVT PVT = getPointerTy(MF->getDataLayout()); 11499 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11500 "Invalid Pointer Size!"); 11501 11502 const TargetRegisterClass *RC = 11503 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11504 Register Tmp = MRI.createVirtualRegister(RC); 11505 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11506 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11507 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11508 unsigned BP = 11509 (PVT == MVT::i64) 11510 ? PPC::X30 11511 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11512 : PPC::R30); 11513 11514 MachineInstrBuilder MIB; 11515 11516 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11517 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11518 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11519 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11520 11521 Register BufReg = MI.getOperand(0).getReg(); 11522 11523 // Reload FP (the jumped-to function may not have had a 11524 // frame pointer, and if so, then its r31 will be restored 11525 // as necessary). 11526 if (PVT == MVT::i64) { 11527 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11528 .addImm(0) 11529 .addReg(BufReg); 11530 } else { 11531 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11532 .addImm(0) 11533 .addReg(BufReg); 11534 } 11535 MIB.cloneMemRefs(MI); 11536 11537 // Reload IP 11538 if (PVT == MVT::i64) { 11539 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11540 .addImm(LabelOffset) 11541 .addReg(BufReg); 11542 } else { 11543 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11544 .addImm(LabelOffset) 11545 .addReg(BufReg); 11546 } 11547 MIB.cloneMemRefs(MI); 11548 11549 // Reload SP 11550 if (PVT == MVT::i64) { 11551 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11552 .addImm(SPOffset) 11553 .addReg(BufReg); 11554 } else { 11555 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11556 .addImm(SPOffset) 11557 .addReg(BufReg); 11558 } 11559 MIB.cloneMemRefs(MI); 11560 11561 // Reload BP 11562 if (PVT == MVT::i64) { 11563 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11564 .addImm(BPOffset) 11565 .addReg(BufReg); 11566 } else { 11567 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11568 .addImm(BPOffset) 11569 .addReg(BufReg); 11570 } 11571 MIB.cloneMemRefs(MI); 11572 11573 // Reload TOC 11574 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11575 setUsesTOCBasePtr(*MBB->getParent()); 11576 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11577 .addImm(TOCOffset) 11578 .addReg(BufReg) 11579 .cloneMemRefs(MI); 11580 } 11581 11582 // Jump 11583 BuildMI(*MBB, MI, DL, 11584 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11585 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11586 11587 MI.eraseFromParent(); 11588 return MBB; 11589 } 11590 11591 MachineBasicBlock * 11592 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11593 MachineBasicBlock *BB) const { 11594 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11595 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11596 if (Subtarget.is64BitELFABI() && 11597 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11598 !Subtarget.isUsingPCRelativeCalls()) { 11599 // Call lowering should have added an r2 operand to indicate a dependence 11600 // on the TOC base pointer value. It can't however, because there is no 11601 // way to mark the dependence as implicit there, and so the stackmap code 11602 // will confuse it with a regular operand. Instead, add the dependence 11603 // here. 11604 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11605 } 11606 11607 return emitPatchPoint(MI, BB); 11608 } 11609 11610 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11611 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11612 return emitEHSjLjSetJmp(MI, BB); 11613 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11614 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11615 return emitEHSjLjLongJmp(MI, BB); 11616 } 11617 11618 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11619 11620 // To "insert" these instructions we actually have to insert their 11621 // control-flow patterns. 11622 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11623 MachineFunction::iterator It = ++BB->getIterator(); 11624 11625 MachineFunction *F = BB->getParent(); 11626 11627 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11628 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11629 MI.getOpcode() == PPC::SELECT_I8) { 11630 SmallVector<MachineOperand, 2> Cond; 11631 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11632 MI.getOpcode() == PPC::SELECT_CC_I8) 11633 Cond.push_back(MI.getOperand(4)); 11634 else 11635 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11636 Cond.push_back(MI.getOperand(1)); 11637 11638 DebugLoc dl = MI.getDebugLoc(); 11639 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11640 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11641 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11642 MI.getOpcode() == PPC::SELECT_CC_F8 || 11643 MI.getOpcode() == PPC::SELECT_CC_F16 || 11644 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11645 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11646 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11647 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11648 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11649 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11650 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11651 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11652 MI.getOpcode() == PPC::SELECT_CC_SPE || 11653 MI.getOpcode() == PPC::SELECT_F4 || 11654 MI.getOpcode() == PPC::SELECT_F8 || 11655 MI.getOpcode() == PPC::SELECT_F16 || 11656 MI.getOpcode() == PPC::SELECT_QFRC || 11657 MI.getOpcode() == PPC::SELECT_QSRC || 11658 MI.getOpcode() == PPC::SELECT_QBRC || 11659 MI.getOpcode() == PPC::SELECT_SPE || 11660 MI.getOpcode() == PPC::SELECT_SPE4 || 11661 MI.getOpcode() == PPC::SELECT_VRRC || 11662 MI.getOpcode() == PPC::SELECT_VSFRC || 11663 MI.getOpcode() == PPC::SELECT_VSSRC || 11664 MI.getOpcode() == PPC::SELECT_VSRC) { 11665 // The incoming instruction knows the destination vreg to set, the 11666 // condition code register to branch on, the true/false values to 11667 // select between, and a branch opcode to use. 11668 11669 // thisMBB: 11670 // ... 11671 // TrueVal = ... 11672 // cmpTY ccX, r1, r2 11673 // bCC copy1MBB 11674 // fallthrough --> copy0MBB 11675 MachineBasicBlock *thisMBB = BB; 11676 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11677 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11678 DebugLoc dl = MI.getDebugLoc(); 11679 F->insert(It, copy0MBB); 11680 F->insert(It, sinkMBB); 11681 11682 // Transfer the remainder of BB and its successor edges to sinkMBB. 11683 sinkMBB->splice(sinkMBB->begin(), BB, 11684 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11685 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11686 11687 // Next, add the true and fallthrough blocks as its successors. 11688 BB->addSuccessor(copy0MBB); 11689 BB->addSuccessor(sinkMBB); 11690 11691 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11692 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11693 MI.getOpcode() == PPC::SELECT_F16 || 11694 MI.getOpcode() == PPC::SELECT_SPE4 || 11695 MI.getOpcode() == PPC::SELECT_SPE || 11696 MI.getOpcode() == PPC::SELECT_QFRC || 11697 MI.getOpcode() == PPC::SELECT_QSRC || 11698 MI.getOpcode() == PPC::SELECT_QBRC || 11699 MI.getOpcode() == PPC::SELECT_VRRC || 11700 MI.getOpcode() == PPC::SELECT_VSFRC || 11701 MI.getOpcode() == PPC::SELECT_VSSRC || 11702 MI.getOpcode() == PPC::SELECT_VSRC) { 11703 BuildMI(BB, dl, TII->get(PPC::BC)) 11704 .addReg(MI.getOperand(1).getReg()) 11705 .addMBB(sinkMBB); 11706 } else { 11707 unsigned SelectPred = MI.getOperand(4).getImm(); 11708 BuildMI(BB, dl, TII->get(PPC::BCC)) 11709 .addImm(SelectPred) 11710 .addReg(MI.getOperand(1).getReg()) 11711 .addMBB(sinkMBB); 11712 } 11713 11714 // copy0MBB: 11715 // %FalseValue = ... 11716 // # fallthrough to sinkMBB 11717 BB = copy0MBB; 11718 11719 // Update machine-CFG edges 11720 BB->addSuccessor(sinkMBB); 11721 11722 // sinkMBB: 11723 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11724 // ... 11725 BB = sinkMBB; 11726 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11727 .addReg(MI.getOperand(3).getReg()) 11728 .addMBB(copy0MBB) 11729 .addReg(MI.getOperand(2).getReg()) 11730 .addMBB(thisMBB); 11731 } else if (MI.getOpcode() == PPC::ReadTB) { 11732 // To read the 64-bit time-base register on a 32-bit target, we read the 11733 // two halves. Should the counter have wrapped while it was being read, we 11734 // need to try again. 11735 // ... 11736 // readLoop: 11737 // mfspr Rx,TBU # load from TBU 11738 // mfspr Ry,TB # load from TB 11739 // mfspr Rz,TBU # load from TBU 11740 // cmpw crX,Rx,Rz # check if 'old'='new' 11741 // bne readLoop # branch if they're not equal 11742 // ... 11743 11744 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11745 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11746 DebugLoc dl = MI.getDebugLoc(); 11747 F->insert(It, readMBB); 11748 F->insert(It, sinkMBB); 11749 11750 // Transfer the remainder of BB and its successor edges to sinkMBB. 11751 sinkMBB->splice(sinkMBB->begin(), BB, 11752 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11753 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11754 11755 BB->addSuccessor(readMBB); 11756 BB = readMBB; 11757 11758 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11759 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11760 Register LoReg = MI.getOperand(0).getReg(); 11761 Register HiReg = MI.getOperand(1).getReg(); 11762 11763 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11764 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11765 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11766 11767 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11768 11769 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11770 .addReg(HiReg) 11771 .addReg(ReadAgainReg); 11772 BuildMI(BB, dl, TII->get(PPC::BCC)) 11773 .addImm(PPC::PRED_NE) 11774 .addReg(CmpReg) 11775 .addMBB(readMBB); 11776 11777 BB->addSuccessor(readMBB); 11778 BB->addSuccessor(sinkMBB); 11779 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11780 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11781 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11782 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11783 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11784 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11785 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11786 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11787 11788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11789 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11790 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11791 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11792 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11793 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11794 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11795 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11796 11797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11798 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11799 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11800 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11801 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11802 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11803 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11804 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11805 11806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11807 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11808 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11809 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11810 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11811 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11812 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11813 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11814 11815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11816 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11817 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11818 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11819 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11820 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11821 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11822 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11823 11824 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11825 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11826 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11827 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11828 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11829 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11830 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11831 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11832 11833 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11834 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11835 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11836 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11837 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11838 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11839 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11840 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11841 11842 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11843 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11844 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11845 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11846 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11847 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11848 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11849 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11850 11851 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11852 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11853 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11854 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11855 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11856 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11857 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11858 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11859 11860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11861 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11862 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11863 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11864 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11865 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11866 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11867 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11868 11869 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11870 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11871 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11872 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11873 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11874 BB = EmitAtomicBinary(MI, BB, 4, 0); 11875 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11876 BB = EmitAtomicBinary(MI, BB, 8, 0); 11877 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11878 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11879 (Subtarget.hasPartwordAtomics() && 11880 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11881 (Subtarget.hasPartwordAtomics() && 11882 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11883 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11884 11885 auto LoadMnemonic = PPC::LDARX; 11886 auto StoreMnemonic = PPC::STDCX; 11887 switch (MI.getOpcode()) { 11888 default: 11889 llvm_unreachable("Compare and swap of unknown size"); 11890 case PPC::ATOMIC_CMP_SWAP_I8: 11891 LoadMnemonic = PPC::LBARX; 11892 StoreMnemonic = PPC::STBCX; 11893 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11894 break; 11895 case PPC::ATOMIC_CMP_SWAP_I16: 11896 LoadMnemonic = PPC::LHARX; 11897 StoreMnemonic = PPC::STHCX; 11898 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11899 break; 11900 case PPC::ATOMIC_CMP_SWAP_I32: 11901 LoadMnemonic = PPC::LWARX; 11902 StoreMnemonic = PPC::STWCX; 11903 break; 11904 case PPC::ATOMIC_CMP_SWAP_I64: 11905 LoadMnemonic = PPC::LDARX; 11906 StoreMnemonic = PPC::STDCX; 11907 break; 11908 } 11909 Register dest = MI.getOperand(0).getReg(); 11910 Register ptrA = MI.getOperand(1).getReg(); 11911 Register ptrB = MI.getOperand(2).getReg(); 11912 Register oldval = MI.getOperand(3).getReg(); 11913 Register newval = MI.getOperand(4).getReg(); 11914 DebugLoc dl = MI.getDebugLoc(); 11915 11916 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11917 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11918 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11919 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11920 F->insert(It, loop1MBB); 11921 F->insert(It, loop2MBB); 11922 F->insert(It, midMBB); 11923 F->insert(It, exitMBB); 11924 exitMBB->splice(exitMBB->begin(), BB, 11925 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11926 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11927 11928 // thisMBB: 11929 // ... 11930 // fallthrough --> loopMBB 11931 BB->addSuccessor(loop1MBB); 11932 11933 // loop1MBB: 11934 // l[bhwd]arx dest, ptr 11935 // cmp[wd] dest, oldval 11936 // bne- midMBB 11937 // loop2MBB: 11938 // st[bhwd]cx. newval, ptr 11939 // bne- loopMBB 11940 // b exitBB 11941 // midMBB: 11942 // st[bhwd]cx. dest, ptr 11943 // exitBB: 11944 BB = loop1MBB; 11945 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11946 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11947 .addReg(oldval) 11948 .addReg(dest); 11949 BuildMI(BB, dl, TII->get(PPC::BCC)) 11950 .addImm(PPC::PRED_NE) 11951 .addReg(PPC::CR0) 11952 .addMBB(midMBB); 11953 BB->addSuccessor(loop2MBB); 11954 BB->addSuccessor(midMBB); 11955 11956 BB = loop2MBB; 11957 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11958 .addReg(newval) 11959 .addReg(ptrA) 11960 .addReg(ptrB); 11961 BuildMI(BB, dl, TII->get(PPC::BCC)) 11962 .addImm(PPC::PRED_NE) 11963 .addReg(PPC::CR0) 11964 .addMBB(loop1MBB); 11965 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11966 BB->addSuccessor(loop1MBB); 11967 BB->addSuccessor(exitMBB); 11968 11969 BB = midMBB; 11970 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11971 .addReg(dest) 11972 .addReg(ptrA) 11973 .addReg(ptrB); 11974 BB->addSuccessor(exitMBB); 11975 11976 // exitMBB: 11977 // ... 11978 BB = exitMBB; 11979 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11980 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11981 // We must use 64-bit registers for addresses when targeting 64-bit, 11982 // since we're actually doing arithmetic on them. Other registers 11983 // can be 32-bit. 11984 bool is64bit = Subtarget.isPPC64(); 11985 bool isLittleEndian = Subtarget.isLittleEndian(); 11986 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11987 11988 Register dest = MI.getOperand(0).getReg(); 11989 Register ptrA = MI.getOperand(1).getReg(); 11990 Register ptrB = MI.getOperand(2).getReg(); 11991 Register oldval = MI.getOperand(3).getReg(); 11992 Register newval = MI.getOperand(4).getReg(); 11993 DebugLoc dl = MI.getDebugLoc(); 11994 11995 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11996 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11997 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11998 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11999 F->insert(It, loop1MBB); 12000 F->insert(It, loop2MBB); 12001 F->insert(It, midMBB); 12002 F->insert(It, exitMBB); 12003 exitMBB->splice(exitMBB->begin(), BB, 12004 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12005 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12006 12007 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12008 const TargetRegisterClass *RC = 12009 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12010 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12011 12012 Register PtrReg = RegInfo.createVirtualRegister(RC); 12013 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12014 Register ShiftReg = 12015 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12016 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12017 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12018 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12019 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12020 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12021 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12022 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12023 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12024 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12025 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12026 Register Ptr1Reg; 12027 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12028 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12029 // thisMBB: 12030 // ... 12031 // fallthrough --> loopMBB 12032 BB->addSuccessor(loop1MBB); 12033 12034 // The 4-byte load must be aligned, while a char or short may be 12035 // anywhere in the word. Hence all this nasty bookkeeping code. 12036 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12037 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12038 // xori shift, shift1, 24 [16] 12039 // rlwinm ptr, ptr1, 0, 0, 29 12040 // slw newval2, newval, shift 12041 // slw oldval2, oldval,shift 12042 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12043 // slw mask, mask2, shift 12044 // and newval3, newval2, mask 12045 // and oldval3, oldval2, mask 12046 // loop1MBB: 12047 // lwarx tmpDest, ptr 12048 // and tmp, tmpDest, mask 12049 // cmpw tmp, oldval3 12050 // bne- midMBB 12051 // loop2MBB: 12052 // andc tmp2, tmpDest, mask 12053 // or tmp4, tmp2, newval3 12054 // stwcx. tmp4, ptr 12055 // bne- loop1MBB 12056 // b exitBB 12057 // midMBB: 12058 // stwcx. tmpDest, ptr 12059 // exitBB: 12060 // srw dest, tmpDest, shift 12061 if (ptrA != ZeroReg) { 12062 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12063 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12064 .addReg(ptrA) 12065 .addReg(ptrB); 12066 } else { 12067 Ptr1Reg = ptrB; 12068 } 12069 12070 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12071 // mode. 12072 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12073 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12074 .addImm(3) 12075 .addImm(27) 12076 .addImm(is8bit ? 28 : 27); 12077 if (!isLittleEndian) 12078 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12079 .addReg(Shift1Reg) 12080 .addImm(is8bit ? 24 : 16); 12081 if (is64bit) 12082 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12083 .addReg(Ptr1Reg) 12084 .addImm(0) 12085 .addImm(61); 12086 else 12087 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12088 .addReg(Ptr1Reg) 12089 .addImm(0) 12090 .addImm(0) 12091 .addImm(29); 12092 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12093 .addReg(newval) 12094 .addReg(ShiftReg); 12095 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12096 .addReg(oldval) 12097 .addReg(ShiftReg); 12098 if (is8bit) 12099 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12100 else { 12101 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12102 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12103 .addReg(Mask3Reg) 12104 .addImm(65535); 12105 } 12106 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12107 .addReg(Mask2Reg) 12108 .addReg(ShiftReg); 12109 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12110 .addReg(NewVal2Reg) 12111 .addReg(MaskReg); 12112 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12113 .addReg(OldVal2Reg) 12114 .addReg(MaskReg); 12115 12116 BB = loop1MBB; 12117 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12118 .addReg(ZeroReg) 12119 .addReg(PtrReg); 12120 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12121 .addReg(TmpDestReg) 12122 .addReg(MaskReg); 12123 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12124 .addReg(TmpReg) 12125 .addReg(OldVal3Reg); 12126 BuildMI(BB, dl, TII->get(PPC::BCC)) 12127 .addImm(PPC::PRED_NE) 12128 .addReg(PPC::CR0) 12129 .addMBB(midMBB); 12130 BB->addSuccessor(loop2MBB); 12131 BB->addSuccessor(midMBB); 12132 12133 BB = loop2MBB; 12134 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12135 .addReg(TmpDestReg) 12136 .addReg(MaskReg); 12137 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12138 .addReg(Tmp2Reg) 12139 .addReg(NewVal3Reg); 12140 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12141 .addReg(Tmp4Reg) 12142 .addReg(ZeroReg) 12143 .addReg(PtrReg); 12144 BuildMI(BB, dl, TII->get(PPC::BCC)) 12145 .addImm(PPC::PRED_NE) 12146 .addReg(PPC::CR0) 12147 .addMBB(loop1MBB); 12148 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12149 BB->addSuccessor(loop1MBB); 12150 BB->addSuccessor(exitMBB); 12151 12152 BB = midMBB; 12153 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12154 .addReg(TmpDestReg) 12155 .addReg(ZeroReg) 12156 .addReg(PtrReg); 12157 BB->addSuccessor(exitMBB); 12158 12159 // exitMBB: 12160 // ... 12161 BB = exitMBB; 12162 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12163 .addReg(TmpReg) 12164 .addReg(ShiftReg); 12165 } else if (MI.getOpcode() == PPC::FADDrtz) { 12166 // This pseudo performs an FADD with rounding mode temporarily forced 12167 // to round-to-zero. We emit this via custom inserter since the FPSCR 12168 // is not modeled at the SelectionDAG level. 12169 Register Dest = MI.getOperand(0).getReg(); 12170 Register Src1 = MI.getOperand(1).getReg(); 12171 Register Src2 = MI.getOperand(2).getReg(); 12172 DebugLoc dl = MI.getDebugLoc(); 12173 12174 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12175 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12176 12177 // Save FPSCR value. 12178 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12179 12180 // Set rounding mode to round-to-zero. 12181 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12182 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12183 12184 // Perform addition. 12185 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12186 12187 // Restore FPSCR value. 12188 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12189 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12190 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12191 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12192 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12193 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12194 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12195 ? PPC::ANDI8_rec 12196 : PPC::ANDI_rec; 12197 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12198 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12199 12200 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12201 Register Dest = RegInfo.createVirtualRegister( 12202 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12203 12204 DebugLoc Dl = MI.getDebugLoc(); 12205 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12206 .addReg(MI.getOperand(1).getReg()) 12207 .addImm(1); 12208 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12209 MI.getOperand(0).getReg()) 12210 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12211 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12212 DebugLoc Dl = MI.getDebugLoc(); 12213 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12214 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12215 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12216 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12217 MI.getOperand(0).getReg()) 12218 .addReg(CRReg); 12219 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12220 DebugLoc Dl = MI.getDebugLoc(); 12221 unsigned Imm = MI.getOperand(1).getImm(); 12222 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12223 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12224 MI.getOperand(0).getReg()) 12225 .addReg(PPC::CR0EQ); 12226 } else if (MI.getOpcode() == PPC::SETRNDi) { 12227 DebugLoc dl = MI.getDebugLoc(); 12228 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12229 12230 // Save FPSCR value. 12231 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12232 12233 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12234 // the following settings: 12235 // 00 Round to nearest 12236 // 01 Round to 0 12237 // 10 Round to +inf 12238 // 11 Round to -inf 12239 12240 // When the operand is immediate, using the two least significant bits of 12241 // the immediate to set the bits 62:63 of FPSCR. 12242 unsigned Mode = MI.getOperand(1).getImm(); 12243 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12244 .addImm(31); 12245 12246 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12247 .addImm(30); 12248 } else if (MI.getOpcode() == PPC::SETRND) { 12249 DebugLoc dl = MI.getDebugLoc(); 12250 12251 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12252 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12253 // If the target doesn't have DirectMove, we should use stack to do the 12254 // conversion, because the target doesn't have the instructions like mtvsrd 12255 // or mfvsrd to do this conversion directly. 12256 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12257 if (Subtarget.hasDirectMove()) { 12258 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12259 .addReg(SrcReg); 12260 } else { 12261 // Use stack to do the register copy. 12262 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12263 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12264 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12265 if (RC == &PPC::F8RCRegClass) { 12266 // Copy register from F8RCRegClass to G8RCRegclass. 12267 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12268 "Unsupported RegClass."); 12269 12270 StoreOp = PPC::STFD; 12271 LoadOp = PPC::LD; 12272 } else { 12273 // Copy register from G8RCRegClass to F8RCRegclass. 12274 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12275 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12276 "Unsupported RegClass."); 12277 } 12278 12279 MachineFrameInfo &MFI = F->getFrameInfo(); 12280 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12281 12282 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12283 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12284 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12285 MFI.getObjectAlign(FrameIdx)); 12286 12287 // Store the SrcReg into the stack. 12288 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12289 .addReg(SrcReg) 12290 .addImm(0) 12291 .addFrameIndex(FrameIdx) 12292 .addMemOperand(MMOStore); 12293 12294 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12295 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12296 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12297 MFI.getObjectAlign(FrameIdx)); 12298 12299 // Load from the stack where SrcReg is stored, and save to DestReg, 12300 // so we have done the RegClass conversion from RegClass::SrcReg to 12301 // RegClass::DestReg. 12302 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12303 .addImm(0) 12304 .addFrameIndex(FrameIdx) 12305 .addMemOperand(MMOLoad); 12306 } 12307 }; 12308 12309 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12310 12311 // Save FPSCR value. 12312 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12313 12314 // When the operand is gprc register, use two least significant bits of the 12315 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12316 // 12317 // copy OldFPSCRTmpReg, OldFPSCRReg 12318 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12319 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12320 // copy NewFPSCRReg, NewFPSCRTmpReg 12321 // mtfsf 255, NewFPSCRReg 12322 MachineOperand SrcOp = MI.getOperand(1); 12323 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12324 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12325 12326 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12327 12328 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12329 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12330 12331 // The first operand of INSERT_SUBREG should be a register which has 12332 // subregisters, we only care about its RegClass, so we should use an 12333 // IMPLICIT_DEF register. 12334 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12335 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12336 .addReg(ImDefReg) 12337 .add(SrcOp) 12338 .addImm(1); 12339 12340 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12341 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12342 .addReg(OldFPSCRTmpReg) 12343 .addReg(ExtSrcReg) 12344 .addImm(0) 12345 .addImm(62); 12346 12347 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12348 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12349 12350 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12351 // bits of FPSCR. 12352 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12353 .addImm(255) 12354 .addReg(NewFPSCRReg) 12355 .addImm(0) 12356 .addImm(0); 12357 } else { 12358 llvm_unreachable("Unexpected instr type to insert"); 12359 } 12360 12361 MI.eraseFromParent(); // The pseudo instruction is gone now. 12362 return BB; 12363 } 12364 12365 //===----------------------------------------------------------------------===// 12366 // Target Optimization Hooks 12367 //===----------------------------------------------------------------------===// 12368 12369 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12370 // For the estimates, convergence is quadratic, so we essentially double the 12371 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12372 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12373 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12374 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12375 if (VT.getScalarType() == MVT::f64) 12376 RefinementSteps++; 12377 return RefinementSteps; 12378 } 12379 12380 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12381 int Enabled, int &RefinementSteps, 12382 bool &UseOneConstNR, 12383 bool Reciprocal) const { 12384 EVT VT = Operand.getValueType(); 12385 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12386 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12387 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12388 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12389 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12390 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12391 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12392 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12393 12394 // The Newton-Raphson computation with a single constant does not provide 12395 // enough accuracy on some CPUs. 12396 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12397 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12398 } 12399 return SDValue(); 12400 } 12401 12402 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12403 int Enabled, 12404 int &RefinementSteps) const { 12405 EVT VT = Operand.getValueType(); 12406 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12407 (VT == MVT::f64 && Subtarget.hasFRE()) || 12408 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12409 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12410 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12411 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12412 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12413 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12414 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12415 } 12416 return SDValue(); 12417 } 12418 12419 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12420 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12421 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12422 // enabled for division), this functionality is redundant with the default 12423 // combiner logic (once the division -> reciprocal/multiply transformation 12424 // has taken place). As a result, this matters more for older cores than for 12425 // newer ones. 12426 12427 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12428 // reciprocal if there are two or more FDIVs (for embedded cores with only 12429 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12430 switch (Subtarget.getCPUDirective()) { 12431 default: 12432 return 3; 12433 case PPC::DIR_440: 12434 case PPC::DIR_A2: 12435 case PPC::DIR_E500: 12436 case PPC::DIR_E500mc: 12437 case PPC::DIR_E5500: 12438 return 2; 12439 } 12440 } 12441 12442 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12443 // collapsed, and so we need to look through chains of them. 12444 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12445 int64_t& Offset, SelectionDAG &DAG) { 12446 if (DAG.isBaseWithConstantOffset(Loc)) { 12447 Base = Loc.getOperand(0); 12448 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12449 12450 // The base might itself be a base plus an offset, and if so, accumulate 12451 // that as well. 12452 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12453 } 12454 } 12455 12456 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12457 unsigned Bytes, int Dist, 12458 SelectionDAG &DAG) { 12459 if (VT.getSizeInBits() / 8 != Bytes) 12460 return false; 12461 12462 SDValue BaseLoc = Base->getBasePtr(); 12463 if (Loc.getOpcode() == ISD::FrameIndex) { 12464 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12465 return false; 12466 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12467 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12468 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12469 int FS = MFI.getObjectSize(FI); 12470 int BFS = MFI.getObjectSize(BFI); 12471 if (FS != BFS || FS != (int)Bytes) return false; 12472 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12473 } 12474 12475 SDValue Base1 = Loc, Base2 = BaseLoc; 12476 int64_t Offset1 = 0, Offset2 = 0; 12477 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12478 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12479 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12480 return true; 12481 12482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12483 const GlobalValue *GV1 = nullptr; 12484 const GlobalValue *GV2 = nullptr; 12485 Offset1 = 0; 12486 Offset2 = 0; 12487 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12488 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12489 if (isGA1 && isGA2 && GV1 == GV2) 12490 return Offset1 == (Offset2 + Dist*Bytes); 12491 return false; 12492 } 12493 12494 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12495 // not enforce equality of the chain operands. 12496 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12497 unsigned Bytes, int Dist, 12498 SelectionDAG &DAG) { 12499 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12500 EVT VT = LS->getMemoryVT(); 12501 SDValue Loc = LS->getBasePtr(); 12502 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12503 } 12504 12505 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12506 EVT VT; 12507 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12508 default: return false; 12509 case Intrinsic::ppc_qpx_qvlfd: 12510 case Intrinsic::ppc_qpx_qvlfda: 12511 VT = MVT::v4f64; 12512 break; 12513 case Intrinsic::ppc_qpx_qvlfs: 12514 case Intrinsic::ppc_qpx_qvlfsa: 12515 VT = MVT::v4f32; 12516 break; 12517 case Intrinsic::ppc_qpx_qvlfcd: 12518 case Intrinsic::ppc_qpx_qvlfcda: 12519 VT = MVT::v2f64; 12520 break; 12521 case Intrinsic::ppc_qpx_qvlfcs: 12522 case Intrinsic::ppc_qpx_qvlfcsa: 12523 VT = MVT::v2f32; 12524 break; 12525 case Intrinsic::ppc_qpx_qvlfiwa: 12526 case Intrinsic::ppc_qpx_qvlfiwz: 12527 case Intrinsic::ppc_altivec_lvx: 12528 case Intrinsic::ppc_altivec_lvxl: 12529 case Intrinsic::ppc_vsx_lxvw4x: 12530 case Intrinsic::ppc_vsx_lxvw4x_be: 12531 VT = MVT::v4i32; 12532 break; 12533 case Intrinsic::ppc_vsx_lxvd2x: 12534 case Intrinsic::ppc_vsx_lxvd2x_be: 12535 VT = MVT::v2f64; 12536 break; 12537 case Intrinsic::ppc_altivec_lvebx: 12538 VT = MVT::i8; 12539 break; 12540 case Intrinsic::ppc_altivec_lvehx: 12541 VT = MVT::i16; 12542 break; 12543 case Intrinsic::ppc_altivec_lvewx: 12544 VT = MVT::i32; 12545 break; 12546 } 12547 12548 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12549 } 12550 12551 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12552 EVT VT; 12553 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12554 default: return false; 12555 case Intrinsic::ppc_qpx_qvstfd: 12556 case Intrinsic::ppc_qpx_qvstfda: 12557 VT = MVT::v4f64; 12558 break; 12559 case Intrinsic::ppc_qpx_qvstfs: 12560 case Intrinsic::ppc_qpx_qvstfsa: 12561 VT = MVT::v4f32; 12562 break; 12563 case Intrinsic::ppc_qpx_qvstfcd: 12564 case Intrinsic::ppc_qpx_qvstfcda: 12565 VT = MVT::v2f64; 12566 break; 12567 case Intrinsic::ppc_qpx_qvstfcs: 12568 case Intrinsic::ppc_qpx_qvstfcsa: 12569 VT = MVT::v2f32; 12570 break; 12571 case Intrinsic::ppc_qpx_qvstfiw: 12572 case Intrinsic::ppc_qpx_qvstfiwa: 12573 case Intrinsic::ppc_altivec_stvx: 12574 case Intrinsic::ppc_altivec_stvxl: 12575 case Intrinsic::ppc_vsx_stxvw4x: 12576 VT = MVT::v4i32; 12577 break; 12578 case Intrinsic::ppc_vsx_stxvd2x: 12579 VT = MVT::v2f64; 12580 break; 12581 case Intrinsic::ppc_vsx_stxvw4x_be: 12582 VT = MVT::v4i32; 12583 break; 12584 case Intrinsic::ppc_vsx_stxvd2x_be: 12585 VT = MVT::v2f64; 12586 break; 12587 case Intrinsic::ppc_altivec_stvebx: 12588 VT = MVT::i8; 12589 break; 12590 case Intrinsic::ppc_altivec_stvehx: 12591 VT = MVT::i16; 12592 break; 12593 case Intrinsic::ppc_altivec_stvewx: 12594 VT = MVT::i32; 12595 break; 12596 } 12597 12598 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12599 } 12600 12601 return false; 12602 } 12603 12604 // Return true is there is a nearyby consecutive load to the one provided 12605 // (regardless of alignment). We search up and down the chain, looking though 12606 // token factors and other loads (but nothing else). As a result, a true result 12607 // indicates that it is safe to create a new consecutive load adjacent to the 12608 // load provided. 12609 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12610 SDValue Chain = LD->getChain(); 12611 EVT VT = LD->getMemoryVT(); 12612 12613 SmallSet<SDNode *, 16> LoadRoots; 12614 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12615 SmallSet<SDNode *, 16> Visited; 12616 12617 // First, search up the chain, branching to follow all token-factor operands. 12618 // If we find a consecutive load, then we're done, otherwise, record all 12619 // nodes just above the top-level loads and token factors. 12620 while (!Queue.empty()) { 12621 SDNode *ChainNext = Queue.pop_back_val(); 12622 if (!Visited.insert(ChainNext).second) 12623 continue; 12624 12625 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12626 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12627 return true; 12628 12629 if (!Visited.count(ChainLD->getChain().getNode())) 12630 Queue.push_back(ChainLD->getChain().getNode()); 12631 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12632 for (const SDUse &O : ChainNext->ops()) 12633 if (!Visited.count(O.getNode())) 12634 Queue.push_back(O.getNode()); 12635 } else 12636 LoadRoots.insert(ChainNext); 12637 } 12638 12639 // Second, search down the chain, starting from the top-level nodes recorded 12640 // in the first phase. These top-level nodes are the nodes just above all 12641 // loads and token factors. Starting with their uses, recursively look though 12642 // all loads (just the chain uses) and token factors to find a consecutive 12643 // load. 12644 Visited.clear(); 12645 Queue.clear(); 12646 12647 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12648 IE = LoadRoots.end(); I != IE; ++I) { 12649 Queue.push_back(*I); 12650 12651 while (!Queue.empty()) { 12652 SDNode *LoadRoot = Queue.pop_back_val(); 12653 if (!Visited.insert(LoadRoot).second) 12654 continue; 12655 12656 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12657 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12658 return true; 12659 12660 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12661 UE = LoadRoot->use_end(); UI != UE; ++UI) 12662 if (((isa<MemSDNode>(*UI) && 12663 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12664 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12665 Queue.push_back(*UI); 12666 } 12667 } 12668 12669 return false; 12670 } 12671 12672 /// This function is called when we have proved that a SETCC node can be replaced 12673 /// by subtraction (and other supporting instructions) so that the result of 12674 /// comparison is kept in a GPR instead of CR. This function is purely for 12675 /// codegen purposes and has some flags to guide the codegen process. 12676 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12677 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12678 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12679 12680 // Zero extend the operands to the largest legal integer. Originally, they 12681 // must be of a strictly smaller size. 12682 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12683 DAG.getConstant(Size, DL, MVT::i32)); 12684 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12685 DAG.getConstant(Size, DL, MVT::i32)); 12686 12687 // Swap if needed. Depends on the condition code. 12688 if (Swap) 12689 std::swap(Op0, Op1); 12690 12691 // Subtract extended integers. 12692 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12693 12694 // Move the sign bit to the least significant position and zero out the rest. 12695 // Now the least significant bit carries the result of original comparison. 12696 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12697 DAG.getConstant(Size - 1, DL, MVT::i32)); 12698 auto Final = Shifted; 12699 12700 // Complement the result if needed. Based on the condition code. 12701 if (Complement) 12702 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12703 DAG.getConstant(1, DL, MVT::i64)); 12704 12705 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12706 } 12707 12708 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12709 DAGCombinerInfo &DCI) const { 12710 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12711 12712 SelectionDAG &DAG = DCI.DAG; 12713 SDLoc DL(N); 12714 12715 // Size of integers being compared has a critical role in the following 12716 // analysis, so we prefer to do this when all types are legal. 12717 if (!DCI.isAfterLegalizeDAG()) 12718 return SDValue(); 12719 12720 // If all users of SETCC extend its value to a legal integer type 12721 // then we replace SETCC with a subtraction 12722 for (SDNode::use_iterator UI = N->use_begin(), 12723 UE = N->use_end(); UI != UE; ++UI) { 12724 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12725 return SDValue(); 12726 } 12727 12728 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12729 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12730 12731 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12732 12733 if (OpSize < Size) { 12734 switch (CC) { 12735 default: break; 12736 case ISD::SETULT: 12737 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12738 case ISD::SETULE: 12739 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12740 case ISD::SETUGT: 12741 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12742 case ISD::SETUGE: 12743 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12744 } 12745 } 12746 12747 return SDValue(); 12748 } 12749 12750 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12751 DAGCombinerInfo &DCI) const { 12752 SelectionDAG &DAG = DCI.DAG; 12753 SDLoc dl(N); 12754 12755 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12756 // If we're tracking CR bits, we need to be careful that we don't have: 12757 // trunc(binary-ops(zext(x), zext(y))) 12758 // or 12759 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12760 // such that we're unnecessarily moving things into GPRs when it would be 12761 // better to keep them in CR bits. 12762 12763 // Note that trunc here can be an actual i1 trunc, or can be the effective 12764 // truncation that comes from a setcc or select_cc. 12765 if (N->getOpcode() == ISD::TRUNCATE && 12766 N->getValueType(0) != MVT::i1) 12767 return SDValue(); 12768 12769 if (N->getOperand(0).getValueType() != MVT::i32 && 12770 N->getOperand(0).getValueType() != MVT::i64) 12771 return SDValue(); 12772 12773 if (N->getOpcode() == ISD::SETCC || 12774 N->getOpcode() == ISD::SELECT_CC) { 12775 // If we're looking at a comparison, then we need to make sure that the 12776 // high bits (all except for the first) don't matter the result. 12777 ISD::CondCode CC = 12778 cast<CondCodeSDNode>(N->getOperand( 12779 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12780 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12781 12782 if (ISD::isSignedIntSetCC(CC)) { 12783 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12784 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12785 return SDValue(); 12786 } else if (ISD::isUnsignedIntSetCC(CC)) { 12787 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12788 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12789 !DAG.MaskedValueIsZero(N->getOperand(1), 12790 APInt::getHighBitsSet(OpBits, OpBits-1))) 12791 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12792 : SDValue()); 12793 } else { 12794 // This is neither a signed nor an unsigned comparison, just make sure 12795 // that the high bits are equal. 12796 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12797 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12798 12799 // We don't really care about what is known about the first bit (if 12800 // anything), so clear it in all masks prior to comparing them. 12801 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12802 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12803 12804 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12805 return SDValue(); 12806 } 12807 } 12808 12809 // We now know that the higher-order bits are irrelevant, we just need to 12810 // make sure that all of the intermediate operations are bit operations, and 12811 // all inputs are extensions. 12812 if (N->getOperand(0).getOpcode() != ISD::AND && 12813 N->getOperand(0).getOpcode() != ISD::OR && 12814 N->getOperand(0).getOpcode() != ISD::XOR && 12815 N->getOperand(0).getOpcode() != ISD::SELECT && 12816 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12817 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12818 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12819 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12820 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12821 return SDValue(); 12822 12823 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12824 N->getOperand(1).getOpcode() != ISD::AND && 12825 N->getOperand(1).getOpcode() != ISD::OR && 12826 N->getOperand(1).getOpcode() != ISD::XOR && 12827 N->getOperand(1).getOpcode() != ISD::SELECT && 12828 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12829 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12830 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12831 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12832 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12833 return SDValue(); 12834 12835 SmallVector<SDValue, 4> Inputs; 12836 SmallVector<SDValue, 8> BinOps, PromOps; 12837 SmallPtrSet<SDNode *, 16> Visited; 12838 12839 for (unsigned i = 0; i < 2; ++i) { 12840 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12841 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12842 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12843 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12844 isa<ConstantSDNode>(N->getOperand(i))) 12845 Inputs.push_back(N->getOperand(i)); 12846 else 12847 BinOps.push_back(N->getOperand(i)); 12848 12849 if (N->getOpcode() == ISD::TRUNCATE) 12850 break; 12851 } 12852 12853 // Visit all inputs, collect all binary operations (and, or, xor and 12854 // select) that are all fed by extensions. 12855 while (!BinOps.empty()) { 12856 SDValue BinOp = BinOps.back(); 12857 BinOps.pop_back(); 12858 12859 if (!Visited.insert(BinOp.getNode()).second) 12860 continue; 12861 12862 PromOps.push_back(BinOp); 12863 12864 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12865 // The condition of the select is not promoted. 12866 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12867 continue; 12868 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12869 continue; 12870 12871 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12872 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12873 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12874 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12875 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12876 Inputs.push_back(BinOp.getOperand(i)); 12877 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12878 BinOp.getOperand(i).getOpcode() == ISD::OR || 12879 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12880 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12881 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12882 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12883 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12884 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12885 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12886 BinOps.push_back(BinOp.getOperand(i)); 12887 } else { 12888 // We have an input that is not an extension or another binary 12889 // operation; we'll abort this transformation. 12890 return SDValue(); 12891 } 12892 } 12893 } 12894 12895 // Make sure that this is a self-contained cluster of operations (which 12896 // is not quite the same thing as saying that everything has only one 12897 // use). 12898 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12899 if (isa<ConstantSDNode>(Inputs[i])) 12900 continue; 12901 12902 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12903 UE = Inputs[i].getNode()->use_end(); 12904 UI != UE; ++UI) { 12905 SDNode *User = *UI; 12906 if (User != N && !Visited.count(User)) 12907 return SDValue(); 12908 12909 // Make sure that we're not going to promote the non-output-value 12910 // operand(s) or SELECT or SELECT_CC. 12911 // FIXME: Although we could sometimes handle this, and it does occur in 12912 // practice that one of the condition inputs to the select is also one of 12913 // the outputs, we currently can't deal with this. 12914 if (User->getOpcode() == ISD::SELECT) { 12915 if (User->getOperand(0) == Inputs[i]) 12916 return SDValue(); 12917 } else if (User->getOpcode() == ISD::SELECT_CC) { 12918 if (User->getOperand(0) == Inputs[i] || 12919 User->getOperand(1) == Inputs[i]) 12920 return SDValue(); 12921 } 12922 } 12923 } 12924 12925 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12926 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12927 UE = PromOps[i].getNode()->use_end(); 12928 UI != UE; ++UI) { 12929 SDNode *User = *UI; 12930 if (User != N && !Visited.count(User)) 12931 return SDValue(); 12932 12933 // Make sure that we're not going to promote the non-output-value 12934 // operand(s) or SELECT or SELECT_CC. 12935 // FIXME: Although we could sometimes handle this, and it does occur in 12936 // practice that one of the condition inputs to the select is also one of 12937 // the outputs, we currently can't deal with this. 12938 if (User->getOpcode() == ISD::SELECT) { 12939 if (User->getOperand(0) == PromOps[i]) 12940 return SDValue(); 12941 } else if (User->getOpcode() == ISD::SELECT_CC) { 12942 if (User->getOperand(0) == PromOps[i] || 12943 User->getOperand(1) == PromOps[i]) 12944 return SDValue(); 12945 } 12946 } 12947 } 12948 12949 // Replace all inputs with the extension operand. 12950 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12951 // Constants may have users outside the cluster of to-be-promoted nodes, 12952 // and so we need to replace those as we do the promotions. 12953 if (isa<ConstantSDNode>(Inputs[i])) 12954 continue; 12955 else 12956 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12957 } 12958 12959 std::list<HandleSDNode> PromOpHandles; 12960 for (auto &PromOp : PromOps) 12961 PromOpHandles.emplace_back(PromOp); 12962 12963 // Replace all operations (these are all the same, but have a different 12964 // (i1) return type). DAG.getNode will validate that the types of 12965 // a binary operator match, so go through the list in reverse so that 12966 // we've likely promoted both operands first. Any intermediate truncations or 12967 // extensions disappear. 12968 while (!PromOpHandles.empty()) { 12969 SDValue PromOp = PromOpHandles.back().getValue(); 12970 PromOpHandles.pop_back(); 12971 12972 if (PromOp.getOpcode() == ISD::TRUNCATE || 12973 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12974 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12975 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12976 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12977 PromOp.getOperand(0).getValueType() != MVT::i1) { 12978 // The operand is not yet ready (see comment below). 12979 PromOpHandles.emplace_front(PromOp); 12980 continue; 12981 } 12982 12983 SDValue RepValue = PromOp.getOperand(0); 12984 if (isa<ConstantSDNode>(RepValue)) 12985 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12986 12987 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12988 continue; 12989 } 12990 12991 unsigned C; 12992 switch (PromOp.getOpcode()) { 12993 default: C = 0; break; 12994 case ISD::SELECT: C = 1; break; 12995 case ISD::SELECT_CC: C = 2; break; 12996 } 12997 12998 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12999 PromOp.getOperand(C).getValueType() != MVT::i1) || 13000 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13001 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13002 // The to-be-promoted operands of this node have not yet been 13003 // promoted (this should be rare because we're going through the 13004 // list backward, but if one of the operands has several users in 13005 // this cluster of to-be-promoted nodes, it is possible). 13006 PromOpHandles.emplace_front(PromOp); 13007 continue; 13008 } 13009 13010 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13011 PromOp.getNode()->op_end()); 13012 13013 // If there are any constant inputs, make sure they're replaced now. 13014 for (unsigned i = 0; i < 2; ++i) 13015 if (isa<ConstantSDNode>(Ops[C+i])) 13016 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13017 13018 DAG.ReplaceAllUsesOfValueWith(PromOp, 13019 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13020 } 13021 13022 // Now we're left with the initial truncation itself. 13023 if (N->getOpcode() == ISD::TRUNCATE) 13024 return N->getOperand(0); 13025 13026 // Otherwise, this is a comparison. The operands to be compared have just 13027 // changed type (to i1), but everything else is the same. 13028 return SDValue(N, 0); 13029 } 13030 13031 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13032 DAGCombinerInfo &DCI) const { 13033 SelectionDAG &DAG = DCI.DAG; 13034 SDLoc dl(N); 13035 13036 // If we're tracking CR bits, we need to be careful that we don't have: 13037 // zext(binary-ops(trunc(x), trunc(y))) 13038 // or 13039 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13040 // such that we're unnecessarily moving things into CR bits that can more 13041 // efficiently stay in GPRs. Note that if we're not certain that the high 13042 // bits are set as required by the final extension, we still may need to do 13043 // some masking to get the proper behavior. 13044 13045 // This same functionality is important on PPC64 when dealing with 13046 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13047 // the return values of functions. Because it is so similar, it is handled 13048 // here as well. 13049 13050 if (N->getValueType(0) != MVT::i32 && 13051 N->getValueType(0) != MVT::i64) 13052 return SDValue(); 13053 13054 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13055 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13056 return SDValue(); 13057 13058 if (N->getOperand(0).getOpcode() != ISD::AND && 13059 N->getOperand(0).getOpcode() != ISD::OR && 13060 N->getOperand(0).getOpcode() != ISD::XOR && 13061 N->getOperand(0).getOpcode() != ISD::SELECT && 13062 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13063 return SDValue(); 13064 13065 SmallVector<SDValue, 4> Inputs; 13066 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13067 SmallPtrSet<SDNode *, 16> Visited; 13068 13069 // Visit all inputs, collect all binary operations (and, or, xor and 13070 // select) that are all fed by truncations. 13071 while (!BinOps.empty()) { 13072 SDValue BinOp = BinOps.back(); 13073 BinOps.pop_back(); 13074 13075 if (!Visited.insert(BinOp.getNode()).second) 13076 continue; 13077 13078 PromOps.push_back(BinOp); 13079 13080 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13081 // The condition of the select is not promoted. 13082 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13083 continue; 13084 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13085 continue; 13086 13087 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13088 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13089 Inputs.push_back(BinOp.getOperand(i)); 13090 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13091 BinOp.getOperand(i).getOpcode() == ISD::OR || 13092 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13093 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13094 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13095 BinOps.push_back(BinOp.getOperand(i)); 13096 } else { 13097 // We have an input that is not a truncation or another binary 13098 // operation; we'll abort this transformation. 13099 return SDValue(); 13100 } 13101 } 13102 } 13103 13104 // The operands of a select that must be truncated when the select is 13105 // promoted because the operand is actually part of the to-be-promoted set. 13106 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13107 13108 // Make sure that this is a self-contained cluster of operations (which 13109 // is not quite the same thing as saying that everything has only one 13110 // use). 13111 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13112 if (isa<ConstantSDNode>(Inputs[i])) 13113 continue; 13114 13115 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13116 UE = Inputs[i].getNode()->use_end(); 13117 UI != UE; ++UI) { 13118 SDNode *User = *UI; 13119 if (User != N && !Visited.count(User)) 13120 return SDValue(); 13121 13122 // If we're going to promote the non-output-value operand(s) or SELECT or 13123 // SELECT_CC, record them for truncation. 13124 if (User->getOpcode() == ISD::SELECT) { 13125 if (User->getOperand(0) == Inputs[i]) 13126 SelectTruncOp[0].insert(std::make_pair(User, 13127 User->getOperand(0).getValueType())); 13128 } else if (User->getOpcode() == ISD::SELECT_CC) { 13129 if (User->getOperand(0) == Inputs[i]) 13130 SelectTruncOp[0].insert(std::make_pair(User, 13131 User->getOperand(0).getValueType())); 13132 if (User->getOperand(1) == Inputs[i]) 13133 SelectTruncOp[1].insert(std::make_pair(User, 13134 User->getOperand(1).getValueType())); 13135 } 13136 } 13137 } 13138 13139 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13140 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13141 UE = PromOps[i].getNode()->use_end(); 13142 UI != UE; ++UI) { 13143 SDNode *User = *UI; 13144 if (User != N && !Visited.count(User)) 13145 return SDValue(); 13146 13147 // If we're going to promote the non-output-value operand(s) or SELECT or 13148 // SELECT_CC, record them for truncation. 13149 if (User->getOpcode() == ISD::SELECT) { 13150 if (User->getOperand(0) == PromOps[i]) 13151 SelectTruncOp[0].insert(std::make_pair(User, 13152 User->getOperand(0).getValueType())); 13153 } else if (User->getOpcode() == ISD::SELECT_CC) { 13154 if (User->getOperand(0) == PromOps[i]) 13155 SelectTruncOp[0].insert(std::make_pair(User, 13156 User->getOperand(0).getValueType())); 13157 if (User->getOperand(1) == PromOps[i]) 13158 SelectTruncOp[1].insert(std::make_pair(User, 13159 User->getOperand(1).getValueType())); 13160 } 13161 } 13162 } 13163 13164 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13165 bool ReallyNeedsExt = false; 13166 if (N->getOpcode() != ISD::ANY_EXTEND) { 13167 // If all of the inputs are not already sign/zero extended, then 13168 // we'll still need to do that at the end. 13169 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13170 if (isa<ConstantSDNode>(Inputs[i])) 13171 continue; 13172 13173 unsigned OpBits = 13174 Inputs[i].getOperand(0).getValueSizeInBits(); 13175 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13176 13177 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13178 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13179 APInt::getHighBitsSet(OpBits, 13180 OpBits-PromBits))) || 13181 (N->getOpcode() == ISD::SIGN_EXTEND && 13182 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13183 (OpBits-(PromBits-1)))) { 13184 ReallyNeedsExt = true; 13185 break; 13186 } 13187 } 13188 } 13189 13190 // Replace all inputs, either with the truncation operand, or a 13191 // truncation or extension to the final output type. 13192 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13193 // Constant inputs need to be replaced with the to-be-promoted nodes that 13194 // use them because they might have users outside of the cluster of 13195 // promoted nodes. 13196 if (isa<ConstantSDNode>(Inputs[i])) 13197 continue; 13198 13199 SDValue InSrc = Inputs[i].getOperand(0); 13200 if (Inputs[i].getValueType() == N->getValueType(0)) 13201 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13202 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13203 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13204 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13205 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13206 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13207 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13208 else 13209 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13210 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13211 } 13212 13213 std::list<HandleSDNode> PromOpHandles; 13214 for (auto &PromOp : PromOps) 13215 PromOpHandles.emplace_back(PromOp); 13216 13217 // Replace all operations (these are all the same, but have a different 13218 // (promoted) return type). DAG.getNode will validate that the types of 13219 // a binary operator match, so go through the list in reverse so that 13220 // we've likely promoted both operands first. 13221 while (!PromOpHandles.empty()) { 13222 SDValue PromOp = PromOpHandles.back().getValue(); 13223 PromOpHandles.pop_back(); 13224 13225 unsigned C; 13226 switch (PromOp.getOpcode()) { 13227 default: C = 0; break; 13228 case ISD::SELECT: C = 1; break; 13229 case ISD::SELECT_CC: C = 2; break; 13230 } 13231 13232 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13233 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13234 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13235 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13236 // The to-be-promoted operands of this node have not yet been 13237 // promoted (this should be rare because we're going through the 13238 // list backward, but if one of the operands has several users in 13239 // this cluster of to-be-promoted nodes, it is possible). 13240 PromOpHandles.emplace_front(PromOp); 13241 continue; 13242 } 13243 13244 // For SELECT and SELECT_CC nodes, we do a similar check for any 13245 // to-be-promoted comparison inputs. 13246 if (PromOp.getOpcode() == ISD::SELECT || 13247 PromOp.getOpcode() == ISD::SELECT_CC) { 13248 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13249 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13250 (SelectTruncOp[1].count(PromOp.getNode()) && 13251 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13252 PromOpHandles.emplace_front(PromOp); 13253 continue; 13254 } 13255 } 13256 13257 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13258 PromOp.getNode()->op_end()); 13259 13260 // If this node has constant inputs, then they'll need to be promoted here. 13261 for (unsigned i = 0; i < 2; ++i) { 13262 if (!isa<ConstantSDNode>(Ops[C+i])) 13263 continue; 13264 if (Ops[C+i].getValueType() == N->getValueType(0)) 13265 continue; 13266 13267 if (N->getOpcode() == ISD::SIGN_EXTEND) 13268 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13269 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13270 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13271 else 13272 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13273 } 13274 13275 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13276 // truncate them again to the original value type. 13277 if (PromOp.getOpcode() == ISD::SELECT || 13278 PromOp.getOpcode() == ISD::SELECT_CC) { 13279 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13280 if (SI0 != SelectTruncOp[0].end()) 13281 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13282 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13283 if (SI1 != SelectTruncOp[1].end()) 13284 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13285 } 13286 13287 DAG.ReplaceAllUsesOfValueWith(PromOp, 13288 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13289 } 13290 13291 // Now we're left with the initial extension itself. 13292 if (!ReallyNeedsExt) 13293 return N->getOperand(0); 13294 13295 // To zero extend, just mask off everything except for the first bit (in the 13296 // i1 case). 13297 if (N->getOpcode() == ISD::ZERO_EXTEND) 13298 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13299 DAG.getConstant(APInt::getLowBitsSet( 13300 N->getValueSizeInBits(0), PromBits), 13301 dl, N->getValueType(0))); 13302 13303 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13304 "Invalid extension type"); 13305 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13306 SDValue ShiftCst = 13307 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13308 return DAG.getNode( 13309 ISD::SRA, dl, N->getValueType(0), 13310 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13311 ShiftCst); 13312 } 13313 13314 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13315 DAGCombinerInfo &DCI) const { 13316 assert(N->getOpcode() == ISD::SETCC && 13317 "Should be called with a SETCC node"); 13318 13319 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13320 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13321 SDValue LHS = N->getOperand(0); 13322 SDValue RHS = N->getOperand(1); 13323 13324 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13325 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13326 LHS.hasOneUse()) 13327 std::swap(LHS, RHS); 13328 13329 // x == 0-y --> x+y == 0 13330 // x != 0-y --> x+y != 0 13331 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13332 RHS.hasOneUse()) { 13333 SDLoc DL(N); 13334 SelectionDAG &DAG = DCI.DAG; 13335 EVT VT = N->getValueType(0); 13336 EVT OpVT = LHS.getValueType(); 13337 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13338 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13339 } 13340 } 13341 13342 return DAGCombineTruncBoolExt(N, DCI); 13343 } 13344 13345 // Is this an extending load from an f32 to an f64? 13346 static bool isFPExtLoad(SDValue Op) { 13347 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13348 return LD->getExtensionType() == ISD::EXTLOAD && 13349 Op.getValueType() == MVT::f64; 13350 return false; 13351 } 13352 13353 /// Reduces the number of fp-to-int conversion when building a vector. 13354 /// 13355 /// If this vector is built out of floating to integer conversions, 13356 /// transform it to a vector built out of floating point values followed by a 13357 /// single floating to integer conversion of the vector. 13358 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13359 /// becomes (fptosi (build_vector ($A, $B, ...))) 13360 SDValue PPCTargetLowering:: 13361 combineElementTruncationToVectorTruncation(SDNode *N, 13362 DAGCombinerInfo &DCI) const { 13363 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13364 "Should be called with a BUILD_VECTOR node"); 13365 13366 SelectionDAG &DAG = DCI.DAG; 13367 SDLoc dl(N); 13368 13369 SDValue FirstInput = N->getOperand(0); 13370 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13371 "The input operand must be an fp-to-int conversion."); 13372 13373 // This combine happens after legalization so the fp_to_[su]i nodes are 13374 // already converted to PPCSISD nodes. 13375 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13376 if (FirstConversion == PPCISD::FCTIDZ || 13377 FirstConversion == PPCISD::FCTIDUZ || 13378 FirstConversion == PPCISD::FCTIWZ || 13379 FirstConversion == PPCISD::FCTIWUZ) { 13380 bool IsSplat = true; 13381 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13382 FirstConversion == PPCISD::FCTIWUZ; 13383 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13384 SmallVector<SDValue, 4> Ops; 13385 EVT TargetVT = N->getValueType(0); 13386 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13387 SDValue NextOp = N->getOperand(i); 13388 if (NextOp.getOpcode() != PPCISD::MFVSR) 13389 return SDValue(); 13390 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13391 if (NextConversion != FirstConversion) 13392 return SDValue(); 13393 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13394 // This is not valid if the input was originally double precision. It is 13395 // also not profitable to do unless this is an extending load in which 13396 // case doing this combine will allow us to combine consecutive loads. 13397 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13398 return SDValue(); 13399 if (N->getOperand(i) != FirstInput) 13400 IsSplat = false; 13401 } 13402 13403 // If this is a splat, we leave it as-is since there will be only a single 13404 // fp-to-int conversion followed by a splat of the integer. This is better 13405 // for 32-bit and smaller ints and neutral for 64-bit ints. 13406 if (IsSplat) 13407 return SDValue(); 13408 13409 // Now that we know we have the right type of node, get its operands 13410 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13411 SDValue In = N->getOperand(i).getOperand(0); 13412 if (Is32Bit) { 13413 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13414 // here, we know that all inputs are extending loads so this is safe). 13415 if (In.isUndef()) 13416 Ops.push_back(DAG.getUNDEF(SrcVT)); 13417 else { 13418 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13419 MVT::f32, In.getOperand(0), 13420 DAG.getIntPtrConstant(1, dl)); 13421 Ops.push_back(Trunc); 13422 } 13423 } else 13424 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13425 } 13426 13427 unsigned Opcode; 13428 if (FirstConversion == PPCISD::FCTIDZ || 13429 FirstConversion == PPCISD::FCTIWZ) 13430 Opcode = ISD::FP_TO_SINT; 13431 else 13432 Opcode = ISD::FP_TO_UINT; 13433 13434 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13435 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13436 return DAG.getNode(Opcode, dl, TargetVT, BV); 13437 } 13438 return SDValue(); 13439 } 13440 13441 /// Reduce the number of loads when building a vector. 13442 /// 13443 /// Building a vector out of multiple loads can be converted to a load 13444 /// of the vector type if the loads are consecutive. If the loads are 13445 /// consecutive but in descending order, a shuffle is added at the end 13446 /// to reorder the vector. 13447 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13448 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13449 "Should be called with a BUILD_VECTOR node"); 13450 13451 SDLoc dl(N); 13452 13453 // Return early for non byte-sized type, as they can't be consecutive. 13454 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13455 return SDValue(); 13456 13457 bool InputsAreConsecutiveLoads = true; 13458 bool InputsAreReverseConsecutive = true; 13459 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13460 SDValue FirstInput = N->getOperand(0); 13461 bool IsRoundOfExtLoad = false; 13462 13463 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13464 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13465 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13466 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13467 } 13468 // Not a build vector of (possibly fp_rounded) loads. 13469 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13470 N->getNumOperands() == 1) 13471 return SDValue(); 13472 13473 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13474 // If any inputs are fp_round(extload), they all must be. 13475 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13476 return SDValue(); 13477 13478 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13479 N->getOperand(i); 13480 if (NextInput.getOpcode() != ISD::LOAD) 13481 return SDValue(); 13482 13483 SDValue PreviousInput = 13484 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13485 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13486 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13487 13488 // If any inputs are fp_round(extload), they all must be. 13489 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13490 return SDValue(); 13491 13492 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13493 InputsAreConsecutiveLoads = false; 13494 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13495 InputsAreReverseConsecutive = false; 13496 13497 // Exit early if the loads are neither consecutive nor reverse consecutive. 13498 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13499 return SDValue(); 13500 } 13501 13502 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13503 "The loads cannot be both consecutive and reverse consecutive."); 13504 13505 SDValue FirstLoadOp = 13506 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13507 SDValue LastLoadOp = 13508 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13509 N->getOperand(N->getNumOperands()-1); 13510 13511 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13512 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13513 if (InputsAreConsecutiveLoads) { 13514 assert(LD1 && "Input needs to be a LoadSDNode."); 13515 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13516 LD1->getBasePtr(), LD1->getPointerInfo(), 13517 LD1->getAlignment()); 13518 } 13519 if (InputsAreReverseConsecutive) { 13520 assert(LDL && "Input needs to be a LoadSDNode."); 13521 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13522 LDL->getBasePtr(), LDL->getPointerInfo(), 13523 LDL->getAlignment()); 13524 SmallVector<int, 16> Ops; 13525 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13526 Ops.push_back(i); 13527 13528 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13529 DAG.getUNDEF(N->getValueType(0)), Ops); 13530 } 13531 return SDValue(); 13532 } 13533 13534 // This function adds the required vector_shuffle needed to get 13535 // the elements of the vector extract in the correct position 13536 // as specified by the CorrectElems encoding. 13537 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13538 SDValue Input, uint64_t Elems, 13539 uint64_t CorrectElems) { 13540 SDLoc dl(N); 13541 13542 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13543 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13544 13545 // Knowing the element indices being extracted from the original 13546 // vector and the order in which they're being inserted, just put 13547 // them at element indices required for the instruction. 13548 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13549 if (DAG.getDataLayout().isLittleEndian()) 13550 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13551 else 13552 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13553 CorrectElems = CorrectElems >> 8; 13554 Elems = Elems >> 8; 13555 } 13556 13557 SDValue Shuffle = 13558 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13559 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13560 13561 EVT VT = N->getValueType(0); 13562 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13563 13564 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13565 Input.getValueType().getVectorElementType(), 13566 VT.getVectorNumElements()); 13567 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13568 DAG.getValueType(ExtVT)); 13569 } 13570 13571 // Look for build vector patterns where input operands come from sign 13572 // extended vector_extract elements of specific indices. If the correct indices 13573 // aren't used, add a vector shuffle to fix up the indices and create 13574 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13575 // during instruction selection. 13576 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13577 // This array encodes the indices that the vector sign extend instructions 13578 // extract from when extending from one type to another for both BE and LE. 13579 // The right nibble of each byte corresponds to the LE incides. 13580 // and the left nibble of each byte corresponds to the BE incides. 13581 // For example: 0x3074B8FC byte->word 13582 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13583 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13584 // For example: 0x000070F8 byte->double word 13585 // For LE: the allowed indices are: 0x0,0x8 13586 // For BE: the allowed indices are: 0x7,0xF 13587 uint64_t TargetElems[] = { 13588 0x3074B8FC, // b->w 13589 0x000070F8, // b->d 13590 0x10325476, // h->w 13591 0x00003074, // h->d 13592 0x00001032, // w->d 13593 }; 13594 13595 uint64_t Elems = 0; 13596 int Index; 13597 SDValue Input; 13598 13599 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13600 if (!Op) 13601 return false; 13602 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13603 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13604 return false; 13605 13606 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13607 // of the right width. 13608 SDValue Extract = Op.getOperand(0); 13609 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13610 Extract = Extract.getOperand(0); 13611 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13612 return false; 13613 13614 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13615 if (!ExtOp) 13616 return false; 13617 13618 Index = ExtOp->getZExtValue(); 13619 if (Input && Input != Extract.getOperand(0)) 13620 return false; 13621 13622 if (!Input) 13623 Input = Extract.getOperand(0); 13624 13625 Elems = Elems << 8; 13626 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13627 Elems |= Index; 13628 13629 return true; 13630 }; 13631 13632 // If the build vector operands aren't sign extended vector extracts, 13633 // of the same input vector, then return. 13634 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13635 if (!isSExtOfVecExtract(N->getOperand(i))) { 13636 return SDValue(); 13637 } 13638 } 13639 13640 // If the vector extract indicies are not correct, add the appropriate 13641 // vector_shuffle. 13642 int TgtElemArrayIdx; 13643 int InputSize = Input.getValueType().getScalarSizeInBits(); 13644 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13645 if (InputSize + OutputSize == 40) 13646 TgtElemArrayIdx = 0; 13647 else if (InputSize + OutputSize == 72) 13648 TgtElemArrayIdx = 1; 13649 else if (InputSize + OutputSize == 48) 13650 TgtElemArrayIdx = 2; 13651 else if (InputSize + OutputSize == 80) 13652 TgtElemArrayIdx = 3; 13653 else if (InputSize + OutputSize == 96) 13654 TgtElemArrayIdx = 4; 13655 else 13656 return SDValue(); 13657 13658 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13659 CorrectElems = DAG.getDataLayout().isLittleEndian() 13660 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13661 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13662 if (Elems != CorrectElems) { 13663 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13664 } 13665 13666 // Regular lowering will catch cases where a shuffle is not needed. 13667 return SDValue(); 13668 } 13669 13670 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13671 DAGCombinerInfo &DCI) const { 13672 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13673 "Should be called with a BUILD_VECTOR node"); 13674 13675 SelectionDAG &DAG = DCI.DAG; 13676 SDLoc dl(N); 13677 13678 if (!Subtarget.hasVSX()) 13679 return SDValue(); 13680 13681 // The target independent DAG combiner will leave a build_vector of 13682 // float-to-int conversions intact. We can generate MUCH better code for 13683 // a float-to-int conversion of a vector of floats. 13684 SDValue FirstInput = N->getOperand(0); 13685 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13686 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13687 if (Reduced) 13688 return Reduced; 13689 } 13690 13691 // If we're building a vector out of consecutive loads, just load that 13692 // vector type. 13693 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13694 if (Reduced) 13695 return Reduced; 13696 13697 // If we're building a vector out of extended elements from another vector 13698 // we have P9 vector integer extend instructions. The code assumes legal 13699 // input types (i.e. it can't handle things like v4i16) so do not run before 13700 // legalization. 13701 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13702 Reduced = combineBVOfVecSExt(N, DAG); 13703 if (Reduced) 13704 return Reduced; 13705 } 13706 13707 13708 if (N->getValueType(0) != MVT::v2f64) 13709 return SDValue(); 13710 13711 // Looking for: 13712 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13713 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13714 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13715 return SDValue(); 13716 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13717 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13718 return SDValue(); 13719 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13720 return SDValue(); 13721 13722 SDValue Ext1 = FirstInput.getOperand(0); 13723 SDValue Ext2 = N->getOperand(1).getOperand(0); 13724 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13725 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13726 return SDValue(); 13727 13728 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13729 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13730 if (!Ext1Op || !Ext2Op) 13731 return SDValue(); 13732 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13733 Ext1.getOperand(0) != Ext2.getOperand(0)) 13734 return SDValue(); 13735 13736 int FirstElem = Ext1Op->getZExtValue(); 13737 int SecondElem = Ext2Op->getZExtValue(); 13738 int SubvecIdx; 13739 if (FirstElem == 0 && SecondElem == 1) 13740 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13741 else if (FirstElem == 2 && SecondElem == 3) 13742 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13743 else 13744 return SDValue(); 13745 13746 SDValue SrcVec = Ext1.getOperand(0); 13747 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13748 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13749 return DAG.getNode(NodeType, dl, MVT::v2f64, 13750 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13751 } 13752 13753 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13754 DAGCombinerInfo &DCI) const { 13755 assert((N->getOpcode() == ISD::SINT_TO_FP || 13756 N->getOpcode() == ISD::UINT_TO_FP) && 13757 "Need an int -> FP conversion node here"); 13758 13759 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13760 return SDValue(); 13761 13762 SelectionDAG &DAG = DCI.DAG; 13763 SDLoc dl(N); 13764 SDValue Op(N, 0); 13765 13766 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13767 // from the hardware. 13768 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13769 return SDValue(); 13770 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13771 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13772 return SDValue(); 13773 13774 SDValue FirstOperand(Op.getOperand(0)); 13775 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13776 (FirstOperand.getValueType() == MVT::i8 || 13777 FirstOperand.getValueType() == MVT::i16); 13778 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13779 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13780 bool DstDouble = Op.getValueType() == MVT::f64; 13781 unsigned ConvOp = Signed ? 13782 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13783 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13784 SDValue WidthConst = 13785 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13786 dl, false); 13787 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13788 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13789 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13790 DAG.getVTList(MVT::f64, MVT::Other), 13791 Ops, MVT::i8, LDN->getMemOperand()); 13792 13793 // For signed conversion, we need to sign-extend the value in the VSR 13794 if (Signed) { 13795 SDValue ExtOps[] = { Ld, WidthConst }; 13796 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13797 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13798 } else 13799 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13800 } 13801 13802 13803 // For i32 intermediate values, unfortunately, the conversion functions 13804 // leave the upper 32 bits of the value are undefined. Within the set of 13805 // scalar instructions, we have no method for zero- or sign-extending the 13806 // value. Thus, we cannot handle i32 intermediate values here. 13807 if (Op.getOperand(0).getValueType() == MVT::i32) 13808 return SDValue(); 13809 13810 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13811 "UINT_TO_FP is supported only with FPCVT"); 13812 13813 // If we have FCFIDS, then use it when converting to single-precision. 13814 // Otherwise, convert to double-precision and then round. 13815 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13816 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13817 : PPCISD::FCFIDS) 13818 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13819 : PPCISD::FCFID); 13820 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13821 ? MVT::f32 13822 : MVT::f64; 13823 13824 // If we're converting from a float, to an int, and back to a float again, 13825 // then we don't need the store/load pair at all. 13826 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13827 Subtarget.hasFPCVT()) || 13828 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13829 SDValue Src = Op.getOperand(0).getOperand(0); 13830 if (Src.getValueType() == MVT::f32) { 13831 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13832 DCI.AddToWorklist(Src.getNode()); 13833 } else if (Src.getValueType() != MVT::f64) { 13834 // Make sure that we don't pick up a ppc_fp128 source value. 13835 return SDValue(); 13836 } 13837 13838 unsigned FCTOp = 13839 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13840 PPCISD::FCTIDUZ; 13841 13842 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13843 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13844 13845 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13846 FP = DAG.getNode(ISD::FP_ROUND, dl, 13847 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13848 DCI.AddToWorklist(FP.getNode()); 13849 } 13850 13851 return FP; 13852 } 13853 13854 return SDValue(); 13855 } 13856 13857 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13858 // builtins) into loads with swaps. 13859 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13860 DAGCombinerInfo &DCI) const { 13861 SelectionDAG &DAG = DCI.DAG; 13862 SDLoc dl(N); 13863 SDValue Chain; 13864 SDValue Base; 13865 MachineMemOperand *MMO; 13866 13867 switch (N->getOpcode()) { 13868 default: 13869 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13870 case ISD::LOAD: { 13871 LoadSDNode *LD = cast<LoadSDNode>(N); 13872 Chain = LD->getChain(); 13873 Base = LD->getBasePtr(); 13874 MMO = LD->getMemOperand(); 13875 // If the MMO suggests this isn't a load of a full vector, leave 13876 // things alone. For a built-in, we have to make the change for 13877 // correctness, so if there is a size problem that will be a bug. 13878 if (MMO->getSize() < 16) 13879 return SDValue(); 13880 break; 13881 } 13882 case ISD::INTRINSIC_W_CHAIN: { 13883 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13884 Chain = Intrin->getChain(); 13885 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13886 // us what we want. Get operand 2 instead. 13887 Base = Intrin->getOperand(2); 13888 MMO = Intrin->getMemOperand(); 13889 break; 13890 } 13891 } 13892 13893 MVT VecTy = N->getValueType(0).getSimpleVT(); 13894 13895 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13896 // aligned and the type is a vector with elements up to 4 bytes 13897 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13898 VecTy.getScalarSizeInBits() <= 32) { 13899 return SDValue(); 13900 } 13901 13902 SDValue LoadOps[] = { Chain, Base }; 13903 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13904 DAG.getVTList(MVT::v2f64, MVT::Other), 13905 LoadOps, MVT::v2f64, MMO); 13906 13907 DCI.AddToWorklist(Load.getNode()); 13908 Chain = Load.getValue(1); 13909 SDValue Swap = DAG.getNode( 13910 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13911 DCI.AddToWorklist(Swap.getNode()); 13912 13913 // Add a bitcast if the resulting load type doesn't match v2f64. 13914 if (VecTy != MVT::v2f64) { 13915 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13916 DCI.AddToWorklist(N.getNode()); 13917 // Package {bitcast value, swap's chain} to match Load's shape. 13918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13919 N, Swap.getValue(1)); 13920 } 13921 13922 return Swap; 13923 } 13924 13925 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13926 // builtins) into stores with swaps. 13927 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13928 DAGCombinerInfo &DCI) const { 13929 SelectionDAG &DAG = DCI.DAG; 13930 SDLoc dl(N); 13931 SDValue Chain; 13932 SDValue Base; 13933 unsigned SrcOpnd; 13934 MachineMemOperand *MMO; 13935 13936 switch (N->getOpcode()) { 13937 default: 13938 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13939 case ISD::STORE: { 13940 StoreSDNode *ST = cast<StoreSDNode>(N); 13941 Chain = ST->getChain(); 13942 Base = ST->getBasePtr(); 13943 MMO = ST->getMemOperand(); 13944 SrcOpnd = 1; 13945 // If the MMO suggests this isn't a store of a full vector, leave 13946 // things alone. For a built-in, we have to make the change for 13947 // correctness, so if there is a size problem that will be a bug. 13948 if (MMO->getSize() < 16) 13949 return SDValue(); 13950 break; 13951 } 13952 case ISD::INTRINSIC_VOID: { 13953 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13954 Chain = Intrin->getChain(); 13955 // Intrin->getBasePtr() oddly does not get what we want. 13956 Base = Intrin->getOperand(3); 13957 MMO = Intrin->getMemOperand(); 13958 SrcOpnd = 2; 13959 break; 13960 } 13961 } 13962 13963 SDValue Src = N->getOperand(SrcOpnd); 13964 MVT VecTy = Src.getValueType().getSimpleVT(); 13965 13966 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13967 // aligned and the type is a vector with elements up to 4 bytes 13968 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13969 VecTy.getScalarSizeInBits() <= 32) { 13970 return SDValue(); 13971 } 13972 13973 // All stores are done as v2f64 and possible bit cast. 13974 if (VecTy != MVT::v2f64) { 13975 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13976 DCI.AddToWorklist(Src.getNode()); 13977 } 13978 13979 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13980 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13981 DCI.AddToWorklist(Swap.getNode()); 13982 Chain = Swap.getValue(1); 13983 SDValue StoreOps[] = { Chain, Swap, Base }; 13984 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13985 DAG.getVTList(MVT::Other), 13986 StoreOps, VecTy, MMO); 13987 DCI.AddToWorklist(Store.getNode()); 13988 return Store; 13989 } 13990 13991 // Handle DAG combine for STORE (FP_TO_INT F). 13992 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13993 DAGCombinerInfo &DCI) const { 13994 13995 SelectionDAG &DAG = DCI.DAG; 13996 SDLoc dl(N); 13997 unsigned Opcode = N->getOperand(1).getOpcode(); 13998 13999 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14000 && "Not a FP_TO_INT Instruction!"); 14001 14002 SDValue Val = N->getOperand(1).getOperand(0); 14003 EVT Op1VT = N->getOperand(1).getValueType(); 14004 EVT ResVT = Val.getValueType(); 14005 14006 // Floating point types smaller than 32 bits are not legal on Power. 14007 if (ResVT.getScalarSizeInBits() < 32) 14008 return SDValue(); 14009 14010 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14011 bool ValidTypeForStoreFltAsInt = 14012 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14013 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14014 14015 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14016 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14017 return SDValue(); 14018 14019 // Extend f32 values to f64 14020 if (ResVT.getScalarSizeInBits() == 32) { 14021 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14022 DCI.AddToWorklist(Val.getNode()); 14023 } 14024 14025 // Set signed or unsigned conversion opcode. 14026 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14027 PPCISD::FP_TO_SINT_IN_VSR : 14028 PPCISD::FP_TO_UINT_IN_VSR; 14029 14030 Val = DAG.getNode(ConvOpcode, 14031 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14032 DCI.AddToWorklist(Val.getNode()); 14033 14034 // Set number of bytes being converted. 14035 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14036 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14037 DAG.getIntPtrConstant(ByteSize, dl, false), 14038 DAG.getValueType(Op1VT) }; 14039 14040 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14041 DAG.getVTList(MVT::Other), Ops, 14042 cast<StoreSDNode>(N)->getMemoryVT(), 14043 cast<StoreSDNode>(N)->getMemOperand()); 14044 14045 DCI.AddToWorklist(Val.getNode()); 14046 return Val; 14047 } 14048 14049 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14050 LSBaseSDNode *LSBase, 14051 DAGCombinerInfo &DCI) const { 14052 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14053 "Not a reverse memop pattern!"); 14054 14055 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14056 auto Mask = SVN->getMask(); 14057 int i = 0; 14058 auto I = Mask.rbegin(); 14059 auto E = Mask.rend(); 14060 14061 for (; I != E; ++I) { 14062 if (*I != i) 14063 return false; 14064 i++; 14065 } 14066 return true; 14067 }; 14068 14069 SelectionDAG &DAG = DCI.DAG; 14070 EVT VT = SVN->getValueType(0); 14071 14072 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14073 return SDValue(); 14074 14075 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14076 // See comment in PPCVSXSwapRemoval.cpp. 14077 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14078 if (!Subtarget.hasP9Vector()) 14079 return SDValue(); 14080 14081 if(!IsElementReverse(SVN)) 14082 return SDValue(); 14083 14084 if (LSBase->getOpcode() == ISD::LOAD) { 14085 SDLoc dl(SVN); 14086 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14087 return DAG.getMemIntrinsicNode( 14088 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14089 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14090 } 14091 14092 if (LSBase->getOpcode() == ISD::STORE) { 14093 SDLoc dl(LSBase); 14094 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14095 LSBase->getBasePtr()}; 14096 return DAG.getMemIntrinsicNode( 14097 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14098 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14099 } 14100 14101 llvm_unreachable("Expected a load or store node here"); 14102 } 14103 14104 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14105 DAGCombinerInfo &DCI) const { 14106 SelectionDAG &DAG = DCI.DAG; 14107 SDLoc dl(N); 14108 switch (N->getOpcode()) { 14109 default: break; 14110 case ISD::ADD: 14111 return combineADD(N, DCI); 14112 case ISD::SHL: 14113 return combineSHL(N, DCI); 14114 case ISD::SRA: 14115 return combineSRA(N, DCI); 14116 case ISD::SRL: 14117 return combineSRL(N, DCI); 14118 case ISD::MUL: 14119 return combineMUL(N, DCI); 14120 case PPCISD::SHL: 14121 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14122 return N->getOperand(0); 14123 break; 14124 case PPCISD::SRL: 14125 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14126 return N->getOperand(0); 14127 break; 14128 case PPCISD::SRA: 14129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14130 if (C->isNullValue() || // 0 >>s V -> 0. 14131 C->isAllOnesValue()) // -1 >>s V -> -1. 14132 return N->getOperand(0); 14133 } 14134 break; 14135 case ISD::SIGN_EXTEND: 14136 case ISD::ZERO_EXTEND: 14137 case ISD::ANY_EXTEND: 14138 return DAGCombineExtBoolTrunc(N, DCI); 14139 case ISD::TRUNCATE: 14140 return combineTRUNCATE(N, DCI); 14141 case ISD::SETCC: 14142 if (SDValue CSCC = combineSetCC(N, DCI)) 14143 return CSCC; 14144 LLVM_FALLTHROUGH; 14145 case ISD::SELECT_CC: 14146 return DAGCombineTruncBoolExt(N, DCI); 14147 case ISD::SINT_TO_FP: 14148 case ISD::UINT_TO_FP: 14149 return combineFPToIntToFP(N, DCI); 14150 case ISD::VECTOR_SHUFFLE: 14151 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14152 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14153 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14154 } 14155 break; 14156 case ISD::STORE: { 14157 14158 EVT Op1VT = N->getOperand(1).getValueType(); 14159 unsigned Opcode = N->getOperand(1).getOpcode(); 14160 14161 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14162 SDValue Val= combineStoreFPToInt(N, DCI); 14163 if (Val) 14164 return Val; 14165 } 14166 14167 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14168 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14169 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14170 if (Val) 14171 return Val; 14172 } 14173 14174 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14175 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14176 N->getOperand(1).getNode()->hasOneUse() && 14177 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14178 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14179 14180 // STBRX can only handle simple types and it makes no sense to store less 14181 // two bytes in byte-reversed order. 14182 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14183 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14184 break; 14185 14186 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14187 // Do an any-extend to 32-bits if this is a half-word input. 14188 if (BSwapOp.getValueType() == MVT::i16) 14189 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14190 14191 // If the type of BSWAP operand is wider than stored memory width 14192 // it need to be shifted to the right side before STBRX. 14193 if (Op1VT.bitsGT(mVT)) { 14194 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14195 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14196 DAG.getConstant(Shift, dl, MVT::i32)); 14197 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14198 if (Op1VT == MVT::i64) 14199 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14200 } 14201 14202 SDValue Ops[] = { 14203 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14204 }; 14205 return 14206 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14207 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14208 cast<StoreSDNode>(N)->getMemOperand()); 14209 } 14210 14211 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14212 // So it can increase the chance of CSE constant construction. 14213 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14214 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14215 // Need to sign-extended to 64-bits to handle negative values. 14216 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14217 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14218 MemVT.getSizeInBits()); 14219 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14220 14221 // DAG.getTruncStore() can't be used here because it doesn't accept 14222 // the general (base + offset) addressing mode. 14223 // So we use UpdateNodeOperands and setTruncatingStore instead. 14224 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14225 N->getOperand(3)); 14226 cast<StoreSDNode>(N)->setTruncatingStore(true); 14227 return SDValue(N, 0); 14228 } 14229 14230 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14231 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14232 if (Op1VT.isSimple()) { 14233 MVT StoreVT = Op1VT.getSimpleVT(); 14234 if (Subtarget.needsSwapsForVSXMemOps() && 14235 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14236 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14237 return expandVSXStoreForLE(N, DCI); 14238 } 14239 break; 14240 } 14241 case ISD::LOAD: { 14242 LoadSDNode *LD = cast<LoadSDNode>(N); 14243 EVT VT = LD->getValueType(0); 14244 14245 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14246 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14247 if (VT.isSimple()) { 14248 MVT LoadVT = VT.getSimpleVT(); 14249 if (Subtarget.needsSwapsForVSXMemOps() && 14250 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14251 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14252 return expandVSXLoadForLE(N, DCI); 14253 } 14254 14255 // We sometimes end up with a 64-bit integer load, from which we extract 14256 // two single-precision floating-point numbers. This happens with 14257 // std::complex<float>, and other similar structures, because of the way we 14258 // canonicalize structure copies. However, if we lack direct moves, 14259 // then the final bitcasts from the extracted integer values to the 14260 // floating-point numbers turn into store/load pairs. Even with direct moves, 14261 // just loading the two floating-point numbers is likely better. 14262 auto ReplaceTwoFloatLoad = [&]() { 14263 if (VT != MVT::i64) 14264 return false; 14265 14266 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14267 LD->isVolatile()) 14268 return false; 14269 14270 // We're looking for a sequence like this: 14271 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14272 // t16: i64 = srl t13, Constant:i32<32> 14273 // t17: i32 = truncate t16 14274 // t18: f32 = bitcast t17 14275 // t19: i32 = truncate t13 14276 // t20: f32 = bitcast t19 14277 14278 if (!LD->hasNUsesOfValue(2, 0)) 14279 return false; 14280 14281 auto UI = LD->use_begin(); 14282 while (UI.getUse().getResNo() != 0) ++UI; 14283 SDNode *Trunc = *UI++; 14284 while (UI.getUse().getResNo() != 0) ++UI; 14285 SDNode *RightShift = *UI; 14286 if (Trunc->getOpcode() != ISD::TRUNCATE) 14287 std::swap(Trunc, RightShift); 14288 14289 if (Trunc->getOpcode() != ISD::TRUNCATE || 14290 Trunc->getValueType(0) != MVT::i32 || 14291 !Trunc->hasOneUse()) 14292 return false; 14293 if (RightShift->getOpcode() != ISD::SRL || 14294 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14295 RightShift->getConstantOperandVal(1) != 32 || 14296 !RightShift->hasOneUse()) 14297 return false; 14298 14299 SDNode *Trunc2 = *RightShift->use_begin(); 14300 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14301 Trunc2->getValueType(0) != MVT::i32 || 14302 !Trunc2->hasOneUse()) 14303 return false; 14304 14305 SDNode *Bitcast = *Trunc->use_begin(); 14306 SDNode *Bitcast2 = *Trunc2->use_begin(); 14307 14308 if (Bitcast->getOpcode() != ISD::BITCAST || 14309 Bitcast->getValueType(0) != MVT::f32) 14310 return false; 14311 if (Bitcast2->getOpcode() != ISD::BITCAST || 14312 Bitcast2->getValueType(0) != MVT::f32) 14313 return false; 14314 14315 if (Subtarget.isLittleEndian()) 14316 std::swap(Bitcast, Bitcast2); 14317 14318 // Bitcast has the second float (in memory-layout order) and Bitcast2 14319 // has the first one. 14320 14321 SDValue BasePtr = LD->getBasePtr(); 14322 if (LD->isIndexed()) { 14323 assert(LD->getAddressingMode() == ISD::PRE_INC && 14324 "Non-pre-inc AM on PPC?"); 14325 BasePtr = 14326 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14327 LD->getOffset()); 14328 } 14329 14330 auto MMOFlags = 14331 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14332 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14333 LD->getPointerInfo(), LD->getAlignment(), 14334 MMOFlags, LD->getAAInfo()); 14335 SDValue AddPtr = 14336 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14337 BasePtr, DAG.getIntPtrConstant(4, dl)); 14338 SDValue FloatLoad2 = DAG.getLoad( 14339 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14340 LD->getPointerInfo().getWithOffset(4), 14341 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14342 14343 if (LD->isIndexed()) { 14344 // Note that DAGCombine should re-form any pre-increment load(s) from 14345 // what is produced here if that makes sense. 14346 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14347 } 14348 14349 DCI.CombineTo(Bitcast2, FloatLoad); 14350 DCI.CombineTo(Bitcast, FloatLoad2); 14351 14352 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14353 SDValue(FloatLoad2.getNode(), 1)); 14354 return true; 14355 }; 14356 14357 if (ReplaceTwoFloatLoad()) 14358 return SDValue(N, 0); 14359 14360 EVT MemVT = LD->getMemoryVT(); 14361 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14362 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14363 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14364 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14365 if (LD->isUnindexed() && VT.isVector() && 14366 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14367 // P8 and later hardware should just use LOAD. 14368 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14369 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14370 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14371 LD->getAlignment() >= ScalarABIAlignment)) && 14372 LD->getAlignment() < ABIAlignment) { 14373 // This is a type-legal unaligned Altivec or QPX load. 14374 SDValue Chain = LD->getChain(); 14375 SDValue Ptr = LD->getBasePtr(); 14376 bool isLittleEndian = Subtarget.isLittleEndian(); 14377 14378 // This implements the loading of unaligned vectors as described in 14379 // the venerable Apple Velocity Engine overview. Specifically: 14380 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14381 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14382 // 14383 // The general idea is to expand a sequence of one or more unaligned 14384 // loads into an alignment-based permutation-control instruction (lvsl 14385 // or lvsr), a series of regular vector loads (which always truncate 14386 // their input address to an aligned address), and a series of 14387 // permutations. The results of these permutations are the requested 14388 // loaded values. The trick is that the last "extra" load is not taken 14389 // from the address you might suspect (sizeof(vector) bytes after the 14390 // last requested load), but rather sizeof(vector) - 1 bytes after the 14391 // last requested vector. The point of this is to avoid a page fault if 14392 // the base address happened to be aligned. This works because if the 14393 // base address is aligned, then adding less than a full vector length 14394 // will cause the last vector in the sequence to be (re)loaded. 14395 // Otherwise, the next vector will be fetched as you might suspect was 14396 // necessary. 14397 14398 // We might be able to reuse the permutation generation from 14399 // a different base address offset from this one by an aligned amount. 14400 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14401 // optimization later. 14402 Intrinsic::ID Intr, IntrLD, IntrPerm; 14403 MVT PermCntlTy, PermTy, LDTy; 14404 if (Subtarget.hasAltivec()) { 14405 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14406 Intrinsic::ppc_altivec_lvsl; 14407 IntrLD = Intrinsic::ppc_altivec_lvx; 14408 IntrPerm = Intrinsic::ppc_altivec_vperm; 14409 PermCntlTy = MVT::v16i8; 14410 PermTy = MVT::v4i32; 14411 LDTy = MVT::v4i32; 14412 } else { 14413 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14414 Intrinsic::ppc_qpx_qvlpcls; 14415 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14416 Intrinsic::ppc_qpx_qvlfs; 14417 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14418 PermCntlTy = MVT::v4f64; 14419 PermTy = MVT::v4f64; 14420 LDTy = MemVT.getSimpleVT(); 14421 } 14422 14423 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14424 14425 // Create the new MMO for the new base load. It is like the original MMO, 14426 // but represents an area in memory almost twice the vector size centered 14427 // on the original address. If the address is unaligned, we might start 14428 // reading up to (sizeof(vector)-1) bytes below the address of the 14429 // original unaligned load. 14430 MachineFunction &MF = DAG.getMachineFunction(); 14431 MachineMemOperand *BaseMMO = 14432 MF.getMachineMemOperand(LD->getMemOperand(), 14433 -(long)MemVT.getStoreSize()+1, 14434 2*MemVT.getStoreSize()-1); 14435 14436 // Create the new base load. 14437 SDValue LDXIntID = 14438 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14439 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14440 SDValue BaseLoad = 14441 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14442 DAG.getVTList(PermTy, MVT::Other), 14443 BaseLoadOps, LDTy, BaseMMO); 14444 14445 // Note that the value of IncOffset (which is provided to the next 14446 // load's pointer info offset value, and thus used to calculate the 14447 // alignment), and the value of IncValue (which is actually used to 14448 // increment the pointer value) are different! This is because we 14449 // require the next load to appear to be aligned, even though it 14450 // is actually offset from the base pointer by a lesser amount. 14451 int IncOffset = VT.getSizeInBits() / 8; 14452 int IncValue = IncOffset; 14453 14454 // Walk (both up and down) the chain looking for another load at the real 14455 // (aligned) offset (the alignment of the other load does not matter in 14456 // this case). If found, then do not use the offset reduction trick, as 14457 // that will prevent the loads from being later combined (as they would 14458 // otherwise be duplicates). 14459 if (!findConsecutiveLoad(LD, DAG)) 14460 --IncValue; 14461 14462 SDValue Increment = 14463 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14464 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14465 14466 MachineMemOperand *ExtraMMO = 14467 MF.getMachineMemOperand(LD->getMemOperand(), 14468 1, 2*MemVT.getStoreSize()-1); 14469 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14470 SDValue ExtraLoad = 14471 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14472 DAG.getVTList(PermTy, MVT::Other), 14473 ExtraLoadOps, LDTy, ExtraMMO); 14474 14475 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14476 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14477 14478 // Because vperm has a big-endian bias, we must reverse the order 14479 // of the input vectors and complement the permute control vector 14480 // when generating little endian code. We have already handled the 14481 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14482 // and ExtraLoad here. 14483 SDValue Perm; 14484 if (isLittleEndian) 14485 Perm = BuildIntrinsicOp(IntrPerm, 14486 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14487 else 14488 Perm = BuildIntrinsicOp(IntrPerm, 14489 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14490 14491 if (VT != PermTy) 14492 Perm = Subtarget.hasAltivec() ? 14493 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14494 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14495 DAG.getTargetConstant(1, dl, MVT::i64)); 14496 // second argument is 1 because this rounding 14497 // is always exact. 14498 14499 // The output of the permutation is our loaded result, the TokenFactor is 14500 // our new chain. 14501 DCI.CombineTo(N, Perm, TF); 14502 return SDValue(N, 0); 14503 } 14504 } 14505 break; 14506 case ISD::INTRINSIC_WO_CHAIN: { 14507 bool isLittleEndian = Subtarget.isLittleEndian(); 14508 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14509 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14510 : Intrinsic::ppc_altivec_lvsl); 14511 if ((IID == Intr || 14512 IID == Intrinsic::ppc_qpx_qvlpcld || 14513 IID == Intrinsic::ppc_qpx_qvlpcls) && 14514 N->getOperand(1)->getOpcode() == ISD::ADD) { 14515 SDValue Add = N->getOperand(1); 14516 14517 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14518 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14519 14520 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14521 APInt::getAllOnesValue(Bits /* alignment */) 14522 .zext(Add.getScalarValueSizeInBits()))) { 14523 SDNode *BasePtr = Add->getOperand(0).getNode(); 14524 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14525 UE = BasePtr->use_end(); 14526 UI != UE; ++UI) { 14527 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14528 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14529 // We've found another LVSL/LVSR, and this address is an aligned 14530 // multiple of that one. The results will be the same, so use the 14531 // one we've just found instead. 14532 14533 return SDValue(*UI, 0); 14534 } 14535 } 14536 } 14537 14538 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14539 SDNode *BasePtr = Add->getOperand(0).getNode(); 14540 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14541 UE = BasePtr->use_end(); UI != UE; ++UI) { 14542 if (UI->getOpcode() == ISD::ADD && 14543 isa<ConstantSDNode>(UI->getOperand(1)) && 14544 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14545 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14546 (1ULL << Bits) == 0) { 14547 SDNode *OtherAdd = *UI; 14548 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14549 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14550 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14551 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14552 return SDValue(*VI, 0); 14553 } 14554 } 14555 } 14556 } 14557 } 14558 } 14559 14560 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14561 // Expose the vabsduw/h/b opportunity for down stream 14562 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14563 (IID == Intrinsic::ppc_altivec_vmaxsw || 14564 IID == Intrinsic::ppc_altivec_vmaxsh || 14565 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14566 SDValue V1 = N->getOperand(1); 14567 SDValue V2 = N->getOperand(2); 14568 if ((V1.getSimpleValueType() == MVT::v4i32 || 14569 V1.getSimpleValueType() == MVT::v8i16 || 14570 V1.getSimpleValueType() == MVT::v16i8) && 14571 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14572 // (0-a, a) 14573 if (V1.getOpcode() == ISD::SUB && 14574 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14575 V1.getOperand(1) == V2) { 14576 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14577 } 14578 // (a, 0-a) 14579 if (V2.getOpcode() == ISD::SUB && 14580 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14581 V2.getOperand(1) == V1) { 14582 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14583 } 14584 // (x-y, y-x) 14585 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14586 V1.getOperand(0) == V2.getOperand(1) && 14587 V1.getOperand(1) == V2.getOperand(0)) { 14588 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14589 } 14590 } 14591 } 14592 } 14593 14594 break; 14595 case ISD::INTRINSIC_W_CHAIN: 14596 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14597 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14598 if (Subtarget.needsSwapsForVSXMemOps()) { 14599 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14600 default: 14601 break; 14602 case Intrinsic::ppc_vsx_lxvw4x: 14603 case Intrinsic::ppc_vsx_lxvd2x: 14604 return expandVSXLoadForLE(N, DCI); 14605 } 14606 } 14607 break; 14608 case ISD::INTRINSIC_VOID: 14609 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14610 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14611 if (Subtarget.needsSwapsForVSXMemOps()) { 14612 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14613 default: 14614 break; 14615 case Intrinsic::ppc_vsx_stxvw4x: 14616 case Intrinsic::ppc_vsx_stxvd2x: 14617 return expandVSXStoreForLE(N, DCI); 14618 } 14619 } 14620 break; 14621 case ISD::BSWAP: 14622 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14623 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14624 N->getOperand(0).hasOneUse() && 14625 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14626 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14627 N->getValueType(0) == MVT::i64))) { 14628 SDValue Load = N->getOperand(0); 14629 LoadSDNode *LD = cast<LoadSDNode>(Load); 14630 // Create the byte-swapping load. 14631 SDValue Ops[] = { 14632 LD->getChain(), // Chain 14633 LD->getBasePtr(), // Ptr 14634 DAG.getValueType(N->getValueType(0)) // VT 14635 }; 14636 SDValue BSLoad = 14637 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14638 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14639 MVT::i64 : MVT::i32, MVT::Other), 14640 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14641 14642 // If this is an i16 load, insert the truncate. 14643 SDValue ResVal = BSLoad; 14644 if (N->getValueType(0) == MVT::i16) 14645 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14646 14647 // First, combine the bswap away. This makes the value produced by the 14648 // load dead. 14649 DCI.CombineTo(N, ResVal); 14650 14651 // Next, combine the load away, we give it a bogus result value but a real 14652 // chain result. The result value is dead because the bswap is dead. 14653 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14654 14655 // Return N so it doesn't get rechecked! 14656 return SDValue(N, 0); 14657 } 14658 break; 14659 case PPCISD::VCMP: 14660 // If a VCMPo node already exists with exactly the same operands as this 14661 // node, use its result instead of this node (VCMPo computes both a CR6 and 14662 // a normal output). 14663 // 14664 if (!N->getOperand(0).hasOneUse() && 14665 !N->getOperand(1).hasOneUse() && 14666 !N->getOperand(2).hasOneUse()) { 14667 14668 // Scan all of the users of the LHS, looking for VCMPo's that match. 14669 SDNode *VCMPoNode = nullptr; 14670 14671 SDNode *LHSN = N->getOperand(0).getNode(); 14672 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14673 UI != E; ++UI) 14674 if (UI->getOpcode() == PPCISD::VCMPo && 14675 UI->getOperand(1) == N->getOperand(1) && 14676 UI->getOperand(2) == N->getOperand(2) && 14677 UI->getOperand(0) == N->getOperand(0)) { 14678 VCMPoNode = *UI; 14679 break; 14680 } 14681 14682 // If there is no VCMPo node, or if the flag value has a single use, don't 14683 // transform this. 14684 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14685 break; 14686 14687 // Look at the (necessarily single) use of the flag value. If it has a 14688 // chain, this transformation is more complex. Note that multiple things 14689 // could use the value result, which we should ignore. 14690 SDNode *FlagUser = nullptr; 14691 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14692 FlagUser == nullptr; ++UI) { 14693 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14694 SDNode *User = *UI; 14695 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14696 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14697 FlagUser = User; 14698 break; 14699 } 14700 } 14701 } 14702 14703 // If the user is a MFOCRF instruction, we know this is safe. 14704 // Otherwise we give up for right now. 14705 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14706 return SDValue(VCMPoNode, 0); 14707 } 14708 break; 14709 case ISD::BRCOND: { 14710 SDValue Cond = N->getOperand(1); 14711 SDValue Target = N->getOperand(2); 14712 14713 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14714 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14715 Intrinsic::loop_decrement) { 14716 14717 // We now need to make the intrinsic dead (it cannot be instruction 14718 // selected). 14719 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14720 assert(Cond.getNode()->hasOneUse() && 14721 "Counter decrement has more than one use"); 14722 14723 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14724 N->getOperand(0), Target); 14725 } 14726 } 14727 break; 14728 case ISD::BR_CC: { 14729 // If this is a branch on an altivec predicate comparison, lower this so 14730 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14731 // lowering is done pre-legalize, because the legalizer lowers the predicate 14732 // compare down to code that is difficult to reassemble. 14733 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14734 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14735 14736 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14737 // value. If so, pass-through the AND to get to the intrinsic. 14738 if (LHS.getOpcode() == ISD::AND && 14739 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14740 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14741 Intrinsic::loop_decrement && 14742 isa<ConstantSDNode>(LHS.getOperand(1)) && 14743 !isNullConstant(LHS.getOperand(1))) 14744 LHS = LHS.getOperand(0); 14745 14746 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14747 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14748 Intrinsic::loop_decrement && 14749 isa<ConstantSDNode>(RHS)) { 14750 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14751 "Counter decrement comparison is not EQ or NE"); 14752 14753 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14754 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14755 (CC == ISD::SETNE && !Val); 14756 14757 // We now need to make the intrinsic dead (it cannot be instruction 14758 // selected). 14759 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14760 assert(LHS.getNode()->hasOneUse() && 14761 "Counter decrement has more than one use"); 14762 14763 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14764 N->getOperand(0), N->getOperand(4)); 14765 } 14766 14767 int CompareOpc; 14768 bool isDot; 14769 14770 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14771 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14772 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14773 assert(isDot && "Can't compare against a vector result!"); 14774 14775 // If this is a comparison against something other than 0/1, then we know 14776 // that the condition is never/always true. 14777 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14778 if (Val != 0 && Val != 1) { 14779 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14780 return N->getOperand(0); 14781 // Always !=, turn it into an unconditional branch. 14782 return DAG.getNode(ISD::BR, dl, MVT::Other, 14783 N->getOperand(0), N->getOperand(4)); 14784 } 14785 14786 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14787 14788 // Create the PPCISD altivec 'dot' comparison node. 14789 SDValue Ops[] = { 14790 LHS.getOperand(2), // LHS of compare 14791 LHS.getOperand(3), // RHS of compare 14792 DAG.getConstant(CompareOpc, dl, MVT::i32) 14793 }; 14794 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14795 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14796 14797 // Unpack the result based on how the target uses it. 14798 PPC::Predicate CompOpc; 14799 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14800 default: // Can't happen, don't crash on invalid number though. 14801 case 0: // Branch on the value of the EQ bit of CR6. 14802 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14803 break; 14804 case 1: // Branch on the inverted value of the EQ bit of CR6. 14805 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14806 break; 14807 case 2: // Branch on the value of the LT bit of CR6. 14808 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14809 break; 14810 case 3: // Branch on the inverted value of the LT bit of CR6. 14811 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14812 break; 14813 } 14814 14815 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14816 DAG.getConstant(CompOpc, dl, MVT::i32), 14817 DAG.getRegister(PPC::CR6, MVT::i32), 14818 N->getOperand(4), CompNode.getValue(1)); 14819 } 14820 break; 14821 } 14822 case ISD::BUILD_VECTOR: 14823 return DAGCombineBuildVector(N, DCI); 14824 case ISD::ABS: 14825 return combineABS(N, DCI); 14826 case ISD::VSELECT: 14827 return combineVSelect(N, DCI); 14828 } 14829 14830 return SDValue(); 14831 } 14832 14833 SDValue 14834 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14835 SelectionDAG &DAG, 14836 SmallVectorImpl<SDNode *> &Created) const { 14837 // fold (sdiv X, pow2) 14838 EVT VT = N->getValueType(0); 14839 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14840 return SDValue(); 14841 if ((VT != MVT::i32 && VT != MVT::i64) || 14842 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14843 return SDValue(); 14844 14845 SDLoc DL(N); 14846 SDValue N0 = N->getOperand(0); 14847 14848 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14849 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14850 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14851 14852 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14853 Created.push_back(Op.getNode()); 14854 14855 if (IsNegPow2) { 14856 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14857 Created.push_back(Op.getNode()); 14858 } 14859 14860 return Op; 14861 } 14862 14863 //===----------------------------------------------------------------------===// 14864 // Inline Assembly Support 14865 //===----------------------------------------------------------------------===// 14866 14867 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14868 KnownBits &Known, 14869 const APInt &DemandedElts, 14870 const SelectionDAG &DAG, 14871 unsigned Depth) const { 14872 Known.resetAll(); 14873 switch (Op.getOpcode()) { 14874 default: break; 14875 case PPCISD::LBRX: { 14876 // lhbrx is known to have the top bits cleared out. 14877 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14878 Known.Zero = 0xFFFF0000; 14879 break; 14880 } 14881 case ISD::INTRINSIC_WO_CHAIN: { 14882 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14883 default: break; 14884 case Intrinsic::ppc_altivec_vcmpbfp_p: 14885 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14886 case Intrinsic::ppc_altivec_vcmpequb_p: 14887 case Intrinsic::ppc_altivec_vcmpequh_p: 14888 case Intrinsic::ppc_altivec_vcmpequw_p: 14889 case Intrinsic::ppc_altivec_vcmpequd_p: 14890 case Intrinsic::ppc_altivec_vcmpgefp_p: 14891 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14892 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14893 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14894 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14895 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14896 case Intrinsic::ppc_altivec_vcmpgtub_p: 14897 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14898 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14899 case Intrinsic::ppc_altivec_vcmpgtud_p: 14900 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14901 break; 14902 } 14903 } 14904 } 14905 } 14906 14907 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14908 switch (Subtarget.getCPUDirective()) { 14909 default: break; 14910 case PPC::DIR_970: 14911 case PPC::DIR_PWR4: 14912 case PPC::DIR_PWR5: 14913 case PPC::DIR_PWR5X: 14914 case PPC::DIR_PWR6: 14915 case PPC::DIR_PWR6X: 14916 case PPC::DIR_PWR7: 14917 case PPC::DIR_PWR8: 14918 case PPC::DIR_PWR9: 14919 case PPC::DIR_PWR10: 14920 case PPC::DIR_PWR_FUTURE: { 14921 if (!ML) 14922 break; 14923 14924 if (!DisableInnermostLoopAlign32) { 14925 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14926 // so that we can decrease cache misses and branch-prediction misses. 14927 // Actual alignment of the loop will depend on the hotness check and other 14928 // logic in alignBlocks. 14929 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14930 return Align(32); 14931 } 14932 14933 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14934 14935 // For small loops (between 5 and 8 instructions), align to a 32-byte 14936 // boundary so that the entire loop fits in one instruction-cache line. 14937 uint64_t LoopSize = 0; 14938 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14939 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14940 LoopSize += TII->getInstSizeInBytes(*J); 14941 if (LoopSize > 32) 14942 break; 14943 } 14944 14945 if (LoopSize > 16 && LoopSize <= 32) 14946 return Align(32); 14947 14948 break; 14949 } 14950 } 14951 14952 return TargetLowering::getPrefLoopAlignment(ML); 14953 } 14954 14955 /// getConstraintType - Given a constraint, return the type of 14956 /// constraint it is for this target. 14957 PPCTargetLowering::ConstraintType 14958 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14959 if (Constraint.size() == 1) { 14960 switch (Constraint[0]) { 14961 default: break; 14962 case 'b': 14963 case 'r': 14964 case 'f': 14965 case 'd': 14966 case 'v': 14967 case 'y': 14968 return C_RegisterClass; 14969 case 'Z': 14970 // FIXME: While Z does indicate a memory constraint, it specifically 14971 // indicates an r+r address (used in conjunction with the 'y' modifier 14972 // in the replacement string). Currently, we're forcing the base 14973 // register to be r0 in the asm printer (which is interpreted as zero) 14974 // and forming the complete address in the second register. This is 14975 // suboptimal. 14976 return C_Memory; 14977 } 14978 } else if (Constraint == "wc") { // individual CR bits. 14979 return C_RegisterClass; 14980 } else if (Constraint == "wa" || Constraint == "wd" || 14981 Constraint == "wf" || Constraint == "ws" || 14982 Constraint == "wi" || Constraint == "ww") { 14983 return C_RegisterClass; // VSX registers. 14984 } 14985 return TargetLowering::getConstraintType(Constraint); 14986 } 14987 14988 /// Examine constraint type and operand type and determine a weight value. 14989 /// This object must already have been set up with the operand type 14990 /// and the current alternative constraint selected. 14991 TargetLowering::ConstraintWeight 14992 PPCTargetLowering::getSingleConstraintMatchWeight( 14993 AsmOperandInfo &info, const char *constraint) const { 14994 ConstraintWeight weight = CW_Invalid; 14995 Value *CallOperandVal = info.CallOperandVal; 14996 // If we don't have a value, we can't do a match, 14997 // but allow it at the lowest weight. 14998 if (!CallOperandVal) 14999 return CW_Default; 15000 Type *type = CallOperandVal->getType(); 15001 15002 // Look at the constraint type. 15003 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15004 return CW_Register; // an individual CR bit. 15005 else if ((StringRef(constraint) == "wa" || 15006 StringRef(constraint) == "wd" || 15007 StringRef(constraint) == "wf") && 15008 type->isVectorTy()) 15009 return CW_Register; 15010 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15011 return CW_Register; // just hold 64-bit integers data. 15012 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15013 return CW_Register; 15014 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15015 return CW_Register; 15016 15017 switch (*constraint) { 15018 default: 15019 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15020 break; 15021 case 'b': 15022 if (type->isIntegerTy()) 15023 weight = CW_Register; 15024 break; 15025 case 'f': 15026 if (type->isFloatTy()) 15027 weight = CW_Register; 15028 break; 15029 case 'd': 15030 if (type->isDoubleTy()) 15031 weight = CW_Register; 15032 break; 15033 case 'v': 15034 if (type->isVectorTy()) 15035 weight = CW_Register; 15036 break; 15037 case 'y': 15038 weight = CW_Register; 15039 break; 15040 case 'Z': 15041 weight = CW_Memory; 15042 break; 15043 } 15044 return weight; 15045 } 15046 15047 std::pair<unsigned, const TargetRegisterClass *> 15048 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15049 StringRef Constraint, 15050 MVT VT) const { 15051 if (Constraint.size() == 1) { 15052 // GCC RS6000 Constraint Letters 15053 switch (Constraint[0]) { 15054 case 'b': // R1-R31 15055 if (VT == MVT::i64 && Subtarget.isPPC64()) 15056 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15057 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15058 case 'r': // R0-R31 15059 if (VT == MVT::i64 && Subtarget.isPPC64()) 15060 return std::make_pair(0U, &PPC::G8RCRegClass); 15061 return std::make_pair(0U, &PPC::GPRCRegClass); 15062 // 'd' and 'f' constraints are both defined to be "the floating point 15063 // registers", where one is for 32-bit and the other for 64-bit. We don't 15064 // really care overly much here so just give them all the same reg classes. 15065 case 'd': 15066 case 'f': 15067 if (Subtarget.hasSPE()) { 15068 if (VT == MVT::f32 || VT == MVT::i32) 15069 return std::make_pair(0U, &PPC::GPRCRegClass); 15070 if (VT == MVT::f64 || VT == MVT::i64) 15071 return std::make_pair(0U, &PPC::SPERCRegClass); 15072 } else { 15073 if (VT == MVT::f32 || VT == MVT::i32) 15074 return std::make_pair(0U, &PPC::F4RCRegClass); 15075 if (VT == MVT::f64 || VT == MVT::i64) 15076 return std::make_pair(0U, &PPC::F8RCRegClass); 15077 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15078 return std::make_pair(0U, &PPC::QFRCRegClass); 15079 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15080 return std::make_pair(0U, &PPC::QSRCRegClass); 15081 } 15082 break; 15083 case 'v': 15084 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15085 return std::make_pair(0U, &PPC::QFRCRegClass); 15086 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15087 return std::make_pair(0U, &PPC::QSRCRegClass); 15088 if (Subtarget.hasAltivec()) 15089 return std::make_pair(0U, &PPC::VRRCRegClass); 15090 break; 15091 case 'y': // crrc 15092 return std::make_pair(0U, &PPC::CRRCRegClass); 15093 } 15094 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15095 // An individual CR bit. 15096 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15097 } else if ((Constraint == "wa" || Constraint == "wd" || 15098 Constraint == "wf" || Constraint == "wi") && 15099 Subtarget.hasVSX()) { 15100 return std::make_pair(0U, &PPC::VSRCRegClass); 15101 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15102 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15103 return std::make_pair(0U, &PPC::VSSRCRegClass); 15104 else 15105 return std::make_pair(0U, &PPC::VSFRCRegClass); 15106 } 15107 15108 // If we name a VSX register, we can't defer to the base class because it 15109 // will not recognize the correct register (their names will be VSL{0-31} 15110 // and V{0-31} so they won't match). So we match them here. 15111 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15112 int VSNum = atoi(Constraint.data() + 3); 15113 assert(VSNum >= 0 && VSNum <= 63 && 15114 "Attempted to access a vsr out of range"); 15115 if (VSNum < 32) 15116 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15117 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15118 } 15119 std::pair<unsigned, const TargetRegisterClass *> R = 15120 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15121 15122 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15123 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15124 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15125 // register. 15126 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15127 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15128 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15129 PPC::GPRCRegClass.contains(R.first)) 15130 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15131 PPC::sub_32, &PPC::G8RCRegClass), 15132 &PPC::G8RCRegClass); 15133 15134 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15135 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15136 R.first = PPC::CR0; 15137 R.second = &PPC::CRRCRegClass; 15138 } 15139 15140 return R; 15141 } 15142 15143 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15144 /// vector. If it is invalid, don't add anything to Ops. 15145 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15146 std::string &Constraint, 15147 std::vector<SDValue>&Ops, 15148 SelectionDAG &DAG) const { 15149 SDValue Result; 15150 15151 // Only support length 1 constraints. 15152 if (Constraint.length() > 1) return; 15153 15154 char Letter = Constraint[0]; 15155 switch (Letter) { 15156 default: break; 15157 case 'I': 15158 case 'J': 15159 case 'K': 15160 case 'L': 15161 case 'M': 15162 case 'N': 15163 case 'O': 15164 case 'P': { 15165 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15166 if (!CST) return; // Must be an immediate to match. 15167 SDLoc dl(Op); 15168 int64_t Value = CST->getSExtValue(); 15169 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15170 // numbers are printed as such. 15171 switch (Letter) { 15172 default: llvm_unreachable("Unknown constraint letter!"); 15173 case 'I': // "I" is a signed 16-bit constant. 15174 if (isInt<16>(Value)) 15175 Result = DAG.getTargetConstant(Value, dl, TCVT); 15176 break; 15177 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15178 if (isShiftedUInt<16, 16>(Value)) 15179 Result = DAG.getTargetConstant(Value, dl, TCVT); 15180 break; 15181 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15182 if (isShiftedInt<16, 16>(Value)) 15183 Result = DAG.getTargetConstant(Value, dl, TCVT); 15184 break; 15185 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15186 if (isUInt<16>(Value)) 15187 Result = DAG.getTargetConstant(Value, dl, TCVT); 15188 break; 15189 case 'M': // "M" is a constant that is greater than 31. 15190 if (Value > 31) 15191 Result = DAG.getTargetConstant(Value, dl, TCVT); 15192 break; 15193 case 'N': // "N" is a positive constant that is an exact power of two. 15194 if (Value > 0 && isPowerOf2_64(Value)) 15195 Result = DAG.getTargetConstant(Value, dl, TCVT); 15196 break; 15197 case 'O': // "O" is the constant zero. 15198 if (Value == 0) 15199 Result = DAG.getTargetConstant(Value, dl, TCVT); 15200 break; 15201 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15202 if (isInt<16>(-Value)) 15203 Result = DAG.getTargetConstant(Value, dl, TCVT); 15204 break; 15205 } 15206 break; 15207 } 15208 } 15209 15210 if (Result.getNode()) { 15211 Ops.push_back(Result); 15212 return; 15213 } 15214 15215 // Handle standard constraint letters. 15216 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15217 } 15218 15219 // isLegalAddressingMode - Return true if the addressing mode represented 15220 // by AM is legal for this target, for a load/store of the specified type. 15221 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15222 const AddrMode &AM, Type *Ty, 15223 unsigned AS, Instruction *I) const { 15224 // PPC does not allow r+i addressing modes for vectors! 15225 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15226 return false; 15227 15228 // PPC allows a sign-extended 16-bit immediate field. 15229 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15230 return false; 15231 15232 // No global is ever allowed as a base. 15233 if (AM.BaseGV) 15234 return false; 15235 15236 // PPC only support r+r, 15237 switch (AM.Scale) { 15238 case 0: // "r+i" or just "i", depending on HasBaseReg. 15239 break; 15240 case 1: 15241 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15242 return false; 15243 // Otherwise we have r+r or r+i. 15244 break; 15245 case 2: 15246 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15247 return false; 15248 // Allow 2*r as r+r. 15249 break; 15250 default: 15251 // No other scales are supported. 15252 return false; 15253 } 15254 15255 return true; 15256 } 15257 15258 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15259 SelectionDAG &DAG) const { 15260 MachineFunction &MF = DAG.getMachineFunction(); 15261 MachineFrameInfo &MFI = MF.getFrameInfo(); 15262 MFI.setReturnAddressIsTaken(true); 15263 15264 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15265 return SDValue(); 15266 15267 SDLoc dl(Op); 15268 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15269 15270 // Make sure the function does not optimize away the store of the RA to 15271 // the stack. 15272 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15273 FuncInfo->setLRStoreRequired(); 15274 bool isPPC64 = Subtarget.isPPC64(); 15275 auto PtrVT = getPointerTy(MF.getDataLayout()); 15276 15277 if (Depth > 0) { 15278 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15279 SDValue Offset = 15280 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15281 isPPC64 ? MVT::i64 : MVT::i32); 15282 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15283 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15284 MachinePointerInfo()); 15285 } 15286 15287 // Just load the return address off the stack. 15288 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15289 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15290 MachinePointerInfo()); 15291 } 15292 15293 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15294 SelectionDAG &DAG) const { 15295 SDLoc dl(Op); 15296 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15297 15298 MachineFunction &MF = DAG.getMachineFunction(); 15299 MachineFrameInfo &MFI = MF.getFrameInfo(); 15300 MFI.setFrameAddressIsTaken(true); 15301 15302 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15303 bool isPPC64 = PtrVT == MVT::i64; 15304 15305 // Naked functions never have a frame pointer, and so we use r1. For all 15306 // other functions, this decision must be delayed until during PEI. 15307 unsigned FrameReg; 15308 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15309 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15310 else 15311 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15312 15313 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15314 PtrVT); 15315 while (Depth--) 15316 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15317 FrameAddr, MachinePointerInfo()); 15318 return FrameAddr; 15319 } 15320 15321 // FIXME? Maybe this could be a TableGen attribute on some registers and 15322 // this table could be generated automatically from RegInfo. 15323 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15324 const MachineFunction &MF) const { 15325 bool isPPC64 = Subtarget.isPPC64(); 15326 15327 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15328 if (!is64Bit && VT != LLT::scalar(32)) 15329 report_fatal_error("Invalid register global variable type"); 15330 15331 Register Reg = StringSwitch<Register>(RegName) 15332 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15333 .Case("r2", isPPC64 ? Register() : PPC::R2) 15334 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15335 .Default(Register()); 15336 15337 if (Reg) 15338 return Reg; 15339 report_fatal_error("Invalid register name global variable"); 15340 } 15341 15342 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15343 // 32-bit SVR4 ABI access everything as got-indirect. 15344 if (Subtarget.is32BitELFABI()) 15345 return true; 15346 15347 // AIX accesses everything indirectly through the TOC, which is similar to 15348 // the GOT. 15349 if (Subtarget.isAIXABI()) 15350 return true; 15351 15352 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15353 // If it is small or large code model, module locals are accessed 15354 // indirectly by loading their address from .toc/.got. 15355 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15356 return true; 15357 15358 // JumpTable and BlockAddress are accessed as got-indirect. 15359 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15360 return true; 15361 15362 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15363 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15364 15365 return false; 15366 } 15367 15368 bool 15369 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15370 // The PowerPC target isn't yet aware of offsets. 15371 return false; 15372 } 15373 15374 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15375 const CallInst &I, 15376 MachineFunction &MF, 15377 unsigned Intrinsic) const { 15378 switch (Intrinsic) { 15379 case Intrinsic::ppc_qpx_qvlfd: 15380 case Intrinsic::ppc_qpx_qvlfs: 15381 case Intrinsic::ppc_qpx_qvlfcd: 15382 case Intrinsic::ppc_qpx_qvlfcs: 15383 case Intrinsic::ppc_qpx_qvlfiwa: 15384 case Intrinsic::ppc_qpx_qvlfiwz: 15385 case Intrinsic::ppc_altivec_lvx: 15386 case Intrinsic::ppc_altivec_lvxl: 15387 case Intrinsic::ppc_altivec_lvebx: 15388 case Intrinsic::ppc_altivec_lvehx: 15389 case Intrinsic::ppc_altivec_lvewx: 15390 case Intrinsic::ppc_vsx_lxvd2x: 15391 case Intrinsic::ppc_vsx_lxvw4x: { 15392 EVT VT; 15393 switch (Intrinsic) { 15394 case Intrinsic::ppc_altivec_lvebx: 15395 VT = MVT::i8; 15396 break; 15397 case Intrinsic::ppc_altivec_lvehx: 15398 VT = MVT::i16; 15399 break; 15400 case Intrinsic::ppc_altivec_lvewx: 15401 VT = MVT::i32; 15402 break; 15403 case Intrinsic::ppc_vsx_lxvd2x: 15404 VT = MVT::v2f64; 15405 break; 15406 case Intrinsic::ppc_qpx_qvlfd: 15407 VT = MVT::v4f64; 15408 break; 15409 case Intrinsic::ppc_qpx_qvlfs: 15410 VT = MVT::v4f32; 15411 break; 15412 case Intrinsic::ppc_qpx_qvlfcd: 15413 VT = MVT::v2f64; 15414 break; 15415 case Intrinsic::ppc_qpx_qvlfcs: 15416 VT = MVT::v2f32; 15417 break; 15418 default: 15419 VT = MVT::v4i32; 15420 break; 15421 } 15422 15423 Info.opc = ISD::INTRINSIC_W_CHAIN; 15424 Info.memVT = VT; 15425 Info.ptrVal = I.getArgOperand(0); 15426 Info.offset = -VT.getStoreSize()+1; 15427 Info.size = 2*VT.getStoreSize()-1; 15428 Info.align = Align(1); 15429 Info.flags = MachineMemOperand::MOLoad; 15430 return true; 15431 } 15432 case Intrinsic::ppc_qpx_qvlfda: 15433 case Intrinsic::ppc_qpx_qvlfsa: 15434 case Intrinsic::ppc_qpx_qvlfcda: 15435 case Intrinsic::ppc_qpx_qvlfcsa: 15436 case Intrinsic::ppc_qpx_qvlfiwaa: 15437 case Intrinsic::ppc_qpx_qvlfiwza: { 15438 EVT VT; 15439 switch (Intrinsic) { 15440 case Intrinsic::ppc_qpx_qvlfda: 15441 VT = MVT::v4f64; 15442 break; 15443 case Intrinsic::ppc_qpx_qvlfsa: 15444 VT = MVT::v4f32; 15445 break; 15446 case Intrinsic::ppc_qpx_qvlfcda: 15447 VT = MVT::v2f64; 15448 break; 15449 case Intrinsic::ppc_qpx_qvlfcsa: 15450 VT = MVT::v2f32; 15451 break; 15452 default: 15453 VT = MVT::v4i32; 15454 break; 15455 } 15456 15457 Info.opc = ISD::INTRINSIC_W_CHAIN; 15458 Info.memVT = VT; 15459 Info.ptrVal = I.getArgOperand(0); 15460 Info.offset = 0; 15461 Info.size = VT.getStoreSize(); 15462 Info.align = Align(1); 15463 Info.flags = MachineMemOperand::MOLoad; 15464 return true; 15465 } 15466 case Intrinsic::ppc_qpx_qvstfd: 15467 case Intrinsic::ppc_qpx_qvstfs: 15468 case Intrinsic::ppc_qpx_qvstfcd: 15469 case Intrinsic::ppc_qpx_qvstfcs: 15470 case Intrinsic::ppc_qpx_qvstfiw: 15471 case Intrinsic::ppc_altivec_stvx: 15472 case Intrinsic::ppc_altivec_stvxl: 15473 case Intrinsic::ppc_altivec_stvebx: 15474 case Intrinsic::ppc_altivec_stvehx: 15475 case Intrinsic::ppc_altivec_stvewx: 15476 case Intrinsic::ppc_vsx_stxvd2x: 15477 case Intrinsic::ppc_vsx_stxvw4x: { 15478 EVT VT; 15479 switch (Intrinsic) { 15480 case Intrinsic::ppc_altivec_stvebx: 15481 VT = MVT::i8; 15482 break; 15483 case Intrinsic::ppc_altivec_stvehx: 15484 VT = MVT::i16; 15485 break; 15486 case Intrinsic::ppc_altivec_stvewx: 15487 VT = MVT::i32; 15488 break; 15489 case Intrinsic::ppc_vsx_stxvd2x: 15490 VT = MVT::v2f64; 15491 break; 15492 case Intrinsic::ppc_qpx_qvstfd: 15493 VT = MVT::v4f64; 15494 break; 15495 case Intrinsic::ppc_qpx_qvstfs: 15496 VT = MVT::v4f32; 15497 break; 15498 case Intrinsic::ppc_qpx_qvstfcd: 15499 VT = MVT::v2f64; 15500 break; 15501 case Intrinsic::ppc_qpx_qvstfcs: 15502 VT = MVT::v2f32; 15503 break; 15504 default: 15505 VT = MVT::v4i32; 15506 break; 15507 } 15508 15509 Info.opc = ISD::INTRINSIC_VOID; 15510 Info.memVT = VT; 15511 Info.ptrVal = I.getArgOperand(1); 15512 Info.offset = -VT.getStoreSize()+1; 15513 Info.size = 2*VT.getStoreSize()-1; 15514 Info.align = Align(1); 15515 Info.flags = MachineMemOperand::MOStore; 15516 return true; 15517 } 15518 case Intrinsic::ppc_qpx_qvstfda: 15519 case Intrinsic::ppc_qpx_qvstfsa: 15520 case Intrinsic::ppc_qpx_qvstfcda: 15521 case Intrinsic::ppc_qpx_qvstfcsa: 15522 case Intrinsic::ppc_qpx_qvstfiwa: { 15523 EVT VT; 15524 switch (Intrinsic) { 15525 case Intrinsic::ppc_qpx_qvstfda: 15526 VT = MVT::v4f64; 15527 break; 15528 case Intrinsic::ppc_qpx_qvstfsa: 15529 VT = MVT::v4f32; 15530 break; 15531 case Intrinsic::ppc_qpx_qvstfcda: 15532 VT = MVT::v2f64; 15533 break; 15534 case Intrinsic::ppc_qpx_qvstfcsa: 15535 VT = MVT::v2f32; 15536 break; 15537 default: 15538 VT = MVT::v4i32; 15539 break; 15540 } 15541 15542 Info.opc = ISD::INTRINSIC_VOID; 15543 Info.memVT = VT; 15544 Info.ptrVal = I.getArgOperand(1); 15545 Info.offset = 0; 15546 Info.size = VT.getStoreSize(); 15547 Info.align = Align(1); 15548 Info.flags = MachineMemOperand::MOStore; 15549 return true; 15550 } 15551 default: 15552 break; 15553 } 15554 15555 return false; 15556 } 15557 15558 /// It returns EVT::Other if the type should be determined using generic 15559 /// target-independent logic. 15560 EVT PPCTargetLowering::getOptimalMemOpType( 15561 const MemOp &Op, const AttributeList &FuncAttributes) const { 15562 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15563 // When expanding a memset, require at least two QPX instructions to cover 15564 // the cost of loading the value to be stored from the constant pool. 15565 if (Subtarget.hasQPX() && Op.size() >= 32 && 15566 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15567 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15568 return MVT::v4f64; 15569 } 15570 15571 // We should use Altivec/VSX loads and stores when available. For unaligned 15572 // addresses, unaligned VSX loads are only fast starting with the P8. 15573 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15574 (Op.isAligned(Align(16)) || 15575 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15576 return MVT::v4i32; 15577 } 15578 15579 if (Subtarget.isPPC64()) { 15580 return MVT::i64; 15581 } 15582 15583 return MVT::i32; 15584 } 15585 15586 /// Returns true if it is beneficial to convert a load of a constant 15587 /// to just the constant itself. 15588 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15589 Type *Ty) const { 15590 assert(Ty->isIntegerTy()); 15591 15592 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15593 return !(BitSize == 0 || BitSize > 64); 15594 } 15595 15596 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15597 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15598 return false; 15599 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15600 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15601 return NumBits1 == 64 && NumBits2 == 32; 15602 } 15603 15604 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15605 if (!VT1.isInteger() || !VT2.isInteger()) 15606 return false; 15607 unsigned NumBits1 = VT1.getSizeInBits(); 15608 unsigned NumBits2 = VT2.getSizeInBits(); 15609 return NumBits1 == 64 && NumBits2 == 32; 15610 } 15611 15612 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15613 // Generally speaking, zexts are not free, but they are free when they can be 15614 // folded with other operations. 15615 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15616 EVT MemVT = LD->getMemoryVT(); 15617 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15618 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15619 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15620 LD->getExtensionType() == ISD::ZEXTLOAD)) 15621 return true; 15622 } 15623 15624 // FIXME: Add other cases... 15625 // - 32-bit shifts with a zext to i64 15626 // - zext after ctlz, bswap, etc. 15627 // - zext after and by a constant mask 15628 15629 return TargetLowering::isZExtFree(Val, VT2); 15630 } 15631 15632 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15633 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15634 "invalid fpext types"); 15635 // Extending to float128 is not free. 15636 if (DestVT == MVT::f128) 15637 return false; 15638 return true; 15639 } 15640 15641 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15642 return isInt<16>(Imm) || isUInt<16>(Imm); 15643 } 15644 15645 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15646 return isInt<16>(Imm) || isUInt<16>(Imm); 15647 } 15648 15649 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15650 unsigned, 15651 unsigned, 15652 MachineMemOperand::Flags, 15653 bool *Fast) const { 15654 if (DisablePPCUnaligned) 15655 return false; 15656 15657 // PowerPC supports unaligned memory access for simple non-vector types. 15658 // Although accessing unaligned addresses is not as efficient as accessing 15659 // aligned addresses, it is generally more efficient than manual expansion, 15660 // and generally only traps for software emulation when crossing page 15661 // boundaries. 15662 15663 if (!VT.isSimple()) 15664 return false; 15665 15666 if (VT.isFloatingPoint() && !VT.isVector() && 15667 !Subtarget.allowsUnalignedFPAccess()) 15668 return false; 15669 15670 if (VT.getSimpleVT().isVector()) { 15671 if (Subtarget.hasVSX()) { 15672 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15673 VT != MVT::v4f32 && VT != MVT::v4i32) 15674 return false; 15675 } else { 15676 return false; 15677 } 15678 } 15679 15680 if (VT == MVT::ppcf128) 15681 return false; 15682 15683 if (Fast) 15684 *Fast = true; 15685 15686 return true; 15687 } 15688 15689 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15690 EVT VT) const { 15691 return isFMAFasterThanFMulAndFAdd( 15692 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15693 } 15694 15695 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15696 Type *Ty) const { 15697 switch (Ty->getScalarType()->getTypeID()) { 15698 case Type::FloatTyID: 15699 case Type::DoubleTyID: 15700 return true; 15701 case Type::FP128TyID: 15702 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15703 default: 15704 return false; 15705 } 15706 } 15707 15708 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15709 // FIXME: add more patterns which are profitable to hoist. 15710 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15711 if (I->getOpcode() != Instruction::FMul) 15712 return true; 15713 15714 if (!I->hasOneUse()) 15715 return true; 15716 15717 Instruction *User = I->user_back(); 15718 assert(User && "A single use instruction with no uses."); 15719 15720 if (User->getOpcode() != Instruction::FSub && 15721 User->getOpcode() != Instruction::FAdd) 15722 return true; 15723 15724 const TargetOptions &Options = getTargetMachine().Options; 15725 const Function *F = I->getFunction(); 15726 const DataLayout &DL = F->getParent()->getDataLayout(); 15727 Type *Ty = User->getOperand(0)->getType(); 15728 15729 return !( 15730 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15731 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15732 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15733 } 15734 15735 const MCPhysReg * 15736 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15737 // LR is a callee-save register, but we must treat it as clobbered by any call 15738 // site. Hence we include LR in the scratch registers, which are in turn added 15739 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15740 // to CTR, which is used by any indirect call. 15741 static const MCPhysReg ScratchRegs[] = { 15742 PPC::X12, PPC::LR8, PPC::CTR8, 0 15743 }; 15744 15745 return ScratchRegs; 15746 } 15747 15748 Register PPCTargetLowering::getExceptionPointerRegister( 15749 const Constant *PersonalityFn) const { 15750 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15751 } 15752 15753 Register PPCTargetLowering::getExceptionSelectorRegister( 15754 const Constant *PersonalityFn) const { 15755 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15756 } 15757 15758 bool 15759 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15760 EVT VT , unsigned DefinedValues) const { 15761 if (VT == MVT::v2i64) 15762 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15763 15764 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15765 return true; 15766 15767 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15768 } 15769 15770 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15771 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15772 return TargetLowering::getSchedulingPreference(N); 15773 15774 return Sched::ILP; 15775 } 15776 15777 // Create a fast isel object. 15778 FastISel * 15779 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15780 const TargetLibraryInfo *LibInfo) const { 15781 return PPC::createFastISel(FuncInfo, LibInfo); 15782 } 15783 15784 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15785 bool PPCTargetLowering::useLoadStackGuardNode() const { 15786 if (!Subtarget.isTargetLinux()) 15787 return TargetLowering::useLoadStackGuardNode(); 15788 return true; 15789 } 15790 15791 // Override to disable global variable loading on Linux. 15792 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15793 if (!Subtarget.isTargetLinux()) 15794 return TargetLowering::insertSSPDeclarations(M); 15795 } 15796 15797 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15798 bool ForCodeSize) const { 15799 if (!VT.isSimple() || !Subtarget.hasVSX()) 15800 return false; 15801 15802 switch(VT.getSimpleVT().SimpleTy) { 15803 default: 15804 // For FP types that are currently not supported by PPC backend, return 15805 // false. Examples: f16, f80. 15806 return false; 15807 case MVT::f32: 15808 case MVT::f64: 15809 case MVT::ppcf128: 15810 return Imm.isPosZero(); 15811 } 15812 } 15813 15814 // For vector shift operation op, fold 15815 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15816 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15817 SelectionDAG &DAG) { 15818 SDValue N0 = N->getOperand(0); 15819 SDValue N1 = N->getOperand(1); 15820 EVT VT = N0.getValueType(); 15821 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15822 unsigned Opcode = N->getOpcode(); 15823 unsigned TargetOpcode; 15824 15825 switch (Opcode) { 15826 default: 15827 llvm_unreachable("Unexpected shift operation"); 15828 case ISD::SHL: 15829 TargetOpcode = PPCISD::SHL; 15830 break; 15831 case ISD::SRL: 15832 TargetOpcode = PPCISD::SRL; 15833 break; 15834 case ISD::SRA: 15835 TargetOpcode = PPCISD::SRA; 15836 break; 15837 } 15838 15839 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15840 N1->getOpcode() == ISD::AND) 15841 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15842 if (Mask->getZExtValue() == OpSizeInBits - 1) 15843 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15844 15845 return SDValue(); 15846 } 15847 15848 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15849 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15850 return Value; 15851 15852 SDValue N0 = N->getOperand(0); 15853 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15854 if (!Subtarget.isISA3_0() || 15855 N0.getOpcode() != ISD::SIGN_EXTEND || 15856 N0.getOperand(0).getValueType() != MVT::i32 || 15857 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15858 return SDValue(); 15859 15860 // We can't save an operation here if the value is already extended, and 15861 // the existing shift is easier to combine. 15862 SDValue ExtsSrc = N0.getOperand(0); 15863 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15864 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15865 return SDValue(); 15866 15867 SDLoc DL(N0); 15868 SDValue ShiftBy = SDValue(CN1, 0); 15869 // We want the shift amount to be i32 on the extswli, but the shift could 15870 // have an i64. 15871 if (ShiftBy.getValueType() == MVT::i64) 15872 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15873 15874 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15875 ShiftBy); 15876 } 15877 15878 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15879 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15880 return Value; 15881 15882 return SDValue(); 15883 } 15884 15885 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15886 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15887 return Value; 15888 15889 return SDValue(); 15890 } 15891 15892 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15893 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15894 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15895 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15896 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15897 const PPCSubtarget &Subtarget) { 15898 if (!Subtarget.isPPC64()) 15899 return SDValue(); 15900 15901 SDValue LHS = N->getOperand(0); 15902 SDValue RHS = N->getOperand(1); 15903 15904 auto isZextOfCompareWithConstant = [](SDValue Op) { 15905 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15906 Op.getValueType() != MVT::i64) 15907 return false; 15908 15909 SDValue Cmp = Op.getOperand(0); 15910 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15911 Cmp.getOperand(0).getValueType() != MVT::i64) 15912 return false; 15913 15914 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15915 int64_t NegConstant = 0 - Constant->getSExtValue(); 15916 // Due to the limitations of the addi instruction, 15917 // -C is required to be [-32768, 32767]. 15918 return isInt<16>(NegConstant); 15919 } 15920 15921 return false; 15922 }; 15923 15924 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15925 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15926 15927 // If there is a pattern, canonicalize a zext operand to the RHS. 15928 if (LHSHasPattern && !RHSHasPattern) 15929 std::swap(LHS, RHS); 15930 else if (!LHSHasPattern && !RHSHasPattern) 15931 return SDValue(); 15932 15933 SDLoc DL(N); 15934 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15935 SDValue Cmp = RHS.getOperand(0); 15936 SDValue Z = Cmp.getOperand(0); 15937 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15938 15939 assert(Constant && "Constant Should not be a null pointer."); 15940 int64_t NegConstant = 0 - Constant->getSExtValue(); 15941 15942 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15943 default: break; 15944 case ISD::SETNE: { 15945 // when C == 0 15946 // --> addze X, (addic Z, -1).carry 15947 // / 15948 // add X, (zext(setne Z, C))-- 15949 // \ when -32768 <= -C <= 32767 && C != 0 15950 // --> addze X, (addic (addi Z, -C), -1).carry 15951 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15952 DAG.getConstant(NegConstant, DL, MVT::i64)); 15953 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15954 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15955 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15956 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15957 SDValue(Addc.getNode(), 1)); 15958 } 15959 case ISD::SETEQ: { 15960 // when C == 0 15961 // --> addze X, (subfic Z, 0).carry 15962 // / 15963 // add X, (zext(sete Z, C))-- 15964 // \ when -32768 <= -C <= 32767 && C != 0 15965 // --> addze X, (subfic (addi Z, -C), 0).carry 15966 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15967 DAG.getConstant(NegConstant, DL, MVT::i64)); 15968 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15969 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15970 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15971 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15972 SDValue(Subc.getNode(), 1)); 15973 } 15974 } 15975 15976 return SDValue(); 15977 } 15978 15979 // Transform 15980 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 15981 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 15982 // In this case both C1 and C2 must be known constants. 15983 // C1+C2 must fit into a 34 bit signed integer. 15984 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 15985 const PPCSubtarget &Subtarget) { 15986 if (!Subtarget.isUsingPCRelativeCalls()) 15987 return SDValue(); 15988 15989 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 15990 // If we find that node try to cast the Global Address and the Constant. 15991 SDValue LHS = N->getOperand(0); 15992 SDValue RHS = N->getOperand(1); 15993 15994 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15995 std::swap(LHS, RHS); 15996 15997 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15998 return SDValue(); 15999 16000 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16001 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16002 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16003 16004 // Check that both casts succeeded. 16005 if (!GSDN || !ConstNode) 16006 return SDValue(); 16007 16008 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16009 SDLoc DL(GSDN); 16010 16011 // The signed int offset needs to fit in 34 bits. 16012 if (!isInt<34>(NewOffset)) 16013 return SDValue(); 16014 16015 // The new global address is a copy of the old global address except 16016 // that it has the updated Offset. 16017 SDValue GA = 16018 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16019 NewOffset, GSDN->getTargetFlags()); 16020 SDValue MatPCRel = 16021 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16022 return MatPCRel; 16023 } 16024 16025 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16026 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16027 return Value; 16028 16029 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16030 return Value; 16031 16032 return SDValue(); 16033 } 16034 16035 // Detect TRUNCATE operations on bitcasts of float128 values. 16036 // What we are looking for here is the situtation where we extract a subset 16037 // of bits from a 128 bit float. 16038 // This can be of two forms: 16039 // 1) BITCAST of f128 feeding TRUNCATE 16040 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16041 // The reason this is required is because we do not have a legal i128 type 16042 // and so we want to prevent having to store the f128 and then reload part 16043 // of it. 16044 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16045 DAGCombinerInfo &DCI) const { 16046 // If we are using CRBits then try that first. 16047 if (Subtarget.useCRBits()) { 16048 // Check if CRBits did anything and return that if it did. 16049 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16050 return CRTruncValue; 16051 } 16052 16053 SDLoc dl(N); 16054 SDValue Op0 = N->getOperand(0); 16055 16056 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16057 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16058 EVT VT = N->getValueType(0); 16059 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16060 return SDValue(); 16061 SDValue Sub = Op0.getOperand(0); 16062 if (Sub.getOpcode() == ISD::SUB) { 16063 SDValue SubOp0 = Sub.getOperand(0); 16064 SDValue SubOp1 = Sub.getOperand(1); 16065 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16066 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16067 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16068 SubOp1.getOperand(0), 16069 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16070 } 16071 } 16072 } 16073 16074 // Looking for a truncate of i128 to i64. 16075 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16076 return SDValue(); 16077 16078 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16079 16080 // SRL feeding TRUNCATE. 16081 if (Op0.getOpcode() == ISD::SRL) { 16082 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16083 // The right shift has to be by 64 bits. 16084 if (!ConstNode || ConstNode->getZExtValue() != 64) 16085 return SDValue(); 16086 16087 // Switch the element number to extract. 16088 EltToExtract = EltToExtract ? 0 : 1; 16089 // Update Op0 past the SRL. 16090 Op0 = Op0.getOperand(0); 16091 } 16092 16093 // BITCAST feeding a TRUNCATE possibly via SRL. 16094 if (Op0.getOpcode() == ISD::BITCAST && 16095 Op0.getValueType() == MVT::i128 && 16096 Op0.getOperand(0).getValueType() == MVT::f128) { 16097 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16098 return DCI.DAG.getNode( 16099 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16100 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16101 } 16102 return SDValue(); 16103 } 16104 16105 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16106 SelectionDAG &DAG = DCI.DAG; 16107 16108 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16109 if (!ConstOpOrElement) 16110 return SDValue(); 16111 16112 // An imul is usually smaller than the alternative sequence for legal type. 16113 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16114 isOperationLegal(ISD::MUL, N->getValueType(0))) 16115 return SDValue(); 16116 16117 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16118 switch (this->Subtarget.getCPUDirective()) { 16119 default: 16120 // TODO: enhance the condition for subtarget before pwr8 16121 return false; 16122 case PPC::DIR_PWR8: 16123 // type mul add shl 16124 // scalar 4 1 1 16125 // vector 7 2 2 16126 return true; 16127 case PPC::DIR_PWR9: 16128 case PPC::DIR_PWR10: 16129 case PPC::DIR_PWR_FUTURE: 16130 // type mul add shl 16131 // scalar 5 2 2 16132 // vector 7 2 2 16133 16134 // The cycle RATIO of related operations are showed as a table above. 16135 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16136 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16137 // are 4, it is always profitable; but for 3 instrs patterns 16138 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16139 // So we should only do it for vector type. 16140 return IsAddOne && IsNeg ? VT.isVector() : true; 16141 } 16142 }; 16143 16144 EVT VT = N->getValueType(0); 16145 SDLoc DL(N); 16146 16147 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16148 bool IsNeg = MulAmt.isNegative(); 16149 APInt MulAmtAbs = MulAmt.abs(); 16150 16151 if ((MulAmtAbs - 1).isPowerOf2()) { 16152 // (mul x, 2^N + 1) => (add (shl x, N), x) 16153 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16154 16155 if (!IsProfitable(IsNeg, true, VT)) 16156 return SDValue(); 16157 16158 SDValue Op0 = N->getOperand(0); 16159 SDValue Op1 = 16160 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16161 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16162 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16163 16164 if (!IsNeg) 16165 return Res; 16166 16167 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16168 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16169 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16170 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16171 16172 if (!IsProfitable(IsNeg, false, VT)) 16173 return SDValue(); 16174 16175 SDValue Op0 = N->getOperand(0); 16176 SDValue Op1 = 16177 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16178 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16179 16180 if (!IsNeg) 16181 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16182 else 16183 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16184 16185 } else { 16186 return SDValue(); 16187 } 16188 } 16189 16190 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16191 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16192 if (!Subtarget.is64BitELFABI()) 16193 return false; 16194 16195 // If not a tail call then no need to proceed. 16196 if (!CI->isTailCall()) 16197 return false; 16198 16199 // If sibling calls have been disabled and tail-calls aren't guaranteed 16200 // there is no reason to duplicate. 16201 auto &TM = getTargetMachine(); 16202 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16203 return false; 16204 16205 // Can't tail call a function called indirectly, or if it has variadic args. 16206 const Function *Callee = CI->getCalledFunction(); 16207 if (!Callee || Callee->isVarArg()) 16208 return false; 16209 16210 // Make sure the callee and caller calling conventions are eligible for tco. 16211 const Function *Caller = CI->getParent()->getParent(); 16212 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16213 CI->getCallingConv())) 16214 return false; 16215 16216 // If the function is local then we have a good chance at tail-calling it 16217 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16218 } 16219 16220 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16221 if (!Subtarget.hasVSX()) 16222 return false; 16223 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16224 return true; 16225 return VT == MVT::f32 || VT == MVT::f64 || 16226 VT == MVT::v4f32 || VT == MVT::v2f64; 16227 } 16228 16229 bool PPCTargetLowering:: 16230 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16231 const Value *Mask = AndI.getOperand(1); 16232 // If the mask is suitable for andi. or andis. we should sink the and. 16233 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16234 // Can't handle constants wider than 64-bits. 16235 if (CI->getBitWidth() > 64) 16236 return false; 16237 int64_t ConstVal = CI->getZExtValue(); 16238 return isUInt<16>(ConstVal) || 16239 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16240 } 16241 16242 // For non-constant masks, we can always use the record-form and. 16243 return true; 16244 } 16245 16246 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16247 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16248 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16249 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16250 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16251 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16252 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16253 assert(Subtarget.hasP9Altivec() && 16254 "Only combine this when P9 altivec supported!"); 16255 EVT VT = N->getValueType(0); 16256 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16257 return SDValue(); 16258 16259 SelectionDAG &DAG = DCI.DAG; 16260 SDLoc dl(N); 16261 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16262 // Even for signed integers, if it's known to be positive (as signed 16263 // integer) due to zero-extended inputs. 16264 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16265 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16266 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16267 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16268 (SubOpcd1 == ISD::ZERO_EXTEND || 16269 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16270 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16271 N->getOperand(0)->getOperand(0), 16272 N->getOperand(0)->getOperand(1), 16273 DAG.getTargetConstant(0, dl, MVT::i32)); 16274 } 16275 16276 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16277 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16278 N->getOperand(0).hasOneUse()) { 16279 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16280 N->getOperand(0)->getOperand(0), 16281 N->getOperand(0)->getOperand(1), 16282 DAG.getTargetConstant(1, dl, MVT::i32)); 16283 } 16284 } 16285 16286 return SDValue(); 16287 } 16288 16289 // For type v4i32/v8ii16/v16i8, transform 16290 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16291 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16292 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16293 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16294 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16295 DAGCombinerInfo &DCI) const { 16296 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16297 assert(Subtarget.hasP9Altivec() && 16298 "Only combine this when P9 altivec supported!"); 16299 16300 SelectionDAG &DAG = DCI.DAG; 16301 SDLoc dl(N); 16302 SDValue Cond = N->getOperand(0); 16303 SDValue TrueOpnd = N->getOperand(1); 16304 SDValue FalseOpnd = N->getOperand(2); 16305 EVT VT = N->getOperand(1).getValueType(); 16306 16307 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16308 FalseOpnd.getOpcode() != ISD::SUB) 16309 return SDValue(); 16310 16311 // ABSD only available for type v4i32/v8i16/v16i8 16312 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16313 return SDValue(); 16314 16315 // At least to save one more dependent computation 16316 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16317 return SDValue(); 16318 16319 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16320 16321 // Can only handle unsigned comparison here 16322 switch (CC) { 16323 default: 16324 return SDValue(); 16325 case ISD::SETUGT: 16326 case ISD::SETUGE: 16327 break; 16328 case ISD::SETULT: 16329 case ISD::SETULE: 16330 std::swap(TrueOpnd, FalseOpnd); 16331 break; 16332 } 16333 16334 SDValue CmpOpnd1 = Cond.getOperand(0); 16335 SDValue CmpOpnd2 = Cond.getOperand(1); 16336 16337 // SETCC CmpOpnd1 CmpOpnd2 cond 16338 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16339 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16340 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16341 TrueOpnd.getOperand(1) == CmpOpnd2 && 16342 FalseOpnd.getOperand(0) == CmpOpnd2 && 16343 FalseOpnd.getOperand(1) == CmpOpnd1) { 16344 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16345 CmpOpnd1, CmpOpnd2, 16346 DAG.getTargetConstant(0, dl, MVT::i32)); 16347 } 16348 16349 return SDValue(); 16350 } 16351