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 295 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 296 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 297 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 299 300 // We don't support sin/cos/sqrt/fmod/pow 301 setOperationAction(ISD::FSIN , MVT::f64, Expand); 302 setOperationAction(ISD::FCOS , MVT::f64, Expand); 303 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 304 setOperationAction(ISD::FREM , MVT::f64, Expand); 305 setOperationAction(ISD::FPOW , MVT::f64, Expand); 306 setOperationAction(ISD::FSIN , MVT::f32, Expand); 307 setOperationAction(ISD::FCOS , MVT::f32, Expand); 308 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 309 setOperationAction(ISD::FREM , MVT::f32, Expand); 310 setOperationAction(ISD::FPOW , MVT::f32, Expand); 311 if (Subtarget.hasSPE()) { 312 setOperationAction(ISD::FMA , MVT::f64, Expand); 313 setOperationAction(ISD::FMA , MVT::f32, Expand); 314 } else { 315 setOperationAction(ISD::FMA , MVT::f64, Legal); 316 setOperationAction(ISD::FMA , MVT::f32, Legal); 317 } 318 319 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 320 321 // If we're enabling GP optimizations, use hardware square root 322 if (!Subtarget.hasFSQRT() && 323 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 324 Subtarget.hasFRE())) 325 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 326 327 if (!Subtarget.hasFSQRT() && 328 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 329 Subtarget.hasFRES())) 330 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 331 332 if (Subtarget.hasFCPSGN()) { 333 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 334 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 335 } else { 336 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 337 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 338 } 339 340 if (Subtarget.hasFPRND()) { 341 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 342 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 343 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 344 setOperationAction(ISD::FROUND, MVT::f64, Legal); 345 346 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 347 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 348 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 349 setOperationAction(ISD::FROUND, MVT::f32, Legal); 350 } 351 352 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 353 // to speed up scalar BSWAP64. 354 // CTPOP or CTTZ were introduced in P8/P9 respectively 355 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 356 if (Subtarget.hasP9Vector()) 357 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 358 else 359 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 360 if (Subtarget.isISA3_0()) { 361 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 362 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 363 } else { 364 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 365 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 366 } 367 368 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 369 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 370 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 371 } else { 372 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 373 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 374 } 375 376 // PowerPC does not have ROTR 377 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 378 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 379 380 if (!Subtarget.useCRBits()) { 381 // PowerPC does not have Select 382 setOperationAction(ISD::SELECT, MVT::i32, Expand); 383 setOperationAction(ISD::SELECT, MVT::i64, Expand); 384 setOperationAction(ISD::SELECT, MVT::f32, Expand); 385 setOperationAction(ISD::SELECT, MVT::f64, Expand); 386 } 387 388 // PowerPC wants to turn select_cc of FP into fsel when possible. 389 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 390 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 391 392 // PowerPC wants to optimize integer setcc a bit 393 if (!Subtarget.useCRBits()) 394 setOperationAction(ISD::SETCC, MVT::i32, Custom); 395 396 // PowerPC does not have BRCOND which requires SetCC 397 if (!Subtarget.useCRBits()) 398 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 399 400 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 401 402 if (Subtarget.hasSPE()) { 403 // SPE has built-in conversions 404 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 405 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 406 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 407 } else { 408 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 409 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 410 411 // PowerPC does not have [U|S]INT_TO_FP 412 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 413 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 414 } 415 416 if (Subtarget.hasDirectMove() && isPPC64) { 417 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 418 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 419 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 420 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 421 if (TM.Options.UnsafeFPMath) { 422 setOperationAction(ISD::LRINT, MVT::f64, Legal); 423 setOperationAction(ISD::LRINT, MVT::f32, Legal); 424 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 425 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 426 setOperationAction(ISD::LROUND, MVT::f64, Legal); 427 setOperationAction(ISD::LROUND, MVT::f32, Legal); 428 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 429 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 430 } 431 } else { 432 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 433 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 434 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 435 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 436 } 437 438 // We cannot sextinreg(i1). Expand to shifts. 439 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 440 441 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 442 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 443 // support continuation, user-level threading, and etc.. As a result, no 444 // other SjLj exception interfaces are implemented and please don't build 445 // your own exception handling based on them. 446 // LLVM/Clang supports zero-cost DWARF exception handling. 447 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 448 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 449 450 // We want to legalize GlobalAddress and ConstantPool nodes into the 451 // appropriate instructions to materialize the address. 452 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 453 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 454 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 455 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 456 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 457 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 458 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 459 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 460 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 461 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 462 463 // TRAP is legal. 464 setOperationAction(ISD::TRAP, MVT::Other, Legal); 465 466 // TRAMPOLINE is custom lowered. 467 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 468 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 469 470 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 471 setOperationAction(ISD::VASTART , MVT::Other, Custom); 472 473 if (Subtarget.is64BitELFABI()) { 474 // VAARG always uses double-word chunks, so promote anything smaller. 475 setOperationAction(ISD::VAARG, MVT::i1, Promote); 476 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 477 setOperationAction(ISD::VAARG, MVT::i8, Promote); 478 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 479 setOperationAction(ISD::VAARG, MVT::i16, Promote); 480 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 481 setOperationAction(ISD::VAARG, MVT::i32, Promote); 482 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 483 setOperationAction(ISD::VAARG, MVT::Other, Expand); 484 } else if (Subtarget.is32BitELFABI()) { 485 // VAARG is custom lowered with the 32-bit SVR4 ABI. 486 setOperationAction(ISD::VAARG, MVT::Other, Custom); 487 setOperationAction(ISD::VAARG, MVT::i64, Custom); 488 } else 489 setOperationAction(ISD::VAARG, MVT::Other, Expand); 490 491 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 492 if (Subtarget.is32BitELFABI()) 493 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 494 else 495 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 496 497 // Use the default implementation. 498 setOperationAction(ISD::VAEND , MVT::Other, Expand); 499 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 500 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 501 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 502 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 503 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 504 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 505 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 506 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 507 508 // We want to custom lower some of our intrinsics. 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 510 511 // To handle counter-based loop conditions. 512 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 513 514 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 515 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 516 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 517 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 518 519 // Comparisons that require checking two conditions. 520 if (Subtarget.hasSPE()) { 521 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 522 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 523 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 524 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 525 } 526 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 527 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 528 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 529 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 530 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 531 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 532 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 533 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 534 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 535 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 536 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 537 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 538 539 if (Subtarget.has64BitSupport()) { 540 // They also have instructions for converting between i64 and fp. 541 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 542 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 543 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 544 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 545 // This is just the low 32 bits of a (signed) fp->i64 conversion. 546 // We cannot do this with Promote because i64 is not a legal type. 547 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 548 549 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 550 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 551 } else { 552 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 553 if (Subtarget.hasSPE()) 554 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 555 else 556 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 557 } 558 559 // With the instructions enabled under FPCVT, we can do everything. 560 if (Subtarget.hasFPCVT()) { 561 if (Subtarget.has64BitSupport()) { 562 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 563 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 564 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 565 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 566 } 567 568 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 569 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 570 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 571 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 572 } 573 574 if (Subtarget.use64BitRegs()) { 575 // 64-bit PowerPC implementations can support i64 types directly 576 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 577 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 578 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 579 // 64-bit PowerPC wants to expand i128 shifts itself. 580 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 581 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 582 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 583 } else { 584 // 32-bit PowerPC wants to expand i64 shifts itself. 585 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 586 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 587 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 588 } 589 590 if (Subtarget.hasVSX()) { 591 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 592 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 593 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 594 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 595 } 596 597 if (Subtarget.hasAltivec()) { 598 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 599 setOperationAction(ISD::SADDSAT, VT, Legal); 600 setOperationAction(ISD::SSUBSAT, VT, Legal); 601 setOperationAction(ISD::UADDSAT, VT, Legal); 602 setOperationAction(ISD::USUBSAT, VT, Legal); 603 } 604 // First set operation action for all vector types to expand. Then we 605 // will selectively turn on ones that can be effectively codegen'd. 606 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 607 // add/sub are legal for all supported vector VT's. 608 setOperationAction(ISD::ADD, VT, Legal); 609 setOperationAction(ISD::SUB, VT, Legal); 610 611 // For v2i64, these are only valid with P8Vector. This is corrected after 612 // the loop. 613 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 614 setOperationAction(ISD::SMAX, VT, Legal); 615 setOperationAction(ISD::SMIN, VT, Legal); 616 setOperationAction(ISD::UMAX, VT, Legal); 617 setOperationAction(ISD::UMIN, VT, Legal); 618 } 619 else { 620 setOperationAction(ISD::SMAX, VT, Expand); 621 setOperationAction(ISD::SMIN, VT, Expand); 622 setOperationAction(ISD::UMAX, VT, Expand); 623 setOperationAction(ISD::UMIN, VT, Expand); 624 } 625 626 if (Subtarget.hasVSX()) { 627 setOperationAction(ISD::FMAXNUM, VT, Legal); 628 setOperationAction(ISD::FMINNUM, VT, Legal); 629 } 630 631 // Vector instructions introduced in P8 632 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 633 setOperationAction(ISD::CTPOP, VT, Legal); 634 setOperationAction(ISD::CTLZ, VT, Legal); 635 } 636 else { 637 setOperationAction(ISD::CTPOP, VT, Expand); 638 setOperationAction(ISD::CTLZ, VT, Expand); 639 } 640 641 // Vector instructions introduced in P9 642 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 643 setOperationAction(ISD::CTTZ, VT, Legal); 644 else 645 setOperationAction(ISD::CTTZ, VT, Expand); 646 647 // We promote all shuffles to v16i8. 648 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 649 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 650 651 // We promote all non-typed operations to v4i32. 652 setOperationAction(ISD::AND , VT, Promote); 653 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 654 setOperationAction(ISD::OR , VT, Promote); 655 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 656 setOperationAction(ISD::XOR , VT, Promote); 657 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 658 setOperationAction(ISD::LOAD , VT, Promote); 659 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 660 setOperationAction(ISD::SELECT, VT, Promote); 661 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 662 setOperationAction(ISD::VSELECT, VT, Legal); 663 setOperationAction(ISD::SELECT_CC, VT, Promote); 664 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 665 setOperationAction(ISD::STORE, VT, Promote); 666 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 667 668 // No other operations are legal. 669 setOperationAction(ISD::MUL , VT, Expand); 670 setOperationAction(ISD::SDIV, VT, Expand); 671 setOperationAction(ISD::SREM, VT, Expand); 672 setOperationAction(ISD::UDIV, VT, Expand); 673 setOperationAction(ISD::UREM, VT, Expand); 674 setOperationAction(ISD::FDIV, VT, Expand); 675 setOperationAction(ISD::FREM, VT, Expand); 676 setOperationAction(ISD::FNEG, VT, Expand); 677 setOperationAction(ISD::FSQRT, VT, Expand); 678 setOperationAction(ISD::FLOG, VT, Expand); 679 setOperationAction(ISD::FLOG10, VT, Expand); 680 setOperationAction(ISD::FLOG2, VT, Expand); 681 setOperationAction(ISD::FEXP, VT, Expand); 682 setOperationAction(ISD::FEXP2, VT, Expand); 683 setOperationAction(ISD::FSIN, VT, Expand); 684 setOperationAction(ISD::FCOS, VT, Expand); 685 setOperationAction(ISD::FABS, VT, Expand); 686 setOperationAction(ISD::FFLOOR, VT, Expand); 687 setOperationAction(ISD::FCEIL, VT, Expand); 688 setOperationAction(ISD::FTRUNC, VT, Expand); 689 setOperationAction(ISD::FRINT, VT, Expand); 690 setOperationAction(ISD::FNEARBYINT, VT, Expand); 691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 692 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 693 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 694 setOperationAction(ISD::MULHU, VT, Expand); 695 setOperationAction(ISD::MULHS, VT, Expand); 696 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 697 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 698 setOperationAction(ISD::UDIVREM, VT, Expand); 699 setOperationAction(ISD::SDIVREM, VT, Expand); 700 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 701 setOperationAction(ISD::FPOW, VT, Expand); 702 setOperationAction(ISD::BSWAP, VT, Expand); 703 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 704 setOperationAction(ISD::ROTL, VT, Expand); 705 setOperationAction(ISD::ROTR, VT, Expand); 706 707 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 708 setTruncStoreAction(VT, InnerVT, Expand); 709 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 710 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 711 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 712 } 713 } 714 if (!Subtarget.hasP8Vector()) { 715 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 716 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 717 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 718 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 719 } 720 721 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 722 setOperationAction(ISD::ABS, VT, Custom); 723 724 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 725 // with merges, splats, etc. 726 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 727 728 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 729 // are cheap, so handle them before they get expanded to scalar. 730 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 731 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 732 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 733 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 734 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 735 736 setOperationAction(ISD::AND , MVT::v4i32, Legal); 737 setOperationAction(ISD::OR , MVT::v4i32, Legal); 738 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 739 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 740 setOperationAction(ISD::SELECT, MVT::v4i32, 741 Subtarget.useCRBits() ? Legal : Expand); 742 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 743 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 744 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 745 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 746 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 747 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 748 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 749 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 750 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 751 752 // Without hasP8Altivec set, v2i64 SMAX isn't available. 753 // But ABS custom lowering requires SMAX support. 754 if (!Subtarget.hasP8Altivec()) 755 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 756 757 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 758 if (Subtarget.hasAltivec()) 759 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 760 setOperationAction(ISD::ROTL, VT, Legal); 761 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 762 if (Subtarget.hasP8Altivec()) 763 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 764 765 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 766 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 767 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 768 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 769 770 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 771 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 772 773 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 774 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 775 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 776 } 777 778 if (Subtarget.hasP8Altivec()) 779 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 780 else 781 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 782 783 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 784 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 785 786 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 787 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 788 789 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 790 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 791 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 792 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 793 794 // Altivec does not contain unordered floating-point compare instructions 795 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 796 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 797 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 798 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 799 800 if (Subtarget.hasVSX()) { 801 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 802 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 803 if (Subtarget.hasP8Vector()) { 804 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 805 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 806 } 807 if (Subtarget.hasDirectMove() && isPPC64) { 808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 812 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 816 } 817 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 818 819 // The nearbyint variants are not allowed to raise the inexact exception 820 // so we can only code-gen them with unsafe math. 821 if (TM.Options.UnsafeFPMath) { 822 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 823 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 824 } 825 826 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 827 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 828 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 829 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 830 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 831 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 832 setOperationAction(ISD::FROUND, MVT::f64, Legal); 833 setOperationAction(ISD::FRINT, MVT::f64, Legal); 834 835 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 836 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 837 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 838 setOperationAction(ISD::FROUND, MVT::f32, Legal); 839 setOperationAction(ISD::FRINT, MVT::f32, Legal); 840 841 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 842 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 843 844 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 845 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 846 847 // Share the Altivec comparison restrictions. 848 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 849 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 850 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 851 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 852 853 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 854 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 855 856 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 857 858 if (Subtarget.hasP8Vector()) 859 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 860 861 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 862 863 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 864 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 865 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 866 867 if (Subtarget.hasP8Altivec()) { 868 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 869 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 870 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 871 872 // 128 bit shifts can be accomplished via 3 instructions for SHL and 873 // SRL, but not for SRA because of the instructions available: 874 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 875 // doing 876 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 877 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 878 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 879 880 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 881 } 882 else { 883 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 884 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 885 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 886 887 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 888 889 // VSX v2i64 only supports non-arithmetic operations. 890 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 891 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 892 } 893 894 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 895 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 896 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 897 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 898 899 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 900 901 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 902 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 903 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 904 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 905 906 // Custom handling for partial vectors of integers converted to 907 // floating point. We already have optimal handling for v2i32 through 908 // the DAG combine, so those aren't necessary. 909 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 911 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 912 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 913 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 914 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 915 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 916 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 917 918 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 919 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 920 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 921 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 922 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 923 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 924 925 if (Subtarget.hasDirectMove()) 926 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 927 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 928 929 // Handle constrained floating-point operations of vector. 930 // The predictor is `hasVSX` because altivec instruction has 931 // no exception but VSX vector instruction has. 932 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 933 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 934 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 935 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 936 937 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 938 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 939 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 940 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 941 942 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 943 } 944 945 if (Subtarget.hasP8Altivec()) { 946 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 947 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 948 } 949 950 if (Subtarget.hasP9Vector()) { 951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 953 954 // 128 bit shifts can be accomplished via 3 instructions for SHL and 955 // SRL, but not for SRA because of the instructions available: 956 // VS{RL} and VS{RL}O. 957 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 958 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 959 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 960 961 if (EnableQuadPrecision) { 962 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 963 setOperationAction(ISD::FADD, MVT::f128, Legal); 964 setOperationAction(ISD::FSUB, MVT::f128, Legal); 965 setOperationAction(ISD::FDIV, MVT::f128, Legal); 966 setOperationAction(ISD::FMUL, MVT::f128, Legal); 967 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 968 // No extending loads to f128 on PPC. 969 for (MVT FPT : MVT::fp_valuetypes()) 970 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 971 setOperationAction(ISD::FMA, MVT::f128, Legal); 972 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 973 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 974 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 975 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 976 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 977 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 978 979 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 980 setOperationAction(ISD::FRINT, MVT::f128, Legal); 981 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 982 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 983 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 984 setOperationAction(ISD::FROUND, MVT::f128, Legal); 985 986 setOperationAction(ISD::SELECT, MVT::f128, Expand); 987 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 988 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 989 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 990 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 991 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 992 // No implementation for these ops for PowerPC. 993 setOperationAction(ISD::FSIN , MVT::f128, Expand); 994 setOperationAction(ISD::FCOS , MVT::f128, Expand); 995 setOperationAction(ISD::FPOW, MVT::f128, Expand); 996 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 997 setOperationAction(ISD::FREM, MVT::f128, Expand); 998 999 // Handle constrained floating-point operations of fp128 1000 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1001 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1002 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1003 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1004 } 1005 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1006 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1007 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1008 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1009 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1010 } 1011 1012 if (Subtarget.hasP9Altivec()) { 1013 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1014 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1015 1016 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1017 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1018 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1019 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1020 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1021 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1022 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1023 } 1024 } 1025 1026 if (Subtarget.hasQPX()) { 1027 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1028 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1029 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1030 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1031 1032 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1033 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1034 1035 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1036 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1037 1038 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1039 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1040 1041 if (!Subtarget.useCRBits()) 1042 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1043 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1044 1045 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1046 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1047 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1048 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1049 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1050 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1051 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1052 1053 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1054 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1055 1056 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1057 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1058 1059 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1060 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1061 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1062 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1063 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1064 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1065 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1066 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1067 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1068 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1069 1070 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1071 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1072 1073 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1074 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1075 1076 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1077 1078 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1079 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1080 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1081 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1082 1083 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1084 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1085 1086 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1087 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1088 1089 if (!Subtarget.useCRBits()) 1090 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1091 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1092 1093 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1094 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1095 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1096 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1097 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1098 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1099 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1100 1101 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1102 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1103 1104 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1105 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1106 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1107 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1108 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1109 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1110 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1111 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1112 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1113 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1114 1115 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1117 1118 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1119 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1120 1121 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1122 1123 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1124 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1125 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1126 1127 if (!Subtarget.useCRBits()) 1128 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1129 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1130 1131 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1132 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1133 1134 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1135 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1136 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1137 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1138 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1139 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1140 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1141 1142 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1143 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1144 1145 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1146 1147 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1148 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1149 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1150 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1151 1152 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1153 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1154 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1155 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1156 1157 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1158 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1159 1160 // These need to set FE_INEXACT, and so cannot be vectorized here. 1161 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1162 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1163 1164 if (TM.Options.UnsafeFPMath) { 1165 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1166 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1167 1168 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1169 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1170 } else { 1171 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1172 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1173 1174 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1175 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1176 } 1177 1178 // TODO: Handle constrained floating-point operations of v4f64 1179 } 1180 1181 if (Subtarget.has64BitSupport()) 1182 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1183 1184 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1185 1186 if (!isPPC64) { 1187 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1188 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1189 } 1190 1191 setBooleanContents(ZeroOrOneBooleanContent); 1192 1193 if (Subtarget.hasAltivec()) { 1194 // Altivec instructions set fields to all zeros or all ones. 1195 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1196 } 1197 1198 if (!isPPC64) { 1199 // These libcalls are not available in 32-bit. 1200 setLibcallName(RTLIB::SHL_I128, nullptr); 1201 setLibcallName(RTLIB::SRL_I128, nullptr); 1202 setLibcallName(RTLIB::SRA_I128, nullptr); 1203 } 1204 1205 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1206 1207 // We have target-specific dag combine patterns for the following nodes: 1208 setTargetDAGCombine(ISD::ADD); 1209 setTargetDAGCombine(ISD::SHL); 1210 setTargetDAGCombine(ISD::SRA); 1211 setTargetDAGCombine(ISD::SRL); 1212 setTargetDAGCombine(ISD::MUL); 1213 setTargetDAGCombine(ISD::SINT_TO_FP); 1214 setTargetDAGCombine(ISD::BUILD_VECTOR); 1215 if (Subtarget.hasFPCVT()) 1216 setTargetDAGCombine(ISD::UINT_TO_FP); 1217 setTargetDAGCombine(ISD::LOAD); 1218 setTargetDAGCombine(ISD::STORE); 1219 setTargetDAGCombine(ISD::BR_CC); 1220 if (Subtarget.useCRBits()) 1221 setTargetDAGCombine(ISD::BRCOND); 1222 setTargetDAGCombine(ISD::BSWAP); 1223 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1224 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1225 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1226 1227 setTargetDAGCombine(ISD::SIGN_EXTEND); 1228 setTargetDAGCombine(ISD::ZERO_EXTEND); 1229 setTargetDAGCombine(ISD::ANY_EXTEND); 1230 1231 setTargetDAGCombine(ISD::TRUNCATE); 1232 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1233 1234 1235 if (Subtarget.useCRBits()) { 1236 setTargetDAGCombine(ISD::TRUNCATE); 1237 setTargetDAGCombine(ISD::SETCC); 1238 setTargetDAGCombine(ISD::SELECT_CC); 1239 } 1240 1241 // Use reciprocal estimates. 1242 if (TM.Options.UnsafeFPMath) { 1243 setTargetDAGCombine(ISD::FDIV); 1244 setTargetDAGCombine(ISD::FSQRT); 1245 } 1246 1247 if (Subtarget.hasP9Altivec()) { 1248 setTargetDAGCombine(ISD::ABS); 1249 setTargetDAGCombine(ISD::VSELECT); 1250 } 1251 1252 if (EnableQuadPrecision) { 1253 setLibcallName(RTLIB::LOG_F128, "logf128"); 1254 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1255 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1256 setLibcallName(RTLIB::EXP_F128, "expf128"); 1257 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1258 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1259 setLibcallName(RTLIB::COS_F128, "cosf128"); 1260 setLibcallName(RTLIB::POW_F128, "powf128"); 1261 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1262 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1263 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1264 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1265 } 1266 1267 // With 32 condition bits, we don't need to sink (and duplicate) compares 1268 // aggressively in CodeGenPrep. 1269 if (Subtarget.useCRBits()) { 1270 setHasMultipleConditionRegisters(); 1271 setJumpIsExpensive(); 1272 } 1273 1274 setMinFunctionAlignment(Align(4)); 1275 1276 switch (Subtarget.getCPUDirective()) { 1277 default: break; 1278 case PPC::DIR_970: 1279 case PPC::DIR_A2: 1280 case PPC::DIR_E500: 1281 case PPC::DIR_E500mc: 1282 case PPC::DIR_E5500: 1283 case PPC::DIR_PWR4: 1284 case PPC::DIR_PWR5: 1285 case PPC::DIR_PWR5X: 1286 case PPC::DIR_PWR6: 1287 case PPC::DIR_PWR6X: 1288 case PPC::DIR_PWR7: 1289 case PPC::DIR_PWR8: 1290 case PPC::DIR_PWR9: 1291 case PPC::DIR_PWR_FUTURE: 1292 setPrefLoopAlignment(Align(16)); 1293 setPrefFunctionAlignment(Align(16)); 1294 break; 1295 } 1296 1297 if (Subtarget.enableMachineScheduler()) 1298 setSchedulingPreference(Sched::Source); 1299 else 1300 setSchedulingPreference(Sched::Hybrid); 1301 1302 computeRegisterProperties(STI.getRegisterInfo()); 1303 1304 // The Freescale cores do better with aggressive inlining of memcpy and 1305 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1306 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1307 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1308 MaxStoresPerMemset = 32; 1309 MaxStoresPerMemsetOptSize = 16; 1310 MaxStoresPerMemcpy = 32; 1311 MaxStoresPerMemcpyOptSize = 8; 1312 MaxStoresPerMemmove = 32; 1313 MaxStoresPerMemmoveOptSize = 8; 1314 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1315 // The A2 also benefits from (very) aggressive inlining of memcpy and 1316 // friends. The overhead of a the function call, even when warm, can be 1317 // over one hundred cycles. 1318 MaxStoresPerMemset = 128; 1319 MaxStoresPerMemcpy = 128; 1320 MaxStoresPerMemmove = 128; 1321 MaxLoadsPerMemcmp = 128; 1322 } else { 1323 MaxLoadsPerMemcmp = 8; 1324 MaxLoadsPerMemcmpOptSize = 4; 1325 } 1326 } 1327 1328 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1329 /// the desired ByVal argument alignment. 1330 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1331 unsigned MaxMaxAlign) { 1332 if (MaxAlign == MaxMaxAlign) 1333 return; 1334 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1335 if (MaxMaxAlign >= 32 && 1336 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1337 MaxAlign = 32; 1338 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1339 MaxAlign < 16) 1340 MaxAlign = 16; 1341 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1342 unsigned EltAlign = 0; 1343 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1344 if (EltAlign > MaxAlign) 1345 MaxAlign = EltAlign; 1346 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1347 for (auto *EltTy : STy->elements()) { 1348 unsigned EltAlign = 0; 1349 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1350 if (EltAlign > MaxAlign) 1351 MaxAlign = EltAlign; 1352 if (MaxAlign == MaxMaxAlign) 1353 break; 1354 } 1355 } 1356 } 1357 1358 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1359 /// function arguments in the caller parameter area. 1360 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1361 const DataLayout &DL) const { 1362 // 16byte and wider vectors are passed on 16byte boundary. 1363 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1364 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1365 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1366 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1367 return Align; 1368 } 1369 1370 bool PPCTargetLowering::useSoftFloat() const { 1371 return Subtarget.useSoftFloat(); 1372 } 1373 1374 bool PPCTargetLowering::hasSPE() const { 1375 return Subtarget.hasSPE(); 1376 } 1377 1378 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1379 return VT.isScalarInteger(); 1380 } 1381 1382 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1383 switch ((PPCISD::NodeType)Opcode) { 1384 case PPCISD::FIRST_NUMBER: break; 1385 case PPCISD::FSEL: return "PPCISD::FSEL"; 1386 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1387 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1388 case PPCISD::FCFID: return "PPCISD::FCFID"; 1389 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1390 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1391 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1392 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1393 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1394 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1395 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1396 case PPCISD::FP_TO_UINT_IN_VSR: 1397 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1398 case PPCISD::FP_TO_SINT_IN_VSR: 1399 return "PPCISD::FP_TO_SINT_IN_VSR"; 1400 case PPCISD::FRE: return "PPCISD::FRE"; 1401 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1402 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1403 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1404 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1405 case PPCISD::VPERM: return "PPCISD::VPERM"; 1406 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1407 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1408 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1409 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1410 case PPCISD::CMPB: return "PPCISD::CMPB"; 1411 case PPCISD::Hi: return "PPCISD::Hi"; 1412 case PPCISD::Lo: return "PPCISD::Lo"; 1413 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1414 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1415 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1416 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1417 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1418 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1419 case PPCISD::SRL: return "PPCISD::SRL"; 1420 case PPCISD::SRA: return "PPCISD::SRA"; 1421 case PPCISD::SHL: return "PPCISD::SHL"; 1422 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1423 case PPCISD::CALL: return "PPCISD::CALL"; 1424 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1425 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1426 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1427 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1428 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1429 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1430 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1431 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1432 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1433 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1434 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1435 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1436 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1437 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1438 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1439 case PPCISD::ANDI_rec_1_EQ_BIT: 1440 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1441 case PPCISD::ANDI_rec_1_GT_BIT: 1442 return "PPCISD::ANDI_rec_1_GT_BIT"; 1443 case PPCISD::VCMP: return "PPCISD::VCMP"; 1444 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1445 case PPCISD::LBRX: return "PPCISD::LBRX"; 1446 case PPCISD::STBRX: return "PPCISD::STBRX"; 1447 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1448 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1449 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1450 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1451 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1452 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1453 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1454 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1455 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1456 case PPCISD::ST_VSR_SCAL_INT: 1457 return "PPCISD::ST_VSR_SCAL_INT"; 1458 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1459 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1460 case PPCISD::BDZ: return "PPCISD::BDZ"; 1461 case PPCISD::MFFS: return "PPCISD::MFFS"; 1462 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1463 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1464 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1465 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1466 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1467 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1468 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1469 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1470 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1471 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1472 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1473 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1474 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1475 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1476 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1477 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1478 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1479 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1480 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1481 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1482 case PPCISD::SC: return "PPCISD::SC"; 1483 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1484 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1485 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1486 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1487 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1488 case PPCISD::VABSD: return "PPCISD::VABSD"; 1489 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1490 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1491 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1492 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1493 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1494 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1495 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1496 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1497 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1498 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1499 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1500 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1501 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1502 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1503 } 1504 return nullptr; 1505 } 1506 1507 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1508 EVT VT) const { 1509 if (!VT.isVector()) 1510 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1511 1512 if (Subtarget.hasQPX()) 1513 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1514 1515 return VT.changeVectorElementTypeToInteger(); 1516 } 1517 1518 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1519 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1520 return true; 1521 } 1522 1523 //===----------------------------------------------------------------------===// 1524 // Node matching predicates, for use by the tblgen matching code. 1525 //===----------------------------------------------------------------------===// 1526 1527 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1528 static bool isFloatingPointZero(SDValue Op) { 1529 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1530 return CFP->getValueAPF().isZero(); 1531 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1532 // Maybe this has already been legalized into the constant pool? 1533 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1534 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1535 return CFP->getValueAPF().isZero(); 1536 } 1537 return false; 1538 } 1539 1540 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1541 /// true if Op is undef or if it matches the specified value. 1542 static bool isConstantOrUndef(int Op, int Val) { 1543 return Op < 0 || Op == Val; 1544 } 1545 1546 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1547 /// VPKUHUM instruction. 1548 /// The ShuffleKind distinguishes between big-endian operations with 1549 /// two different inputs (0), either-endian operations with two identical 1550 /// inputs (1), and little-endian operations with two different inputs (2). 1551 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1552 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1553 SelectionDAG &DAG) { 1554 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1555 if (ShuffleKind == 0) { 1556 if (IsLE) 1557 return false; 1558 for (unsigned i = 0; i != 16; ++i) 1559 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1560 return false; 1561 } else if (ShuffleKind == 2) { 1562 if (!IsLE) 1563 return false; 1564 for (unsigned i = 0; i != 16; ++i) 1565 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1566 return false; 1567 } else if (ShuffleKind == 1) { 1568 unsigned j = IsLE ? 0 : 1; 1569 for (unsigned i = 0; i != 8; ++i) 1570 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1571 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1572 return false; 1573 } 1574 return true; 1575 } 1576 1577 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1578 /// VPKUWUM instruction. 1579 /// The ShuffleKind distinguishes between big-endian operations with 1580 /// two different inputs (0), either-endian operations with two identical 1581 /// inputs (1), and little-endian operations with two different inputs (2). 1582 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1583 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1584 SelectionDAG &DAG) { 1585 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1586 if (ShuffleKind == 0) { 1587 if (IsLE) 1588 return false; 1589 for (unsigned i = 0; i != 16; i += 2) 1590 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1591 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1592 return false; 1593 } else if (ShuffleKind == 2) { 1594 if (!IsLE) 1595 return false; 1596 for (unsigned i = 0; i != 16; i += 2) 1597 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1598 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1599 return false; 1600 } else if (ShuffleKind == 1) { 1601 unsigned j = IsLE ? 0 : 2; 1602 for (unsigned i = 0; i != 8; i += 2) 1603 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1604 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1605 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1606 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1607 return false; 1608 } 1609 return true; 1610 } 1611 1612 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1613 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1614 /// current subtarget. 1615 /// 1616 /// The ShuffleKind distinguishes between big-endian operations with 1617 /// two different inputs (0), either-endian operations with two identical 1618 /// inputs (1), and little-endian operations with two different inputs (2). 1619 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1620 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1621 SelectionDAG &DAG) { 1622 const PPCSubtarget& Subtarget = 1623 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1624 if (!Subtarget.hasP8Vector()) 1625 return false; 1626 1627 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1628 if (ShuffleKind == 0) { 1629 if (IsLE) 1630 return false; 1631 for (unsigned i = 0; i != 16; i += 4) 1632 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1633 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1634 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1635 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1636 return false; 1637 } else if (ShuffleKind == 2) { 1638 if (!IsLE) 1639 return false; 1640 for (unsigned i = 0; i != 16; i += 4) 1641 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1642 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1643 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1644 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1645 return false; 1646 } else if (ShuffleKind == 1) { 1647 unsigned j = IsLE ? 0 : 4; 1648 for (unsigned i = 0; i != 8; i += 4) 1649 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1650 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1651 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1652 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1653 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1654 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1655 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1656 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1657 return false; 1658 } 1659 return true; 1660 } 1661 1662 /// isVMerge - Common function, used to match vmrg* shuffles. 1663 /// 1664 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1665 unsigned LHSStart, unsigned RHSStart) { 1666 if (N->getValueType(0) != MVT::v16i8) 1667 return false; 1668 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1669 "Unsupported merge size!"); 1670 1671 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1672 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1673 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1674 LHSStart+j+i*UnitSize) || 1675 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1676 RHSStart+j+i*UnitSize)) 1677 return false; 1678 } 1679 return true; 1680 } 1681 1682 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1683 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1684 /// The ShuffleKind distinguishes between big-endian merges with two 1685 /// different inputs (0), either-endian merges with two identical inputs (1), 1686 /// and little-endian merges with two different inputs (2). For the latter, 1687 /// the input operands are swapped (see PPCInstrAltivec.td). 1688 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1689 unsigned ShuffleKind, SelectionDAG &DAG) { 1690 if (DAG.getDataLayout().isLittleEndian()) { 1691 if (ShuffleKind == 1) // unary 1692 return isVMerge(N, UnitSize, 0, 0); 1693 else if (ShuffleKind == 2) // swapped 1694 return isVMerge(N, UnitSize, 0, 16); 1695 else 1696 return false; 1697 } else { 1698 if (ShuffleKind == 1) // unary 1699 return isVMerge(N, UnitSize, 8, 8); 1700 else if (ShuffleKind == 0) // normal 1701 return isVMerge(N, UnitSize, 8, 24); 1702 else 1703 return false; 1704 } 1705 } 1706 1707 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1708 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1709 /// The ShuffleKind distinguishes between big-endian merges with two 1710 /// different inputs (0), either-endian merges with two identical inputs (1), 1711 /// and little-endian merges with two different inputs (2). For the latter, 1712 /// the input operands are swapped (see PPCInstrAltivec.td). 1713 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1714 unsigned ShuffleKind, SelectionDAG &DAG) { 1715 if (DAG.getDataLayout().isLittleEndian()) { 1716 if (ShuffleKind == 1) // unary 1717 return isVMerge(N, UnitSize, 8, 8); 1718 else if (ShuffleKind == 2) // swapped 1719 return isVMerge(N, UnitSize, 8, 24); 1720 else 1721 return false; 1722 } else { 1723 if (ShuffleKind == 1) // unary 1724 return isVMerge(N, UnitSize, 0, 0); 1725 else if (ShuffleKind == 0) // normal 1726 return isVMerge(N, UnitSize, 0, 16); 1727 else 1728 return false; 1729 } 1730 } 1731 1732 /** 1733 * Common function used to match vmrgew and vmrgow shuffles 1734 * 1735 * The indexOffset determines whether to look for even or odd words in 1736 * the shuffle mask. This is based on the of the endianness of the target 1737 * machine. 1738 * - Little Endian: 1739 * - Use offset of 0 to check for odd elements 1740 * - Use offset of 4 to check for even elements 1741 * - Big Endian: 1742 * - Use offset of 0 to check for even elements 1743 * - Use offset of 4 to check for odd elements 1744 * A detailed description of the vector element ordering for little endian and 1745 * big endian can be found at 1746 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1747 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1748 * compiler differences mean to you 1749 * 1750 * The mask to the shuffle vector instruction specifies the indices of the 1751 * elements from the two input vectors to place in the result. The elements are 1752 * numbered in array-access order, starting with the first vector. These vectors 1753 * are always of type v16i8, thus each vector will contain 16 elements of size 1754 * 8. More info on the shuffle vector can be found in the 1755 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1756 * Language Reference. 1757 * 1758 * The RHSStartValue indicates whether the same input vectors are used (unary) 1759 * or two different input vectors are used, based on the following: 1760 * - If the instruction uses the same vector for both inputs, the range of the 1761 * indices will be 0 to 15. In this case, the RHSStart value passed should 1762 * be 0. 1763 * - If the instruction has two different vectors then the range of the 1764 * indices will be 0 to 31. In this case, the RHSStart value passed should 1765 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1766 * to 31 specify elements in the second vector). 1767 * 1768 * \param[in] N The shuffle vector SD Node to analyze 1769 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1770 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1771 * vector to the shuffle_vector instruction 1772 * \return true iff this shuffle vector represents an even or odd word merge 1773 */ 1774 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1775 unsigned RHSStartValue) { 1776 if (N->getValueType(0) != MVT::v16i8) 1777 return false; 1778 1779 for (unsigned i = 0; i < 2; ++i) 1780 for (unsigned j = 0; j < 4; ++j) 1781 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1782 i*RHSStartValue+j+IndexOffset) || 1783 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1784 i*RHSStartValue+j+IndexOffset+8)) 1785 return false; 1786 return true; 1787 } 1788 1789 /** 1790 * Determine if the specified shuffle mask is suitable for the vmrgew or 1791 * vmrgow instructions. 1792 * 1793 * \param[in] N The shuffle vector SD Node to analyze 1794 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1795 * \param[in] ShuffleKind Identify the type of merge: 1796 * - 0 = big-endian merge with two different inputs; 1797 * - 1 = either-endian merge with two identical inputs; 1798 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1799 * little-endian merges). 1800 * \param[in] DAG The current SelectionDAG 1801 * \return true iff this shuffle mask 1802 */ 1803 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1804 unsigned ShuffleKind, SelectionDAG &DAG) { 1805 if (DAG.getDataLayout().isLittleEndian()) { 1806 unsigned indexOffset = CheckEven ? 4 : 0; 1807 if (ShuffleKind == 1) // Unary 1808 return isVMerge(N, indexOffset, 0); 1809 else if (ShuffleKind == 2) // swapped 1810 return isVMerge(N, indexOffset, 16); 1811 else 1812 return false; 1813 } 1814 else { 1815 unsigned indexOffset = CheckEven ? 0 : 4; 1816 if (ShuffleKind == 1) // Unary 1817 return isVMerge(N, indexOffset, 0); 1818 else if (ShuffleKind == 0) // Normal 1819 return isVMerge(N, indexOffset, 16); 1820 else 1821 return false; 1822 } 1823 return false; 1824 } 1825 1826 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1827 /// amount, otherwise return -1. 1828 /// The ShuffleKind distinguishes between big-endian operations with two 1829 /// different inputs (0), either-endian operations with two identical inputs 1830 /// (1), and little-endian operations with two different inputs (2). For the 1831 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1832 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1833 SelectionDAG &DAG) { 1834 if (N->getValueType(0) != MVT::v16i8) 1835 return -1; 1836 1837 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1838 1839 // Find the first non-undef value in the shuffle mask. 1840 unsigned i; 1841 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1842 /*search*/; 1843 1844 if (i == 16) return -1; // all undef. 1845 1846 // Otherwise, check to see if the rest of the elements are consecutively 1847 // numbered from this value. 1848 unsigned ShiftAmt = SVOp->getMaskElt(i); 1849 if (ShiftAmt < i) return -1; 1850 1851 ShiftAmt -= i; 1852 bool isLE = DAG.getDataLayout().isLittleEndian(); 1853 1854 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1855 // Check the rest of the elements to see if they are consecutive. 1856 for (++i; i != 16; ++i) 1857 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1858 return -1; 1859 } else if (ShuffleKind == 1) { 1860 // Check the rest of the elements to see if they are consecutive. 1861 for (++i; i != 16; ++i) 1862 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1863 return -1; 1864 } else 1865 return -1; 1866 1867 if (isLE) 1868 ShiftAmt = 16 - ShiftAmt; 1869 1870 return ShiftAmt; 1871 } 1872 1873 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1874 /// specifies a splat of a single element that is suitable for input to 1875 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1876 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1877 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1878 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1879 1880 // The consecutive indices need to specify an element, not part of two 1881 // different elements. So abandon ship early if this isn't the case. 1882 if (N->getMaskElt(0) % EltSize != 0) 1883 return false; 1884 1885 // This is a splat operation if each element of the permute is the same, and 1886 // if the value doesn't reference the second vector. 1887 unsigned ElementBase = N->getMaskElt(0); 1888 1889 // FIXME: Handle UNDEF elements too! 1890 if (ElementBase >= 16) 1891 return false; 1892 1893 // Check that the indices are consecutive, in the case of a multi-byte element 1894 // splatted with a v16i8 mask. 1895 for (unsigned i = 1; i != EltSize; ++i) 1896 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1897 return false; 1898 1899 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1900 if (N->getMaskElt(i) < 0) continue; 1901 for (unsigned j = 0; j != EltSize; ++j) 1902 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1903 return false; 1904 } 1905 return true; 1906 } 1907 1908 /// Check that the mask is shuffling N byte elements. Within each N byte 1909 /// element of the mask, the indices could be either in increasing or 1910 /// decreasing order as long as they are consecutive. 1911 /// \param[in] N the shuffle vector SD Node to analyze 1912 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1913 /// Word/DoubleWord/QuadWord). 1914 /// \param[in] StepLen the delta indices number among the N byte element, if 1915 /// the mask is in increasing/decreasing order then it is 1/-1. 1916 /// \return true iff the mask is shuffling N byte elements. 1917 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1918 int StepLen) { 1919 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1920 "Unexpected element width."); 1921 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1922 1923 unsigned NumOfElem = 16 / Width; 1924 unsigned MaskVal[16]; // Width is never greater than 16 1925 for (unsigned i = 0; i < NumOfElem; ++i) { 1926 MaskVal[0] = N->getMaskElt(i * Width); 1927 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1928 return false; 1929 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1930 return false; 1931 } 1932 1933 for (unsigned int j = 1; j < Width; ++j) { 1934 MaskVal[j] = N->getMaskElt(i * Width + j); 1935 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1936 return false; 1937 } 1938 } 1939 } 1940 1941 return true; 1942 } 1943 1944 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1945 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1946 if (!isNByteElemShuffleMask(N, 4, 1)) 1947 return false; 1948 1949 // Now we look at mask elements 0,4,8,12 1950 unsigned M0 = N->getMaskElt(0) / 4; 1951 unsigned M1 = N->getMaskElt(4) / 4; 1952 unsigned M2 = N->getMaskElt(8) / 4; 1953 unsigned M3 = N->getMaskElt(12) / 4; 1954 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1955 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1956 1957 // Below, let H and L be arbitrary elements of the shuffle mask 1958 // where H is in the range [4,7] and L is in the range [0,3]. 1959 // H, 1, 2, 3 or L, 5, 6, 7 1960 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1961 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1962 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1963 InsertAtByte = IsLE ? 12 : 0; 1964 Swap = M0 < 4; 1965 return true; 1966 } 1967 // 0, H, 2, 3 or 4, L, 6, 7 1968 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1969 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1970 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1971 InsertAtByte = IsLE ? 8 : 4; 1972 Swap = M1 < 4; 1973 return true; 1974 } 1975 // 0, 1, H, 3 or 4, 5, L, 7 1976 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1977 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1978 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1979 InsertAtByte = IsLE ? 4 : 8; 1980 Swap = M2 < 4; 1981 return true; 1982 } 1983 // 0, 1, 2, H or 4, 5, 6, L 1984 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1985 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1986 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1987 InsertAtByte = IsLE ? 0 : 12; 1988 Swap = M3 < 4; 1989 return true; 1990 } 1991 1992 // If both vector operands for the shuffle are the same vector, the mask will 1993 // contain only elements from the first one and the second one will be undef. 1994 if (N->getOperand(1).isUndef()) { 1995 ShiftElts = 0; 1996 Swap = true; 1997 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1998 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1999 InsertAtByte = IsLE ? 12 : 0; 2000 return true; 2001 } 2002 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2003 InsertAtByte = IsLE ? 8 : 4; 2004 return true; 2005 } 2006 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2007 InsertAtByte = IsLE ? 4 : 8; 2008 return true; 2009 } 2010 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2011 InsertAtByte = IsLE ? 0 : 12; 2012 return true; 2013 } 2014 } 2015 2016 return false; 2017 } 2018 2019 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2020 bool &Swap, bool IsLE) { 2021 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2022 // Ensure each byte index of the word is consecutive. 2023 if (!isNByteElemShuffleMask(N, 4, 1)) 2024 return false; 2025 2026 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2027 unsigned M0 = N->getMaskElt(0) / 4; 2028 unsigned M1 = N->getMaskElt(4) / 4; 2029 unsigned M2 = N->getMaskElt(8) / 4; 2030 unsigned M3 = N->getMaskElt(12) / 4; 2031 2032 // If both vector operands for the shuffle are the same vector, the mask will 2033 // contain only elements from the first one and the second one will be undef. 2034 if (N->getOperand(1).isUndef()) { 2035 assert(M0 < 4 && "Indexing into an undef vector?"); 2036 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2037 return false; 2038 2039 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2040 Swap = false; 2041 return true; 2042 } 2043 2044 // Ensure each word index of the ShuffleVector Mask is consecutive. 2045 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2046 return false; 2047 2048 if (IsLE) { 2049 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2050 // Input vectors don't need to be swapped if the leading element 2051 // of the result is one of the 3 left elements of the second vector 2052 // (or if there is no shift to be done at all). 2053 Swap = false; 2054 ShiftElts = (8 - M0) % 8; 2055 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2056 // Input vectors need to be swapped if the leading element 2057 // of the result is one of the 3 left elements of the first vector 2058 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2059 Swap = true; 2060 ShiftElts = (4 - M0) % 4; 2061 } 2062 2063 return true; 2064 } else { // BE 2065 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2066 // Input vectors don't need to be swapped if the leading element 2067 // of the result is one of the 4 elements of the first vector. 2068 Swap = false; 2069 ShiftElts = M0; 2070 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2071 // Input vectors need to be swapped if the leading element 2072 // of the result is one of the 4 elements of the right vector. 2073 Swap = true; 2074 ShiftElts = M0 - 4; 2075 } 2076 2077 return true; 2078 } 2079 } 2080 2081 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2082 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2083 2084 if (!isNByteElemShuffleMask(N, Width, -1)) 2085 return false; 2086 2087 for (int i = 0; i < 16; i += Width) 2088 if (N->getMaskElt(i) != i + Width - 1) 2089 return false; 2090 2091 return true; 2092 } 2093 2094 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2095 return isXXBRShuffleMaskHelper(N, 2); 2096 } 2097 2098 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2099 return isXXBRShuffleMaskHelper(N, 4); 2100 } 2101 2102 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2103 return isXXBRShuffleMaskHelper(N, 8); 2104 } 2105 2106 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2107 return isXXBRShuffleMaskHelper(N, 16); 2108 } 2109 2110 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2111 /// if the inputs to the instruction should be swapped and set \p DM to the 2112 /// value for the immediate. 2113 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2114 /// AND element 0 of the result comes from the first input (LE) or second input 2115 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2116 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2117 /// mask. 2118 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2119 bool &Swap, bool IsLE) { 2120 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2121 2122 // Ensure each byte index of the double word is consecutive. 2123 if (!isNByteElemShuffleMask(N, 8, 1)) 2124 return false; 2125 2126 unsigned M0 = N->getMaskElt(0) / 8; 2127 unsigned M1 = N->getMaskElt(8) / 8; 2128 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2129 2130 // If both vector operands for the shuffle are the same vector, the mask will 2131 // contain only elements from the first one and the second one will be undef. 2132 if (N->getOperand(1).isUndef()) { 2133 if ((M0 | M1) < 2) { 2134 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2135 Swap = false; 2136 return true; 2137 } else 2138 return false; 2139 } 2140 2141 if (IsLE) { 2142 if (M0 > 1 && M1 < 2) { 2143 Swap = false; 2144 } else if (M0 < 2 && M1 > 1) { 2145 M0 = (M0 + 2) % 4; 2146 M1 = (M1 + 2) % 4; 2147 Swap = true; 2148 } else 2149 return false; 2150 2151 // Note: if control flow comes here that means Swap is already set above 2152 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2153 return true; 2154 } else { // BE 2155 if (M0 < 2 && M1 > 1) { 2156 Swap = false; 2157 } else if (M0 > 1 && M1 < 2) { 2158 M0 = (M0 + 2) % 4; 2159 M1 = (M1 + 2) % 4; 2160 Swap = true; 2161 } else 2162 return false; 2163 2164 // Note: if control flow comes here that means Swap is already set above 2165 DM = (M0 << 1) + (M1 & 1); 2166 return true; 2167 } 2168 } 2169 2170 2171 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2172 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2173 /// elements are counted from the left of the vector register). 2174 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2175 SelectionDAG &DAG) { 2176 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2177 assert(isSplatShuffleMask(SVOp, EltSize)); 2178 if (DAG.getDataLayout().isLittleEndian()) 2179 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2180 else 2181 return SVOp->getMaskElt(0) / EltSize; 2182 } 2183 2184 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2185 /// by using a vspltis[bhw] instruction of the specified element size, return 2186 /// the constant being splatted. The ByteSize field indicates the number of 2187 /// bytes of each element [124] -> [bhw]. 2188 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2189 SDValue OpVal(nullptr, 0); 2190 2191 // If ByteSize of the splat is bigger than the element size of the 2192 // build_vector, then we have a case where we are checking for a splat where 2193 // multiple elements of the buildvector are folded together into a single 2194 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2195 unsigned EltSize = 16/N->getNumOperands(); 2196 if (EltSize < ByteSize) { 2197 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2198 SDValue UniquedVals[4]; 2199 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2200 2201 // See if all of the elements in the buildvector agree across. 2202 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2203 if (N->getOperand(i).isUndef()) continue; 2204 // If the element isn't a constant, bail fully out. 2205 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2206 2207 if (!UniquedVals[i&(Multiple-1)].getNode()) 2208 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2209 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2210 return SDValue(); // no match. 2211 } 2212 2213 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2214 // either constant or undef values that are identical for each chunk. See 2215 // if these chunks can form into a larger vspltis*. 2216 2217 // Check to see if all of the leading entries are either 0 or -1. If 2218 // neither, then this won't fit into the immediate field. 2219 bool LeadingZero = true; 2220 bool LeadingOnes = true; 2221 for (unsigned i = 0; i != Multiple-1; ++i) { 2222 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2223 2224 LeadingZero &= isNullConstant(UniquedVals[i]); 2225 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2226 } 2227 // Finally, check the least significant entry. 2228 if (LeadingZero) { 2229 if (!UniquedVals[Multiple-1].getNode()) 2230 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2231 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2232 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2233 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2234 } 2235 if (LeadingOnes) { 2236 if (!UniquedVals[Multiple-1].getNode()) 2237 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2238 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2239 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2240 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2241 } 2242 2243 return SDValue(); 2244 } 2245 2246 // Check to see if this buildvec has a single non-undef value in its elements. 2247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2248 if (N->getOperand(i).isUndef()) continue; 2249 if (!OpVal.getNode()) 2250 OpVal = N->getOperand(i); 2251 else if (OpVal != N->getOperand(i)) 2252 return SDValue(); 2253 } 2254 2255 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2256 2257 unsigned ValSizeInBytes = EltSize; 2258 uint64_t Value = 0; 2259 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2260 Value = CN->getZExtValue(); 2261 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2262 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2263 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2264 } 2265 2266 // If the splat value is larger than the element value, then we can never do 2267 // this splat. The only case that we could fit the replicated bits into our 2268 // immediate field for would be zero, and we prefer to use vxor for it. 2269 if (ValSizeInBytes < ByteSize) return SDValue(); 2270 2271 // If the element value is larger than the splat value, check if it consists 2272 // of a repeated bit pattern of size ByteSize. 2273 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2274 return SDValue(); 2275 2276 // Properly sign extend the value. 2277 int MaskVal = SignExtend32(Value, ByteSize * 8); 2278 2279 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2280 if (MaskVal == 0) return SDValue(); 2281 2282 // Finally, if this value fits in a 5 bit sext field, return it 2283 if (SignExtend32<5>(MaskVal) == MaskVal) 2284 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2285 return SDValue(); 2286 } 2287 2288 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2289 /// amount, otherwise return -1. 2290 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2291 EVT VT = N->getValueType(0); 2292 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2293 return -1; 2294 2295 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2296 2297 // Find the first non-undef value in the shuffle mask. 2298 unsigned i; 2299 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2300 /*search*/; 2301 2302 if (i == 4) return -1; // all undef. 2303 2304 // Otherwise, check to see if the rest of the elements are consecutively 2305 // numbered from this value. 2306 unsigned ShiftAmt = SVOp->getMaskElt(i); 2307 if (ShiftAmt < i) return -1; 2308 ShiftAmt -= i; 2309 2310 // Check the rest of the elements to see if they are consecutive. 2311 for (++i; i != 4; ++i) 2312 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2313 return -1; 2314 2315 return ShiftAmt; 2316 } 2317 2318 //===----------------------------------------------------------------------===// 2319 // Addressing Mode Selection 2320 //===----------------------------------------------------------------------===// 2321 2322 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2323 /// or 64-bit immediate, and if the value can be accurately represented as a 2324 /// sign extension from a 16-bit value. If so, this returns true and the 2325 /// immediate. 2326 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2327 if (!isa<ConstantSDNode>(N)) 2328 return false; 2329 2330 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2331 if (N->getValueType(0) == MVT::i32) 2332 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2333 else 2334 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2335 } 2336 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2337 return isIntS16Immediate(Op.getNode(), Imm); 2338 } 2339 2340 2341 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2342 /// be represented as an indexed [r+r] operation. 2343 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2344 SDValue &Index, 2345 SelectionDAG &DAG) const { 2346 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2347 UI != E; ++UI) { 2348 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2349 if (Memop->getMemoryVT() == MVT::f64) { 2350 Base = N.getOperand(0); 2351 Index = N.getOperand(1); 2352 return true; 2353 } 2354 } 2355 } 2356 return false; 2357 } 2358 2359 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2360 /// can be represented as an indexed [r+r] operation. Returns false if it 2361 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2362 /// non-zero and N can be represented by a base register plus a signed 16-bit 2363 /// displacement, make a more precise judgement by checking (displacement % \p 2364 /// EncodingAlignment). 2365 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2366 SDValue &Index, SelectionDAG &DAG, 2367 unsigned EncodingAlignment) const { 2368 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2369 // a [pc+imm]. 2370 if (SelectAddressPCRel(N, Base)) 2371 return false; 2372 2373 int16_t imm = 0; 2374 if (N.getOpcode() == ISD::ADD) { 2375 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2376 // SPE load/store can only handle 8-bit offsets. 2377 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2378 return true; 2379 if (isIntS16Immediate(N.getOperand(1), imm) && 2380 (!EncodingAlignment || !(imm % EncodingAlignment))) 2381 return false; // r+i 2382 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2383 return false; // r+i 2384 2385 Base = N.getOperand(0); 2386 Index = N.getOperand(1); 2387 return true; 2388 } else if (N.getOpcode() == ISD::OR) { 2389 if (isIntS16Immediate(N.getOperand(1), imm) && 2390 (!EncodingAlignment || !(imm % EncodingAlignment))) 2391 return false; // r+i can fold it if we can. 2392 2393 // If this is an or of disjoint bitfields, we can codegen this as an add 2394 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2395 // disjoint. 2396 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2397 2398 if (LHSKnown.Zero.getBoolValue()) { 2399 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2400 // If all of the bits are known zero on the LHS or RHS, the add won't 2401 // carry. 2402 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2403 Base = N.getOperand(0); 2404 Index = N.getOperand(1); 2405 return true; 2406 } 2407 } 2408 } 2409 2410 return false; 2411 } 2412 2413 // If we happen to be doing an i64 load or store into a stack slot that has 2414 // less than a 4-byte alignment, then the frame-index elimination may need to 2415 // use an indexed load or store instruction (because the offset may not be a 2416 // multiple of 4). The extra register needed to hold the offset comes from the 2417 // register scavenger, and it is possible that the scavenger will need to use 2418 // an emergency spill slot. As a result, we need to make sure that a spill slot 2419 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2420 // stack slot. 2421 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2422 // FIXME: This does not handle the LWA case. 2423 if (VT != MVT::i64) 2424 return; 2425 2426 // NOTE: We'll exclude negative FIs here, which come from argument 2427 // lowering, because there are no known test cases triggering this problem 2428 // using packed structures (or similar). We can remove this exclusion if 2429 // we find such a test case. The reason why this is so test-case driven is 2430 // because this entire 'fixup' is only to prevent crashes (from the 2431 // register scavenger) on not-really-valid inputs. For example, if we have: 2432 // %a = alloca i1 2433 // %b = bitcast i1* %a to i64* 2434 // store i64* a, i64 b 2435 // then the store should really be marked as 'align 1', but is not. If it 2436 // were marked as 'align 1' then the indexed form would have been 2437 // instruction-selected initially, and the problem this 'fixup' is preventing 2438 // won't happen regardless. 2439 if (FrameIdx < 0) 2440 return; 2441 2442 MachineFunction &MF = DAG.getMachineFunction(); 2443 MachineFrameInfo &MFI = MF.getFrameInfo(); 2444 2445 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2446 return; 2447 2448 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2449 FuncInfo->setHasNonRISpills(); 2450 } 2451 2452 /// Returns true if the address N can be represented by a base register plus 2453 /// a signed 16-bit displacement [r+imm], and if it is not better 2454 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2455 /// displacements that are multiples of that value. 2456 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2457 SDValue &Base, 2458 SelectionDAG &DAG, 2459 unsigned EncodingAlignment) const { 2460 // FIXME dl should come from parent load or store, not from address 2461 SDLoc dl(N); 2462 2463 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2464 // a [pc+imm]. 2465 if (SelectAddressPCRel(N, Base)) 2466 return false; 2467 2468 // If this can be more profitably realized as r+r, fail. 2469 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2470 return false; 2471 2472 if (N.getOpcode() == ISD::ADD) { 2473 int16_t imm = 0; 2474 if (isIntS16Immediate(N.getOperand(1), imm) && 2475 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2476 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2477 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2478 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2479 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2480 } else { 2481 Base = N.getOperand(0); 2482 } 2483 return true; // [r+i] 2484 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2485 // Match LOAD (ADD (X, Lo(G))). 2486 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2487 && "Cannot handle constant offsets yet!"); 2488 Disp = N.getOperand(1).getOperand(0); // The global address. 2489 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2490 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2491 Disp.getOpcode() == ISD::TargetConstantPool || 2492 Disp.getOpcode() == ISD::TargetJumpTable); 2493 Base = N.getOperand(0); 2494 return true; // [&g+r] 2495 } 2496 } else if (N.getOpcode() == ISD::OR) { 2497 int16_t imm = 0; 2498 if (isIntS16Immediate(N.getOperand(1), imm) && 2499 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2500 // If this is an or of disjoint bitfields, we can codegen this as an add 2501 // (for better address arithmetic) if the LHS and RHS of the OR are 2502 // provably disjoint. 2503 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2504 2505 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2506 // If all of the bits are known zero on the LHS or RHS, the add won't 2507 // carry. 2508 if (FrameIndexSDNode *FI = 2509 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2510 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2511 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2512 } else { 2513 Base = N.getOperand(0); 2514 } 2515 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2516 return true; 2517 } 2518 } 2519 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2520 // Loading from a constant address. 2521 2522 // If this address fits entirely in a 16-bit sext immediate field, codegen 2523 // this as "d, 0" 2524 int16_t Imm; 2525 if (isIntS16Immediate(CN, Imm) && 2526 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2527 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2528 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2529 CN->getValueType(0)); 2530 return true; 2531 } 2532 2533 // Handle 32-bit sext immediates with LIS + addr mode. 2534 if ((CN->getValueType(0) == MVT::i32 || 2535 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2536 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2537 int Addr = (int)CN->getZExtValue(); 2538 2539 // Otherwise, break this down into an LIS + disp. 2540 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2541 2542 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2543 MVT::i32); 2544 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2545 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2546 return true; 2547 } 2548 } 2549 2550 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2551 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2552 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2553 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2554 } else 2555 Base = N; 2556 return true; // [r+0] 2557 } 2558 2559 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2560 /// represented as an indexed [r+r] operation. 2561 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2562 SDValue &Index, 2563 SelectionDAG &DAG) const { 2564 // Check to see if we can easily represent this as an [r+r] address. This 2565 // will fail if it thinks that the address is more profitably represented as 2566 // reg+imm, e.g. where imm = 0. 2567 if (SelectAddressRegReg(N, Base, Index, DAG)) 2568 return true; 2569 2570 // If the address is the result of an add, we will utilize the fact that the 2571 // address calculation includes an implicit add. However, we can reduce 2572 // register pressure if we do not materialize a constant just for use as the 2573 // index register. We only get rid of the add if it is not an add of a 2574 // value and a 16-bit signed constant and both have a single use. 2575 int16_t imm = 0; 2576 if (N.getOpcode() == ISD::ADD && 2577 (!isIntS16Immediate(N.getOperand(1), imm) || 2578 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2579 Base = N.getOperand(0); 2580 Index = N.getOperand(1); 2581 return true; 2582 } 2583 2584 // Otherwise, do it the hard way, using R0 as the base register. 2585 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2586 N.getValueType()); 2587 Index = N; 2588 return true; 2589 } 2590 2591 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2592 Ty *PCRelCand = dyn_cast<Ty>(N); 2593 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2594 } 2595 2596 /// Returns true if this address is a PC Relative address. 2597 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2598 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2599 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2600 // This is a materialize PC Relative node. Always select this as PC Relative. 2601 Base = N; 2602 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2603 return true; 2604 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2605 isValidPCRelNode<GlobalAddressSDNode>(N) || 2606 isValidPCRelNode<JumpTableSDNode>(N) || 2607 isValidPCRelNode<BlockAddressSDNode>(N)) 2608 return true; 2609 return false; 2610 } 2611 2612 /// Returns true if we should use a direct load into vector instruction 2613 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2614 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2615 2616 // If there are any other uses other than scalar to vector, then we should 2617 // keep it as a scalar load -> direct move pattern to prevent multiple 2618 // loads. 2619 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2620 if (!LD) 2621 return false; 2622 2623 EVT MemVT = LD->getMemoryVT(); 2624 if (!MemVT.isSimple()) 2625 return false; 2626 switch(MemVT.getSimpleVT().SimpleTy) { 2627 case MVT::i64: 2628 break; 2629 case MVT::i32: 2630 if (!ST.hasP8Vector()) 2631 return false; 2632 break; 2633 case MVT::i16: 2634 case MVT::i8: 2635 if (!ST.hasP9Vector()) 2636 return false; 2637 break; 2638 default: 2639 return false; 2640 } 2641 2642 SDValue LoadedVal(N, 0); 2643 if (!LoadedVal.hasOneUse()) 2644 return false; 2645 2646 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2647 UI != UE; ++UI) 2648 if (UI.getUse().get().getResNo() == 0 && 2649 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2650 return false; 2651 2652 return true; 2653 } 2654 2655 /// getPreIndexedAddressParts - returns true by value, base pointer and 2656 /// offset pointer and addressing mode by reference if the node's address 2657 /// can be legally represented as pre-indexed load / store address. 2658 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2659 SDValue &Offset, 2660 ISD::MemIndexedMode &AM, 2661 SelectionDAG &DAG) const { 2662 if (DisablePPCPreinc) return false; 2663 2664 bool isLoad = true; 2665 SDValue Ptr; 2666 EVT VT; 2667 unsigned Alignment; 2668 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2669 Ptr = LD->getBasePtr(); 2670 VT = LD->getMemoryVT(); 2671 Alignment = LD->getAlignment(); 2672 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2673 Ptr = ST->getBasePtr(); 2674 VT = ST->getMemoryVT(); 2675 Alignment = ST->getAlignment(); 2676 isLoad = false; 2677 } else 2678 return false; 2679 2680 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2681 // instructions because we can fold these into a more efficient instruction 2682 // instead, (such as LXSD). 2683 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2684 return false; 2685 } 2686 2687 // PowerPC doesn't have preinc load/store instructions for vectors (except 2688 // for QPX, which does have preinc r+r forms). 2689 if (VT.isVector()) { 2690 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2691 return false; 2692 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2693 AM = ISD::PRE_INC; 2694 return true; 2695 } 2696 } 2697 2698 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2699 // Common code will reject creating a pre-inc form if the base pointer 2700 // is a frame index, or if N is a store and the base pointer is either 2701 // the same as or a predecessor of the value being stored. Check for 2702 // those situations here, and try with swapped Base/Offset instead. 2703 bool Swap = false; 2704 2705 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2706 Swap = true; 2707 else if (!isLoad) { 2708 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2709 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2710 Swap = true; 2711 } 2712 2713 if (Swap) 2714 std::swap(Base, Offset); 2715 2716 AM = ISD::PRE_INC; 2717 return true; 2718 } 2719 2720 // LDU/STU can only handle immediates that are a multiple of 4. 2721 if (VT != MVT::i64) { 2722 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2723 return false; 2724 } else { 2725 // LDU/STU need an address with at least 4-byte alignment. 2726 if (Alignment < 4) 2727 return false; 2728 2729 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2730 return false; 2731 } 2732 2733 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2734 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2735 // sext i32 to i64 when addr mode is r+i. 2736 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2737 LD->getExtensionType() == ISD::SEXTLOAD && 2738 isa<ConstantSDNode>(Offset)) 2739 return false; 2740 } 2741 2742 AM = ISD::PRE_INC; 2743 return true; 2744 } 2745 2746 //===----------------------------------------------------------------------===// 2747 // LowerOperation implementation 2748 //===----------------------------------------------------------------------===// 2749 2750 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2751 /// and LoOpFlags to the target MO flags. 2752 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2753 unsigned &HiOpFlags, unsigned &LoOpFlags, 2754 const GlobalValue *GV = nullptr) { 2755 HiOpFlags = PPCII::MO_HA; 2756 LoOpFlags = PPCII::MO_LO; 2757 2758 // Don't use the pic base if not in PIC relocation model. 2759 if (IsPIC) { 2760 HiOpFlags |= PPCII::MO_PIC_FLAG; 2761 LoOpFlags |= PPCII::MO_PIC_FLAG; 2762 } 2763 } 2764 2765 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2766 SelectionDAG &DAG) { 2767 SDLoc DL(HiPart); 2768 EVT PtrVT = HiPart.getValueType(); 2769 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2770 2771 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2772 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2773 2774 // With PIC, the first instruction is actually "GR+hi(&G)". 2775 if (isPIC) 2776 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2777 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2778 2779 // Generate non-pic code that has direct accesses to the constant pool. 2780 // The address of the global is just (hi(&g)+lo(&g)). 2781 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2782 } 2783 2784 static void setUsesTOCBasePtr(MachineFunction &MF) { 2785 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2786 FuncInfo->setUsesTOCBasePtr(); 2787 } 2788 2789 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2790 setUsesTOCBasePtr(DAG.getMachineFunction()); 2791 } 2792 2793 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2794 SDValue GA) const { 2795 const bool Is64Bit = Subtarget.isPPC64(); 2796 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2797 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2798 : Subtarget.isAIXABI() 2799 ? DAG.getRegister(PPC::R2, VT) 2800 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2801 SDValue Ops[] = { GA, Reg }; 2802 return DAG.getMemIntrinsicNode( 2803 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2804 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2805 MachineMemOperand::MOLoad); 2806 } 2807 2808 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2809 SelectionDAG &DAG) const { 2810 EVT PtrVT = Op.getValueType(); 2811 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2812 const Constant *C = CP->getConstVal(); 2813 2814 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2815 // The actual address of the GlobalValue is stored in the TOC. 2816 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2817 if (Subtarget.isUsingPCRelativeCalls()) { 2818 SDLoc DL(CP); 2819 EVT Ty = getPointerTy(DAG.getDataLayout()); 2820 SDValue ConstPool = DAG.getTargetConstantPool(C, Ty, 2821 CP->getAlignment(), 2822 CP->getOffset(), 2823 PPCII::MO_PCREL_FLAG); 2824 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2825 } 2826 setUsesTOCBasePtr(DAG); 2827 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2828 return getTOCEntry(DAG, SDLoc(CP), GA); 2829 } 2830 2831 unsigned MOHiFlag, MOLoFlag; 2832 bool IsPIC = isPositionIndependent(); 2833 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2834 2835 if (IsPIC && Subtarget.isSVR4ABI()) { 2836 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2837 PPCII::MO_PIC_FLAG); 2838 return getTOCEntry(DAG, SDLoc(CP), GA); 2839 } 2840 2841 SDValue CPIHi = 2842 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2843 SDValue CPILo = 2844 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2845 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2846 } 2847 2848 // For 64-bit PowerPC, prefer the more compact relative encodings. 2849 // This trades 32 bits per jump table entry for one or two instructions 2850 // on the jump site. 2851 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2852 if (isJumpTableRelative()) 2853 return MachineJumpTableInfo::EK_LabelDifference32; 2854 2855 return TargetLowering::getJumpTableEncoding(); 2856 } 2857 2858 bool PPCTargetLowering::isJumpTableRelative() const { 2859 if (UseAbsoluteJumpTables) 2860 return false; 2861 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2862 return true; 2863 return TargetLowering::isJumpTableRelative(); 2864 } 2865 2866 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2867 SelectionDAG &DAG) const { 2868 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2869 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2870 2871 switch (getTargetMachine().getCodeModel()) { 2872 case CodeModel::Small: 2873 case CodeModel::Medium: 2874 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2875 default: 2876 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2877 getPointerTy(DAG.getDataLayout())); 2878 } 2879 } 2880 2881 const MCExpr * 2882 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2883 unsigned JTI, 2884 MCContext &Ctx) const { 2885 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2886 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2887 2888 switch (getTargetMachine().getCodeModel()) { 2889 case CodeModel::Small: 2890 case CodeModel::Medium: 2891 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2892 default: 2893 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2894 } 2895 } 2896 2897 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2898 EVT PtrVT = Op.getValueType(); 2899 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2900 2901 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2902 if (Subtarget.isUsingPCRelativeCalls()) { 2903 SDLoc DL(JT); 2904 EVT Ty = getPointerTy(DAG.getDataLayout()); 2905 SDValue GA = 2906 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2907 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2908 return MatAddr; 2909 } 2910 2911 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2912 // The actual address of the GlobalValue is stored in the TOC. 2913 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2914 setUsesTOCBasePtr(DAG); 2915 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2916 return getTOCEntry(DAG, SDLoc(JT), GA); 2917 } 2918 2919 unsigned MOHiFlag, MOLoFlag; 2920 bool IsPIC = isPositionIndependent(); 2921 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2922 2923 if (IsPIC && Subtarget.isSVR4ABI()) { 2924 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2925 PPCII::MO_PIC_FLAG); 2926 return getTOCEntry(DAG, SDLoc(GA), GA); 2927 } 2928 2929 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2930 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2931 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2932 } 2933 2934 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2935 SelectionDAG &DAG) const { 2936 EVT PtrVT = Op.getValueType(); 2937 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2938 const BlockAddress *BA = BASDN->getBlockAddress(); 2939 2940 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2941 if (Subtarget.isUsingPCRelativeCalls()) { 2942 SDLoc DL(BASDN); 2943 EVT Ty = getPointerTy(DAG.getDataLayout()); 2944 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2945 PPCII::MO_PCREL_FLAG); 2946 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2947 return MatAddr; 2948 } 2949 2950 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2951 // The actual BlockAddress is stored in the TOC. 2952 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2953 setUsesTOCBasePtr(DAG); 2954 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2955 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2956 } 2957 2958 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2959 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2960 return getTOCEntry( 2961 DAG, SDLoc(BASDN), 2962 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2963 2964 unsigned MOHiFlag, MOLoFlag; 2965 bool IsPIC = isPositionIndependent(); 2966 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2967 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2968 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2969 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2970 } 2971 2972 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2973 SelectionDAG &DAG) const { 2974 // FIXME: TLS addresses currently use medium model code sequences, 2975 // which is the most useful form. Eventually support for small and 2976 // large models could be added if users need it, at the cost of 2977 // additional complexity. 2978 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2979 if (DAG.getTarget().useEmulatedTLS()) 2980 return LowerToTLSEmulatedModel(GA, DAG); 2981 2982 SDLoc dl(GA); 2983 const GlobalValue *GV = GA->getGlobal(); 2984 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2985 bool is64bit = Subtarget.isPPC64(); 2986 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2987 PICLevel::Level picLevel = M->getPICLevel(); 2988 2989 const TargetMachine &TM = getTargetMachine(); 2990 TLSModel::Model Model = TM.getTLSModel(GV); 2991 2992 if (Model == TLSModel::LocalExec) { 2993 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2994 PPCII::MO_TPREL_HA); 2995 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2996 PPCII::MO_TPREL_LO); 2997 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2998 : DAG.getRegister(PPC::R2, MVT::i32); 2999 3000 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3001 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3002 } 3003 3004 if (Model == TLSModel::InitialExec) { 3005 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3006 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3007 PPCII::MO_TLS); 3008 SDValue GOTPtr; 3009 if (is64bit) { 3010 setUsesTOCBasePtr(DAG); 3011 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3012 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3013 PtrVT, GOTReg, TGA); 3014 } else { 3015 if (!TM.isPositionIndependent()) 3016 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3017 else if (picLevel == PICLevel::SmallPIC) 3018 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3019 else 3020 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3021 } 3022 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3023 PtrVT, TGA, GOTPtr); 3024 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3025 } 3026 3027 if (Model == TLSModel::GeneralDynamic) { 3028 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3029 SDValue GOTPtr; 3030 if (is64bit) { 3031 setUsesTOCBasePtr(DAG); 3032 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3033 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3034 GOTReg, TGA); 3035 } else { 3036 if (picLevel == PICLevel::SmallPIC) 3037 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3038 else 3039 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3040 } 3041 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3042 GOTPtr, TGA, TGA); 3043 } 3044 3045 if (Model == TLSModel::LocalDynamic) { 3046 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3047 SDValue GOTPtr; 3048 if (is64bit) { 3049 setUsesTOCBasePtr(DAG); 3050 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3051 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3052 GOTReg, TGA); 3053 } else { 3054 if (picLevel == PICLevel::SmallPIC) 3055 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3056 else 3057 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3058 } 3059 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3060 PtrVT, GOTPtr, TGA, TGA); 3061 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3062 PtrVT, TLSAddr, TGA); 3063 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3064 } 3065 3066 llvm_unreachable("Unknown TLS model!"); 3067 } 3068 3069 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3070 SelectionDAG &DAG) const { 3071 EVT PtrVT = Op.getValueType(); 3072 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3073 SDLoc DL(GSDN); 3074 const GlobalValue *GV = GSDN->getGlobal(); 3075 3076 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3077 // The actual address of the GlobalValue is stored in the TOC. 3078 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3079 if (Subtarget.isUsingPCRelativeCalls()) { 3080 EVT Ty = getPointerTy(DAG.getDataLayout()); 3081 if (isAccessedAsGotIndirect(Op)) { 3082 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3083 PPCII::MO_PCREL_FLAG | 3084 PPCII::MO_GOT_FLAG); 3085 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3086 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3087 MachinePointerInfo()); 3088 return Load; 3089 } else { 3090 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3091 PPCII::MO_PCREL_FLAG); 3092 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3093 } 3094 } 3095 setUsesTOCBasePtr(DAG); 3096 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3097 return getTOCEntry(DAG, DL, GA); 3098 } 3099 3100 unsigned MOHiFlag, MOLoFlag; 3101 bool IsPIC = isPositionIndependent(); 3102 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3103 3104 if (IsPIC && Subtarget.isSVR4ABI()) { 3105 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3106 GSDN->getOffset(), 3107 PPCII::MO_PIC_FLAG); 3108 return getTOCEntry(DAG, DL, GA); 3109 } 3110 3111 SDValue GAHi = 3112 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3113 SDValue GALo = 3114 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3115 3116 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3117 } 3118 3119 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3120 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3121 SDLoc dl(Op); 3122 3123 if (Op.getValueType() == MVT::v2i64) { 3124 // When the operands themselves are v2i64 values, we need to do something 3125 // special because VSX has no underlying comparison operations for these. 3126 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3127 // Equality can be handled by casting to the legal type for Altivec 3128 // comparisons, everything else needs to be expanded. 3129 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3130 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3131 DAG.getSetCC(dl, MVT::v4i32, 3132 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3133 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3134 CC)); 3135 } 3136 3137 return SDValue(); 3138 } 3139 3140 // We handle most of these in the usual way. 3141 return Op; 3142 } 3143 3144 // If we're comparing for equality to zero, expose the fact that this is 3145 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3146 // fold the new nodes. 3147 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3148 return V; 3149 3150 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3151 // Leave comparisons against 0 and -1 alone for now, since they're usually 3152 // optimized. FIXME: revisit this when we can custom lower all setcc 3153 // optimizations. 3154 if (C->isAllOnesValue() || C->isNullValue()) 3155 return SDValue(); 3156 } 3157 3158 // If we have an integer seteq/setne, turn it into a compare against zero 3159 // by xor'ing the rhs with the lhs, which is faster than setting a 3160 // condition register, reading it back out, and masking the correct bit. The 3161 // normal approach here uses sub to do this instead of xor. Using xor exposes 3162 // the result to other bit-twiddling opportunities. 3163 EVT LHSVT = Op.getOperand(0).getValueType(); 3164 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3165 EVT VT = Op.getValueType(); 3166 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3167 Op.getOperand(1)); 3168 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3169 } 3170 return SDValue(); 3171 } 3172 3173 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3174 SDNode *Node = Op.getNode(); 3175 EVT VT = Node->getValueType(0); 3176 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3177 SDValue InChain = Node->getOperand(0); 3178 SDValue VAListPtr = Node->getOperand(1); 3179 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3180 SDLoc dl(Node); 3181 3182 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3183 3184 // gpr_index 3185 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3186 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3187 InChain = GprIndex.getValue(1); 3188 3189 if (VT == MVT::i64) { 3190 // Check if GprIndex is even 3191 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3192 DAG.getConstant(1, dl, MVT::i32)); 3193 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3194 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3195 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3196 DAG.getConstant(1, dl, MVT::i32)); 3197 // Align GprIndex to be even if it isn't 3198 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3199 GprIndex); 3200 } 3201 3202 // fpr index is 1 byte after gpr 3203 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3204 DAG.getConstant(1, dl, MVT::i32)); 3205 3206 // fpr 3207 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3208 FprPtr, MachinePointerInfo(SV), MVT::i8); 3209 InChain = FprIndex.getValue(1); 3210 3211 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3212 DAG.getConstant(8, dl, MVT::i32)); 3213 3214 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3215 DAG.getConstant(4, dl, MVT::i32)); 3216 3217 // areas 3218 SDValue OverflowArea = 3219 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3220 InChain = OverflowArea.getValue(1); 3221 3222 SDValue RegSaveArea = 3223 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3224 InChain = RegSaveArea.getValue(1); 3225 3226 // select overflow_area if index > 8 3227 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3228 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3229 3230 // adjustment constant gpr_index * 4/8 3231 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3232 VT.isInteger() ? GprIndex : FprIndex, 3233 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3234 MVT::i32)); 3235 3236 // OurReg = RegSaveArea + RegConstant 3237 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3238 RegConstant); 3239 3240 // Floating types are 32 bytes into RegSaveArea 3241 if (VT.isFloatingPoint()) 3242 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3243 DAG.getConstant(32, dl, MVT::i32)); 3244 3245 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3246 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3247 VT.isInteger() ? GprIndex : FprIndex, 3248 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3249 MVT::i32)); 3250 3251 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3252 VT.isInteger() ? VAListPtr : FprPtr, 3253 MachinePointerInfo(SV), MVT::i8); 3254 3255 // determine if we should load from reg_save_area or overflow_area 3256 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3257 3258 // increase overflow_area by 4/8 if gpr/fpr > 8 3259 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3260 DAG.getConstant(VT.isInteger() ? 4 : 8, 3261 dl, MVT::i32)); 3262 3263 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3264 OverflowAreaPlusN); 3265 3266 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3267 MachinePointerInfo(), MVT::i32); 3268 3269 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3270 } 3271 3272 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3273 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3274 3275 // We have to copy the entire va_list struct: 3276 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3277 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3278 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3279 false, true, false, MachinePointerInfo(), 3280 MachinePointerInfo()); 3281 } 3282 3283 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3284 SelectionDAG &DAG) const { 3285 if (Subtarget.isAIXABI()) 3286 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3287 3288 return Op.getOperand(0); 3289 } 3290 3291 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3292 SelectionDAG &DAG) const { 3293 if (Subtarget.isAIXABI()) 3294 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3295 3296 SDValue Chain = Op.getOperand(0); 3297 SDValue Trmp = Op.getOperand(1); // trampoline 3298 SDValue FPtr = Op.getOperand(2); // nested function 3299 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3300 SDLoc dl(Op); 3301 3302 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3303 bool isPPC64 = (PtrVT == MVT::i64); 3304 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3305 3306 TargetLowering::ArgListTy Args; 3307 TargetLowering::ArgListEntry Entry; 3308 3309 Entry.Ty = IntPtrTy; 3310 Entry.Node = Trmp; Args.push_back(Entry); 3311 3312 // TrampSize == (isPPC64 ? 48 : 40); 3313 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3314 isPPC64 ? MVT::i64 : MVT::i32); 3315 Args.push_back(Entry); 3316 3317 Entry.Node = FPtr; Args.push_back(Entry); 3318 Entry.Node = Nest; Args.push_back(Entry); 3319 3320 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3321 TargetLowering::CallLoweringInfo CLI(DAG); 3322 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3323 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3324 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3325 3326 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3327 return CallResult.second; 3328 } 3329 3330 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3331 MachineFunction &MF = DAG.getMachineFunction(); 3332 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3333 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3334 3335 SDLoc dl(Op); 3336 3337 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3338 // vastart just stores the address of the VarArgsFrameIndex slot into the 3339 // memory location argument. 3340 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3341 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3342 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3343 MachinePointerInfo(SV)); 3344 } 3345 3346 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3347 // We suppose the given va_list is already allocated. 3348 // 3349 // typedef struct { 3350 // char gpr; /* index into the array of 8 GPRs 3351 // * stored in the register save area 3352 // * gpr=0 corresponds to r3, 3353 // * gpr=1 to r4, etc. 3354 // */ 3355 // char fpr; /* index into the array of 8 FPRs 3356 // * stored in the register save area 3357 // * fpr=0 corresponds to f1, 3358 // * fpr=1 to f2, etc. 3359 // */ 3360 // char *overflow_arg_area; 3361 // /* location on stack that holds 3362 // * the next overflow argument 3363 // */ 3364 // char *reg_save_area; 3365 // /* where r3:r10 and f1:f8 (if saved) 3366 // * are stored 3367 // */ 3368 // } va_list[1]; 3369 3370 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3371 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3372 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3373 PtrVT); 3374 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3375 PtrVT); 3376 3377 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3378 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3379 3380 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3381 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3382 3383 uint64_t FPROffset = 1; 3384 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3385 3386 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3387 3388 // Store first byte : number of int regs 3389 SDValue firstStore = 3390 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3391 MachinePointerInfo(SV), MVT::i8); 3392 uint64_t nextOffset = FPROffset; 3393 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3394 ConstFPROffset); 3395 3396 // Store second byte : number of float regs 3397 SDValue secondStore = 3398 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3399 MachinePointerInfo(SV, nextOffset), MVT::i8); 3400 nextOffset += StackOffset; 3401 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3402 3403 // Store second word : arguments given on stack 3404 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3405 MachinePointerInfo(SV, nextOffset)); 3406 nextOffset += FrameOffset; 3407 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3408 3409 // Store third word : arguments given in registers 3410 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3411 MachinePointerInfo(SV, nextOffset)); 3412 } 3413 3414 /// FPR - The set of FP registers that should be allocated for arguments 3415 /// on Darwin and AIX. 3416 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3417 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3418 PPC::F11, PPC::F12, PPC::F13}; 3419 3420 /// QFPR - The set of QPX registers that should be allocated for arguments. 3421 static const MCPhysReg QFPR[] = { 3422 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3423 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3424 3425 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3426 /// the stack. 3427 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3428 unsigned PtrByteSize) { 3429 unsigned ArgSize = ArgVT.getStoreSize(); 3430 if (Flags.isByVal()) 3431 ArgSize = Flags.getByValSize(); 3432 3433 // Round up to multiples of the pointer size, except for array members, 3434 // which are always packed. 3435 if (!Flags.isInConsecutiveRegs()) 3436 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3437 3438 return ArgSize; 3439 } 3440 3441 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3442 /// on the stack. 3443 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3444 ISD::ArgFlagsTy Flags, 3445 unsigned PtrByteSize) { 3446 Align Alignment(PtrByteSize); 3447 3448 // Altivec parameters are padded to a 16 byte boundary. 3449 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3450 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3451 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3452 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3453 Alignment = Align(16); 3454 // QPX vector types stored in double-precision are padded to a 32 byte 3455 // boundary. 3456 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3457 Alignment = Align(32); 3458 3459 // ByVal parameters are aligned as requested. 3460 if (Flags.isByVal()) { 3461 auto BVAlign = Flags.getNonZeroByValAlign(); 3462 if (BVAlign > PtrByteSize) { 3463 if (BVAlign.value() % PtrByteSize != 0) 3464 llvm_unreachable( 3465 "ByVal alignment is not a multiple of the pointer size"); 3466 3467 Alignment = BVAlign; 3468 } 3469 } 3470 3471 // Array members are always packed to their original alignment. 3472 if (Flags.isInConsecutiveRegs()) { 3473 // If the array member was split into multiple registers, the first 3474 // needs to be aligned to the size of the full type. (Except for 3475 // ppcf128, which is only aligned as its f64 components.) 3476 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3477 Alignment = Align(OrigVT.getStoreSize()); 3478 else 3479 Alignment = Align(ArgVT.getStoreSize()); 3480 } 3481 3482 return Alignment; 3483 } 3484 3485 /// CalculateStackSlotUsed - Return whether this argument will use its 3486 /// stack slot (instead of being passed in registers). ArgOffset, 3487 /// AvailableFPRs, and AvailableVRs must hold the current argument 3488 /// position, and will be updated to account for this argument. 3489 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3490 ISD::ArgFlagsTy Flags, 3491 unsigned PtrByteSize, 3492 unsigned LinkageSize, 3493 unsigned ParamAreaSize, 3494 unsigned &ArgOffset, 3495 unsigned &AvailableFPRs, 3496 unsigned &AvailableVRs, bool HasQPX) { 3497 bool UseMemory = false; 3498 3499 // Respect alignment of argument on the stack. 3500 Align Alignment = 3501 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3502 ArgOffset = alignTo(ArgOffset, Alignment); 3503 // If there's no space left in the argument save area, we must 3504 // use memory (this check also catches zero-sized arguments). 3505 if (ArgOffset >= LinkageSize + ParamAreaSize) 3506 UseMemory = true; 3507 3508 // Allocate argument on the stack. 3509 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3510 if (Flags.isInConsecutiveRegsLast()) 3511 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3512 // If we overran the argument save area, we must use memory 3513 // (this check catches arguments passed partially in memory) 3514 if (ArgOffset > LinkageSize + ParamAreaSize) 3515 UseMemory = true; 3516 3517 // However, if the argument is actually passed in an FPR or a VR, 3518 // we don't use memory after all. 3519 if (!Flags.isByVal()) { 3520 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3521 // QPX registers overlap with the scalar FP registers. 3522 (HasQPX && (ArgVT == MVT::v4f32 || 3523 ArgVT == MVT::v4f64 || 3524 ArgVT == MVT::v4i1))) 3525 if (AvailableFPRs > 0) { 3526 --AvailableFPRs; 3527 return false; 3528 } 3529 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3530 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3531 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3532 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3533 if (AvailableVRs > 0) { 3534 --AvailableVRs; 3535 return false; 3536 } 3537 } 3538 3539 return UseMemory; 3540 } 3541 3542 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3543 /// ensure minimum alignment required for target. 3544 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3545 unsigned NumBytes) { 3546 return alignTo(NumBytes, Lowering->getStackAlign()); 3547 } 3548 3549 SDValue PPCTargetLowering::LowerFormalArguments( 3550 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3551 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3552 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3553 if (Subtarget.isAIXABI()) 3554 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3555 InVals); 3556 if (Subtarget.is64BitELFABI()) 3557 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3558 InVals); 3559 if (Subtarget.is32BitELFABI()) 3560 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3561 InVals); 3562 3563 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3564 InVals); 3565 } 3566 3567 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3568 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3569 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3570 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3571 3572 // 32-bit SVR4 ABI Stack Frame Layout: 3573 // +-----------------------------------+ 3574 // +--> | Back chain | 3575 // | +-----------------------------------+ 3576 // | | Floating-point register save area | 3577 // | +-----------------------------------+ 3578 // | | General register save area | 3579 // | +-----------------------------------+ 3580 // | | CR save word | 3581 // | +-----------------------------------+ 3582 // | | VRSAVE save word | 3583 // | +-----------------------------------+ 3584 // | | Alignment padding | 3585 // | +-----------------------------------+ 3586 // | | Vector register save area | 3587 // | +-----------------------------------+ 3588 // | | Local variable space | 3589 // | +-----------------------------------+ 3590 // | | Parameter list area | 3591 // | +-----------------------------------+ 3592 // | | LR save word | 3593 // | +-----------------------------------+ 3594 // SP--> +--- | Back chain | 3595 // +-----------------------------------+ 3596 // 3597 // Specifications: 3598 // System V Application Binary Interface PowerPC Processor Supplement 3599 // AltiVec Technology Programming Interface Manual 3600 3601 MachineFunction &MF = DAG.getMachineFunction(); 3602 MachineFrameInfo &MFI = MF.getFrameInfo(); 3603 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3604 3605 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3606 // Potential tail calls could cause overwriting of argument stack slots. 3607 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3608 (CallConv == CallingConv::Fast)); 3609 unsigned PtrByteSize = 4; 3610 3611 // Assign locations to all of the incoming arguments. 3612 SmallVector<CCValAssign, 16> ArgLocs; 3613 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3614 *DAG.getContext()); 3615 3616 // Reserve space for the linkage area on the stack. 3617 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3618 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3619 if (useSoftFloat()) 3620 CCInfo.PreAnalyzeFormalArguments(Ins); 3621 3622 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3623 CCInfo.clearWasPPCF128(); 3624 3625 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3626 CCValAssign &VA = ArgLocs[i]; 3627 3628 // Arguments stored in registers. 3629 if (VA.isRegLoc()) { 3630 const TargetRegisterClass *RC; 3631 EVT ValVT = VA.getValVT(); 3632 3633 switch (ValVT.getSimpleVT().SimpleTy) { 3634 default: 3635 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3636 case MVT::i1: 3637 case MVT::i32: 3638 RC = &PPC::GPRCRegClass; 3639 break; 3640 case MVT::f32: 3641 if (Subtarget.hasP8Vector()) 3642 RC = &PPC::VSSRCRegClass; 3643 else if (Subtarget.hasSPE()) 3644 RC = &PPC::GPRCRegClass; 3645 else 3646 RC = &PPC::F4RCRegClass; 3647 break; 3648 case MVT::f64: 3649 if (Subtarget.hasVSX()) 3650 RC = &PPC::VSFRCRegClass; 3651 else if (Subtarget.hasSPE()) 3652 // SPE passes doubles in GPR pairs. 3653 RC = &PPC::GPRCRegClass; 3654 else 3655 RC = &PPC::F8RCRegClass; 3656 break; 3657 case MVT::v16i8: 3658 case MVT::v8i16: 3659 case MVT::v4i32: 3660 RC = &PPC::VRRCRegClass; 3661 break; 3662 case MVT::v4f32: 3663 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3664 break; 3665 case MVT::v2f64: 3666 case MVT::v2i64: 3667 RC = &PPC::VRRCRegClass; 3668 break; 3669 case MVT::v4f64: 3670 RC = &PPC::QFRCRegClass; 3671 break; 3672 case MVT::v4i1: 3673 RC = &PPC::QBRCRegClass; 3674 break; 3675 } 3676 3677 SDValue ArgValue; 3678 // Transform the arguments stored in physical registers into 3679 // virtual ones. 3680 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3681 assert(i + 1 < e && "No second half of double precision argument"); 3682 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3683 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3684 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3685 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3686 if (!Subtarget.isLittleEndian()) 3687 std::swap (ArgValueLo, ArgValueHi); 3688 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3689 ArgValueHi); 3690 } else { 3691 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3692 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3693 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3694 if (ValVT == MVT::i1) 3695 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3696 } 3697 3698 InVals.push_back(ArgValue); 3699 } else { 3700 // Argument stored in memory. 3701 assert(VA.isMemLoc()); 3702 3703 // Get the extended size of the argument type in stack 3704 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3705 // Get the actual size of the argument type 3706 unsigned ObjSize = VA.getValVT().getStoreSize(); 3707 unsigned ArgOffset = VA.getLocMemOffset(); 3708 // Stack objects in PPC32 are right justified. 3709 ArgOffset += ArgSize - ObjSize; 3710 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3711 3712 // Create load nodes to retrieve arguments from the stack. 3713 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3714 InVals.push_back( 3715 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3716 } 3717 } 3718 3719 // Assign locations to all of the incoming aggregate by value arguments. 3720 // Aggregates passed by value are stored in the local variable space of the 3721 // caller's stack frame, right above the parameter list area. 3722 SmallVector<CCValAssign, 16> ByValArgLocs; 3723 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3724 ByValArgLocs, *DAG.getContext()); 3725 3726 // Reserve stack space for the allocations in CCInfo. 3727 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3728 3729 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3730 3731 // Area that is at least reserved in the caller of this function. 3732 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3733 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3734 3735 // Set the size that is at least reserved in caller of this function. Tail 3736 // call optimized function's reserved stack space needs to be aligned so that 3737 // taking the difference between two stack areas will result in an aligned 3738 // stack. 3739 MinReservedArea = 3740 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3741 FuncInfo->setMinReservedArea(MinReservedArea); 3742 3743 SmallVector<SDValue, 8> MemOps; 3744 3745 // If the function takes variable number of arguments, make a frame index for 3746 // the start of the first vararg value... for expansion of llvm.va_start. 3747 if (isVarArg) { 3748 static const MCPhysReg GPArgRegs[] = { 3749 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3750 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3751 }; 3752 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3753 3754 static const MCPhysReg FPArgRegs[] = { 3755 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3756 PPC::F8 3757 }; 3758 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3759 3760 if (useSoftFloat() || hasSPE()) 3761 NumFPArgRegs = 0; 3762 3763 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3764 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3765 3766 // Make room for NumGPArgRegs and NumFPArgRegs. 3767 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3768 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3769 3770 FuncInfo->setVarArgsStackOffset( 3771 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3772 CCInfo.getNextStackOffset(), true)); 3773 3774 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3775 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3776 3777 // The fixed integer arguments of a variadic function are stored to the 3778 // VarArgsFrameIndex on the stack so that they may be loaded by 3779 // dereferencing the result of va_next. 3780 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3781 // Get an existing live-in vreg, or add a new one. 3782 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3783 if (!VReg) 3784 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3785 3786 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3787 SDValue Store = 3788 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3789 MemOps.push_back(Store); 3790 // Increment the address by four for the next argument to store 3791 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3792 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3793 } 3794 3795 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3796 // is set. 3797 // The double arguments are stored to the VarArgsFrameIndex 3798 // on the stack. 3799 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3800 // Get an existing live-in vreg, or add a new one. 3801 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3802 if (!VReg) 3803 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3804 3805 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3806 SDValue Store = 3807 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3808 MemOps.push_back(Store); 3809 // Increment the address by eight for the next argument to store 3810 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3811 PtrVT); 3812 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3813 } 3814 } 3815 3816 if (!MemOps.empty()) 3817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3818 3819 return Chain; 3820 } 3821 3822 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3823 // value to MVT::i64 and then truncate to the correct register size. 3824 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3825 EVT ObjectVT, SelectionDAG &DAG, 3826 SDValue ArgVal, 3827 const SDLoc &dl) const { 3828 if (Flags.isSExt()) 3829 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3830 DAG.getValueType(ObjectVT)); 3831 else if (Flags.isZExt()) 3832 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3833 DAG.getValueType(ObjectVT)); 3834 3835 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3836 } 3837 3838 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3839 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3840 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3841 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3842 // TODO: add description of PPC stack frame format, or at least some docs. 3843 // 3844 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3845 bool isLittleEndian = Subtarget.isLittleEndian(); 3846 MachineFunction &MF = DAG.getMachineFunction(); 3847 MachineFrameInfo &MFI = MF.getFrameInfo(); 3848 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3849 3850 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3851 "fastcc not supported on varargs functions"); 3852 3853 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3854 // Potential tail calls could cause overwriting of argument stack slots. 3855 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3856 (CallConv == CallingConv::Fast)); 3857 unsigned PtrByteSize = 8; 3858 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3859 3860 static const MCPhysReg GPR[] = { 3861 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3862 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3863 }; 3864 static const MCPhysReg VR[] = { 3865 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3866 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3867 }; 3868 3869 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3870 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3871 const unsigned Num_VR_Regs = array_lengthof(VR); 3872 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3873 3874 // Do a first pass over the arguments to determine whether the ABI 3875 // guarantees that our caller has allocated the parameter save area 3876 // on its stack frame. In the ELFv1 ABI, this is always the case; 3877 // in the ELFv2 ABI, it is true if this is a vararg function or if 3878 // any parameter is located in a stack slot. 3879 3880 bool HasParameterArea = !isELFv2ABI || isVarArg; 3881 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3882 unsigned NumBytes = LinkageSize; 3883 unsigned AvailableFPRs = Num_FPR_Regs; 3884 unsigned AvailableVRs = Num_VR_Regs; 3885 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3886 if (Ins[i].Flags.isNest()) 3887 continue; 3888 3889 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3890 PtrByteSize, LinkageSize, ParamAreaSize, 3891 NumBytes, AvailableFPRs, AvailableVRs, 3892 Subtarget.hasQPX())) 3893 HasParameterArea = true; 3894 } 3895 3896 // Add DAG nodes to load the arguments or copy them out of registers. On 3897 // entry to a function on PPC, the arguments start after the linkage area, 3898 // although the first ones are often in registers. 3899 3900 unsigned ArgOffset = LinkageSize; 3901 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3902 unsigned &QFPR_idx = FPR_idx; 3903 SmallVector<SDValue, 8> MemOps; 3904 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3905 unsigned CurArgIdx = 0; 3906 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3907 SDValue ArgVal; 3908 bool needsLoad = false; 3909 EVT ObjectVT = Ins[ArgNo].VT; 3910 EVT OrigVT = Ins[ArgNo].ArgVT; 3911 unsigned ObjSize = ObjectVT.getStoreSize(); 3912 unsigned ArgSize = ObjSize; 3913 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3914 if (Ins[ArgNo].isOrigArg()) { 3915 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3916 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3917 } 3918 // We re-align the argument offset for each argument, except when using the 3919 // fast calling convention, when we need to make sure we do that only when 3920 // we'll actually use a stack slot. 3921 unsigned CurArgOffset; 3922 Align Alignment; 3923 auto ComputeArgOffset = [&]() { 3924 /* Respect alignment of argument on the stack. */ 3925 Alignment = 3926 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3927 ArgOffset = alignTo(ArgOffset, Alignment); 3928 CurArgOffset = ArgOffset; 3929 }; 3930 3931 if (CallConv != CallingConv::Fast) { 3932 ComputeArgOffset(); 3933 3934 /* Compute GPR index associated with argument offset. */ 3935 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3936 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3937 } 3938 3939 // FIXME the codegen can be much improved in some cases. 3940 // We do not have to keep everything in memory. 3941 if (Flags.isByVal()) { 3942 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3943 3944 if (CallConv == CallingConv::Fast) 3945 ComputeArgOffset(); 3946 3947 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3948 ObjSize = Flags.getByValSize(); 3949 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3950 // Empty aggregate parameters do not take up registers. Examples: 3951 // struct { } a; 3952 // union { } b; 3953 // int c[0]; 3954 // etc. However, we have to provide a place-holder in InVals, so 3955 // pretend we have an 8-byte item at the current address for that 3956 // purpose. 3957 if (!ObjSize) { 3958 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3959 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3960 InVals.push_back(FIN); 3961 continue; 3962 } 3963 3964 // Create a stack object covering all stack doublewords occupied 3965 // by the argument. If the argument is (fully or partially) on 3966 // the stack, or if the argument is fully in registers but the 3967 // caller has allocated the parameter save anyway, we can refer 3968 // directly to the caller's stack frame. Otherwise, create a 3969 // local copy in our own frame. 3970 int FI; 3971 if (HasParameterArea || 3972 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3973 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3974 else 3975 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3976 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3977 3978 // Handle aggregates smaller than 8 bytes. 3979 if (ObjSize < PtrByteSize) { 3980 // The value of the object is its address, which differs from the 3981 // address of the enclosing doubleword on big-endian systems. 3982 SDValue Arg = FIN; 3983 if (!isLittleEndian) { 3984 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3985 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3986 } 3987 InVals.push_back(Arg); 3988 3989 if (GPR_idx != Num_GPR_Regs) { 3990 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3991 FuncInfo->addLiveInAttr(VReg, Flags); 3992 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3993 SDValue Store; 3994 3995 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3996 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3997 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3998 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3999 MachinePointerInfo(&*FuncArg), ObjType); 4000 } else { 4001 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4002 // store the whole register as-is to the parameter save area 4003 // slot. 4004 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4005 MachinePointerInfo(&*FuncArg)); 4006 } 4007 4008 MemOps.push_back(Store); 4009 } 4010 // Whether we copied from a register or not, advance the offset 4011 // into the parameter save area by a full doubleword. 4012 ArgOffset += PtrByteSize; 4013 continue; 4014 } 4015 4016 // The value of the object is its address, which is the address of 4017 // its first stack doubleword. 4018 InVals.push_back(FIN); 4019 4020 // Store whatever pieces of the object are in registers to memory. 4021 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4022 if (GPR_idx == Num_GPR_Regs) 4023 break; 4024 4025 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4026 FuncInfo->addLiveInAttr(VReg, Flags); 4027 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4028 SDValue Addr = FIN; 4029 if (j) { 4030 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4031 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4032 } 4033 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4034 MachinePointerInfo(&*FuncArg, j)); 4035 MemOps.push_back(Store); 4036 ++GPR_idx; 4037 } 4038 ArgOffset += ArgSize; 4039 continue; 4040 } 4041 4042 switch (ObjectVT.getSimpleVT().SimpleTy) { 4043 default: llvm_unreachable("Unhandled argument type!"); 4044 case MVT::i1: 4045 case MVT::i32: 4046 case MVT::i64: 4047 if (Flags.isNest()) { 4048 // The 'nest' parameter, if any, is passed in R11. 4049 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4050 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4051 4052 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4053 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4054 4055 break; 4056 } 4057 4058 // These can be scalar arguments or elements of an integer array type 4059 // passed directly. Clang may use those instead of "byval" aggregate 4060 // types to avoid forcing arguments to memory unnecessarily. 4061 if (GPR_idx != Num_GPR_Regs) { 4062 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4063 FuncInfo->addLiveInAttr(VReg, Flags); 4064 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4065 4066 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4067 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4068 // value to MVT::i64 and then truncate to the correct register size. 4069 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4070 } else { 4071 if (CallConv == CallingConv::Fast) 4072 ComputeArgOffset(); 4073 4074 needsLoad = true; 4075 ArgSize = PtrByteSize; 4076 } 4077 if (CallConv != CallingConv::Fast || needsLoad) 4078 ArgOffset += 8; 4079 break; 4080 4081 case MVT::f32: 4082 case MVT::f64: 4083 // These can be scalar arguments or elements of a float array type 4084 // passed directly. The latter are used to implement ELFv2 homogenous 4085 // float aggregates. 4086 if (FPR_idx != Num_FPR_Regs) { 4087 unsigned VReg; 4088 4089 if (ObjectVT == MVT::f32) 4090 VReg = MF.addLiveIn(FPR[FPR_idx], 4091 Subtarget.hasP8Vector() 4092 ? &PPC::VSSRCRegClass 4093 : &PPC::F4RCRegClass); 4094 else 4095 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4096 ? &PPC::VSFRCRegClass 4097 : &PPC::F8RCRegClass); 4098 4099 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4100 ++FPR_idx; 4101 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4102 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4103 // once we support fp <-> gpr moves. 4104 4105 // This can only ever happen in the presence of f32 array types, 4106 // since otherwise we never run out of FPRs before running out 4107 // of GPRs. 4108 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4109 FuncInfo->addLiveInAttr(VReg, Flags); 4110 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4111 4112 if (ObjectVT == MVT::f32) { 4113 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4114 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4115 DAG.getConstant(32, dl, MVT::i32)); 4116 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4117 } 4118 4119 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4120 } else { 4121 if (CallConv == CallingConv::Fast) 4122 ComputeArgOffset(); 4123 4124 needsLoad = true; 4125 } 4126 4127 // When passing an array of floats, the array occupies consecutive 4128 // space in the argument area; only round up to the next doubleword 4129 // at the end of the array. Otherwise, each float takes 8 bytes. 4130 if (CallConv != CallingConv::Fast || needsLoad) { 4131 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4132 ArgOffset += ArgSize; 4133 if (Flags.isInConsecutiveRegsLast()) 4134 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4135 } 4136 break; 4137 case MVT::v4f32: 4138 case MVT::v4i32: 4139 case MVT::v8i16: 4140 case MVT::v16i8: 4141 case MVT::v2f64: 4142 case MVT::v2i64: 4143 case MVT::v1i128: 4144 case MVT::f128: 4145 if (!Subtarget.hasQPX()) { 4146 // These can be scalar arguments or elements of a vector array type 4147 // passed directly. The latter are used to implement ELFv2 homogenous 4148 // vector aggregates. 4149 if (VR_idx != Num_VR_Regs) { 4150 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4151 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4152 ++VR_idx; 4153 } else { 4154 if (CallConv == CallingConv::Fast) 4155 ComputeArgOffset(); 4156 needsLoad = true; 4157 } 4158 if (CallConv != CallingConv::Fast || needsLoad) 4159 ArgOffset += 16; 4160 break; 4161 } // not QPX 4162 4163 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4164 "Invalid QPX parameter type"); 4165 LLVM_FALLTHROUGH; 4166 4167 case MVT::v4f64: 4168 case MVT::v4i1: 4169 // QPX vectors are treated like their scalar floating-point subregisters 4170 // (except that they're larger). 4171 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4172 if (QFPR_idx != Num_QFPR_Regs) { 4173 const TargetRegisterClass *RC; 4174 switch (ObjectVT.getSimpleVT().SimpleTy) { 4175 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4176 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4177 default: RC = &PPC::QBRCRegClass; break; 4178 } 4179 4180 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4181 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4182 ++QFPR_idx; 4183 } else { 4184 if (CallConv == CallingConv::Fast) 4185 ComputeArgOffset(); 4186 needsLoad = true; 4187 } 4188 if (CallConv != CallingConv::Fast || needsLoad) 4189 ArgOffset += Sz; 4190 break; 4191 } 4192 4193 // We need to load the argument to a virtual register if we determined 4194 // above that we ran out of physical registers of the appropriate type. 4195 if (needsLoad) { 4196 if (ObjSize < ArgSize && !isLittleEndian) 4197 CurArgOffset += ArgSize - ObjSize; 4198 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4199 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4200 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4201 } 4202 4203 InVals.push_back(ArgVal); 4204 } 4205 4206 // Area that is at least reserved in the caller of this function. 4207 unsigned MinReservedArea; 4208 if (HasParameterArea) 4209 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4210 else 4211 MinReservedArea = LinkageSize; 4212 4213 // Set the size that is at least reserved in caller of this function. Tail 4214 // call optimized functions' reserved stack space needs to be aligned so that 4215 // taking the difference between two stack areas will result in an aligned 4216 // stack. 4217 MinReservedArea = 4218 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4219 FuncInfo->setMinReservedArea(MinReservedArea); 4220 4221 // If the function takes variable number of arguments, make a frame index for 4222 // the start of the first vararg value... for expansion of llvm.va_start. 4223 if (isVarArg) { 4224 int Depth = ArgOffset; 4225 4226 FuncInfo->setVarArgsFrameIndex( 4227 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4228 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4229 4230 // If this function is vararg, store any remaining integer argument regs 4231 // to their spots on the stack so that they may be loaded by dereferencing 4232 // the result of va_next. 4233 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4234 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4235 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4236 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4237 SDValue Store = 4238 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4239 MemOps.push_back(Store); 4240 // Increment the address by four for the next argument to store 4241 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4242 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4243 } 4244 } 4245 4246 if (!MemOps.empty()) 4247 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4248 4249 return Chain; 4250 } 4251 4252 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4253 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4254 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4255 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4256 // TODO: add description of PPC stack frame format, or at least some docs. 4257 // 4258 MachineFunction &MF = DAG.getMachineFunction(); 4259 MachineFrameInfo &MFI = MF.getFrameInfo(); 4260 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4261 4262 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4263 bool isPPC64 = PtrVT == MVT::i64; 4264 // Potential tail calls could cause overwriting of argument stack slots. 4265 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4266 (CallConv == CallingConv::Fast)); 4267 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4268 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4269 unsigned ArgOffset = LinkageSize; 4270 // Area that is at least reserved in caller of this function. 4271 unsigned MinReservedArea = ArgOffset; 4272 4273 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4274 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4275 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4276 }; 4277 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4278 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4279 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4280 }; 4281 static const MCPhysReg VR[] = { 4282 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4283 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4284 }; 4285 4286 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4287 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4288 const unsigned Num_VR_Regs = array_lengthof( VR); 4289 4290 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4291 4292 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4293 4294 // In 32-bit non-varargs functions, the stack space for vectors is after the 4295 // stack space for non-vectors. We do not use this space unless we have 4296 // too many vectors to fit in registers, something that only occurs in 4297 // constructed examples:), but we have to walk the arglist to figure 4298 // that out...for the pathological case, compute VecArgOffset as the 4299 // start of the vector parameter area. Computing VecArgOffset is the 4300 // entire point of the following loop. 4301 unsigned VecArgOffset = ArgOffset; 4302 if (!isVarArg && !isPPC64) { 4303 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4304 ++ArgNo) { 4305 EVT ObjectVT = Ins[ArgNo].VT; 4306 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4307 4308 if (Flags.isByVal()) { 4309 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4310 unsigned ObjSize = Flags.getByValSize(); 4311 unsigned ArgSize = 4312 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4313 VecArgOffset += ArgSize; 4314 continue; 4315 } 4316 4317 switch(ObjectVT.getSimpleVT().SimpleTy) { 4318 default: llvm_unreachable("Unhandled argument type!"); 4319 case MVT::i1: 4320 case MVT::i32: 4321 case MVT::f32: 4322 VecArgOffset += 4; 4323 break; 4324 case MVT::i64: // PPC64 4325 case MVT::f64: 4326 // FIXME: We are guaranteed to be !isPPC64 at this point. 4327 // Does MVT::i64 apply? 4328 VecArgOffset += 8; 4329 break; 4330 case MVT::v4f32: 4331 case MVT::v4i32: 4332 case MVT::v8i16: 4333 case MVT::v16i8: 4334 // Nothing to do, we're only looking at Nonvector args here. 4335 break; 4336 } 4337 } 4338 } 4339 // We've found where the vector parameter area in memory is. Skip the 4340 // first 12 parameters; these don't use that memory. 4341 VecArgOffset = ((VecArgOffset+15)/16)*16; 4342 VecArgOffset += 12*16; 4343 4344 // Add DAG nodes to load the arguments or copy them out of registers. On 4345 // entry to a function on PPC, the arguments start after the linkage area, 4346 // although the first ones are often in registers. 4347 4348 SmallVector<SDValue, 8> MemOps; 4349 unsigned nAltivecParamsAtEnd = 0; 4350 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4351 unsigned CurArgIdx = 0; 4352 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4353 SDValue ArgVal; 4354 bool needsLoad = false; 4355 EVT ObjectVT = Ins[ArgNo].VT; 4356 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4357 unsigned ArgSize = ObjSize; 4358 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4359 if (Ins[ArgNo].isOrigArg()) { 4360 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4361 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4362 } 4363 unsigned CurArgOffset = ArgOffset; 4364 4365 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4366 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4367 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4368 if (isVarArg || isPPC64) { 4369 MinReservedArea = ((MinReservedArea+15)/16)*16; 4370 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4371 Flags, 4372 PtrByteSize); 4373 } else nAltivecParamsAtEnd++; 4374 } else 4375 // Calculate min reserved area. 4376 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4377 Flags, 4378 PtrByteSize); 4379 4380 // FIXME the codegen can be much improved in some cases. 4381 // We do not have to keep everything in memory. 4382 if (Flags.isByVal()) { 4383 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4384 4385 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4386 ObjSize = Flags.getByValSize(); 4387 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4388 // Objects of size 1 and 2 are right justified, everything else is 4389 // left justified. This means the memory address is adjusted forwards. 4390 if (ObjSize==1 || ObjSize==2) { 4391 CurArgOffset = CurArgOffset + (4 - ObjSize); 4392 } 4393 // The value of the object is its address. 4394 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4395 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4396 InVals.push_back(FIN); 4397 if (ObjSize==1 || ObjSize==2) { 4398 if (GPR_idx != Num_GPR_Regs) { 4399 unsigned VReg; 4400 if (isPPC64) 4401 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4402 else 4403 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4404 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4405 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4406 SDValue Store = 4407 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4408 MachinePointerInfo(&*FuncArg), ObjType); 4409 MemOps.push_back(Store); 4410 ++GPR_idx; 4411 } 4412 4413 ArgOffset += PtrByteSize; 4414 4415 continue; 4416 } 4417 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4418 // Store whatever pieces of the object are in registers 4419 // to memory. ArgOffset will be the address of the beginning 4420 // of the object. 4421 if (GPR_idx != Num_GPR_Regs) { 4422 unsigned VReg; 4423 if (isPPC64) 4424 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4425 else 4426 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4427 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4429 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4430 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4431 MachinePointerInfo(&*FuncArg, j)); 4432 MemOps.push_back(Store); 4433 ++GPR_idx; 4434 ArgOffset += PtrByteSize; 4435 } else { 4436 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4437 break; 4438 } 4439 } 4440 continue; 4441 } 4442 4443 switch (ObjectVT.getSimpleVT().SimpleTy) { 4444 default: llvm_unreachable("Unhandled argument type!"); 4445 case MVT::i1: 4446 case MVT::i32: 4447 if (!isPPC64) { 4448 if (GPR_idx != Num_GPR_Regs) { 4449 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4450 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4451 4452 if (ObjectVT == MVT::i1) 4453 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4454 4455 ++GPR_idx; 4456 } else { 4457 needsLoad = true; 4458 ArgSize = PtrByteSize; 4459 } 4460 // All int arguments reserve stack space in the Darwin ABI. 4461 ArgOffset += PtrByteSize; 4462 break; 4463 } 4464 LLVM_FALLTHROUGH; 4465 case MVT::i64: // PPC64 4466 if (GPR_idx != Num_GPR_Regs) { 4467 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4468 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4469 4470 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4471 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4472 // value to MVT::i64 and then truncate to the correct register size. 4473 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4474 4475 ++GPR_idx; 4476 } else { 4477 needsLoad = true; 4478 ArgSize = PtrByteSize; 4479 } 4480 // All int arguments reserve stack space in the Darwin ABI. 4481 ArgOffset += 8; 4482 break; 4483 4484 case MVT::f32: 4485 case MVT::f64: 4486 // Every 4 bytes of argument space consumes one of the GPRs available for 4487 // argument passing. 4488 if (GPR_idx != Num_GPR_Regs) { 4489 ++GPR_idx; 4490 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4491 ++GPR_idx; 4492 } 4493 if (FPR_idx != Num_FPR_Regs) { 4494 unsigned VReg; 4495 4496 if (ObjectVT == MVT::f32) 4497 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4498 else 4499 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4500 4501 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4502 ++FPR_idx; 4503 } else { 4504 needsLoad = true; 4505 } 4506 4507 // All FP arguments reserve stack space in the Darwin ABI. 4508 ArgOffset += isPPC64 ? 8 : ObjSize; 4509 break; 4510 case MVT::v4f32: 4511 case MVT::v4i32: 4512 case MVT::v8i16: 4513 case MVT::v16i8: 4514 // Note that vector arguments in registers don't reserve stack space, 4515 // except in varargs functions. 4516 if (VR_idx != Num_VR_Regs) { 4517 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4518 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4519 if (isVarArg) { 4520 while ((ArgOffset % 16) != 0) { 4521 ArgOffset += PtrByteSize; 4522 if (GPR_idx != Num_GPR_Regs) 4523 GPR_idx++; 4524 } 4525 ArgOffset += 16; 4526 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4527 } 4528 ++VR_idx; 4529 } else { 4530 if (!isVarArg && !isPPC64) { 4531 // Vectors go after all the nonvectors. 4532 CurArgOffset = VecArgOffset; 4533 VecArgOffset += 16; 4534 } else { 4535 // Vectors are aligned. 4536 ArgOffset = ((ArgOffset+15)/16)*16; 4537 CurArgOffset = ArgOffset; 4538 ArgOffset += 16; 4539 } 4540 needsLoad = true; 4541 } 4542 break; 4543 } 4544 4545 // We need to load the argument to a virtual register if we determined above 4546 // that we ran out of physical registers of the appropriate type. 4547 if (needsLoad) { 4548 int FI = MFI.CreateFixedObject(ObjSize, 4549 CurArgOffset + (ArgSize - ObjSize), 4550 isImmutable); 4551 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4552 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4553 } 4554 4555 InVals.push_back(ArgVal); 4556 } 4557 4558 // Allow for Altivec parameters at the end, if needed. 4559 if (nAltivecParamsAtEnd) { 4560 MinReservedArea = ((MinReservedArea+15)/16)*16; 4561 MinReservedArea += 16*nAltivecParamsAtEnd; 4562 } 4563 4564 // Area that is at least reserved in the caller of this function. 4565 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4566 4567 // Set the size that is at least reserved in caller of this function. Tail 4568 // call optimized functions' reserved stack space needs to be aligned so that 4569 // taking the difference between two stack areas will result in an aligned 4570 // stack. 4571 MinReservedArea = 4572 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4573 FuncInfo->setMinReservedArea(MinReservedArea); 4574 4575 // If the function takes variable number of arguments, make a frame index for 4576 // the start of the first vararg value... for expansion of llvm.va_start. 4577 if (isVarArg) { 4578 int Depth = ArgOffset; 4579 4580 FuncInfo->setVarArgsFrameIndex( 4581 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4582 Depth, true)); 4583 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4584 4585 // If this function is vararg, store any remaining integer argument regs 4586 // to their spots on the stack so that they may be loaded by dereferencing 4587 // the result of va_next. 4588 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4589 unsigned VReg; 4590 4591 if (isPPC64) 4592 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4593 else 4594 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4595 4596 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4597 SDValue Store = 4598 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4599 MemOps.push_back(Store); 4600 // Increment the address by four for the next argument to store 4601 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4602 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4603 } 4604 } 4605 4606 if (!MemOps.empty()) 4607 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4608 4609 return Chain; 4610 } 4611 4612 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4613 /// adjusted to accommodate the arguments for the tailcall. 4614 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4615 unsigned ParamSize) { 4616 4617 if (!isTailCall) return 0; 4618 4619 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4620 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4621 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4622 // Remember only if the new adjustment is bigger. 4623 if (SPDiff < FI->getTailCallSPDelta()) 4624 FI->setTailCallSPDelta(SPDiff); 4625 4626 return SPDiff; 4627 } 4628 4629 static bool isFunctionGlobalAddress(SDValue Callee); 4630 4631 static bool 4632 callsShareTOCBase(const Function *Caller, SDValue Callee, 4633 const TargetMachine &TM) { 4634 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4635 // don't have enough information to determine if the caller and calle share 4636 // the same TOC base, so we have to pessimistically assume they don't for 4637 // correctness. 4638 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4639 if (!G) 4640 return false; 4641 4642 const GlobalValue *GV = G->getGlobal(); 4643 // The medium and large code models are expected to provide a sufficiently 4644 // large TOC to provide all data addressing needs of a module with a 4645 // single TOC. Since each module will be addressed with a single TOC then we 4646 // only need to check that caller and callee don't cross dso boundaries. 4647 if (CodeModel::Medium == TM.getCodeModel() || 4648 CodeModel::Large == TM.getCodeModel()) 4649 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4650 4651 // Otherwise we need to ensure callee and caller are in the same section, 4652 // since the linker may allocate multiple TOCs, and we don't know which 4653 // sections will belong to the same TOC base. 4654 4655 if (!GV->isStrongDefinitionForLinker()) 4656 return false; 4657 4658 // Any explicitly-specified sections and section prefixes must also match. 4659 // Also, if we're using -ffunction-sections, then each function is always in 4660 // a different section (the same is true for COMDAT functions). 4661 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4662 GV->getSection() != Caller->getSection()) 4663 return false; 4664 if (const auto *F = dyn_cast<Function>(GV)) { 4665 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4666 return false; 4667 } 4668 4669 // If the callee might be interposed, then we can't assume the ultimate call 4670 // target will be in the same section. Even in cases where we can assume that 4671 // interposition won't happen, in any case where the linker might insert a 4672 // stub to allow for interposition, we must generate code as though 4673 // interposition might occur. To understand why this matters, consider a 4674 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4675 // in the same section, but a is in a different module (i.e. has a different 4676 // TOC base pointer). If the linker allows for interposition between b and c, 4677 // then it will generate a stub for the call edge between b and c which will 4678 // save the TOC pointer into the designated stack slot allocated by b. If we 4679 // return true here, and therefore allow a tail call between b and c, that 4680 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4681 // pointer into the stack slot allocated by a (where the a -> b stub saved 4682 // a's TOC base pointer). If we're not considering a tail call, but rather, 4683 // whether a nop is needed after the call instruction in b, because the linker 4684 // will insert a stub, it might complain about a missing nop if we omit it 4685 // (although many don't complain in this case). 4686 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4687 return false; 4688 4689 return true; 4690 } 4691 4692 static bool 4693 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4694 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4695 assert(Subtarget.is64BitELFABI()); 4696 4697 const unsigned PtrByteSize = 8; 4698 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4699 4700 static const MCPhysReg GPR[] = { 4701 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4702 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4703 }; 4704 static const MCPhysReg VR[] = { 4705 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4706 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4707 }; 4708 4709 const unsigned NumGPRs = array_lengthof(GPR); 4710 const unsigned NumFPRs = 13; 4711 const unsigned NumVRs = array_lengthof(VR); 4712 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4713 4714 unsigned NumBytes = LinkageSize; 4715 unsigned AvailableFPRs = NumFPRs; 4716 unsigned AvailableVRs = NumVRs; 4717 4718 for (const ISD::OutputArg& Param : Outs) { 4719 if (Param.Flags.isNest()) continue; 4720 4721 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4722 PtrByteSize, LinkageSize, ParamAreaSize, 4723 NumBytes, AvailableFPRs, AvailableVRs, 4724 Subtarget.hasQPX())) 4725 return true; 4726 } 4727 return false; 4728 } 4729 4730 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4731 if (CB.arg_size() != CallerFn->arg_size()) 4732 return false; 4733 4734 auto CalleeArgIter = CB.arg_begin(); 4735 auto CalleeArgEnd = CB.arg_end(); 4736 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4737 4738 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4739 const Value* CalleeArg = *CalleeArgIter; 4740 const Value* CallerArg = &(*CallerArgIter); 4741 if (CalleeArg == CallerArg) 4742 continue; 4743 4744 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4745 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4746 // } 4747 // 1st argument of callee is undef and has the same type as caller. 4748 if (CalleeArg->getType() == CallerArg->getType() && 4749 isa<UndefValue>(CalleeArg)) 4750 continue; 4751 4752 return false; 4753 } 4754 4755 return true; 4756 } 4757 4758 // Returns true if TCO is possible between the callers and callees 4759 // calling conventions. 4760 static bool 4761 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4762 CallingConv::ID CalleeCC) { 4763 // Tail calls are possible with fastcc and ccc. 4764 auto isTailCallableCC = [] (CallingConv::ID CC){ 4765 return CC == CallingConv::C || CC == CallingConv::Fast; 4766 }; 4767 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4768 return false; 4769 4770 // We can safely tail call both fastcc and ccc callees from a c calling 4771 // convention caller. If the caller is fastcc, we may have less stack space 4772 // than a non-fastcc caller with the same signature so disable tail-calls in 4773 // that case. 4774 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4775 } 4776 4777 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4778 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4779 const SmallVectorImpl<ISD::OutputArg> &Outs, 4780 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4781 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4782 4783 if (DisableSCO && !TailCallOpt) return false; 4784 4785 // Variadic argument functions are not supported. 4786 if (isVarArg) return false; 4787 4788 auto &Caller = DAG.getMachineFunction().getFunction(); 4789 // Check that the calling conventions are compatible for tco. 4790 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4791 return false; 4792 4793 // Caller contains any byval parameter is not supported. 4794 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4795 return false; 4796 4797 // Callee contains any byval parameter is not supported, too. 4798 // Note: This is a quick work around, because in some cases, e.g. 4799 // caller's stack size > callee's stack size, we are still able to apply 4800 // sibling call optimization. For example, gcc is able to do SCO for caller1 4801 // in the following example, but not for caller2. 4802 // struct test { 4803 // long int a; 4804 // char ary[56]; 4805 // } gTest; 4806 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4807 // b->a = v.a; 4808 // return 0; 4809 // } 4810 // void caller1(struct test a, struct test c, struct test *b) { 4811 // callee(gTest, b); } 4812 // void caller2(struct test *b) { callee(gTest, b); } 4813 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4814 return false; 4815 4816 // If callee and caller use different calling conventions, we cannot pass 4817 // parameters on stack since offsets for the parameter area may be different. 4818 if (Caller.getCallingConv() != CalleeCC && 4819 needStackSlotPassParameters(Subtarget, Outs)) 4820 return false; 4821 4822 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4823 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4824 // callee potentially have different TOC bases then we cannot tail call since 4825 // we need to restore the TOC pointer after the call. 4826 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4827 // We cannot guarantee this for indirect calls or calls to external functions. 4828 // When PC-Relative addressing is used, the concept of the TOC is no longer 4829 // applicable so this check is not required. 4830 // Check first for indirect calls. 4831 if (!Subtarget.isUsingPCRelativeCalls() && 4832 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4833 return false; 4834 4835 // Check if we share the TOC base. 4836 if (!Subtarget.isUsingPCRelativeCalls() && 4837 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4838 return false; 4839 4840 // TCO allows altering callee ABI, so we don't have to check further. 4841 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4842 return true; 4843 4844 if (DisableSCO) return false; 4845 4846 // If callee use the same argument list that caller is using, then we can 4847 // apply SCO on this case. If it is not, then we need to check if callee needs 4848 // stack for passing arguments. 4849 // PC Relative tail calls may not have a CallBase. 4850 // If there is no CallBase we cannot verify if we have the same argument 4851 // list so assume that we don't have the same argument list. 4852 if (CB && !hasSameArgumentList(&Caller, *CB) && 4853 needStackSlotPassParameters(Subtarget, Outs)) 4854 return false; 4855 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4856 return false; 4857 4858 return true; 4859 } 4860 4861 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4862 /// for tail call optimization. Targets which want to do tail call 4863 /// optimization should implement this function. 4864 bool 4865 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4866 CallingConv::ID CalleeCC, 4867 bool isVarArg, 4868 const SmallVectorImpl<ISD::InputArg> &Ins, 4869 SelectionDAG& DAG) const { 4870 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4871 return false; 4872 4873 // Variable argument functions are not supported. 4874 if (isVarArg) 4875 return false; 4876 4877 MachineFunction &MF = DAG.getMachineFunction(); 4878 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4879 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4880 // Functions containing by val parameters are not supported. 4881 for (unsigned i = 0; i != Ins.size(); i++) { 4882 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4883 if (Flags.isByVal()) return false; 4884 } 4885 4886 // Non-PIC/GOT tail calls are supported. 4887 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4888 return true; 4889 4890 // At the moment we can only do local tail calls (in same module, hidden 4891 // or protected) if we are generating PIC. 4892 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4893 return G->getGlobal()->hasHiddenVisibility() 4894 || G->getGlobal()->hasProtectedVisibility(); 4895 } 4896 4897 return false; 4898 } 4899 4900 /// isCallCompatibleAddress - Return the immediate to use if the specified 4901 /// 32-bit value is representable in the immediate field of a BxA instruction. 4902 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4903 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4904 if (!C) return nullptr; 4905 4906 int Addr = C->getZExtValue(); 4907 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4908 SignExtend32<26>(Addr) != Addr) 4909 return nullptr; // Top 6 bits have to be sext of immediate. 4910 4911 return DAG 4912 .getConstant( 4913 (int)C->getZExtValue() >> 2, SDLoc(Op), 4914 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4915 .getNode(); 4916 } 4917 4918 namespace { 4919 4920 struct TailCallArgumentInfo { 4921 SDValue Arg; 4922 SDValue FrameIdxOp; 4923 int FrameIdx = 0; 4924 4925 TailCallArgumentInfo() = default; 4926 }; 4927 4928 } // end anonymous namespace 4929 4930 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4931 static void StoreTailCallArgumentsToStackSlot( 4932 SelectionDAG &DAG, SDValue Chain, 4933 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4934 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4935 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4936 SDValue Arg = TailCallArgs[i].Arg; 4937 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4938 int FI = TailCallArgs[i].FrameIdx; 4939 // Store relative to framepointer. 4940 MemOpChains.push_back(DAG.getStore( 4941 Chain, dl, Arg, FIN, 4942 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4943 } 4944 } 4945 4946 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4947 /// the appropriate stack slot for the tail call optimized function call. 4948 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4949 SDValue OldRetAddr, SDValue OldFP, 4950 int SPDiff, const SDLoc &dl) { 4951 if (SPDiff) { 4952 // Calculate the new stack slot for the return address. 4953 MachineFunction &MF = DAG.getMachineFunction(); 4954 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4955 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4956 bool isPPC64 = Subtarget.isPPC64(); 4957 int SlotSize = isPPC64 ? 8 : 4; 4958 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4959 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4960 NewRetAddrLoc, true); 4961 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4962 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4963 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4964 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4965 } 4966 return Chain; 4967 } 4968 4969 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4970 /// the position of the argument. 4971 static void 4972 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4973 SDValue Arg, int SPDiff, unsigned ArgOffset, 4974 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4975 int Offset = ArgOffset + SPDiff; 4976 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4977 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4978 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4979 SDValue FIN = DAG.getFrameIndex(FI, VT); 4980 TailCallArgumentInfo Info; 4981 Info.Arg = Arg; 4982 Info.FrameIdxOp = FIN; 4983 Info.FrameIdx = FI; 4984 TailCallArguments.push_back(Info); 4985 } 4986 4987 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4988 /// stack slot. Returns the chain as result and the loaded frame pointers in 4989 /// LROpOut/FPOpout. Used when tail calling. 4990 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4991 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4992 SDValue &FPOpOut, const SDLoc &dl) const { 4993 if (SPDiff) { 4994 // Load the LR and FP stack slot for later adjusting. 4995 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4996 LROpOut = getReturnAddrFrameIndex(DAG); 4997 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4998 Chain = SDValue(LROpOut.getNode(), 1); 4999 } 5000 return Chain; 5001 } 5002 5003 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5004 /// by "Src" to address "Dst" of size "Size". Alignment information is 5005 /// specified by the specific parameter attribute. The copy will be passed as 5006 /// a byval function parameter. 5007 /// Sometimes what we are copying is the end of a larger object, the part that 5008 /// does not fit in registers. 5009 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5010 SDValue Chain, ISD::ArgFlagsTy Flags, 5011 SelectionDAG &DAG, const SDLoc &dl) { 5012 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5013 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5014 Flags.getNonZeroByValAlign(), false, false, false, 5015 MachinePointerInfo(), MachinePointerInfo()); 5016 } 5017 5018 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5019 /// tail calls. 5020 static void LowerMemOpCallTo( 5021 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5022 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5023 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5024 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5025 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5026 if (!isTailCall) { 5027 if (isVector) { 5028 SDValue StackPtr; 5029 if (isPPC64) 5030 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5031 else 5032 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5033 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5034 DAG.getConstant(ArgOffset, dl, PtrVT)); 5035 } 5036 MemOpChains.push_back( 5037 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5038 // Calculate and remember argument location. 5039 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5040 TailCallArguments); 5041 } 5042 5043 static void 5044 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5045 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5046 SDValue FPOp, 5047 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5048 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5049 // might overwrite each other in case of tail call optimization. 5050 SmallVector<SDValue, 8> MemOpChains2; 5051 // Do not flag preceding copytoreg stuff together with the following stuff. 5052 InFlag = SDValue(); 5053 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5054 MemOpChains2, dl); 5055 if (!MemOpChains2.empty()) 5056 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5057 5058 // Store the return address to the appropriate stack slot. 5059 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5060 5061 // Emit callseq_end just before tailcall node. 5062 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5063 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5064 InFlag = Chain.getValue(1); 5065 } 5066 5067 // Is this global address that of a function that can be called by name? (as 5068 // opposed to something that must hold a descriptor for an indirect call). 5069 static bool isFunctionGlobalAddress(SDValue Callee) { 5070 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5071 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5072 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5073 return false; 5074 5075 return G->getGlobal()->getValueType()->isFunctionTy(); 5076 } 5077 5078 return false; 5079 } 5080 5081 SDValue PPCTargetLowering::LowerCallResult( 5082 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5083 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5084 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5085 SmallVector<CCValAssign, 16> RVLocs; 5086 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5087 *DAG.getContext()); 5088 5089 CCRetInfo.AnalyzeCallResult( 5090 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5091 ? RetCC_PPC_Cold 5092 : RetCC_PPC); 5093 5094 // Copy all of the result registers out of their specified physreg. 5095 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5096 CCValAssign &VA = RVLocs[i]; 5097 assert(VA.isRegLoc() && "Can only return in registers!"); 5098 5099 SDValue Val; 5100 5101 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5102 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5103 InFlag); 5104 Chain = Lo.getValue(1); 5105 InFlag = Lo.getValue(2); 5106 VA = RVLocs[++i]; // skip ahead to next loc 5107 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5108 InFlag); 5109 Chain = Hi.getValue(1); 5110 InFlag = Hi.getValue(2); 5111 if (!Subtarget.isLittleEndian()) 5112 std::swap (Lo, Hi); 5113 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5114 } else { 5115 Val = DAG.getCopyFromReg(Chain, dl, 5116 VA.getLocReg(), VA.getLocVT(), InFlag); 5117 Chain = Val.getValue(1); 5118 InFlag = Val.getValue(2); 5119 } 5120 5121 switch (VA.getLocInfo()) { 5122 default: llvm_unreachable("Unknown loc info!"); 5123 case CCValAssign::Full: break; 5124 case CCValAssign::AExt: 5125 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5126 break; 5127 case CCValAssign::ZExt: 5128 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5129 DAG.getValueType(VA.getValVT())); 5130 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5131 break; 5132 case CCValAssign::SExt: 5133 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5134 DAG.getValueType(VA.getValVT())); 5135 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5136 break; 5137 } 5138 5139 InVals.push_back(Val); 5140 } 5141 5142 return Chain; 5143 } 5144 5145 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5146 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5147 // PatchPoint calls are not indirect. 5148 if (isPatchPoint) 5149 return false; 5150 5151 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5152 return false; 5153 5154 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5155 // becuase the immediate function pointer points to a descriptor instead of 5156 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5157 // pointer immediate points to the global entry point, while the BLA would 5158 // need to jump to the local entry point (see rL211174). 5159 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5160 isBLACompatibleAddress(Callee, DAG)) 5161 return false; 5162 5163 return true; 5164 } 5165 5166 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5167 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5168 return Subtarget.isAIXABI() || 5169 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5170 } 5171 5172 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5173 const Function &Caller, 5174 const SDValue &Callee, 5175 const PPCSubtarget &Subtarget, 5176 const TargetMachine &TM) { 5177 if (CFlags.IsTailCall) 5178 return PPCISD::TC_RETURN; 5179 5180 // This is a call through a function pointer. 5181 if (CFlags.IsIndirect) { 5182 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5183 // indirect calls. The save of the caller's TOC pointer to the stack will be 5184 // inserted into the DAG as part of call lowering. The restore of the TOC 5185 // pointer is modeled by using a pseudo instruction for the call opcode that 5186 // represents the 2 instruction sequence of an indirect branch and link, 5187 // immediately followed by a load of the TOC pointer from the the stack save 5188 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5189 // as it is not saved or used. 5190 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5191 : PPCISD::BCTRL; 5192 } 5193 5194 if (Subtarget.isUsingPCRelativeCalls()) { 5195 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5196 return PPCISD::CALL_NOTOC; 5197 } 5198 5199 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5200 // immediately following the call instruction if the caller and callee may 5201 // have different TOC bases. At link time if the linker determines the calls 5202 // may not share a TOC base, the call is redirected to a trampoline inserted 5203 // by the linker. The trampoline will (among other things) save the callers 5204 // TOC pointer at an ABI designated offset in the linkage area and the linker 5205 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5206 // into gpr2. 5207 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5208 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5209 : PPCISD::CALL_NOP; 5210 5211 return PPCISD::CALL; 5212 } 5213 5214 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5215 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5216 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5217 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5218 return SDValue(Dest, 0); 5219 5220 // Returns true if the callee is local, and false otherwise. 5221 auto isLocalCallee = [&]() { 5222 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5223 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5224 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5225 5226 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5227 !dyn_cast_or_null<GlobalIFunc>(GV); 5228 }; 5229 5230 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5231 // a static relocation model causes some versions of GNU LD (2.17.50, at 5232 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5233 // built with secure-PLT. 5234 bool UsePlt = 5235 Subtarget.is32BitELFABI() && !isLocalCallee() && 5236 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5237 5238 // On AIX, direct function calls reference the symbol for the function's 5239 // entry point, which is named by prepending a "." before the function's 5240 // C-linkage name. 5241 const auto getAIXFuncEntryPointSymbolSDNode = 5242 [&](StringRef FuncName, bool IsDeclaration, 5243 const XCOFF::StorageClass &SC) { 5244 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5245 5246 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5247 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5248 5249 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5250 // On AIX, an undefined symbol needs to be associated with a 5251 // MCSectionXCOFF to get the correct storage mapping class. 5252 // In this case, XCOFF::XMC_PR. 5253 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5254 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5255 SectionKind::getMetadata()); 5256 S->setRepresentedCsect(Sec); 5257 } 5258 5259 MVT PtrVT = 5260 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5261 return DAG.getMCSymbol(S, PtrVT); 5262 }; 5263 5264 if (isFunctionGlobalAddress(Callee)) { 5265 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5266 const GlobalValue *GV = G->getGlobal(); 5267 5268 if (!Subtarget.isAIXABI()) 5269 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5270 UsePlt ? PPCII::MO_PLT : 0); 5271 5272 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5273 const GlobalObject *GO = cast<GlobalObject>(GV); 5274 const XCOFF::StorageClass SC = 5275 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5276 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5277 SC); 5278 } 5279 5280 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5281 const char *SymName = S->getSymbol(); 5282 if (!Subtarget.isAIXABI()) 5283 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5284 UsePlt ? PPCII::MO_PLT : 0); 5285 5286 // If there exists a user-declared function whose name is the same as the 5287 // ExternalSymbol's, then we pick up the user-declared version. 5288 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5289 if (const Function *F = 5290 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5291 const XCOFF::StorageClass SC = 5292 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5293 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5294 SC); 5295 } 5296 5297 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5298 } 5299 5300 // No transformation needed. 5301 assert(Callee.getNode() && "What no callee?"); 5302 return Callee; 5303 } 5304 5305 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5306 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5307 "Expected a CALLSEQ_STARTSDNode."); 5308 5309 // The last operand is the chain, except when the node has glue. If the node 5310 // has glue, then the last operand is the glue, and the chain is the second 5311 // last operand. 5312 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5313 if (LastValue.getValueType() != MVT::Glue) 5314 return LastValue; 5315 5316 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5317 } 5318 5319 // Creates the node that moves a functions address into the count register 5320 // to prepare for an indirect call instruction. 5321 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5322 SDValue &Glue, SDValue &Chain, 5323 const SDLoc &dl) { 5324 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5325 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5326 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5327 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5328 // The glue is the second value produced. 5329 Glue = Chain.getValue(1); 5330 } 5331 5332 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5333 SDValue &Glue, SDValue &Chain, 5334 SDValue CallSeqStart, 5335 const CallBase *CB, const SDLoc &dl, 5336 bool hasNest, 5337 const PPCSubtarget &Subtarget) { 5338 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5339 // entry point, but to the function descriptor (the function entry point 5340 // address is part of the function descriptor though). 5341 // The function descriptor is a three doubleword structure with the 5342 // following fields: function entry point, TOC base address and 5343 // environment pointer. 5344 // Thus for a call through a function pointer, the following actions need 5345 // to be performed: 5346 // 1. Save the TOC of the caller in the TOC save area of its stack 5347 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5348 // 2. Load the address of the function entry point from the function 5349 // descriptor. 5350 // 3. Load the TOC of the callee from the function descriptor into r2. 5351 // 4. Load the environment pointer from the function descriptor into 5352 // r11. 5353 // 5. Branch to the function entry point address. 5354 // 6. On return of the callee, the TOC of the caller needs to be 5355 // restored (this is done in FinishCall()). 5356 // 5357 // The loads are scheduled at the beginning of the call sequence, and the 5358 // register copies are flagged together to ensure that no other 5359 // operations can be scheduled in between. E.g. without flagging the 5360 // copies together, a TOC access in the caller could be scheduled between 5361 // the assignment of the callee TOC and the branch to the callee, which leads 5362 // to incorrect code. 5363 5364 // Start by loading the function address from the descriptor. 5365 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5366 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5367 ? (MachineMemOperand::MODereferenceable | 5368 MachineMemOperand::MOInvariant) 5369 : MachineMemOperand::MONone; 5370 5371 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5372 5373 // Registers used in building the DAG. 5374 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5375 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5376 5377 // Offsets of descriptor members. 5378 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5379 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5380 5381 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5382 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5383 5384 // One load for the functions entry point address. 5385 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5386 Alignment, MMOFlags); 5387 5388 // One for loading the TOC anchor for the module that contains the called 5389 // function. 5390 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5391 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5392 SDValue TOCPtr = 5393 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5394 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5395 5396 // One for loading the environment pointer. 5397 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5398 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5399 SDValue LoadEnvPtr = 5400 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5401 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5402 5403 5404 // Then copy the newly loaded TOC anchor to the TOC pointer. 5405 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5406 Chain = TOCVal.getValue(0); 5407 Glue = TOCVal.getValue(1); 5408 5409 // If the function call has an explicit 'nest' parameter, it takes the 5410 // place of the environment pointer. 5411 assert((!hasNest || !Subtarget.isAIXABI()) && 5412 "Nest parameter is not supported on AIX."); 5413 if (!hasNest) { 5414 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5415 Chain = EnvVal.getValue(0); 5416 Glue = EnvVal.getValue(1); 5417 } 5418 5419 // The rest of the indirect call sequence is the same as the non-descriptor 5420 // DAG. 5421 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5422 } 5423 5424 static void 5425 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5426 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5427 SelectionDAG &DAG, 5428 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5429 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5430 const PPCSubtarget &Subtarget) { 5431 const bool IsPPC64 = Subtarget.isPPC64(); 5432 // MVT for a general purpose register. 5433 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5434 5435 // First operand is always the chain. 5436 Ops.push_back(Chain); 5437 5438 // If it's a direct call pass the callee as the second operand. 5439 if (!CFlags.IsIndirect) 5440 Ops.push_back(Callee); 5441 else { 5442 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5443 5444 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5445 // on the stack (this would have been done in `LowerCall_64SVR4` or 5446 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5447 // represents both the indirect branch and a load that restores the TOC 5448 // pointer from the linkage area. The operand for the TOC restore is an add 5449 // of the TOC save offset to the stack pointer. This must be the second 5450 // operand: after the chain input but before any other variadic arguments. 5451 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5452 // saved or used. 5453 if (isTOCSaveRestoreRequired(Subtarget)) { 5454 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5455 5456 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5457 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5458 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5459 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5460 Ops.push_back(AddTOC); 5461 } 5462 5463 // Add the register used for the environment pointer. 5464 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5465 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5466 RegVT)); 5467 5468 5469 // Add CTR register as callee so a bctr can be emitted later. 5470 if (CFlags.IsTailCall) 5471 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5472 } 5473 5474 // If this is a tail call add stack pointer delta. 5475 if (CFlags.IsTailCall) 5476 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5477 5478 // Add argument registers to the end of the list so that they are known live 5479 // into the call. 5480 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5481 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5482 RegsToPass[i].second.getValueType())); 5483 5484 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5485 // no way to mark dependencies as implicit here. 5486 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5487 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5488 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5489 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5490 5491 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5492 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5493 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5494 5495 // Add a register mask operand representing the call-preserved registers. 5496 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5497 const uint32_t *Mask = 5498 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5499 assert(Mask && "Missing call preserved mask for calling convention"); 5500 Ops.push_back(DAG.getRegisterMask(Mask)); 5501 5502 // If the glue is valid, it is the last operand. 5503 if (Glue.getNode()) 5504 Ops.push_back(Glue); 5505 } 5506 5507 SDValue PPCTargetLowering::FinishCall( 5508 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5509 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5510 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5511 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5512 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5513 5514 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5515 Subtarget.isAIXABI()) 5516 setUsesTOCBasePtr(DAG); 5517 5518 unsigned CallOpc = 5519 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5520 Subtarget, DAG.getTarget()); 5521 5522 if (!CFlags.IsIndirect) 5523 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5524 else if (Subtarget.usesFunctionDescriptors()) 5525 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5526 dl, CFlags.HasNest, Subtarget); 5527 else 5528 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5529 5530 // Build the operand list for the call instruction. 5531 SmallVector<SDValue, 8> Ops; 5532 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5533 SPDiff, Subtarget); 5534 5535 // Emit tail call. 5536 if (CFlags.IsTailCall) { 5537 // Indirect tail call when using PC Relative calls do not have the same 5538 // constraints. 5539 assert(((Callee.getOpcode() == ISD::Register && 5540 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5541 Callee.getOpcode() == ISD::TargetExternalSymbol || 5542 Callee.getOpcode() == ISD::TargetGlobalAddress || 5543 isa<ConstantSDNode>(Callee) || 5544 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5545 "Expecting a global address, external symbol, absolute value, " 5546 "register or an indirect tail call when PC Relative calls are " 5547 "used."); 5548 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5549 assert(CallOpc == PPCISD::TC_RETURN && 5550 "Unexpected call opcode for a tail call."); 5551 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5552 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5553 } 5554 5555 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5556 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5557 Glue = Chain.getValue(1); 5558 5559 // When performing tail call optimization the callee pops its arguments off 5560 // the stack. Account for this here so these bytes can be pushed back on in 5561 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5562 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5563 getTargetMachine().Options.GuaranteedTailCallOpt) 5564 ? NumBytes 5565 : 0; 5566 5567 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5568 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5569 Glue, dl); 5570 Glue = Chain.getValue(1); 5571 5572 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5573 DAG, InVals); 5574 } 5575 5576 SDValue 5577 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5578 SmallVectorImpl<SDValue> &InVals) const { 5579 SelectionDAG &DAG = CLI.DAG; 5580 SDLoc &dl = CLI.DL; 5581 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5582 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5583 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5584 SDValue Chain = CLI.Chain; 5585 SDValue Callee = CLI.Callee; 5586 bool &isTailCall = CLI.IsTailCall; 5587 CallingConv::ID CallConv = CLI.CallConv; 5588 bool isVarArg = CLI.IsVarArg; 5589 bool isPatchPoint = CLI.IsPatchPoint; 5590 const CallBase *CB = CLI.CB; 5591 5592 if (isTailCall) { 5593 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5594 isTailCall = false; 5595 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5596 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5597 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5598 else 5599 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5600 Ins, DAG); 5601 if (isTailCall) { 5602 ++NumTailCalls; 5603 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5604 ++NumSiblingCalls; 5605 5606 // PC Relative calls no longer guarantee that the callee is a Global 5607 // Address Node. The callee could be an indirect tail call in which 5608 // case the SDValue for the callee could be a load (to load the address 5609 // of a function pointer) or it may be a register copy (to move the 5610 // address of the callee from a function parameter into a virtual 5611 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5612 assert((Subtarget.isUsingPCRelativeCalls() || 5613 isa<GlobalAddressSDNode>(Callee)) && 5614 "Callee should be an llvm::Function object."); 5615 5616 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5617 << "\nTCO callee: "); 5618 LLVM_DEBUG(Callee.dump()); 5619 } 5620 } 5621 5622 if (!isTailCall && CB && CB->isMustTailCall()) 5623 report_fatal_error("failed to perform tail call elimination on a call " 5624 "site marked musttail"); 5625 5626 // When long calls (i.e. indirect calls) are always used, calls are always 5627 // made via function pointer. If we have a function name, first translate it 5628 // into a pointer. 5629 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5630 !isTailCall) 5631 Callee = LowerGlobalAddress(Callee, DAG); 5632 5633 CallFlags CFlags( 5634 CallConv, isTailCall, isVarArg, isPatchPoint, 5635 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5636 // hasNest 5637 Subtarget.is64BitELFABI() && 5638 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5639 5640 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5641 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5642 InVals, CB); 5643 5644 if (Subtarget.isSVR4ABI()) 5645 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5646 InVals, CB); 5647 5648 if (Subtarget.isAIXABI()) 5649 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5650 InVals, CB); 5651 5652 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5653 InVals, CB); 5654 } 5655 5656 SDValue PPCTargetLowering::LowerCall_32SVR4( 5657 SDValue Chain, SDValue Callee, CallFlags CFlags, 5658 const SmallVectorImpl<ISD::OutputArg> &Outs, 5659 const SmallVectorImpl<SDValue> &OutVals, 5660 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5661 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5662 const CallBase *CB) const { 5663 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5664 // of the 32-bit SVR4 ABI stack frame layout. 5665 5666 const CallingConv::ID CallConv = CFlags.CallConv; 5667 const bool IsVarArg = CFlags.IsVarArg; 5668 const bool IsTailCall = CFlags.IsTailCall; 5669 5670 assert((CallConv == CallingConv::C || 5671 CallConv == CallingConv::Cold || 5672 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5673 5674 unsigned PtrByteSize = 4; 5675 5676 MachineFunction &MF = DAG.getMachineFunction(); 5677 5678 // Mark this function as potentially containing a function that contains a 5679 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5680 // and restoring the callers stack pointer in this functions epilog. This is 5681 // done because by tail calling the called function might overwrite the value 5682 // in this function's (MF) stack pointer stack slot 0(SP). 5683 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5684 CallConv == CallingConv::Fast) 5685 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5686 5687 // Count how many bytes are to be pushed on the stack, including the linkage 5688 // area, parameter list area and the part of the local variable space which 5689 // contains copies of aggregates which are passed by value. 5690 5691 // Assign locations to all of the outgoing arguments. 5692 SmallVector<CCValAssign, 16> ArgLocs; 5693 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5694 5695 // Reserve space for the linkage area on the stack. 5696 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5697 PtrByteSize); 5698 if (useSoftFloat()) 5699 CCInfo.PreAnalyzeCallOperands(Outs); 5700 5701 if (IsVarArg) { 5702 // Handle fixed and variable vector arguments differently. 5703 // Fixed vector arguments go into registers as long as registers are 5704 // available. Variable vector arguments always go into memory. 5705 unsigned NumArgs = Outs.size(); 5706 5707 for (unsigned i = 0; i != NumArgs; ++i) { 5708 MVT ArgVT = Outs[i].VT; 5709 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5710 bool Result; 5711 5712 if (Outs[i].IsFixed) { 5713 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5714 CCInfo); 5715 } else { 5716 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5717 ArgFlags, CCInfo); 5718 } 5719 5720 if (Result) { 5721 #ifndef NDEBUG 5722 errs() << "Call operand #" << i << " has unhandled type " 5723 << EVT(ArgVT).getEVTString() << "\n"; 5724 #endif 5725 llvm_unreachable(nullptr); 5726 } 5727 } 5728 } else { 5729 // All arguments are treated the same. 5730 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5731 } 5732 CCInfo.clearWasPPCF128(); 5733 5734 // Assign locations to all of the outgoing aggregate by value arguments. 5735 SmallVector<CCValAssign, 16> ByValArgLocs; 5736 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5737 5738 // Reserve stack space for the allocations in CCInfo. 5739 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5740 5741 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5742 5743 // Size of the linkage area, parameter list area and the part of the local 5744 // space variable where copies of aggregates which are passed by value are 5745 // stored. 5746 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5747 5748 // Calculate by how many bytes the stack has to be adjusted in case of tail 5749 // call optimization. 5750 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5751 5752 // Adjust the stack pointer for the new arguments... 5753 // These operations are automatically eliminated by the prolog/epilog pass 5754 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5755 SDValue CallSeqStart = Chain; 5756 5757 // Load the return address and frame pointer so it can be moved somewhere else 5758 // later. 5759 SDValue LROp, FPOp; 5760 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5761 5762 // Set up a copy of the stack pointer for use loading and storing any 5763 // arguments that may not fit in the registers available for argument 5764 // passing. 5765 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5766 5767 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5768 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5769 SmallVector<SDValue, 8> MemOpChains; 5770 5771 bool seenFloatArg = false; 5772 // Walk the register/memloc assignments, inserting copies/loads. 5773 // i - Tracks the index into the list of registers allocated for the call 5774 // RealArgIdx - Tracks the index into the list of actual function arguments 5775 // j - Tracks the index into the list of byval arguments 5776 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5777 i != e; 5778 ++i, ++RealArgIdx) { 5779 CCValAssign &VA = ArgLocs[i]; 5780 SDValue Arg = OutVals[RealArgIdx]; 5781 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5782 5783 if (Flags.isByVal()) { 5784 // Argument is an aggregate which is passed by value, thus we need to 5785 // create a copy of it in the local variable space of the current stack 5786 // frame (which is the stack frame of the caller) and pass the address of 5787 // this copy to the callee. 5788 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5789 CCValAssign &ByValVA = ByValArgLocs[j++]; 5790 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5791 5792 // Memory reserved in the local variable space of the callers stack frame. 5793 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5794 5795 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5796 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5797 StackPtr, PtrOff); 5798 5799 // Create a copy of the argument in the local area of the current 5800 // stack frame. 5801 SDValue MemcpyCall = 5802 CreateCopyOfByValArgument(Arg, PtrOff, 5803 CallSeqStart.getNode()->getOperand(0), 5804 Flags, DAG, dl); 5805 5806 // This must go outside the CALLSEQ_START..END. 5807 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5808 SDLoc(MemcpyCall)); 5809 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5810 NewCallSeqStart.getNode()); 5811 Chain = CallSeqStart = NewCallSeqStart; 5812 5813 // Pass the address of the aggregate copy on the stack either in a 5814 // physical register or in the parameter list area of the current stack 5815 // frame to the callee. 5816 Arg = PtrOff; 5817 } 5818 5819 // When useCRBits() is true, there can be i1 arguments. 5820 // It is because getRegisterType(MVT::i1) => MVT::i1, 5821 // and for other integer types getRegisterType() => MVT::i32. 5822 // Extend i1 and ensure callee will get i32. 5823 if (Arg.getValueType() == MVT::i1) 5824 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5825 dl, MVT::i32, Arg); 5826 5827 if (VA.isRegLoc()) { 5828 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5829 // Put argument in a physical register. 5830 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5831 bool IsLE = Subtarget.isLittleEndian(); 5832 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5833 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5834 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5835 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5836 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5837 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5838 SVal.getValue(0))); 5839 } else 5840 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5841 } else { 5842 // Put argument in the parameter list area of the current stack frame. 5843 assert(VA.isMemLoc()); 5844 unsigned LocMemOffset = VA.getLocMemOffset(); 5845 5846 if (!IsTailCall) { 5847 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5848 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5849 StackPtr, PtrOff); 5850 5851 MemOpChains.push_back( 5852 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5853 } else { 5854 // Calculate and remember argument location. 5855 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5856 TailCallArguments); 5857 } 5858 } 5859 } 5860 5861 if (!MemOpChains.empty()) 5862 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5863 5864 // Build a sequence of copy-to-reg nodes chained together with token chain 5865 // and flag operands which copy the outgoing args into the appropriate regs. 5866 SDValue InFlag; 5867 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5868 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5869 RegsToPass[i].second, InFlag); 5870 InFlag = Chain.getValue(1); 5871 } 5872 5873 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5874 // registers. 5875 if (IsVarArg) { 5876 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5877 SDValue Ops[] = { Chain, InFlag }; 5878 5879 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5880 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5881 5882 InFlag = Chain.getValue(1); 5883 } 5884 5885 if (IsTailCall) 5886 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5887 TailCallArguments); 5888 5889 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5890 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5891 } 5892 5893 // Copy an argument into memory, being careful to do this outside the 5894 // call sequence for the call to which the argument belongs. 5895 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5896 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5897 SelectionDAG &DAG, const SDLoc &dl) const { 5898 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5899 CallSeqStart.getNode()->getOperand(0), 5900 Flags, DAG, dl); 5901 // The MEMCPY must go outside the CALLSEQ_START..END. 5902 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5903 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5904 SDLoc(MemcpyCall)); 5905 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5906 NewCallSeqStart.getNode()); 5907 return NewCallSeqStart; 5908 } 5909 5910 SDValue PPCTargetLowering::LowerCall_64SVR4( 5911 SDValue Chain, SDValue Callee, CallFlags CFlags, 5912 const SmallVectorImpl<ISD::OutputArg> &Outs, 5913 const SmallVectorImpl<SDValue> &OutVals, 5914 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5915 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5916 const CallBase *CB) const { 5917 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5918 bool isLittleEndian = Subtarget.isLittleEndian(); 5919 unsigned NumOps = Outs.size(); 5920 bool IsSibCall = false; 5921 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5922 5923 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5924 unsigned PtrByteSize = 8; 5925 5926 MachineFunction &MF = DAG.getMachineFunction(); 5927 5928 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5929 IsSibCall = true; 5930 5931 // Mark this function as potentially containing a function that contains a 5932 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5933 // and restoring the callers stack pointer in this functions epilog. This is 5934 // done because by tail calling the called function might overwrite the value 5935 // in this function's (MF) stack pointer stack slot 0(SP). 5936 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5937 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5938 5939 assert(!(IsFastCall && CFlags.IsVarArg) && 5940 "fastcc not supported on varargs functions"); 5941 5942 // Count how many bytes are to be pushed on the stack, including the linkage 5943 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5944 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5945 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5946 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5947 unsigned NumBytes = LinkageSize; 5948 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5949 unsigned &QFPR_idx = FPR_idx; 5950 5951 static const MCPhysReg GPR[] = { 5952 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5953 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5954 }; 5955 static const MCPhysReg VR[] = { 5956 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5957 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5958 }; 5959 5960 const unsigned NumGPRs = array_lengthof(GPR); 5961 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5962 const unsigned NumVRs = array_lengthof(VR); 5963 const unsigned NumQFPRs = NumFPRs; 5964 5965 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5966 // can be passed to the callee in registers. 5967 // For the fast calling convention, there is another check below. 5968 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5969 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5970 if (!HasParameterArea) { 5971 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5972 unsigned AvailableFPRs = NumFPRs; 5973 unsigned AvailableVRs = NumVRs; 5974 unsigned NumBytesTmp = NumBytes; 5975 for (unsigned i = 0; i != NumOps; ++i) { 5976 if (Outs[i].Flags.isNest()) continue; 5977 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5978 PtrByteSize, LinkageSize, ParamAreaSize, 5979 NumBytesTmp, AvailableFPRs, AvailableVRs, 5980 Subtarget.hasQPX())) 5981 HasParameterArea = true; 5982 } 5983 } 5984 5985 // When using the fast calling convention, we don't provide backing for 5986 // arguments that will be in registers. 5987 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5988 5989 // Avoid allocating parameter area for fastcc functions if all the arguments 5990 // can be passed in the registers. 5991 if (IsFastCall) 5992 HasParameterArea = false; 5993 5994 // Add up all the space actually used. 5995 for (unsigned i = 0; i != NumOps; ++i) { 5996 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5997 EVT ArgVT = Outs[i].VT; 5998 EVT OrigVT = Outs[i].ArgVT; 5999 6000 if (Flags.isNest()) 6001 continue; 6002 6003 if (IsFastCall) { 6004 if (Flags.isByVal()) { 6005 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6006 if (NumGPRsUsed > NumGPRs) 6007 HasParameterArea = true; 6008 } else { 6009 switch (ArgVT.getSimpleVT().SimpleTy) { 6010 default: llvm_unreachable("Unexpected ValueType for argument!"); 6011 case MVT::i1: 6012 case MVT::i32: 6013 case MVT::i64: 6014 if (++NumGPRsUsed <= NumGPRs) 6015 continue; 6016 break; 6017 case MVT::v4i32: 6018 case MVT::v8i16: 6019 case MVT::v16i8: 6020 case MVT::v2f64: 6021 case MVT::v2i64: 6022 case MVT::v1i128: 6023 case MVT::f128: 6024 if (++NumVRsUsed <= NumVRs) 6025 continue; 6026 break; 6027 case MVT::v4f32: 6028 // When using QPX, this is handled like a FP register, otherwise, it 6029 // is an Altivec register. 6030 if (Subtarget.hasQPX()) { 6031 if (++NumFPRsUsed <= NumFPRs) 6032 continue; 6033 } else { 6034 if (++NumVRsUsed <= NumVRs) 6035 continue; 6036 } 6037 break; 6038 case MVT::f32: 6039 case MVT::f64: 6040 case MVT::v4f64: // QPX 6041 case MVT::v4i1: // QPX 6042 if (++NumFPRsUsed <= NumFPRs) 6043 continue; 6044 break; 6045 } 6046 HasParameterArea = true; 6047 } 6048 } 6049 6050 /* Respect alignment of argument on the stack. */ 6051 auto Alignement = 6052 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6053 NumBytes = alignTo(NumBytes, Alignement); 6054 6055 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6056 if (Flags.isInConsecutiveRegsLast()) 6057 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6058 } 6059 6060 unsigned NumBytesActuallyUsed = NumBytes; 6061 6062 // In the old ELFv1 ABI, 6063 // the prolog code of the callee may store up to 8 GPR argument registers to 6064 // the stack, allowing va_start to index over them in memory if its varargs. 6065 // Because we cannot tell if this is needed on the caller side, we have to 6066 // conservatively assume that it is needed. As such, make sure we have at 6067 // least enough stack space for the caller to store the 8 GPRs. 6068 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6069 // really requires memory operands, e.g. a vararg function. 6070 if (HasParameterArea) 6071 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6072 else 6073 NumBytes = LinkageSize; 6074 6075 // Tail call needs the stack to be aligned. 6076 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6077 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6078 6079 int SPDiff = 0; 6080 6081 // Calculate by how many bytes the stack has to be adjusted in case of tail 6082 // call optimization. 6083 if (!IsSibCall) 6084 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6085 6086 // To protect arguments on the stack from being clobbered in a tail call, 6087 // force all the loads to happen before doing any other lowering. 6088 if (CFlags.IsTailCall) 6089 Chain = DAG.getStackArgumentTokenFactor(Chain); 6090 6091 // Adjust the stack pointer for the new arguments... 6092 // These operations are automatically eliminated by the prolog/epilog pass 6093 if (!IsSibCall) 6094 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6095 SDValue CallSeqStart = Chain; 6096 6097 // Load the return address and frame pointer so it can be move somewhere else 6098 // later. 6099 SDValue LROp, FPOp; 6100 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6101 6102 // Set up a copy of the stack pointer for use loading and storing any 6103 // arguments that may not fit in the registers available for argument 6104 // passing. 6105 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6106 6107 // Figure out which arguments are going to go in registers, and which in 6108 // memory. Also, if this is a vararg function, floating point operations 6109 // must be stored to our stack, and loaded into integer regs as well, if 6110 // any integer regs are available for argument passing. 6111 unsigned ArgOffset = LinkageSize; 6112 6113 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6114 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6115 6116 SmallVector<SDValue, 8> MemOpChains; 6117 for (unsigned i = 0; i != NumOps; ++i) { 6118 SDValue Arg = OutVals[i]; 6119 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6120 EVT ArgVT = Outs[i].VT; 6121 EVT OrigVT = Outs[i].ArgVT; 6122 6123 // PtrOff will be used to store the current argument to the stack if a 6124 // register cannot be found for it. 6125 SDValue PtrOff; 6126 6127 // We re-align the argument offset for each argument, except when using the 6128 // fast calling convention, when we need to make sure we do that only when 6129 // we'll actually use a stack slot. 6130 auto ComputePtrOff = [&]() { 6131 /* Respect alignment of argument on the stack. */ 6132 auto Alignment = 6133 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6134 ArgOffset = alignTo(ArgOffset, Alignment); 6135 6136 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6137 6138 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6139 }; 6140 6141 if (!IsFastCall) { 6142 ComputePtrOff(); 6143 6144 /* Compute GPR index associated with argument offset. */ 6145 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6146 GPR_idx = std::min(GPR_idx, NumGPRs); 6147 } 6148 6149 // Promote integers to 64-bit values. 6150 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6151 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6152 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6153 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6154 } 6155 6156 // FIXME memcpy is used way more than necessary. Correctness first. 6157 // Note: "by value" is code for passing a structure by value, not 6158 // basic types. 6159 if (Flags.isByVal()) { 6160 // Note: Size includes alignment padding, so 6161 // struct x { short a; char b; } 6162 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6163 // These are the proper values we need for right-justifying the 6164 // aggregate in a parameter register. 6165 unsigned Size = Flags.getByValSize(); 6166 6167 // An empty aggregate parameter takes up no storage and no 6168 // registers. 6169 if (Size == 0) 6170 continue; 6171 6172 if (IsFastCall) 6173 ComputePtrOff(); 6174 6175 // All aggregates smaller than 8 bytes must be passed right-justified. 6176 if (Size==1 || Size==2 || Size==4) { 6177 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6178 if (GPR_idx != NumGPRs) { 6179 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6180 MachinePointerInfo(), VT); 6181 MemOpChains.push_back(Load.getValue(1)); 6182 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6183 6184 ArgOffset += PtrByteSize; 6185 continue; 6186 } 6187 } 6188 6189 if (GPR_idx == NumGPRs && Size < 8) { 6190 SDValue AddPtr = PtrOff; 6191 if (!isLittleEndian) { 6192 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6193 PtrOff.getValueType()); 6194 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6195 } 6196 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6197 CallSeqStart, 6198 Flags, DAG, dl); 6199 ArgOffset += PtrByteSize; 6200 continue; 6201 } 6202 // Copy entire object into memory. There are cases where gcc-generated 6203 // code assumes it is there, even if it could be put entirely into 6204 // registers. (This is not what the doc says.) 6205 6206 // FIXME: The above statement is likely due to a misunderstanding of the 6207 // documents. All arguments must be copied into the parameter area BY 6208 // THE CALLEE in the event that the callee takes the address of any 6209 // formal argument. That has not yet been implemented. However, it is 6210 // reasonable to use the stack area as a staging area for the register 6211 // load. 6212 6213 // Skip this for small aggregates, as we will use the same slot for a 6214 // right-justified copy, below. 6215 if (Size >= 8) 6216 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6217 CallSeqStart, 6218 Flags, DAG, dl); 6219 6220 // When a register is available, pass a small aggregate right-justified. 6221 if (Size < 8 && GPR_idx != NumGPRs) { 6222 // The easiest way to get this right-justified in a register 6223 // is to copy the structure into the rightmost portion of a 6224 // local variable slot, then load the whole slot into the 6225 // register. 6226 // FIXME: The memcpy seems to produce pretty awful code for 6227 // small aggregates, particularly for packed ones. 6228 // FIXME: It would be preferable to use the slot in the 6229 // parameter save area instead of a new local variable. 6230 SDValue AddPtr = PtrOff; 6231 if (!isLittleEndian) { 6232 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6233 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6234 } 6235 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6236 CallSeqStart, 6237 Flags, DAG, dl); 6238 6239 // Load the slot into the register. 6240 SDValue Load = 6241 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6242 MemOpChains.push_back(Load.getValue(1)); 6243 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6244 6245 // Done with this argument. 6246 ArgOffset += PtrByteSize; 6247 continue; 6248 } 6249 6250 // For aggregates larger than PtrByteSize, copy the pieces of the 6251 // object that fit into registers from the parameter save area. 6252 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6253 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6254 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6255 if (GPR_idx != NumGPRs) { 6256 SDValue Load = 6257 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6258 MemOpChains.push_back(Load.getValue(1)); 6259 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6260 ArgOffset += PtrByteSize; 6261 } else { 6262 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6263 break; 6264 } 6265 } 6266 continue; 6267 } 6268 6269 switch (Arg.getSimpleValueType().SimpleTy) { 6270 default: llvm_unreachable("Unexpected ValueType for argument!"); 6271 case MVT::i1: 6272 case MVT::i32: 6273 case MVT::i64: 6274 if (Flags.isNest()) { 6275 // The 'nest' parameter, if any, is passed in R11. 6276 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6277 break; 6278 } 6279 6280 // These can be scalar arguments or elements of an integer array type 6281 // passed directly. Clang may use those instead of "byval" aggregate 6282 // types to avoid forcing arguments to memory unnecessarily. 6283 if (GPR_idx != NumGPRs) { 6284 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6285 } else { 6286 if (IsFastCall) 6287 ComputePtrOff(); 6288 6289 assert(HasParameterArea && 6290 "Parameter area must exist to pass an argument in memory."); 6291 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6292 true, CFlags.IsTailCall, false, MemOpChains, 6293 TailCallArguments, dl); 6294 if (IsFastCall) 6295 ArgOffset += PtrByteSize; 6296 } 6297 if (!IsFastCall) 6298 ArgOffset += PtrByteSize; 6299 break; 6300 case MVT::f32: 6301 case MVT::f64: { 6302 // These can be scalar arguments or elements of a float array type 6303 // passed directly. The latter are used to implement ELFv2 homogenous 6304 // float aggregates. 6305 6306 // Named arguments go into FPRs first, and once they overflow, the 6307 // remaining arguments go into GPRs and then the parameter save area. 6308 // Unnamed arguments for vararg functions always go to GPRs and 6309 // then the parameter save area. For now, put all arguments to vararg 6310 // routines always in both locations (FPR *and* GPR or stack slot). 6311 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6312 bool NeededLoad = false; 6313 6314 // First load the argument into the next available FPR. 6315 if (FPR_idx != NumFPRs) 6316 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6317 6318 // Next, load the argument into GPR or stack slot if needed. 6319 if (!NeedGPROrStack) 6320 ; 6321 else if (GPR_idx != NumGPRs && !IsFastCall) { 6322 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6323 // once we support fp <-> gpr moves. 6324 6325 // In the non-vararg case, this can only ever happen in the 6326 // presence of f32 array types, since otherwise we never run 6327 // out of FPRs before running out of GPRs. 6328 SDValue ArgVal; 6329 6330 // Double values are always passed in a single GPR. 6331 if (Arg.getValueType() != MVT::f32) { 6332 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6333 6334 // Non-array float values are extended and passed in a GPR. 6335 } else if (!Flags.isInConsecutiveRegs()) { 6336 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6337 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6338 6339 // If we have an array of floats, we collect every odd element 6340 // together with its predecessor into one GPR. 6341 } else if (ArgOffset % PtrByteSize != 0) { 6342 SDValue Lo, Hi; 6343 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6344 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6345 if (!isLittleEndian) 6346 std::swap(Lo, Hi); 6347 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6348 6349 // The final element, if even, goes into the first half of a GPR. 6350 } else if (Flags.isInConsecutiveRegsLast()) { 6351 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6352 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6353 if (!isLittleEndian) 6354 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6355 DAG.getConstant(32, dl, MVT::i32)); 6356 6357 // Non-final even elements are skipped; they will be handled 6358 // together the with subsequent argument on the next go-around. 6359 } else 6360 ArgVal = SDValue(); 6361 6362 if (ArgVal.getNode()) 6363 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6364 } else { 6365 if (IsFastCall) 6366 ComputePtrOff(); 6367 6368 // Single-precision floating-point values are mapped to the 6369 // second (rightmost) word of the stack doubleword. 6370 if (Arg.getValueType() == MVT::f32 && 6371 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6372 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6373 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6374 } 6375 6376 assert(HasParameterArea && 6377 "Parameter area must exist to pass an argument in memory."); 6378 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6379 true, CFlags.IsTailCall, false, MemOpChains, 6380 TailCallArguments, dl); 6381 6382 NeededLoad = true; 6383 } 6384 // When passing an array of floats, the array occupies consecutive 6385 // space in the argument area; only round up to the next doubleword 6386 // at the end of the array. Otherwise, each float takes 8 bytes. 6387 if (!IsFastCall || NeededLoad) { 6388 ArgOffset += (Arg.getValueType() == MVT::f32 && 6389 Flags.isInConsecutiveRegs()) ? 4 : 8; 6390 if (Flags.isInConsecutiveRegsLast()) 6391 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6392 } 6393 break; 6394 } 6395 case MVT::v4f32: 6396 case MVT::v4i32: 6397 case MVT::v8i16: 6398 case MVT::v16i8: 6399 case MVT::v2f64: 6400 case MVT::v2i64: 6401 case MVT::v1i128: 6402 case MVT::f128: 6403 if (!Subtarget.hasQPX()) { 6404 // These can be scalar arguments or elements of a vector array type 6405 // passed directly. The latter are used to implement ELFv2 homogenous 6406 // vector aggregates. 6407 6408 // For a varargs call, named arguments go into VRs or on the stack as 6409 // usual; unnamed arguments always go to the stack or the corresponding 6410 // GPRs when within range. For now, we always put the value in both 6411 // locations (or even all three). 6412 if (CFlags.IsVarArg) { 6413 assert(HasParameterArea && 6414 "Parameter area must exist if we have a varargs call."); 6415 // We could elide this store in the case where the object fits 6416 // entirely in R registers. Maybe later. 6417 SDValue Store = 6418 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6419 MemOpChains.push_back(Store); 6420 if (VR_idx != NumVRs) { 6421 SDValue Load = 6422 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6423 MemOpChains.push_back(Load.getValue(1)); 6424 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6425 } 6426 ArgOffset += 16; 6427 for (unsigned i=0; i<16; i+=PtrByteSize) { 6428 if (GPR_idx == NumGPRs) 6429 break; 6430 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6431 DAG.getConstant(i, dl, PtrVT)); 6432 SDValue Load = 6433 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6434 MemOpChains.push_back(Load.getValue(1)); 6435 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6436 } 6437 break; 6438 } 6439 6440 // Non-varargs Altivec params go into VRs or on the stack. 6441 if (VR_idx != NumVRs) { 6442 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6443 } else { 6444 if (IsFastCall) 6445 ComputePtrOff(); 6446 6447 assert(HasParameterArea && 6448 "Parameter area must exist to pass an argument in memory."); 6449 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6450 true, CFlags.IsTailCall, true, MemOpChains, 6451 TailCallArguments, dl); 6452 if (IsFastCall) 6453 ArgOffset += 16; 6454 } 6455 6456 if (!IsFastCall) 6457 ArgOffset += 16; 6458 break; 6459 } // not QPX 6460 6461 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6462 "Invalid QPX parameter type"); 6463 6464 LLVM_FALLTHROUGH; 6465 case MVT::v4f64: 6466 case MVT::v4i1: { 6467 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6468 if (CFlags.IsVarArg) { 6469 assert(HasParameterArea && 6470 "Parameter area must exist if we have a varargs call."); 6471 // We could elide this store in the case where the object fits 6472 // entirely in R registers. Maybe later. 6473 SDValue Store = 6474 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6475 MemOpChains.push_back(Store); 6476 if (QFPR_idx != NumQFPRs) { 6477 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6478 PtrOff, MachinePointerInfo()); 6479 MemOpChains.push_back(Load.getValue(1)); 6480 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6481 } 6482 ArgOffset += (IsF32 ? 16 : 32); 6483 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6484 if (GPR_idx == NumGPRs) 6485 break; 6486 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6487 DAG.getConstant(i, dl, PtrVT)); 6488 SDValue Load = 6489 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6490 MemOpChains.push_back(Load.getValue(1)); 6491 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6492 } 6493 break; 6494 } 6495 6496 // Non-varargs QPX params go into registers or on the stack. 6497 if (QFPR_idx != NumQFPRs) { 6498 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6499 } else { 6500 if (IsFastCall) 6501 ComputePtrOff(); 6502 6503 assert(HasParameterArea && 6504 "Parameter area must exist to pass an argument in memory."); 6505 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6506 true, CFlags.IsTailCall, true, MemOpChains, 6507 TailCallArguments, dl); 6508 if (IsFastCall) 6509 ArgOffset += (IsF32 ? 16 : 32); 6510 } 6511 6512 if (!IsFastCall) 6513 ArgOffset += (IsF32 ? 16 : 32); 6514 break; 6515 } 6516 } 6517 } 6518 6519 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6520 "mismatch in size of parameter area"); 6521 (void)NumBytesActuallyUsed; 6522 6523 if (!MemOpChains.empty()) 6524 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6525 6526 // Check if this is an indirect call (MTCTR/BCTRL). 6527 // See prepareDescriptorIndirectCall and buildCallOperands for more 6528 // information about calls through function pointers in the 64-bit SVR4 ABI. 6529 if (CFlags.IsIndirect) { 6530 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6531 // caller in the TOC save area. 6532 if (isTOCSaveRestoreRequired(Subtarget)) { 6533 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6534 // Load r2 into a virtual register and store it to the TOC save area. 6535 setUsesTOCBasePtr(DAG); 6536 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6537 // TOC save area offset. 6538 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6539 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6540 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6541 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6542 MachinePointerInfo::getStack( 6543 DAG.getMachineFunction(), TOCSaveOffset)); 6544 } 6545 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6546 // This does not mean the MTCTR instruction must use R12; it's easier 6547 // to model this as an extra parameter, so do that. 6548 if (isELFv2ABI && !CFlags.IsPatchPoint) 6549 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6550 } 6551 6552 // Build a sequence of copy-to-reg nodes chained together with token chain 6553 // and flag operands which copy the outgoing args into the appropriate regs. 6554 SDValue InFlag; 6555 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6556 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6557 RegsToPass[i].second, InFlag); 6558 InFlag = Chain.getValue(1); 6559 } 6560 6561 if (CFlags.IsTailCall && !IsSibCall) 6562 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6563 TailCallArguments); 6564 6565 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6566 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6567 } 6568 6569 SDValue PPCTargetLowering::LowerCall_Darwin( 6570 SDValue Chain, SDValue Callee, CallFlags CFlags, 6571 const SmallVectorImpl<ISD::OutputArg> &Outs, 6572 const SmallVectorImpl<SDValue> &OutVals, 6573 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6574 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6575 const CallBase *CB) const { 6576 unsigned NumOps = Outs.size(); 6577 6578 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6579 bool isPPC64 = PtrVT == MVT::i64; 6580 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6581 6582 MachineFunction &MF = DAG.getMachineFunction(); 6583 6584 // Mark this function as potentially containing a function that contains a 6585 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6586 // and restoring the callers stack pointer in this functions epilog. This is 6587 // done because by tail calling the called function might overwrite the value 6588 // in this function's (MF) stack pointer stack slot 0(SP). 6589 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6590 CFlags.CallConv == CallingConv::Fast) 6591 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6592 6593 // Count how many bytes are to be pushed on the stack, including the linkage 6594 // area, and parameter passing area. We start with 24/48 bytes, which is 6595 // prereserved space for [SP][CR][LR][3 x unused]. 6596 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6597 unsigned NumBytes = LinkageSize; 6598 6599 // Add up all the space actually used. 6600 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6601 // they all go in registers, but we must reserve stack space for them for 6602 // possible use by the caller. In varargs or 64-bit calls, parameters are 6603 // assigned stack space in order, with padding so Altivec parameters are 6604 // 16-byte aligned. 6605 unsigned nAltivecParamsAtEnd = 0; 6606 for (unsigned i = 0; i != NumOps; ++i) { 6607 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6608 EVT ArgVT = Outs[i].VT; 6609 // Varargs Altivec parameters are padded to a 16 byte boundary. 6610 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6611 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6612 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6613 if (!CFlags.IsVarArg && !isPPC64) { 6614 // Non-varargs Altivec parameters go after all the non-Altivec 6615 // parameters; handle those later so we know how much padding we need. 6616 nAltivecParamsAtEnd++; 6617 continue; 6618 } 6619 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6620 NumBytes = ((NumBytes+15)/16)*16; 6621 } 6622 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6623 } 6624 6625 // Allow for Altivec parameters at the end, if needed. 6626 if (nAltivecParamsAtEnd) { 6627 NumBytes = ((NumBytes+15)/16)*16; 6628 NumBytes += 16*nAltivecParamsAtEnd; 6629 } 6630 6631 // The prolog code of the callee may store up to 8 GPR argument registers to 6632 // the stack, allowing va_start to index over them in memory if its varargs. 6633 // Because we cannot tell if this is needed on the caller side, we have to 6634 // conservatively assume that it is needed. As such, make sure we have at 6635 // least enough stack space for the caller to store the 8 GPRs. 6636 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6637 6638 // Tail call needs the stack to be aligned. 6639 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6640 CFlags.CallConv == CallingConv::Fast) 6641 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6642 6643 // Calculate by how many bytes the stack has to be adjusted in case of tail 6644 // call optimization. 6645 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6646 6647 // To protect arguments on the stack from being clobbered in a tail call, 6648 // force all the loads to happen before doing any other lowering. 6649 if (CFlags.IsTailCall) 6650 Chain = DAG.getStackArgumentTokenFactor(Chain); 6651 6652 // Adjust the stack pointer for the new arguments... 6653 // These operations are automatically eliminated by the prolog/epilog pass 6654 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6655 SDValue CallSeqStart = Chain; 6656 6657 // Load the return address and frame pointer so it can be move somewhere else 6658 // later. 6659 SDValue LROp, FPOp; 6660 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6661 6662 // Set up a copy of the stack pointer for use loading and storing any 6663 // arguments that may not fit in the registers available for argument 6664 // passing. 6665 SDValue StackPtr; 6666 if (isPPC64) 6667 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6668 else 6669 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6670 6671 // Figure out which arguments are going to go in registers, and which in 6672 // memory. Also, if this is a vararg function, floating point operations 6673 // must be stored to our stack, and loaded into integer regs as well, if 6674 // any integer regs are available for argument passing. 6675 unsigned ArgOffset = LinkageSize; 6676 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6677 6678 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6679 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6680 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6681 }; 6682 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6683 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6684 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6685 }; 6686 static const MCPhysReg VR[] = { 6687 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6688 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6689 }; 6690 const unsigned NumGPRs = array_lengthof(GPR_32); 6691 const unsigned NumFPRs = 13; 6692 const unsigned NumVRs = array_lengthof(VR); 6693 6694 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6695 6696 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6697 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6698 6699 SmallVector<SDValue, 8> MemOpChains; 6700 for (unsigned i = 0; i != NumOps; ++i) { 6701 SDValue Arg = OutVals[i]; 6702 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6703 6704 // PtrOff will be used to store the current argument to the stack if a 6705 // register cannot be found for it. 6706 SDValue PtrOff; 6707 6708 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6709 6710 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6711 6712 // On PPC64, promote integers to 64-bit values. 6713 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6714 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6715 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6716 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6717 } 6718 6719 // FIXME memcpy is used way more than necessary. Correctness first. 6720 // Note: "by value" is code for passing a structure by value, not 6721 // basic types. 6722 if (Flags.isByVal()) { 6723 unsigned Size = Flags.getByValSize(); 6724 // Very small objects are passed right-justified. Everything else is 6725 // passed left-justified. 6726 if (Size==1 || Size==2) { 6727 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6728 if (GPR_idx != NumGPRs) { 6729 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6730 MachinePointerInfo(), VT); 6731 MemOpChains.push_back(Load.getValue(1)); 6732 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6733 6734 ArgOffset += PtrByteSize; 6735 } else { 6736 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6737 PtrOff.getValueType()); 6738 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6739 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6740 CallSeqStart, 6741 Flags, DAG, dl); 6742 ArgOffset += PtrByteSize; 6743 } 6744 continue; 6745 } 6746 // Copy entire object into memory. There are cases where gcc-generated 6747 // code assumes it is there, even if it could be put entirely into 6748 // registers. (This is not what the doc says.) 6749 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6750 CallSeqStart, 6751 Flags, DAG, dl); 6752 6753 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6754 // copy the pieces of the object that fit into registers from the 6755 // parameter save area. 6756 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6757 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6758 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6759 if (GPR_idx != NumGPRs) { 6760 SDValue Load = 6761 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6762 MemOpChains.push_back(Load.getValue(1)); 6763 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6764 ArgOffset += PtrByteSize; 6765 } else { 6766 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6767 break; 6768 } 6769 } 6770 continue; 6771 } 6772 6773 switch (Arg.getSimpleValueType().SimpleTy) { 6774 default: llvm_unreachable("Unexpected ValueType for argument!"); 6775 case MVT::i1: 6776 case MVT::i32: 6777 case MVT::i64: 6778 if (GPR_idx != NumGPRs) { 6779 if (Arg.getValueType() == MVT::i1) 6780 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6781 6782 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6783 } else { 6784 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6785 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6786 TailCallArguments, dl); 6787 } 6788 ArgOffset += PtrByteSize; 6789 break; 6790 case MVT::f32: 6791 case MVT::f64: 6792 if (FPR_idx != NumFPRs) { 6793 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6794 6795 if (CFlags.IsVarArg) { 6796 SDValue Store = 6797 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6798 MemOpChains.push_back(Store); 6799 6800 // Float varargs are always shadowed in available integer registers 6801 if (GPR_idx != NumGPRs) { 6802 SDValue Load = 6803 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6804 MemOpChains.push_back(Load.getValue(1)); 6805 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6806 } 6807 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6808 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6809 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6810 SDValue Load = 6811 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6812 MemOpChains.push_back(Load.getValue(1)); 6813 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6814 } 6815 } else { 6816 // If we have any FPRs remaining, we may also have GPRs remaining. 6817 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6818 // GPRs. 6819 if (GPR_idx != NumGPRs) 6820 ++GPR_idx; 6821 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6822 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6823 ++GPR_idx; 6824 } 6825 } else 6826 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6827 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6828 TailCallArguments, dl); 6829 if (isPPC64) 6830 ArgOffset += 8; 6831 else 6832 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6833 break; 6834 case MVT::v4f32: 6835 case MVT::v4i32: 6836 case MVT::v8i16: 6837 case MVT::v16i8: 6838 if (CFlags.IsVarArg) { 6839 // These go aligned on the stack, or in the corresponding R registers 6840 // when within range. The Darwin PPC ABI doc claims they also go in 6841 // V registers; in fact gcc does this only for arguments that are 6842 // prototyped, not for those that match the ... We do it for all 6843 // arguments, seems to work. 6844 while (ArgOffset % 16 !=0) { 6845 ArgOffset += PtrByteSize; 6846 if (GPR_idx != NumGPRs) 6847 GPR_idx++; 6848 } 6849 // We could elide this store in the case where the object fits 6850 // entirely in R registers. Maybe later. 6851 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6852 DAG.getConstant(ArgOffset, dl, PtrVT)); 6853 SDValue Store = 6854 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6855 MemOpChains.push_back(Store); 6856 if (VR_idx != NumVRs) { 6857 SDValue Load = 6858 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6859 MemOpChains.push_back(Load.getValue(1)); 6860 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6861 } 6862 ArgOffset += 16; 6863 for (unsigned i=0; i<16; i+=PtrByteSize) { 6864 if (GPR_idx == NumGPRs) 6865 break; 6866 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6867 DAG.getConstant(i, dl, PtrVT)); 6868 SDValue Load = 6869 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6870 MemOpChains.push_back(Load.getValue(1)); 6871 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6872 } 6873 break; 6874 } 6875 6876 // Non-varargs Altivec params generally go in registers, but have 6877 // stack space allocated at the end. 6878 if (VR_idx != NumVRs) { 6879 // Doesn't have GPR space allocated. 6880 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6881 } else if (nAltivecParamsAtEnd==0) { 6882 // We are emitting Altivec params in order. 6883 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6884 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6885 TailCallArguments, dl); 6886 ArgOffset += 16; 6887 } 6888 break; 6889 } 6890 } 6891 // If all Altivec parameters fit in registers, as they usually do, 6892 // they get stack space following the non-Altivec parameters. We 6893 // don't track this here because nobody below needs it. 6894 // If there are more Altivec parameters than fit in registers emit 6895 // the stores here. 6896 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6897 unsigned j = 0; 6898 // Offset is aligned; skip 1st 12 params which go in V registers. 6899 ArgOffset = ((ArgOffset+15)/16)*16; 6900 ArgOffset += 12*16; 6901 for (unsigned i = 0; i != NumOps; ++i) { 6902 SDValue Arg = OutVals[i]; 6903 EVT ArgType = Outs[i].VT; 6904 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6905 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6906 if (++j > NumVRs) { 6907 SDValue PtrOff; 6908 // We are emitting Altivec params in order. 6909 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6910 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6911 TailCallArguments, dl); 6912 ArgOffset += 16; 6913 } 6914 } 6915 } 6916 } 6917 6918 if (!MemOpChains.empty()) 6919 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6920 6921 // On Darwin, R12 must contain the address of an indirect callee. This does 6922 // not mean the MTCTR instruction must use R12; it's easier to model this as 6923 // an extra parameter, so do that. 6924 if (CFlags.IsIndirect) { 6925 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6926 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6927 PPC::R12), Callee)); 6928 } 6929 6930 // Build a sequence of copy-to-reg nodes chained together with token chain 6931 // and flag operands which copy the outgoing args into the appropriate regs. 6932 SDValue InFlag; 6933 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6934 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6935 RegsToPass[i].second, InFlag); 6936 InFlag = Chain.getValue(1); 6937 } 6938 6939 if (CFlags.IsTailCall) 6940 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6941 TailCallArguments); 6942 6943 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6944 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6945 } 6946 6947 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6948 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6949 CCState &State) { 6950 6951 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6952 State.getMachineFunction().getSubtarget()); 6953 const bool IsPPC64 = Subtarget.isPPC64(); 6954 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6955 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6956 6957 assert((!ValVT.isInteger() || 6958 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6959 "Integer argument exceeds register size: should have been legalized"); 6960 6961 if (ValVT == MVT::f128) 6962 report_fatal_error("f128 is unimplemented on AIX."); 6963 6964 if (ArgFlags.isNest()) 6965 report_fatal_error("Nest arguments are unimplemented."); 6966 6967 if (ValVT.isVector() || LocVT.isVector()) 6968 report_fatal_error("Vector arguments are unimplemented on AIX."); 6969 6970 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6971 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6972 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6973 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6974 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6975 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6976 6977 if (ArgFlags.isByVal()) { 6978 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 6979 report_fatal_error("Pass-by-value arguments with alignment greater than " 6980 "register width are not supported."); 6981 6982 const unsigned ByValSize = ArgFlags.getByValSize(); 6983 6984 // An empty aggregate parameter takes up no storage and no registers, 6985 // but needs a MemLoc for a stack slot for the formal arguments side. 6986 if (ByValSize == 0) { 6987 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6988 State.getNextStackOffset(), RegVT, 6989 LocInfo)); 6990 return false; 6991 } 6992 6993 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 6994 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 6995 for (const unsigned E = Offset + StackSize; Offset < E; 6996 Offset += PtrByteSize) { 6997 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6998 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6999 else { 7000 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7001 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7002 LocInfo)); 7003 break; 7004 } 7005 } 7006 return false; 7007 } 7008 7009 // Arguments always reserve parameter save area. 7010 switch (ValVT.SimpleTy) { 7011 default: 7012 report_fatal_error("Unhandled value type for argument."); 7013 case MVT::i64: 7014 // i64 arguments should have been split to i32 for PPC32. 7015 assert(IsPPC64 && "PPC32 should have split i64 values."); 7016 LLVM_FALLTHROUGH; 7017 case MVT::i1: 7018 case MVT::i32: { 7019 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 7020 // AIX integer arguments are always passed in register width. 7021 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7022 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7023 : CCValAssign::LocInfo::ZExt; 7024 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7025 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7026 else 7027 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7028 7029 return false; 7030 } 7031 case MVT::f32: 7032 case MVT::f64: { 7033 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7034 const unsigned StoreSize = LocVT.getStoreSize(); 7035 // Floats are always 4-byte aligned in the PSA on AIX. 7036 // This includes f64 in 64-bit mode for ABI compatibility. 7037 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 7038 unsigned FReg = State.AllocateReg(FPR); 7039 if (FReg) 7040 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7041 7042 // Reserve and initialize GPRs or initialize the PSA as required. 7043 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 7044 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7045 assert(FReg && "An FPR should be available when a GPR is reserved."); 7046 if (State.isVarArg()) { 7047 // Successfully reserved GPRs are only initialized for vararg calls. 7048 // Custom handling is required for: 7049 // f64 in PPC32 needs to be split into 2 GPRs. 7050 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7051 State.addLoc( 7052 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7053 } 7054 } else { 7055 // If there are insufficient GPRs, the PSA needs to be initialized. 7056 // Initialization occurs even if an FPR was initialized for 7057 // compatibility with the AIX XL compiler. The full memory for the 7058 // argument will be initialized even if a prior word is saved in GPR. 7059 // A custom memLoc is used when the argument also passes in FPR so 7060 // that the callee handling can skip over it easily. 7061 State.addLoc( 7062 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7063 LocInfo) 7064 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7065 break; 7066 } 7067 } 7068 7069 return false; 7070 } 7071 } 7072 return true; 7073 } 7074 7075 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7076 bool IsPPC64) { 7077 assert((IsPPC64 || SVT != MVT::i64) && 7078 "i64 should have been split for 32-bit codegen."); 7079 7080 switch (SVT) { 7081 default: 7082 report_fatal_error("Unexpected value type for formal argument"); 7083 case MVT::i1: 7084 case MVT::i32: 7085 case MVT::i64: 7086 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7087 case MVT::f32: 7088 return &PPC::F4RCRegClass; 7089 case MVT::f64: 7090 return &PPC::F8RCRegClass; 7091 } 7092 } 7093 7094 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7095 SelectionDAG &DAG, SDValue ArgValue, 7096 MVT LocVT, const SDLoc &dl) { 7097 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7098 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7099 7100 if (Flags.isSExt()) 7101 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7102 DAG.getValueType(ValVT)); 7103 else if (Flags.isZExt()) 7104 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7105 DAG.getValueType(ValVT)); 7106 7107 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7108 } 7109 7110 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7111 const unsigned LASize = FL->getLinkageSize(); 7112 7113 if (PPC::GPRCRegClass.contains(Reg)) { 7114 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7115 "Reg must be a valid argument register!"); 7116 return LASize + 4 * (Reg - PPC::R3); 7117 } 7118 7119 if (PPC::G8RCRegClass.contains(Reg)) { 7120 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7121 "Reg must be a valid argument register!"); 7122 return LASize + 8 * (Reg - PPC::X3); 7123 } 7124 7125 llvm_unreachable("Only general purpose registers expected."); 7126 } 7127 7128 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7129 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7130 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7131 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7132 7133 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7134 CallConv == CallingConv::Fast) && 7135 "Unexpected calling convention!"); 7136 7137 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7138 report_fatal_error("Tail call support is unimplemented on AIX."); 7139 7140 if (useSoftFloat()) 7141 report_fatal_error("Soft float support is unimplemented on AIX."); 7142 7143 const PPCSubtarget &Subtarget = 7144 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7145 if (Subtarget.hasQPX()) 7146 report_fatal_error("QPX support is not supported on AIX."); 7147 7148 const bool IsPPC64 = Subtarget.isPPC64(); 7149 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7150 7151 // Assign locations to all of the incoming arguments. 7152 SmallVector<CCValAssign, 16> ArgLocs; 7153 MachineFunction &MF = DAG.getMachineFunction(); 7154 MachineFrameInfo &MFI = MF.getFrameInfo(); 7155 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7156 7157 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7158 // Reserve space for the linkage area on the stack. 7159 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7160 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7161 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7162 7163 SmallVector<SDValue, 8> MemOps; 7164 7165 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7166 CCValAssign &VA = ArgLocs[I++]; 7167 MVT LocVT = VA.getLocVT(); 7168 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7169 7170 // For compatibility with the AIX XL compiler, the float args in the 7171 // parameter save area are initialized even if the argument is available 7172 // in register. The caller is required to initialize both the register 7173 // and memory, however, the callee can choose to expect it in either. 7174 // The memloc is dismissed here because the argument is retrieved from 7175 // the register. 7176 if (VA.isMemLoc() && VA.needsCustom()) 7177 continue; 7178 7179 if (Flags.isByVal() && VA.isMemLoc()) { 7180 const unsigned Size = 7181 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7182 PtrByteSize); 7183 const int FI = MF.getFrameInfo().CreateFixedObject( 7184 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7185 /* IsAliased */ true); 7186 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7187 InVals.push_back(FIN); 7188 7189 continue; 7190 } 7191 7192 if (Flags.isByVal()) { 7193 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7194 7195 const MCPhysReg ArgReg = VA.getLocReg(); 7196 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7197 7198 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7199 report_fatal_error("Over aligned byvals not supported yet."); 7200 7201 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7202 const int FI = MF.getFrameInfo().CreateFixedObject( 7203 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7204 /* IsAliased */ true); 7205 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7206 InVals.push_back(FIN); 7207 7208 // Add live ins for all the RegLocs for the same ByVal. 7209 const TargetRegisterClass *RegClass = 7210 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7211 7212 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7213 unsigned Offset) { 7214 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7215 // Since the callers side has left justified the aggregate in the 7216 // register, we can simply store the entire register into the stack 7217 // slot. 7218 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7219 // The store to the fixedstack object is needed becuase accessing a 7220 // field of the ByVal will use a gep and load. Ideally we will optimize 7221 // to extracting the value from the register directly, and elide the 7222 // stores when the arguments address is not taken, but that will need to 7223 // be future work. 7224 SDValue Store = 7225 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7226 DAG.getObjectPtrOffset(dl, FIN, Offset), 7227 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7228 7229 MemOps.push_back(Store); 7230 }; 7231 7232 unsigned Offset = 0; 7233 HandleRegLoc(VA.getLocReg(), Offset); 7234 Offset += PtrByteSize; 7235 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7236 Offset += PtrByteSize) { 7237 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7238 "RegLocs should be for ByVal argument."); 7239 7240 const CCValAssign RL = ArgLocs[I++]; 7241 HandleRegLoc(RL.getLocReg(), Offset); 7242 } 7243 7244 if (Offset != StackSize) { 7245 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7246 "Expected MemLoc for remaining bytes."); 7247 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7248 // Consume the MemLoc.The InVal has already been emitted, so nothing 7249 // more needs to be done. 7250 ++I; 7251 } 7252 7253 continue; 7254 } 7255 7256 EVT ValVT = VA.getValVT(); 7257 if (VA.isRegLoc() && !VA.needsCustom()) { 7258 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7259 unsigned VReg = 7260 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7261 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7262 if (ValVT.isScalarInteger() && 7263 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7264 ArgValue = 7265 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7266 } 7267 InVals.push_back(ArgValue); 7268 continue; 7269 } 7270 if (VA.isMemLoc()) { 7271 const unsigned LocSize = LocVT.getStoreSize(); 7272 const unsigned ValSize = ValVT.getStoreSize(); 7273 assert((ValSize <= LocSize) && 7274 "Object size is larger than size of MemLoc"); 7275 int CurArgOffset = VA.getLocMemOffset(); 7276 // Objects are right-justified because AIX is big-endian. 7277 if (LocSize > ValSize) 7278 CurArgOffset += LocSize - ValSize; 7279 // Potential tail calls could cause overwriting of argument stack slots. 7280 const bool IsImmutable = 7281 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7282 (CallConv == CallingConv::Fast)); 7283 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7284 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7285 SDValue ArgValue = 7286 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7287 InVals.push_back(ArgValue); 7288 continue; 7289 } 7290 } 7291 7292 // On AIX a minimum of 8 words is saved to the parameter save area. 7293 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7294 // Area that is at least reserved in the caller of this function. 7295 unsigned CallerReservedArea = 7296 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7297 7298 // Set the size that is at least reserved in caller of this function. Tail 7299 // call optimized function's reserved stack space needs to be aligned so 7300 // that taking the difference between two stack areas will result in an 7301 // aligned stack. 7302 CallerReservedArea = 7303 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7304 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7305 FuncInfo->setMinReservedArea(CallerReservedArea); 7306 7307 if (isVarArg) { 7308 FuncInfo->setVarArgsFrameIndex( 7309 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7310 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7311 7312 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7313 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7314 7315 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7316 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7317 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7318 7319 // The fixed integer arguments of a variadic function are stored to the 7320 // VarArgsFrameIndex on the stack so that they may be loaded by 7321 // dereferencing the result of va_next. 7322 for (unsigned GPRIndex = 7323 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7324 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7325 7326 const unsigned VReg = 7327 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7328 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7329 7330 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7331 SDValue Store = 7332 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7333 MemOps.push_back(Store); 7334 // Increment the address for the next argument to store. 7335 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7336 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7337 } 7338 } 7339 7340 if (!MemOps.empty()) 7341 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7342 7343 return Chain; 7344 } 7345 7346 SDValue PPCTargetLowering::LowerCall_AIX( 7347 SDValue Chain, SDValue Callee, CallFlags CFlags, 7348 const SmallVectorImpl<ISD::OutputArg> &Outs, 7349 const SmallVectorImpl<SDValue> &OutVals, 7350 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7351 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7352 const CallBase *CB) const { 7353 7354 assert((CFlags.CallConv == CallingConv::C || 7355 CFlags.CallConv == CallingConv::Cold || 7356 CFlags.CallConv == CallingConv::Fast) && 7357 "Unexpected calling convention!"); 7358 7359 if (CFlags.IsPatchPoint) 7360 report_fatal_error("This call type is unimplemented on AIX."); 7361 7362 const PPCSubtarget& Subtarget = 7363 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7364 if (Subtarget.hasQPX()) 7365 report_fatal_error("QPX is not supported on AIX."); 7366 if (Subtarget.hasAltivec()) 7367 report_fatal_error("Altivec support is unimplemented on AIX."); 7368 7369 MachineFunction &MF = DAG.getMachineFunction(); 7370 SmallVector<CCValAssign, 16> ArgLocs; 7371 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7372 *DAG.getContext()); 7373 7374 // Reserve space for the linkage save area (LSA) on the stack. 7375 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7376 // [SP][CR][LR][2 x reserved][TOC]. 7377 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7378 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7379 const bool IsPPC64 = Subtarget.isPPC64(); 7380 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7381 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7382 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7383 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7384 7385 // The prolog code of the callee may store up to 8 GPR argument registers to 7386 // the stack, allowing va_start to index over them in memory if the callee 7387 // is variadic. 7388 // Because we cannot tell if this is needed on the caller side, we have to 7389 // conservatively assume that it is needed. As such, make sure we have at 7390 // least enough stack space for the caller to store the 8 GPRs. 7391 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7392 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7393 CCInfo.getNextStackOffset()); 7394 7395 // Adjust the stack pointer for the new arguments... 7396 // These operations are automatically eliminated by the prolog/epilog pass. 7397 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7398 SDValue CallSeqStart = Chain; 7399 7400 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7401 SmallVector<SDValue, 8> MemOpChains; 7402 7403 // Set up a copy of the stack pointer for loading and storing any 7404 // arguments that may not fit in the registers available for argument 7405 // passing. 7406 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7407 : DAG.getRegister(PPC::R1, MVT::i32); 7408 7409 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7410 const unsigned ValNo = ArgLocs[I].getValNo(); 7411 SDValue Arg = OutVals[ValNo]; 7412 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7413 7414 if (Flags.isByVal()) { 7415 const unsigned ByValSize = Flags.getByValSize(); 7416 7417 // Nothing to do for zero-sized ByVals on the caller side. 7418 if (!ByValSize) { 7419 ++I; 7420 continue; 7421 } 7422 7423 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7424 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7425 (LoadOffset != 0) 7426 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7427 : Arg, 7428 MachinePointerInfo(), VT); 7429 }; 7430 7431 unsigned LoadOffset = 0; 7432 7433 // Initialize registers, which are fully occupied by the by-val argument. 7434 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7435 SDValue Load = GetLoad(PtrVT, LoadOffset); 7436 MemOpChains.push_back(Load.getValue(1)); 7437 LoadOffset += PtrByteSize; 7438 const CCValAssign &ByValVA = ArgLocs[I++]; 7439 assert(ByValVA.getValNo() == ValNo && 7440 "Unexpected location for pass-by-value argument."); 7441 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7442 } 7443 7444 if (LoadOffset == ByValSize) 7445 continue; 7446 7447 // There must be one more loc to handle the remainder. 7448 assert(ArgLocs[I].getValNo() == ValNo && 7449 "Expected additional location for by-value argument."); 7450 7451 if (ArgLocs[I].isMemLoc()) { 7452 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7453 const CCValAssign &ByValVA = ArgLocs[I++]; 7454 ISD::ArgFlagsTy MemcpyFlags = Flags; 7455 // Only memcpy the bytes that don't pass in register. 7456 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7457 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7458 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7459 : Arg, 7460 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7461 CallSeqStart, MemcpyFlags, DAG, dl); 7462 continue; 7463 } 7464 7465 // Initialize the final register residue. 7466 // Any residue that occupies the final by-val arg register must be 7467 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7468 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7469 // 2 and 1 byte loads. 7470 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7471 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7472 "Unexpected register residue for by-value argument."); 7473 SDValue ResidueVal; 7474 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7475 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7476 const MVT VT = 7477 N == 1 ? MVT::i8 7478 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7479 SDValue Load = GetLoad(VT, LoadOffset); 7480 MemOpChains.push_back(Load.getValue(1)); 7481 LoadOffset += N; 7482 Bytes += N; 7483 7484 // By-val arguments are passed left-justfied in register. 7485 // Every load here needs to be shifted, otherwise a full register load 7486 // should have been used. 7487 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7488 "Unexpected load emitted during handling of pass-by-value " 7489 "argument."); 7490 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7491 EVT ShiftAmountTy = 7492 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7493 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7494 SDValue ShiftedLoad = 7495 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7496 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7497 ShiftedLoad) 7498 : ShiftedLoad; 7499 } 7500 7501 const CCValAssign &ByValVA = ArgLocs[I++]; 7502 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7503 continue; 7504 } 7505 7506 CCValAssign &VA = ArgLocs[I++]; 7507 const MVT LocVT = VA.getLocVT(); 7508 const MVT ValVT = VA.getValVT(); 7509 7510 switch (VA.getLocInfo()) { 7511 default: 7512 report_fatal_error("Unexpected argument extension type."); 7513 case CCValAssign::Full: 7514 break; 7515 case CCValAssign::ZExt: 7516 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7517 break; 7518 case CCValAssign::SExt: 7519 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7520 break; 7521 } 7522 7523 if (VA.isRegLoc() && !VA.needsCustom()) { 7524 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7525 continue; 7526 } 7527 7528 if (VA.isMemLoc()) { 7529 SDValue PtrOff = 7530 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7531 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7532 MemOpChains.push_back( 7533 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7534 7535 continue; 7536 } 7537 7538 // Custom handling is used for GPR initializations for vararg float 7539 // arguments. 7540 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7541 ValVT.isFloatingPoint() && LocVT.isInteger() && 7542 "Unexpected register handling for calling convention."); 7543 7544 SDValue ArgAsInt = 7545 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7546 7547 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7548 // f32 in 32-bit GPR 7549 // f64 in 64-bit GPR 7550 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7551 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7552 // f32 in 64-bit GPR. 7553 RegsToPass.push_back(std::make_pair( 7554 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7555 else { 7556 // f64 in two 32-bit GPRs 7557 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7558 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7559 "Unexpected custom register for argument!"); 7560 CCValAssign &GPR1 = VA; 7561 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7562 DAG.getConstant(32, dl, MVT::i8)); 7563 RegsToPass.push_back(std::make_pair( 7564 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7565 7566 if (I != E) { 7567 // If only 1 GPR was available, there will only be one custom GPR and 7568 // the argument will also pass in memory. 7569 CCValAssign &PeekArg = ArgLocs[I]; 7570 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7571 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7572 CCValAssign &GPR2 = ArgLocs[I++]; 7573 RegsToPass.push_back(std::make_pair( 7574 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7575 } 7576 } 7577 } 7578 } 7579 7580 if (!MemOpChains.empty()) 7581 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7582 7583 // For indirect calls, we need to save the TOC base to the stack for 7584 // restoration after the call. 7585 if (CFlags.IsIndirect) { 7586 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7587 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7588 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7589 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7590 const unsigned TOCSaveOffset = 7591 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7592 7593 setUsesTOCBasePtr(DAG); 7594 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7595 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7596 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7597 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7598 Chain = DAG.getStore( 7599 Val.getValue(1), dl, Val, AddPtr, 7600 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7601 } 7602 7603 // Build a sequence of copy-to-reg nodes chained together with token chain 7604 // and flag operands which copy the outgoing args into the appropriate regs. 7605 SDValue InFlag; 7606 for (auto Reg : RegsToPass) { 7607 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7608 InFlag = Chain.getValue(1); 7609 } 7610 7611 const int SPDiff = 0; 7612 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7613 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7614 } 7615 7616 bool 7617 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7618 MachineFunction &MF, bool isVarArg, 7619 const SmallVectorImpl<ISD::OutputArg> &Outs, 7620 LLVMContext &Context) const { 7621 SmallVector<CCValAssign, 16> RVLocs; 7622 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7623 return CCInfo.CheckReturn( 7624 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7625 ? RetCC_PPC_Cold 7626 : RetCC_PPC); 7627 } 7628 7629 SDValue 7630 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7631 bool isVarArg, 7632 const SmallVectorImpl<ISD::OutputArg> &Outs, 7633 const SmallVectorImpl<SDValue> &OutVals, 7634 const SDLoc &dl, SelectionDAG &DAG) const { 7635 SmallVector<CCValAssign, 16> RVLocs; 7636 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7637 *DAG.getContext()); 7638 CCInfo.AnalyzeReturn(Outs, 7639 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7640 ? RetCC_PPC_Cold 7641 : RetCC_PPC); 7642 7643 SDValue Flag; 7644 SmallVector<SDValue, 4> RetOps(1, Chain); 7645 7646 // Copy the result values into the output registers. 7647 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7648 CCValAssign &VA = RVLocs[i]; 7649 assert(VA.isRegLoc() && "Can only return in registers!"); 7650 7651 SDValue Arg = OutVals[RealResIdx]; 7652 7653 switch (VA.getLocInfo()) { 7654 default: llvm_unreachable("Unknown loc info!"); 7655 case CCValAssign::Full: break; 7656 case CCValAssign::AExt: 7657 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7658 break; 7659 case CCValAssign::ZExt: 7660 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7661 break; 7662 case CCValAssign::SExt: 7663 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7664 break; 7665 } 7666 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7667 bool isLittleEndian = Subtarget.isLittleEndian(); 7668 // Legalize ret f64 -> ret 2 x i32. 7669 SDValue SVal = 7670 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7671 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7672 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7673 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7674 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7675 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7676 Flag = Chain.getValue(1); 7677 VA = RVLocs[++i]; // skip ahead to next loc 7678 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7679 } else 7680 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7681 Flag = Chain.getValue(1); 7682 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7683 } 7684 7685 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7686 const MCPhysReg *I = 7687 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7688 if (I) { 7689 for (; *I; ++I) { 7690 7691 if (PPC::G8RCRegClass.contains(*I)) 7692 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7693 else if (PPC::F8RCRegClass.contains(*I)) 7694 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7695 else if (PPC::CRRCRegClass.contains(*I)) 7696 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7697 else if (PPC::VRRCRegClass.contains(*I)) 7698 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7699 else 7700 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7701 } 7702 } 7703 7704 RetOps[0] = Chain; // Update chain. 7705 7706 // Add the flag if we have it. 7707 if (Flag.getNode()) 7708 RetOps.push_back(Flag); 7709 7710 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7711 } 7712 7713 SDValue 7714 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7715 SelectionDAG &DAG) const { 7716 SDLoc dl(Op); 7717 7718 // Get the correct type for integers. 7719 EVT IntVT = Op.getValueType(); 7720 7721 // Get the inputs. 7722 SDValue Chain = Op.getOperand(0); 7723 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7724 // Build a DYNAREAOFFSET node. 7725 SDValue Ops[2] = {Chain, FPSIdx}; 7726 SDVTList VTs = DAG.getVTList(IntVT); 7727 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7728 } 7729 7730 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7731 SelectionDAG &DAG) const { 7732 // When we pop the dynamic allocation we need to restore the SP link. 7733 SDLoc dl(Op); 7734 7735 // Get the correct type for pointers. 7736 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7737 7738 // Construct the stack pointer operand. 7739 bool isPPC64 = Subtarget.isPPC64(); 7740 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7741 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7742 7743 // Get the operands for the STACKRESTORE. 7744 SDValue Chain = Op.getOperand(0); 7745 SDValue SaveSP = Op.getOperand(1); 7746 7747 // Load the old link SP. 7748 SDValue LoadLinkSP = 7749 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7750 7751 // Restore the stack pointer. 7752 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7753 7754 // Store the old link SP. 7755 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7756 } 7757 7758 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7759 MachineFunction &MF = DAG.getMachineFunction(); 7760 bool isPPC64 = Subtarget.isPPC64(); 7761 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7762 7763 // Get current frame pointer save index. The users of this index will be 7764 // primarily DYNALLOC instructions. 7765 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7766 int RASI = FI->getReturnAddrSaveIndex(); 7767 7768 // If the frame pointer save index hasn't been defined yet. 7769 if (!RASI) { 7770 // Find out what the fix offset of the frame pointer save area. 7771 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7772 // Allocate the frame index for frame pointer save area. 7773 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7774 // Save the result. 7775 FI->setReturnAddrSaveIndex(RASI); 7776 } 7777 return DAG.getFrameIndex(RASI, PtrVT); 7778 } 7779 7780 SDValue 7781 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7782 MachineFunction &MF = DAG.getMachineFunction(); 7783 bool isPPC64 = Subtarget.isPPC64(); 7784 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7785 7786 // Get current frame pointer save index. The users of this index will be 7787 // primarily DYNALLOC instructions. 7788 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7789 int FPSI = FI->getFramePointerSaveIndex(); 7790 7791 // If the frame pointer save index hasn't been defined yet. 7792 if (!FPSI) { 7793 // Find out what the fix offset of the frame pointer save area. 7794 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7795 // Allocate the frame index for frame pointer save area. 7796 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7797 // Save the result. 7798 FI->setFramePointerSaveIndex(FPSI); 7799 } 7800 return DAG.getFrameIndex(FPSI, PtrVT); 7801 } 7802 7803 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7804 SelectionDAG &DAG) const { 7805 // Get the inputs. 7806 SDValue Chain = Op.getOperand(0); 7807 SDValue Size = Op.getOperand(1); 7808 SDLoc dl(Op); 7809 7810 // Get the correct type for pointers. 7811 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7812 // Negate the size. 7813 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7814 DAG.getConstant(0, dl, PtrVT), Size); 7815 // Construct a node for the frame pointer save index. 7816 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7817 // Build a DYNALLOC node. 7818 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7819 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7820 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7821 } 7822 7823 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7824 SelectionDAG &DAG) const { 7825 MachineFunction &MF = DAG.getMachineFunction(); 7826 7827 bool isPPC64 = Subtarget.isPPC64(); 7828 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7829 7830 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7831 return DAG.getFrameIndex(FI, PtrVT); 7832 } 7833 7834 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7835 SelectionDAG &DAG) const { 7836 SDLoc DL(Op); 7837 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7838 DAG.getVTList(MVT::i32, MVT::Other), 7839 Op.getOperand(0), Op.getOperand(1)); 7840 } 7841 7842 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7843 SelectionDAG &DAG) const { 7844 SDLoc DL(Op); 7845 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7846 Op.getOperand(0), Op.getOperand(1)); 7847 } 7848 7849 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7850 if (Op.getValueType().isVector()) 7851 return LowerVectorLoad(Op, DAG); 7852 7853 assert(Op.getValueType() == MVT::i1 && 7854 "Custom lowering only for i1 loads"); 7855 7856 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7857 7858 SDLoc dl(Op); 7859 LoadSDNode *LD = cast<LoadSDNode>(Op); 7860 7861 SDValue Chain = LD->getChain(); 7862 SDValue BasePtr = LD->getBasePtr(); 7863 MachineMemOperand *MMO = LD->getMemOperand(); 7864 7865 SDValue NewLD = 7866 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7867 BasePtr, MVT::i8, MMO); 7868 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7869 7870 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7871 return DAG.getMergeValues(Ops, dl); 7872 } 7873 7874 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7875 if (Op.getOperand(1).getValueType().isVector()) 7876 return LowerVectorStore(Op, DAG); 7877 7878 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7879 "Custom lowering only for i1 stores"); 7880 7881 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7882 7883 SDLoc dl(Op); 7884 StoreSDNode *ST = cast<StoreSDNode>(Op); 7885 7886 SDValue Chain = ST->getChain(); 7887 SDValue BasePtr = ST->getBasePtr(); 7888 SDValue Value = ST->getValue(); 7889 MachineMemOperand *MMO = ST->getMemOperand(); 7890 7891 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7892 Value); 7893 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7894 } 7895 7896 // FIXME: Remove this once the ANDI glue bug is fixed: 7897 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7898 assert(Op.getValueType() == MVT::i1 && 7899 "Custom lowering only for i1 results"); 7900 7901 SDLoc DL(Op); 7902 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7903 } 7904 7905 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7906 SelectionDAG &DAG) const { 7907 7908 // Implements a vector truncate that fits in a vector register as a shuffle. 7909 // We want to legalize vector truncates down to where the source fits in 7910 // a vector register (and target is therefore smaller than vector register 7911 // size). At that point legalization will try to custom lower the sub-legal 7912 // result and get here - where we can contain the truncate as a single target 7913 // operation. 7914 7915 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7916 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7917 // 7918 // We will implement it for big-endian ordering as this (where x denotes 7919 // undefined): 7920 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7921 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7922 // 7923 // The same operation in little-endian ordering will be: 7924 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7925 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7926 7927 assert(Op.getValueType().isVector() && "Vector type expected."); 7928 7929 SDLoc DL(Op); 7930 SDValue N1 = Op.getOperand(0); 7931 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7932 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7933 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7934 7935 EVT TrgVT = Op.getValueType(); 7936 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7937 EVT EltVT = TrgVT.getVectorElementType(); 7938 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7939 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7940 7941 // First list the elements we want to keep. 7942 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7943 SmallVector<int, 16> ShuffV; 7944 if (Subtarget.isLittleEndian()) 7945 for (unsigned i = 0; i < TrgNumElts; ++i) 7946 ShuffV.push_back(i * SizeMult); 7947 else 7948 for (unsigned i = 1; i <= TrgNumElts; ++i) 7949 ShuffV.push_back(i * SizeMult - 1); 7950 7951 // Populate the remaining elements with undefs. 7952 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7953 // ShuffV.push_back(i + WideNumElts); 7954 ShuffV.push_back(WideNumElts + 1); 7955 7956 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7957 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7958 } 7959 7960 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7961 /// possible. 7962 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7963 // Not FP? Not a fsel. 7964 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7965 !Op.getOperand(2).getValueType().isFloatingPoint()) 7966 return Op; 7967 7968 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7969 7970 EVT ResVT = Op.getValueType(); 7971 EVT CmpVT = Op.getOperand(0).getValueType(); 7972 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7973 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7974 SDLoc dl(Op); 7975 7976 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7977 // presence of infinities. 7978 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7979 switch (CC) { 7980 default: 7981 break; 7982 case ISD::SETOGT: 7983 case ISD::SETGT: 7984 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7985 case ISD::SETOLT: 7986 case ISD::SETLT: 7987 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7988 } 7989 } 7990 7991 // We might be able to do better than this under some circumstances, but in 7992 // general, fsel-based lowering of select is a finite-math-only optimization. 7993 // For more information, see section F.3 of the 2.06 ISA specification. 7994 // With ISA 3.0 7995 if (!DAG.getTarget().Options.NoInfsFPMath || 7996 !DAG.getTarget().Options.NoNaNsFPMath) 7997 return Op; 7998 7999 // TODO: Propagate flags from the select rather than global settings. 8000 SDNodeFlags Flags; 8001 Flags.setNoInfs(true); 8002 Flags.setNoNaNs(true); 8003 8004 // If the RHS of the comparison is a 0.0, we don't need to do the 8005 // subtraction at all. 8006 SDValue Sel1; 8007 if (isFloatingPointZero(RHS)) 8008 switch (CC) { 8009 default: break; // SETUO etc aren't handled by fsel. 8010 case ISD::SETNE: 8011 std::swap(TV, FV); 8012 LLVM_FALLTHROUGH; 8013 case ISD::SETEQ: 8014 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8015 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8016 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8017 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8018 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8019 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8020 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8021 case ISD::SETULT: 8022 case ISD::SETLT: 8023 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8024 LLVM_FALLTHROUGH; 8025 case ISD::SETOGE: 8026 case ISD::SETGE: 8027 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8028 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8029 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8030 case ISD::SETUGT: 8031 case ISD::SETGT: 8032 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8033 LLVM_FALLTHROUGH; 8034 case ISD::SETOLE: 8035 case ISD::SETLE: 8036 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8037 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8038 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8039 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8040 } 8041 8042 SDValue Cmp; 8043 switch (CC) { 8044 default: break; // SETUO etc aren't handled by fsel. 8045 case ISD::SETNE: 8046 std::swap(TV, FV); 8047 LLVM_FALLTHROUGH; 8048 case ISD::SETEQ: 8049 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8050 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8051 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8052 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8053 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8054 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8055 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8056 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8057 case ISD::SETULT: 8058 case ISD::SETLT: 8059 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8060 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8061 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8062 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8063 case ISD::SETOGE: 8064 case ISD::SETGE: 8065 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8066 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8067 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8068 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8069 case ISD::SETUGT: 8070 case ISD::SETGT: 8071 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8072 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8073 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8074 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8075 case ISD::SETOLE: 8076 case ISD::SETLE: 8077 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8078 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8079 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8080 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8081 } 8082 return Op; 8083 } 8084 8085 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8086 SelectionDAG &DAG, 8087 const SDLoc &dl) const { 8088 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8089 SDValue Src = Op.getOperand(0); 8090 if (Src.getValueType() == MVT::f32) 8091 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8092 8093 SDValue Tmp; 8094 switch (Op.getSimpleValueType().SimpleTy) { 8095 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8096 case MVT::i32: 8097 Tmp = DAG.getNode( 8098 Op.getOpcode() == ISD::FP_TO_SINT 8099 ? PPCISD::FCTIWZ 8100 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8101 dl, MVT::f64, Src); 8102 break; 8103 case MVT::i64: 8104 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8105 "i64 FP_TO_UINT is supported only with FPCVT"); 8106 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8107 PPCISD::FCTIDUZ, 8108 dl, MVT::f64, Src); 8109 break; 8110 } 8111 8112 // Convert the FP value to an int value through memory. 8113 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8114 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8115 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8116 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8117 MachinePointerInfo MPI = 8118 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8119 8120 // Emit a store to the stack slot. 8121 SDValue Chain; 8122 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8123 if (i32Stack) { 8124 MachineFunction &MF = DAG.getMachineFunction(); 8125 Alignment = Align(4); 8126 MachineMemOperand *MMO = 8127 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8128 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8129 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8130 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8131 } else 8132 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8133 8134 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8135 // add in a bias on big endian. 8136 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8137 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8138 DAG.getConstant(4, dl, FIPtr.getValueType())); 8139 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8140 } 8141 8142 RLI.Chain = Chain; 8143 RLI.Ptr = FIPtr; 8144 RLI.MPI = MPI; 8145 RLI.Alignment = Alignment; 8146 } 8147 8148 /// Custom lowers floating point to integer conversions to use 8149 /// the direct move instructions available in ISA 2.07 to avoid the 8150 /// need for load/store combinations. 8151 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8152 SelectionDAG &DAG, 8153 const SDLoc &dl) const { 8154 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8155 SDValue Src = Op.getOperand(0); 8156 8157 if (Src.getValueType() == MVT::f32) 8158 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8159 8160 SDValue Tmp; 8161 switch (Op.getSimpleValueType().SimpleTy) { 8162 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8163 case MVT::i32: 8164 Tmp = DAG.getNode( 8165 Op.getOpcode() == ISD::FP_TO_SINT 8166 ? PPCISD::FCTIWZ 8167 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8168 dl, MVT::f64, Src); 8169 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8170 break; 8171 case MVT::i64: 8172 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8173 "i64 FP_TO_UINT is supported only with FPCVT"); 8174 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8175 PPCISD::FCTIDUZ, 8176 dl, MVT::f64, Src); 8177 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8178 break; 8179 } 8180 return Tmp; 8181 } 8182 8183 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8184 const SDLoc &dl) const { 8185 8186 // FP to INT conversions are legal for f128. 8187 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8188 return Op; 8189 8190 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8191 // PPC (the libcall is not available). 8192 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8193 if (Op.getValueType() == MVT::i32) { 8194 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8195 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8196 MVT::f64, Op.getOperand(0), 8197 DAG.getIntPtrConstant(0, dl)); 8198 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8199 MVT::f64, Op.getOperand(0), 8200 DAG.getIntPtrConstant(1, dl)); 8201 8202 // Add the two halves of the long double in round-to-zero mode. 8203 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8204 8205 // Now use a smaller FP_TO_SINT. 8206 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8207 } 8208 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8209 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8210 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8211 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8212 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8213 // FIXME: generated code sucks. 8214 // TODO: Are there fast-math-flags to propagate to this FSUB? 8215 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8216 Op.getOperand(0), Tmp); 8217 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8218 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8219 DAG.getConstant(0x80000000, dl, MVT::i32)); 8220 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8221 Op.getOperand(0)); 8222 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8223 ISD::SETGE); 8224 } 8225 } 8226 8227 return SDValue(); 8228 } 8229 8230 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8231 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8232 8233 ReuseLoadInfo RLI; 8234 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8235 8236 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8237 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8238 } 8239 8240 // We're trying to insert a regular store, S, and then a load, L. If the 8241 // incoming value, O, is a load, we might just be able to have our load use the 8242 // address used by O. However, we don't know if anything else will store to 8243 // that address before we can load from it. To prevent this situation, we need 8244 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8245 // the same chain operand as O, we create a token factor from the chain results 8246 // of O and L, and we replace all uses of O's chain result with that token 8247 // factor (see spliceIntoChain below for this last part). 8248 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8249 ReuseLoadInfo &RLI, 8250 SelectionDAG &DAG, 8251 ISD::LoadExtType ET) const { 8252 SDLoc dl(Op); 8253 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8254 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8255 if (ET == ISD::NON_EXTLOAD && 8256 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8257 isOperationLegalOrCustom(Op.getOpcode(), 8258 Op.getOperand(0).getValueType())) { 8259 8260 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8261 return true; 8262 } 8263 8264 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8265 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8266 LD->isNonTemporal()) 8267 return false; 8268 if (LD->getMemoryVT() != MemVT) 8269 return false; 8270 8271 RLI.Ptr = LD->getBasePtr(); 8272 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8273 assert(LD->getAddressingMode() == ISD::PRE_INC && 8274 "Non-pre-inc AM on PPC?"); 8275 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8276 LD->getOffset()); 8277 } 8278 8279 RLI.Chain = LD->getChain(); 8280 RLI.MPI = LD->getPointerInfo(); 8281 RLI.IsDereferenceable = LD->isDereferenceable(); 8282 RLI.IsInvariant = LD->isInvariant(); 8283 RLI.Alignment = LD->getAlign(); 8284 RLI.AAInfo = LD->getAAInfo(); 8285 RLI.Ranges = LD->getRanges(); 8286 8287 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8288 return true; 8289 } 8290 8291 // Given the head of the old chain, ResChain, insert a token factor containing 8292 // it and NewResChain, and make users of ResChain now be users of that token 8293 // factor. 8294 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8295 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8296 SDValue NewResChain, 8297 SelectionDAG &DAG) const { 8298 if (!ResChain) 8299 return; 8300 8301 SDLoc dl(NewResChain); 8302 8303 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8304 NewResChain, DAG.getUNDEF(MVT::Other)); 8305 assert(TF.getNode() != NewResChain.getNode() && 8306 "A new TF really is required here"); 8307 8308 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8309 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8310 } 8311 8312 /// Analyze profitability of direct move 8313 /// prefer float load to int load plus direct move 8314 /// when there is no integer use of int load 8315 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8316 SDNode *Origin = Op.getOperand(0).getNode(); 8317 if (Origin->getOpcode() != ISD::LOAD) 8318 return true; 8319 8320 // If there is no LXSIBZX/LXSIHZX, like Power8, 8321 // prefer direct move if the memory size is 1 or 2 bytes. 8322 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8323 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8324 return true; 8325 8326 for (SDNode::use_iterator UI = Origin->use_begin(), 8327 UE = Origin->use_end(); 8328 UI != UE; ++UI) { 8329 8330 // Only look at the users of the loaded value. 8331 if (UI.getUse().get().getResNo() != 0) 8332 continue; 8333 8334 if (UI->getOpcode() != ISD::SINT_TO_FP && 8335 UI->getOpcode() != ISD::UINT_TO_FP) 8336 return true; 8337 } 8338 8339 return false; 8340 } 8341 8342 /// Custom lowers integer to floating point conversions to use 8343 /// the direct move instructions available in ISA 2.07 to avoid the 8344 /// need for load/store combinations. 8345 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8346 SelectionDAG &DAG, 8347 const SDLoc &dl) const { 8348 assert((Op.getValueType() == MVT::f32 || 8349 Op.getValueType() == MVT::f64) && 8350 "Invalid floating point type as target of conversion"); 8351 assert(Subtarget.hasFPCVT() && 8352 "Int to FP conversions with direct moves require FPCVT"); 8353 SDValue FP; 8354 SDValue Src = Op.getOperand(0); 8355 bool SinglePrec = Op.getValueType() == MVT::f32; 8356 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8357 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8358 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8359 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8360 8361 if (WordInt) { 8362 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8363 dl, MVT::f64, Src); 8364 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8365 } 8366 else { 8367 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8368 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8369 } 8370 8371 return FP; 8372 } 8373 8374 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8375 8376 EVT VecVT = Vec.getValueType(); 8377 assert(VecVT.isVector() && "Expected a vector type."); 8378 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8379 8380 EVT EltVT = VecVT.getVectorElementType(); 8381 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8382 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8383 8384 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8385 SmallVector<SDValue, 16> Ops(NumConcat); 8386 Ops[0] = Vec; 8387 SDValue UndefVec = DAG.getUNDEF(VecVT); 8388 for (unsigned i = 1; i < NumConcat; ++i) 8389 Ops[i] = UndefVec; 8390 8391 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8392 } 8393 8394 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8395 const SDLoc &dl) const { 8396 8397 unsigned Opc = Op.getOpcode(); 8398 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8399 "Unexpected conversion type"); 8400 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8401 "Supports conversions to v2f64/v4f32 only."); 8402 8403 bool SignedConv = Opc == ISD::SINT_TO_FP; 8404 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8405 8406 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8407 EVT WideVT = Wide.getValueType(); 8408 unsigned WideNumElts = WideVT.getVectorNumElements(); 8409 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8410 8411 SmallVector<int, 16> ShuffV; 8412 for (unsigned i = 0; i < WideNumElts; ++i) 8413 ShuffV.push_back(i + WideNumElts); 8414 8415 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8416 int SaveElts = FourEltRes ? 4 : 2; 8417 if (Subtarget.isLittleEndian()) 8418 for (int i = 0; i < SaveElts; i++) 8419 ShuffV[i * Stride] = i; 8420 else 8421 for (int i = 1; i <= SaveElts; i++) 8422 ShuffV[i * Stride - 1] = i - 1; 8423 8424 SDValue ShuffleSrc2 = 8425 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8426 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8427 8428 SDValue Extend; 8429 if (SignedConv) { 8430 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8431 EVT ExtVT = Op.getOperand(0).getValueType(); 8432 if (Subtarget.hasP9Altivec()) 8433 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8434 IntermediateVT.getVectorNumElements()); 8435 8436 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8437 DAG.getValueType(ExtVT)); 8438 } else 8439 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8440 8441 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8442 } 8443 8444 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8445 SelectionDAG &DAG) const { 8446 SDLoc dl(Op); 8447 8448 EVT InVT = Op.getOperand(0).getValueType(); 8449 EVT OutVT = Op.getValueType(); 8450 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8451 isOperationCustom(Op.getOpcode(), InVT)) 8452 return LowerINT_TO_FPVector(Op, DAG, dl); 8453 8454 // Conversions to f128 are legal. 8455 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8456 return Op; 8457 8458 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8459 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8460 return SDValue(); 8461 8462 SDValue Value = Op.getOperand(0); 8463 // The values are now known to be -1 (false) or 1 (true). To convert this 8464 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8465 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8466 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8467 8468 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8469 8470 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8471 8472 if (Op.getValueType() != MVT::v4f64) 8473 Value = DAG.getNode(ISD::FP_ROUND, dl, 8474 Op.getValueType(), Value, 8475 DAG.getIntPtrConstant(1, dl)); 8476 return Value; 8477 } 8478 8479 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8480 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8481 return SDValue(); 8482 8483 if (Op.getOperand(0).getValueType() == MVT::i1) 8484 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8485 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8486 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8487 8488 // If we have direct moves, we can do all the conversion, skip the store/load 8489 // however, without FPCVT we can't do most conversions. 8490 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8491 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8492 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8493 8494 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8495 "UINT_TO_FP is supported only with FPCVT"); 8496 8497 // If we have FCFIDS, then use it when converting to single-precision. 8498 // Otherwise, convert to double-precision and then round. 8499 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8500 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8501 : PPCISD::FCFIDS) 8502 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8503 : PPCISD::FCFID); 8504 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8505 ? MVT::f32 8506 : MVT::f64; 8507 8508 if (Op.getOperand(0).getValueType() == MVT::i64) { 8509 SDValue SINT = Op.getOperand(0); 8510 // When converting to single-precision, we actually need to convert 8511 // to double-precision first and then round to single-precision. 8512 // To avoid double-rounding effects during that operation, we have 8513 // to prepare the input operand. Bits that might be truncated when 8514 // converting to double-precision are replaced by a bit that won't 8515 // be lost at this stage, but is below the single-precision rounding 8516 // position. 8517 // 8518 // However, if -enable-unsafe-fp-math is in effect, accept double 8519 // rounding to avoid the extra overhead. 8520 if (Op.getValueType() == MVT::f32 && 8521 !Subtarget.hasFPCVT() && 8522 !DAG.getTarget().Options.UnsafeFPMath) { 8523 8524 // Twiddle input to make sure the low 11 bits are zero. (If this 8525 // is the case, we are guaranteed the value will fit into the 53 bit 8526 // mantissa of an IEEE double-precision value without rounding.) 8527 // If any of those low 11 bits were not zero originally, make sure 8528 // bit 12 (value 2048) is set instead, so that the final rounding 8529 // to single-precision gets the correct result. 8530 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8531 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8532 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8533 Round, DAG.getConstant(2047, dl, MVT::i64)); 8534 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8535 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8536 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8537 8538 // However, we cannot use that value unconditionally: if the magnitude 8539 // of the input value is small, the bit-twiddling we did above might 8540 // end up visibly changing the output. Fortunately, in that case, we 8541 // don't need to twiddle bits since the original input will convert 8542 // exactly to double-precision floating-point already. Therefore, 8543 // construct a conditional to use the original value if the top 11 8544 // bits are all sign-bit copies, and use the rounded value computed 8545 // above otherwise. 8546 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8547 SINT, DAG.getConstant(53, dl, MVT::i32)); 8548 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8549 Cond, DAG.getConstant(1, dl, MVT::i64)); 8550 Cond = DAG.getSetCC( 8551 dl, 8552 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8553 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8554 8555 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8556 } 8557 8558 ReuseLoadInfo RLI; 8559 SDValue Bits; 8560 8561 MachineFunction &MF = DAG.getMachineFunction(); 8562 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8563 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8564 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8565 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8566 } else if (Subtarget.hasLFIWAX() && 8567 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8568 MachineMemOperand *MMO = 8569 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8570 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8571 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8572 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8573 DAG.getVTList(MVT::f64, MVT::Other), 8574 Ops, MVT::i32, MMO); 8575 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8576 } else if (Subtarget.hasFPCVT() && 8577 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8578 MachineMemOperand *MMO = 8579 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8580 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8581 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8582 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8583 DAG.getVTList(MVT::f64, MVT::Other), 8584 Ops, MVT::i32, MMO); 8585 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8586 } else if (((Subtarget.hasLFIWAX() && 8587 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8588 (Subtarget.hasFPCVT() && 8589 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8590 SINT.getOperand(0).getValueType() == MVT::i32) { 8591 MachineFrameInfo &MFI = MF.getFrameInfo(); 8592 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8593 8594 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8595 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8596 8597 SDValue Store = 8598 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8599 MachinePointerInfo::getFixedStack( 8600 DAG.getMachineFunction(), FrameIdx)); 8601 8602 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8603 "Expected an i32 store"); 8604 8605 RLI.Ptr = FIdx; 8606 RLI.Chain = Store; 8607 RLI.MPI = 8608 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8609 RLI.Alignment = Align(4); 8610 8611 MachineMemOperand *MMO = 8612 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8613 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8614 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8615 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8616 PPCISD::LFIWZX : PPCISD::LFIWAX, 8617 dl, DAG.getVTList(MVT::f64, MVT::Other), 8618 Ops, MVT::i32, MMO); 8619 } else 8620 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8621 8622 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8623 8624 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8625 FP = DAG.getNode(ISD::FP_ROUND, dl, 8626 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8627 return FP; 8628 } 8629 8630 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8631 "Unhandled INT_TO_FP type in custom expander!"); 8632 // Since we only generate this in 64-bit mode, we can take advantage of 8633 // 64-bit registers. In particular, sign extend the input value into the 8634 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8635 // then lfd it and fcfid it. 8636 MachineFunction &MF = DAG.getMachineFunction(); 8637 MachineFrameInfo &MFI = MF.getFrameInfo(); 8638 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8639 8640 SDValue Ld; 8641 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8642 ReuseLoadInfo RLI; 8643 bool ReusingLoad; 8644 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8645 DAG))) { 8646 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8647 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8648 8649 SDValue Store = 8650 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8651 MachinePointerInfo::getFixedStack( 8652 DAG.getMachineFunction(), FrameIdx)); 8653 8654 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8655 "Expected an i32 store"); 8656 8657 RLI.Ptr = FIdx; 8658 RLI.Chain = Store; 8659 RLI.MPI = 8660 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8661 RLI.Alignment = Align(4); 8662 } 8663 8664 MachineMemOperand *MMO = 8665 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8666 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8667 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8668 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8669 PPCISD::LFIWZX : PPCISD::LFIWAX, 8670 dl, DAG.getVTList(MVT::f64, MVT::Other), 8671 Ops, MVT::i32, MMO); 8672 if (ReusingLoad) 8673 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8674 } else { 8675 assert(Subtarget.isPPC64() && 8676 "i32->FP without LFIWAX supported only on PPC64"); 8677 8678 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8679 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8680 8681 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8682 Op.getOperand(0)); 8683 8684 // STD the extended value into the stack slot. 8685 SDValue Store = DAG.getStore( 8686 DAG.getEntryNode(), dl, Ext64, FIdx, 8687 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8688 8689 // Load the value as a double. 8690 Ld = DAG.getLoad( 8691 MVT::f64, dl, Store, FIdx, 8692 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8693 } 8694 8695 // FCFID it and return it. 8696 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8697 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8698 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8699 DAG.getIntPtrConstant(0, dl)); 8700 return FP; 8701 } 8702 8703 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8704 SelectionDAG &DAG) const { 8705 SDLoc dl(Op); 8706 /* 8707 The rounding mode is in bits 30:31 of FPSR, and has the following 8708 settings: 8709 00 Round to nearest 8710 01 Round to 0 8711 10 Round to +inf 8712 11 Round to -inf 8713 8714 FLT_ROUNDS, on the other hand, expects the following: 8715 -1 Undefined 8716 0 Round to 0 8717 1 Round to nearest 8718 2 Round to +inf 8719 3 Round to -inf 8720 8721 To perform the conversion, we do: 8722 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8723 */ 8724 8725 MachineFunction &MF = DAG.getMachineFunction(); 8726 EVT VT = Op.getValueType(); 8727 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8728 8729 // Save FP Control Word to register 8730 SDValue Chain = Op.getOperand(0); 8731 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8732 Chain = MFFS.getValue(1); 8733 8734 // Save FP register to stack slot 8735 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8736 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8737 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8738 8739 // Load FP Control Word from low 32 bits of stack slot. 8740 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8741 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8742 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8743 Chain = CWD.getValue(1); 8744 8745 // Transform as necessary 8746 SDValue CWD1 = 8747 DAG.getNode(ISD::AND, dl, MVT::i32, 8748 CWD, DAG.getConstant(3, dl, MVT::i32)); 8749 SDValue CWD2 = 8750 DAG.getNode(ISD::SRL, dl, MVT::i32, 8751 DAG.getNode(ISD::AND, dl, MVT::i32, 8752 DAG.getNode(ISD::XOR, dl, MVT::i32, 8753 CWD, DAG.getConstant(3, dl, MVT::i32)), 8754 DAG.getConstant(3, dl, MVT::i32)), 8755 DAG.getConstant(1, dl, MVT::i32)); 8756 8757 SDValue RetVal = 8758 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8759 8760 RetVal = 8761 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8762 dl, VT, RetVal); 8763 8764 return DAG.getMergeValues({RetVal, Chain}, dl); 8765 } 8766 8767 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8768 EVT VT = Op.getValueType(); 8769 unsigned BitWidth = VT.getSizeInBits(); 8770 SDLoc dl(Op); 8771 assert(Op.getNumOperands() == 3 && 8772 VT == Op.getOperand(1).getValueType() && 8773 "Unexpected SHL!"); 8774 8775 // Expand into a bunch of logical ops. Note that these ops 8776 // depend on the PPC behavior for oversized shift amounts. 8777 SDValue Lo = Op.getOperand(0); 8778 SDValue Hi = Op.getOperand(1); 8779 SDValue Amt = Op.getOperand(2); 8780 EVT AmtVT = Amt.getValueType(); 8781 8782 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8783 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8784 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8785 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8786 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8787 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8788 DAG.getConstant(-BitWidth, dl, AmtVT)); 8789 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8790 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8791 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8792 SDValue OutOps[] = { OutLo, OutHi }; 8793 return DAG.getMergeValues(OutOps, dl); 8794 } 8795 8796 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8797 EVT VT = Op.getValueType(); 8798 SDLoc dl(Op); 8799 unsigned BitWidth = VT.getSizeInBits(); 8800 assert(Op.getNumOperands() == 3 && 8801 VT == Op.getOperand(1).getValueType() && 8802 "Unexpected SRL!"); 8803 8804 // Expand into a bunch of logical ops. Note that these ops 8805 // depend on the PPC behavior for oversized shift amounts. 8806 SDValue Lo = Op.getOperand(0); 8807 SDValue Hi = Op.getOperand(1); 8808 SDValue Amt = Op.getOperand(2); 8809 EVT AmtVT = Amt.getValueType(); 8810 8811 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8812 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8813 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8814 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8815 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8816 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8817 DAG.getConstant(-BitWidth, dl, AmtVT)); 8818 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8819 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8820 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8821 SDValue OutOps[] = { OutLo, OutHi }; 8822 return DAG.getMergeValues(OutOps, dl); 8823 } 8824 8825 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8826 SDLoc dl(Op); 8827 EVT VT = Op.getValueType(); 8828 unsigned BitWidth = VT.getSizeInBits(); 8829 assert(Op.getNumOperands() == 3 && 8830 VT == Op.getOperand(1).getValueType() && 8831 "Unexpected SRA!"); 8832 8833 // Expand into a bunch of logical ops, followed by a select_cc. 8834 SDValue Lo = Op.getOperand(0); 8835 SDValue Hi = Op.getOperand(1); 8836 SDValue Amt = Op.getOperand(2); 8837 EVT AmtVT = Amt.getValueType(); 8838 8839 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8840 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8841 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8842 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8843 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8844 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8845 DAG.getConstant(-BitWidth, dl, AmtVT)); 8846 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8847 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8848 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8849 Tmp4, Tmp6, ISD::SETLE); 8850 SDValue OutOps[] = { OutLo, OutHi }; 8851 return DAG.getMergeValues(OutOps, dl); 8852 } 8853 8854 //===----------------------------------------------------------------------===// 8855 // Vector related lowering. 8856 // 8857 8858 /// BuildSplatI - Build a canonical splati of Val with an element size of 8859 /// SplatSize. Cast the result to VT. 8860 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8861 SelectionDAG &DAG, const SDLoc &dl) { 8862 static const MVT VTys[] = { // canonical VT to use for each size. 8863 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8864 }; 8865 8866 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8867 8868 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8869 if (Val == -1) 8870 SplatSize = 1; 8871 8872 EVT CanonicalVT = VTys[SplatSize-1]; 8873 8874 // Build a canonical splat for this value. 8875 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8876 } 8877 8878 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8879 /// specified intrinsic ID. 8880 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8881 const SDLoc &dl, EVT DestVT = MVT::Other) { 8882 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8883 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8884 DAG.getConstant(IID, dl, MVT::i32), Op); 8885 } 8886 8887 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8888 /// specified intrinsic ID. 8889 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8890 SelectionDAG &DAG, const SDLoc &dl, 8891 EVT DestVT = MVT::Other) { 8892 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8893 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8894 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8895 } 8896 8897 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8898 /// specified intrinsic ID. 8899 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8900 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8901 EVT DestVT = MVT::Other) { 8902 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8903 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8904 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8905 } 8906 8907 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8908 /// amount. The result has the specified value type. 8909 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8910 SelectionDAG &DAG, const SDLoc &dl) { 8911 // Force LHS/RHS to be the right type. 8912 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8913 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8914 8915 int Ops[16]; 8916 for (unsigned i = 0; i != 16; ++i) 8917 Ops[i] = i + Amt; 8918 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8919 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8920 } 8921 8922 /// Do we have an efficient pattern in a .td file for this node? 8923 /// 8924 /// \param V - pointer to the BuildVectorSDNode being matched 8925 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8926 /// 8927 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8928 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8929 /// the opposite is true (expansion is beneficial) are: 8930 /// - The node builds a vector out of integers that are not 32 or 64-bits 8931 /// - The node builds a vector out of constants 8932 /// - The node is a "load-and-splat" 8933 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8934 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8935 bool HasDirectMove, 8936 bool HasP8Vector) { 8937 EVT VecVT = V->getValueType(0); 8938 bool RightType = VecVT == MVT::v2f64 || 8939 (HasP8Vector && VecVT == MVT::v4f32) || 8940 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8941 if (!RightType) 8942 return false; 8943 8944 bool IsSplat = true; 8945 bool IsLoad = false; 8946 SDValue Op0 = V->getOperand(0); 8947 8948 // This function is called in a block that confirms the node is not a constant 8949 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8950 // different constants. 8951 if (V->isConstant()) 8952 return false; 8953 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8954 if (V->getOperand(i).isUndef()) 8955 return false; 8956 // We want to expand nodes that represent load-and-splat even if the 8957 // loaded value is a floating point truncation or conversion to int. 8958 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8959 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8960 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8961 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8962 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8963 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8964 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8965 IsLoad = true; 8966 // If the operands are different or the input is not a load and has more 8967 // uses than just this BV node, then it isn't a splat. 8968 if (V->getOperand(i) != Op0 || 8969 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8970 IsSplat = false; 8971 } 8972 return !(IsSplat && IsLoad); 8973 } 8974 8975 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8976 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8977 8978 SDLoc dl(Op); 8979 SDValue Op0 = Op->getOperand(0); 8980 8981 if (!EnableQuadPrecision || 8982 (Op.getValueType() != MVT::f128 ) || 8983 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8984 (Op0.getOperand(0).getValueType() != MVT::i64) || 8985 (Op0.getOperand(1).getValueType() != MVT::i64)) 8986 return SDValue(); 8987 8988 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8989 Op0.getOperand(1)); 8990 } 8991 8992 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8993 const SDValue *InputLoad = &Op; 8994 if (InputLoad->getOpcode() == ISD::BITCAST) 8995 InputLoad = &InputLoad->getOperand(0); 8996 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8997 InputLoad = &InputLoad->getOperand(0); 8998 if (InputLoad->getOpcode() != ISD::LOAD) 8999 return nullptr; 9000 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9001 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9002 } 9003 9004 // If this is a case we can't handle, return null and let the default 9005 // expansion code take care of it. If we CAN select this case, and if it 9006 // selects to a single instruction, return Op. Otherwise, if we can codegen 9007 // this case more efficiently than a constant pool load, lower it to the 9008 // sequence of ops that should be used. 9009 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9010 SelectionDAG &DAG) const { 9011 SDLoc dl(Op); 9012 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9013 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9014 9015 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9016 // We first build an i32 vector, load it into a QPX register, 9017 // then convert it to a floating-point vector and compare it 9018 // to a zero vector to get the boolean result. 9019 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9020 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9021 MachinePointerInfo PtrInfo = 9022 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9023 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9024 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9025 9026 assert(BVN->getNumOperands() == 4 && 9027 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9028 9029 bool IsConst = true; 9030 for (unsigned i = 0; i < 4; ++i) { 9031 if (BVN->getOperand(i).isUndef()) continue; 9032 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9033 IsConst = false; 9034 break; 9035 } 9036 } 9037 9038 if (IsConst) { 9039 Constant *One = 9040 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9041 Constant *NegOne = 9042 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9043 9044 Constant *CV[4]; 9045 for (unsigned i = 0; i < 4; ++i) { 9046 if (BVN->getOperand(i).isUndef()) 9047 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9048 else if (isNullConstant(BVN->getOperand(i))) 9049 CV[i] = NegOne; 9050 else 9051 CV[i] = One; 9052 } 9053 9054 Constant *CP = ConstantVector::get(CV); 9055 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 9056 16 /* alignment */); 9057 9058 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9059 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9060 return DAG.getMemIntrinsicNode( 9061 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9062 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9063 } 9064 9065 SmallVector<SDValue, 4> Stores; 9066 for (unsigned i = 0; i < 4; ++i) { 9067 if (BVN->getOperand(i).isUndef()) continue; 9068 9069 unsigned Offset = 4*i; 9070 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9071 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9072 9073 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9074 if (StoreSize > 4) { 9075 Stores.push_back( 9076 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9077 PtrInfo.getWithOffset(Offset), MVT::i32)); 9078 } else { 9079 SDValue StoreValue = BVN->getOperand(i); 9080 if (StoreSize < 4) 9081 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9082 9083 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9084 PtrInfo.getWithOffset(Offset))); 9085 } 9086 } 9087 9088 SDValue StoreChain; 9089 if (!Stores.empty()) 9090 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9091 else 9092 StoreChain = DAG.getEntryNode(); 9093 9094 // Now load from v4i32 into the QPX register; this will extend it to 9095 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9096 // is typed as v4f64 because the QPX register integer states are not 9097 // explicitly represented. 9098 9099 SDValue Ops[] = {StoreChain, 9100 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9101 FIdx}; 9102 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9103 9104 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9105 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9106 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9107 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9108 LoadedVect); 9109 9110 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9111 9112 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9113 } 9114 9115 // All other QPX vectors are handled by generic code. 9116 if (Subtarget.hasQPX()) 9117 return SDValue(); 9118 9119 // Check if this is a splat of a constant value. 9120 APInt APSplatBits, APSplatUndef; 9121 unsigned SplatBitSize; 9122 bool HasAnyUndefs; 9123 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9124 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9125 SplatBitSize > 32) { 9126 9127 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9128 // Handle load-and-splat patterns as we have instructions that will do this 9129 // in one go. 9130 if (InputLoad && DAG.isSplatValue(Op, true)) { 9131 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9132 9133 // We have handling for 4 and 8 byte elements. 9134 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9135 9136 // Checking for a single use of this load, we have to check for vector 9137 // width (128 bits) / ElementSize uses (since each operand of the 9138 // BUILD_VECTOR is a separate use of the value. 9139 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9140 ((Subtarget.hasVSX() && ElementSize == 64) || 9141 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9142 SDValue Ops[] = { 9143 LD->getChain(), // Chain 9144 LD->getBasePtr(), // Ptr 9145 DAG.getValueType(Op.getValueType()) // VT 9146 }; 9147 return 9148 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9149 DAG.getVTList(Op.getValueType(), MVT::Other), 9150 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9151 } 9152 } 9153 9154 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9155 // lowered to VSX instructions under certain conditions. 9156 // Without VSX, there is no pattern more efficient than expanding the node. 9157 if (Subtarget.hasVSX() && 9158 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9159 Subtarget.hasP8Vector())) 9160 return Op; 9161 return SDValue(); 9162 } 9163 9164 unsigned SplatBits = APSplatBits.getZExtValue(); 9165 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9166 unsigned SplatSize = SplatBitSize / 8; 9167 9168 // First, handle single instruction cases. 9169 9170 // All zeros? 9171 if (SplatBits == 0) { 9172 // Canonicalize all zero vectors to be v4i32. 9173 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9174 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9175 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9176 } 9177 return Op; 9178 } 9179 9180 // We have XXSPLTIB for constant splats one byte wide 9181 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9182 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9183 if (Subtarget.hasP9Vector() && SplatSize == 1) 9184 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9185 9186 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9187 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9188 (32-SplatBitSize)); 9189 if (SextVal >= -16 && SextVal <= 15) 9190 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9191 9192 // Two instruction sequences. 9193 9194 // If this value is in the range [-32,30] and is even, use: 9195 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9196 // If this value is in the range [17,31] and is odd, use: 9197 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9198 // If this value is in the range [-31,-17] and is odd, use: 9199 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9200 // Note the last two are three-instruction sequences. 9201 if (SextVal >= -32 && SextVal <= 31) { 9202 // To avoid having these optimizations undone by constant folding, 9203 // we convert to a pseudo that will be expanded later into one of 9204 // the above forms. 9205 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9206 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9207 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9208 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9209 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9210 if (VT == Op.getValueType()) 9211 return RetVal; 9212 else 9213 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9214 } 9215 9216 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9217 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9218 // for fneg/fabs. 9219 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9220 // Make -1 and vspltisw -1: 9221 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9222 9223 // Make the VSLW intrinsic, computing 0x8000_0000. 9224 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9225 OnesV, DAG, dl); 9226 9227 // xor by OnesV to invert it. 9228 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9229 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9230 } 9231 9232 // Check to see if this is a wide variety of vsplti*, binop self cases. 9233 static const signed char SplatCsts[] = { 9234 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9235 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9236 }; 9237 9238 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9239 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9240 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9241 int i = SplatCsts[idx]; 9242 9243 // Figure out what shift amount will be used by altivec if shifted by i in 9244 // this splat size. 9245 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9246 9247 // vsplti + shl self. 9248 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9249 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9250 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9251 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9252 Intrinsic::ppc_altivec_vslw 9253 }; 9254 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9255 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9256 } 9257 9258 // vsplti + srl 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_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9263 Intrinsic::ppc_altivec_vsrw 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 + sra 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_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9274 Intrinsic::ppc_altivec_vsraw 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 + rol self. 9281 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9282 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9283 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9284 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9285 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9286 Intrinsic::ppc_altivec_vrlw 9287 }; 9288 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9289 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9290 } 9291 9292 // t = vsplti c, result = vsldoi t, t, 1 9293 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9294 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9295 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9296 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9297 } 9298 // t = vsplti c, result = vsldoi t, t, 2 9299 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9300 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9301 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9302 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9303 } 9304 // t = vsplti c, result = vsldoi t, t, 3 9305 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9306 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9307 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9308 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9309 } 9310 } 9311 9312 return SDValue(); 9313 } 9314 9315 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9316 /// the specified operations to build the shuffle. 9317 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9318 SDValue RHS, SelectionDAG &DAG, 9319 const SDLoc &dl) { 9320 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9321 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9322 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9323 9324 enum { 9325 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9326 OP_VMRGHW, 9327 OP_VMRGLW, 9328 OP_VSPLTISW0, 9329 OP_VSPLTISW1, 9330 OP_VSPLTISW2, 9331 OP_VSPLTISW3, 9332 OP_VSLDOI4, 9333 OP_VSLDOI8, 9334 OP_VSLDOI12 9335 }; 9336 9337 if (OpNum == OP_COPY) { 9338 if (LHSID == (1*9+2)*9+3) return LHS; 9339 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9340 return RHS; 9341 } 9342 9343 SDValue OpLHS, OpRHS; 9344 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9345 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9346 9347 int ShufIdxs[16]; 9348 switch (OpNum) { 9349 default: llvm_unreachable("Unknown i32 permute!"); 9350 case OP_VMRGHW: 9351 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9352 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9353 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9354 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9355 break; 9356 case OP_VMRGLW: 9357 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9358 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9359 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9360 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9361 break; 9362 case OP_VSPLTISW0: 9363 for (unsigned i = 0; i != 16; ++i) 9364 ShufIdxs[i] = (i&3)+0; 9365 break; 9366 case OP_VSPLTISW1: 9367 for (unsigned i = 0; i != 16; ++i) 9368 ShufIdxs[i] = (i&3)+4; 9369 break; 9370 case OP_VSPLTISW2: 9371 for (unsigned i = 0; i != 16; ++i) 9372 ShufIdxs[i] = (i&3)+8; 9373 break; 9374 case OP_VSPLTISW3: 9375 for (unsigned i = 0; i != 16; ++i) 9376 ShufIdxs[i] = (i&3)+12; 9377 break; 9378 case OP_VSLDOI4: 9379 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9380 case OP_VSLDOI8: 9381 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9382 case OP_VSLDOI12: 9383 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9384 } 9385 EVT VT = OpLHS.getValueType(); 9386 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9387 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9388 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9389 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9390 } 9391 9392 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9393 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9394 /// SDValue. 9395 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9396 SelectionDAG &DAG) const { 9397 const unsigned BytesInVector = 16; 9398 bool IsLE = Subtarget.isLittleEndian(); 9399 SDLoc dl(N); 9400 SDValue V1 = N->getOperand(0); 9401 SDValue V2 = N->getOperand(1); 9402 unsigned ShiftElts = 0, InsertAtByte = 0; 9403 bool Swap = false; 9404 9405 // Shifts required to get the byte we want at element 7. 9406 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9407 0, 15, 14, 13, 12, 11, 10, 9}; 9408 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9409 1, 2, 3, 4, 5, 6, 7, 8}; 9410 9411 ArrayRef<int> Mask = N->getMask(); 9412 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9413 9414 // For each mask element, find out if we're just inserting something 9415 // from V2 into V1 or vice versa. 9416 // Possible permutations inserting an element from V2 into V1: 9417 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9418 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9419 // ... 9420 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9421 // Inserting from V1 into V2 will be similar, except mask range will be 9422 // [16,31]. 9423 9424 bool FoundCandidate = false; 9425 // If both vector operands for the shuffle are the same vector, the mask 9426 // will contain only elements from the first one and the second one will be 9427 // undef. 9428 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9429 // Go through the mask of half-words to find an element that's being moved 9430 // from one vector to the other. 9431 for (unsigned i = 0; i < BytesInVector; ++i) { 9432 unsigned CurrentElement = Mask[i]; 9433 // If 2nd operand is undefined, we should only look for element 7 in the 9434 // Mask. 9435 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9436 continue; 9437 9438 bool OtherElementsInOrder = true; 9439 // Examine the other elements in the Mask to see if they're in original 9440 // order. 9441 for (unsigned j = 0; j < BytesInVector; ++j) { 9442 if (j == i) 9443 continue; 9444 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9445 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9446 // in which we always assume we're always picking from the 1st operand. 9447 int MaskOffset = 9448 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9449 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9450 OtherElementsInOrder = false; 9451 break; 9452 } 9453 } 9454 // If other elements are in original order, we record the number of shifts 9455 // we need to get the element we want into element 7. Also record which byte 9456 // in the vector we should insert into. 9457 if (OtherElementsInOrder) { 9458 // If 2nd operand is undefined, we assume no shifts and no swapping. 9459 if (V2.isUndef()) { 9460 ShiftElts = 0; 9461 Swap = false; 9462 } else { 9463 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9464 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9465 : BigEndianShifts[CurrentElement & 0xF]; 9466 Swap = CurrentElement < BytesInVector; 9467 } 9468 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9469 FoundCandidate = true; 9470 break; 9471 } 9472 } 9473 9474 if (!FoundCandidate) 9475 return SDValue(); 9476 9477 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9478 // optionally with VECSHL if shift is required. 9479 if (Swap) 9480 std::swap(V1, V2); 9481 if (V2.isUndef()) 9482 V2 = V1; 9483 if (ShiftElts) { 9484 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9485 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9486 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9487 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9488 } 9489 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9490 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9491 } 9492 9493 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9494 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9495 /// SDValue. 9496 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9497 SelectionDAG &DAG) const { 9498 const unsigned NumHalfWords = 8; 9499 const unsigned BytesInVector = NumHalfWords * 2; 9500 // Check that the shuffle is on half-words. 9501 if (!isNByteElemShuffleMask(N, 2, 1)) 9502 return SDValue(); 9503 9504 bool IsLE = Subtarget.isLittleEndian(); 9505 SDLoc dl(N); 9506 SDValue V1 = N->getOperand(0); 9507 SDValue V2 = N->getOperand(1); 9508 unsigned ShiftElts = 0, InsertAtByte = 0; 9509 bool Swap = false; 9510 9511 // Shifts required to get the half-word we want at element 3. 9512 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9513 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9514 9515 uint32_t Mask = 0; 9516 uint32_t OriginalOrderLow = 0x1234567; 9517 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9518 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9519 // 32-bit space, only need 4-bit nibbles per element. 9520 for (unsigned i = 0; i < NumHalfWords; ++i) { 9521 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9522 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9523 } 9524 9525 // For each mask element, find out if we're just inserting something 9526 // from V2 into V1 or vice versa. Possible permutations inserting an element 9527 // from V2 into V1: 9528 // X, 1, 2, 3, 4, 5, 6, 7 9529 // 0, X, 2, 3, 4, 5, 6, 7 9530 // 0, 1, X, 3, 4, 5, 6, 7 9531 // 0, 1, 2, X, 4, 5, 6, 7 9532 // 0, 1, 2, 3, X, 5, 6, 7 9533 // 0, 1, 2, 3, 4, X, 6, 7 9534 // 0, 1, 2, 3, 4, 5, X, 7 9535 // 0, 1, 2, 3, 4, 5, 6, X 9536 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9537 9538 bool FoundCandidate = false; 9539 // Go through the mask of half-words to find an element that's being moved 9540 // from one vector to the other. 9541 for (unsigned i = 0; i < NumHalfWords; ++i) { 9542 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9543 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9544 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9545 uint32_t TargetOrder = 0x0; 9546 9547 // If both vector operands for the shuffle are the same vector, the mask 9548 // will contain only elements from the first one and the second one will be 9549 // undef. 9550 if (V2.isUndef()) { 9551 ShiftElts = 0; 9552 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9553 TargetOrder = OriginalOrderLow; 9554 Swap = false; 9555 // Skip if not the correct element or mask of other elements don't equal 9556 // to our expected order. 9557 if (MaskOneElt == VINSERTHSrcElem && 9558 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9559 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9560 FoundCandidate = true; 9561 break; 9562 } 9563 } else { // If both operands are defined. 9564 // Target order is [8,15] if the current mask is between [0,7]. 9565 TargetOrder = 9566 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9567 // Skip if mask of other elements don't equal our expected order. 9568 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9569 // We only need the last 3 bits for the number of shifts. 9570 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9571 : BigEndianShifts[MaskOneElt & 0x7]; 9572 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9573 Swap = MaskOneElt < NumHalfWords; 9574 FoundCandidate = true; 9575 break; 9576 } 9577 } 9578 } 9579 9580 if (!FoundCandidate) 9581 return SDValue(); 9582 9583 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9584 // optionally with VECSHL if shift is required. 9585 if (Swap) 9586 std::swap(V1, V2); 9587 if (V2.isUndef()) 9588 V2 = V1; 9589 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9590 if (ShiftElts) { 9591 // Double ShiftElts because we're left shifting on v16i8 type. 9592 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9593 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9594 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9595 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9596 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9597 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9598 } 9599 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9600 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9601 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9602 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9603 } 9604 9605 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9606 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9607 /// return the code it can be lowered into. Worst case, it can always be 9608 /// lowered into a vperm. 9609 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9610 SelectionDAG &DAG) const { 9611 SDLoc dl(Op); 9612 SDValue V1 = Op.getOperand(0); 9613 SDValue V2 = Op.getOperand(1); 9614 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9615 EVT VT = Op.getValueType(); 9616 bool isLittleEndian = Subtarget.isLittleEndian(); 9617 9618 unsigned ShiftElts, InsertAtByte; 9619 bool Swap = false; 9620 9621 // If this is a load-and-splat, we can do that with a single instruction 9622 // in some cases. However if the load has multiple uses, we don't want to 9623 // combine it because that will just produce multiple loads. 9624 const SDValue *InputLoad = getNormalLoadInput(V1); 9625 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9626 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9627 InputLoad->hasOneUse()) { 9628 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9629 int SplatIdx = 9630 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9631 9632 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9633 // For 4-byte load-and-splat, we need Power9. 9634 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9635 uint64_t Offset = 0; 9636 if (IsFourByte) 9637 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9638 else 9639 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9640 SDValue BasePtr = LD->getBasePtr(); 9641 if (Offset != 0) 9642 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9643 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9644 SDValue Ops[] = { 9645 LD->getChain(), // Chain 9646 BasePtr, // BasePtr 9647 DAG.getValueType(Op.getValueType()) // VT 9648 }; 9649 SDVTList VTL = 9650 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9651 SDValue LdSplt = 9652 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9653 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9654 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9655 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9656 return LdSplt; 9657 } 9658 } 9659 if (Subtarget.hasP9Vector() && 9660 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9661 isLittleEndian)) { 9662 if (Swap) 9663 std::swap(V1, V2); 9664 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9665 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9666 if (ShiftElts) { 9667 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9668 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9669 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9670 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9671 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9672 } 9673 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9674 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9675 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9676 } 9677 9678 if (Subtarget.hasP9Altivec()) { 9679 SDValue NewISDNode; 9680 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9681 return NewISDNode; 9682 9683 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9684 return NewISDNode; 9685 } 9686 9687 if (Subtarget.hasVSX() && 9688 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9689 if (Swap) 9690 std::swap(V1, V2); 9691 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9692 SDValue Conv2 = 9693 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9694 9695 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9696 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9697 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9698 } 9699 9700 if (Subtarget.hasVSX() && 9701 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9702 if (Swap) 9703 std::swap(V1, V2); 9704 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9705 SDValue Conv2 = 9706 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9707 9708 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9709 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9710 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9711 } 9712 9713 if (Subtarget.hasP9Vector()) { 9714 if (PPC::isXXBRHShuffleMask(SVOp)) { 9715 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9716 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9717 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9718 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9719 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9720 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9721 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9722 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9723 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9724 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9725 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9726 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9727 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9728 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9729 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9730 } 9731 } 9732 9733 if (Subtarget.hasVSX()) { 9734 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9735 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9736 9737 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9738 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9739 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9740 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9741 } 9742 9743 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9744 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9745 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9746 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9747 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9748 } 9749 } 9750 9751 if (Subtarget.hasQPX()) { 9752 if (VT.getVectorNumElements() != 4) 9753 return SDValue(); 9754 9755 if (V2.isUndef()) V2 = V1; 9756 9757 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9758 if (AlignIdx != -1) { 9759 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9760 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9761 } else if (SVOp->isSplat()) { 9762 int SplatIdx = SVOp->getSplatIndex(); 9763 if (SplatIdx >= 4) { 9764 std::swap(V1, V2); 9765 SplatIdx -= 4; 9766 } 9767 9768 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9769 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9770 } 9771 9772 // Lower this into a qvgpci/qvfperm pair. 9773 9774 // Compute the qvgpci literal 9775 unsigned idx = 0; 9776 for (unsigned i = 0; i < 4; ++i) { 9777 int m = SVOp->getMaskElt(i); 9778 unsigned mm = m >= 0 ? (unsigned) m : i; 9779 idx |= mm << (3-i)*3; 9780 } 9781 9782 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9783 DAG.getConstant(idx, dl, MVT::i32)); 9784 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9785 } 9786 9787 // Cases that are handled by instructions that take permute immediates 9788 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9789 // selected by the instruction selector. 9790 if (V2.isUndef()) { 9791 if (PPC::isSplatShuffleMask(SVOp, 1) || 9792 PPC::isSplatShuffleMask(SVOp, 2) || 9793 PPC::isSplatShuffleMask(SVOp, 4) || 9794 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9795 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9796 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9797 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9798 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9799 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9800 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9801 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9802 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9803 (Subtarget.hasP8Altivec() && ( 9804 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9805 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9806 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9807 return Op; 9808 } 9809 } 9810 9811 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9812 // and produce a fixed permutation. If any of these match, do not lower to 9813 // VPERM. 9814 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9815 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9816 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9817 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9818 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9819 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9820 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9821 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9822 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9823 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9824 (Subtarget.hasP8Altivec() && ( 9825 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9826 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9827 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9828 return Op; 9829 9830 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9831 // perfect shuffle table to emit an optimal matching sequence. 9832 ArrayRef<int> PermMask = SVOp->getMask(); 9833 9834 unsigned PFIndexes[4]; 9835 bool isFourElementShuffle = true; 9836 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9837 unsigned EltNo = 8; // Start out undef. 9838 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9839 if (PermMask[i*4+j] < 0) 9840 continue; // Undef, ignore it. 9841 9842 unsigned ByteSource = PermMask[i*4+j]; 9843 if ((ByteSource & 3) != j) { 9844 isFourElementShuffle = false; 9845 break; 9846 } 9847 9848 if (EltNo == 8) { 9849 EltNo = ByteSource/4; 9850 } else if (EltNo != ByteSource/4) { 9851 isFourElementShuffle = false; 9852 break; 9853 } 9854 } 9855 PFIndexes[i] = EltNo; 9856 } 9857 9858 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9859 // perfect shuffle vector to determine if it is cost effective to do this as 9860 // discrete instructions, or whether we should use a vperm. 9861 // For now, we skip this for little endian until such time as we have a 9862 // little-endian perfect shuffle table. 9863 if (isFourElementShuffle && !isLittleEndian) { 9864 // Compute the index in the perfect shuffle table. 9865 unsigned PFTableIndex = 9866 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9867 9868 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9869 unsigned Cost = (PFEntry >> 30); 9870 9871 // Determining when to avoid vperm is tricky. Many things affect the cost 9872 // of vperm, particularly how many times the perm mask needs to be computed. 9873 // For example, if the perm mask can be hoisted out of a loop or is already 9874 // used (perhaps because there are multiple permutes with the same shuffle 9875 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9876 // the loop requires an extra register. 9877 // 9878 // As a compromise, we only emit discrete instructions if the shuffle can be 9879 // generated in 3 or fewer operations. When we have loop information 9880 // available, if this block is within a loop, we should avoid using vperm 9881 // for 3-operation perms and use a constant pool load instead. 9882 if (Cost < 3) 9883 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9884 } 9885 9886 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9887 // vector that will get spilled to the constant pool. 9888 if (V2.isUndef()) V2 = V1; 9889 9890 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9891 // that it is in input element units, not in bytes. Convert now. 9892 9893 // For little endian, the order of the input vectors is reversed, and 9894 // the permutation mask is complemented with respect to 31. This is 9895 // necessary to produce proper semantics with the big-endian-biased vperm 9896 // instruction. 9897 EVT EltVT = V1.getValueType().getVectorElementType(); 9898 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9899 9900 SmallVector<SDValue, 16> ResultMask; 9901 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9902 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9903 9904 for (unsigned j = 0; j != BytesPerElement; ++j) 9905 if (isLittleEndian) 9906 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9907 dl, MVT::i32)); 9908 else 9909 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9910 MVT::i32)); 9911 } 9912 9913 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9914 if (isLittleEndian) 9915 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9916 V2, V1, VPermMask); 9917 else 9918 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9919 V1, V2, VPermMask); 9920 } 9921 9922 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9923 /// vector comparison. If it is, return true and fill in Opc/isDot with 9924 /// information about the intrinsic. 9925 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9926 bool &isDot, const PPCSubtarget &Subtarget) { 9927 unsigned IntrinsicID = 9928 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9929 CompareOpc = -1; 9930 isDot = false; 9931 switch (IntrinsicID) { 9932 default: 9933 return false; 9934 // Comparison predicates. 9935 case Intrinsic::ppc_altivec_vcmpbfp_p: 9936 CompareOpc = 966; 9937 isDot = true; 9938 break; 9939 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9940 CompareOpc = 198; 9941 isDot = true; 9942 break; 9943 case Intrinsic::ppc_altivec_vcmpequb_p: 9944 CompareOpc = 6; 9945 isDot = true; 9946 break; 9947 case Intrinsic::ppc_altivec_vcmpequh_p: 9948 CompareOpc = 70; 9949 isDot = true; 9950 break; 9951 case Intrinsic::ppc_altivec_vcmpequw_p: 9952 CompareOpc = 134; 9953 isDot = true; 9954 break; 9955 case Intrinsic::ppc_altivec_vcmpequd_p: 9956 if (Subtarget.hasP8Altivec()) { 9957 CompareOpc = 199; 9958 isDot = true; 9959 } else 9960 return false; 9961 break; 9962 case Intrinsic::ppc_altivec_vcmpneb_p: 9963 case Intrinsic::ppc_altivec_vcmpneh_p: 9964 case Intrinsic::ppc_altivec_vcmpnew_p: 9965 case Intrinsic::ppc_altivec_vcmpnezb_p: 9966 case Intrinsic::ppc_altivec_vcmpnezh_p: 9967 case Intrinsic::ppc_altivec_vcmpnezw_p: 9968 if (Subtarget.hasP9Altivec()) { 9969 switch (IntrinsicID) { 9970 default: 9971 llvm_unreachable("Unknown comparison intrinsic."); 9972 case Intrinsic::ppc_altivec_vcmpneb_p: 9973 CompareOpc = 7; 9974 break; 9975 case Intrinsic::ppc_altivec_vcmpneh_p: 9976 CompareOpc = 71; 9977 break; 9978 case Intrinsic::ppc_altivec_vcmpnew_p: 9979 CompareOpc = 135; 9980 break; 9981 case Intrinsic::ppc_altivec_vcmpnezb_p: 9982 CompareOpc = 263; 9983 break; 9984 case Intrinsic::ppc_altivec_vcmpnezh_p: 9985 CompareOpc = 327; 9986 break; 9987 case Intrinsic::ppc_altivec_vcmpnezw_p: 9988 CompareOpc = 391; 9989 break; 9990 } 9991 isDot = true; 9992 } else 9993 return false; 9994 break; 9995 case Intrinsic::ppc_altivec_vcmpgefp_p: 9996 CompareOpc = 454; 9997 isDot = true; 9998 break; 9999 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10000 CompareOpc = 710; 10001 isDot = true; 10002 break; 10003 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10004 CompareOpc = 774; 10005 isDot = true; 10006 break; 10007 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10008 CompareOpc = 838; 10009 isDot = true; 10010 break; 10011 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10012 CompareOpc = 902; 10013 isDot = true; 10014 break; 10015 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10016 if (Subtarget.hasP8Altivec()) { 10017 CompareOpc = 967; 10018 isDot = true; 10019 } else 10020 return false; 10021 break; 10022 case Intrinsic::ppc_altivec_vcmpgtub_p: 10023 CompareOpc = 518; 10024 isDot = true; 10025 break; 10026 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10027 CompareOpc = 582; 10028 isDot = true; 10029 break; 10030 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10031 CompareOpc = 646; 10032 isDot = true; 10033 break; 10034 case Intrinsic::ppc_altivec_vcmpgtud_p: 10035 if (Subtarget.hasP8Altivec()) { 10036 CompareOpc = 711; 10037 isDot = true; 10038 } else 10039 return false; 10040 break; 10041 10042 // VSX predicate comparisons use the same infrastructure 10043 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10044 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10045 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10046 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10047 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10048 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10049 if (Subtarget.hasVSX()) { 10050 switch (IntrinsicID) { 10051 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10052 CompareOpc = 99; 10053 break; 10054 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10055 CompareOpc = 115; 10056 break; 10057 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10058 CompareOpc = 107; 10059 break; 10060 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10061 CompareOpc = 67; 10062 break; 10063 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10064 CompareOpc = 83; 10065 break; 10066 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10067 CompareOpc = 75; 10068 break; 10069 } 10070 isDot = true; 10071 } else 10072 return false; 10073 break; 10074 10075 // Normal Comparisons. 10076 case Intrinsic::ppc_altivec_vcmpbfp: 10077 CompareOpc = 966; 10078 break; 10079 case Intrinsic::ppc_altivec_vcmpeqfp: 10080 CompareOpc = 198; 10081 break; 10082 case Intrinsic::ppc_altivec_vcmpequb: 10083 CompareOpc = 6; 10084 break; 10085 case Intrinsic::ppc_altivec_vcmpequh: 10086 CompareOpc = 70; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpequw: 10089 CompareOpc = 134; 10090 break; 10091 case Intrinsic::ppc_altivec_vcmpequd: 10092 if (Subtarget.hasP8Altivec()) 10093 CompareOpc = 199; 10094 else 10095 return false; 10096 break; 10097 case Intrinsic::ppc_altivec_vcmpneb: 10098 case Intrinsic::ppc_altivec_vcmpneh: 10099 case Intrinsic::ppc_altivec_vcmpnew: 10100 case Intrinsic::ppc_altivec_vcmpnezb: 10101 case Intrinsic::ppc_altivec_vcmpnezh: 10102 case Intrinsic::ppc_altivec_vcmpnezw: 10103 if (Subtarget.hasP9Altivec()) 10104 switch (IntrinsicID) { 10105 default: 10106 llvm_unreachable("Unknown comparison intrinsic."); 10107 case Intrinsic::ppc_altivec_vcmpneb: 10108 CompareOpc = 7; 10109 break; 10110 case Intrinsic::ppc_altivec_vcmpneh: 10111 CompareOpc = 71; 10112 break; 10113 case Intrinsic::ppc_altivec_vcmpnew: 10114 CompareOpc = 135; 10115 break; 10116 case Intrinsic::ppc_altivec_vcmpnezb: 10117 CompareOpc = 263; 10118 break; 10119 case Intrinsic::ppc_altivec_vcmpnezh: 10120 CompareOpc = 327; 10121 break; 10122 case Intrinsic::ppc_altivec_vcmpnezw: 10123 CompareOpc = 391; 10124 break; 10125 } 10126 else 10127 return false; 10128 break; 10129 case Intrinsic::ppc_altivec_vcmpgefp: 10130 CompareOpc = 454; 10131 break; 10132 case Intrinsic::ppc_altivec_vcmpgtfp: 10133 CompareOpc = 710; 10134 break; 10135 case Intrinsic::ppc_altivec_vcmpgtsb: 10136 CompareOpc = 774; 10137 break; 10138 case Intrinsic::ppc_altivec_vcmpgtsh: 10139 CompareOpc = 838; 10140 break; 10141 case Intrinsic::ppc_altivec_vcmpgtsw: 10142 CompareOpc = 902; 10143 break; 10144 case Intrinsic::ppc_altivec_vcmpgtsd: 10145 if (Subtarget.hasP8Altivec()) 10146 CompareOpc = 967; 10147 else 10148 return false; 10149 break; 10150 case Intrinsic::ppc_altivec_vcmpgtub: 10151 CompareOpc = 518; 10152 break; 10153 case Intrinsic::ppc_altivec_vcmpgtuh: 10154 CompareOpc = 582; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpgtuw: 10157 CompareOpc = 646; 10158 break; 10159 case Intrinsic::ppc_altivec_vcmpgtud: 10160 if (Subtarget.hasP8Altivec()) 10161 CompareOpc = 711; 10162 else 10163 return false; 10164 break; 10165 } 10166 return true; 10167 } 10168 10169 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10170 /// lower, do it, otherwise return null. 10171 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10172 SelectionDAG &DAG) const { 10173 unsigned IntrinsicID = 10174 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10175 10176 SDLoc dl(Op); 10177 10178 if (IntrinsicID == Intrinsic::thread_pointer) { 10179 // Reads the thread pointer register, used for __builtin_thread_pointer. 10180 if (Subtarget.isPPC64()) 10181 return DAG.getRegister(PPC::X13, MVT::i64); 10182 return DAG.getRegister(PPC::R2, MVT::i32); 10183 } 10184 10185 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10186 // opcode number of the comparison. 10187 int CompareOpc; 10188 bool isDot; 10189 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10190 return SDValue(); // Don't custom lower most intrinsics. 10191 10192 // If this is a non-dot comparison, make the VCMP node and we are done. 10193 if (!isDot) { 10194 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10195 Op.getOperand(1), Op.getOperand(2), 10196 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10197 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10198 } 10199 10200 // Create the PPCISD altivec 'dot' comparison node. 10201 SDValue Ops[] = { 10202 Op.getOperand(2), // LHS 10203 Op.getOperand(3), // RHS 10204 DAG.getConstant(CompareOpc, dl, MVT::i32) 10205 }; 10206 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10207 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10208 10209 // Now that we have the comparison, emit a copy from the CR to a GPR. 10210 // This is flagged to the above dot comparison. 10211 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10212 DAG.getRegister(PPC::CR6, MVT::i32), 10213 CompNode.getValue(1)); 10214 10215 // Unpack the result based on how the target uses it. 10216 unsigned BitNo; // Bit # of CR6. 10217 bool InvertBit; // Invert result? 10218 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10219 default: // Can't happen, don't crash on invalid number though. 10220 case 0: // Return the value of the EQ bit of CR6. 10221 BitNo = 0; InvertBit = false; 10222 break; 10223 case 1: // Return the inverted value of the EQ bit of CR6. 10224 BitNo = 0; InvertBit = true; 10225 break; 10226 case 2: // Return the value of the LT bit of CR6. 10227 BitNo = 2; InvertBit = false; 10228 break; 10229 case 3: // Return the inverted value of the LT bit of CR6. 10230 BitNo = 2; InvertBit = true; 10231 break; 10232 } 10233 10234 // Shift the bit into the low position. 10235 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10236 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10237 // Isolate the bit. 10238 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10239 DAG.getConstant(1, dl, MVT::i32)); 10240 10241 // If we are supposed to, toggle the bit. 10242 if (InvertBit) 10243 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10244 DAG.getConstant(1, dl, MVT::i32)); 10245 return Flags; 10246 } 10247 10248 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10249 SelectionDAG &DAG) const { 10250 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10251 // the beginning of the argument list. 10252 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10253 SDLoc DL(Op); 10254 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10255 case Intrinsic::ppc_cfence: { 10256 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10257 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10258 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10259 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10260 Op.getOperand(ArgStart + 1)), 10261 Op.getOperand(0)), 10262 0); 10263 } 10264 default: 10265 break; 10266 } 10267 return SDValue(); 10268 } 10269 10270 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10271 // Check for a DIV with the same operands as this REM. 10272 for (auto UI : Op.getOperand(1)->uses()) { 10273 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10274 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10275 if (UI->getOperand(0) == Op.getOperand(0) && 10276 UI->getOperand(1) == Op.getOperand(1)) 10277 return SDValue(); 10278 } 10279 return Op; 10280 } 10281 10282 // Lower scalar BSWAP64 to xxbrd. 10283 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10284 SDLoc dl(Op); 10285 // MTVSRDD 10286 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10287 Op.getOperand(0)); 10288 // XXBRD 10289 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10290 // MFVSRD 10291 int VectorIndex = 0; 10292 if (Subtarget.isLittleEndian()) 10293 VectorIndex = 1; 10294 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10295 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10296 return Op; 10297 } 10298 10299 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10300 // compared to a value that is atomically loaded (atomic loads zero-extend). 10301 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10302 SelectionDAG &DAG) const { 10303 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10304 "Expecting an atomic compare-and-swap here."); 10305 SDLoc dl(Op); 10306 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10307 EVT MemVT = AtomicNode->getMemoryVT(); 10308 if (MemVT.getSizeInBits() >= 32) 10309 return Op; 10310 10311 SDValue CmpOp = Op.getOperand(2); 10312 // If this is already correctly zero-extended, leave it alone. 10313 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10314 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10315 return Op; 10316 10317 // Clear the high bits of the compare operand. 10318 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10319 SDValue NewCmpOp = 10320 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10321 DAG.getConstant(MaskVal, dl, MVT::i32)); 10322 10323 // Replace the existing compare operand with the properly zero-extended one. 10324 SmallVector<SDValue, 4> Ops; 10325 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10326 Ops.push_back(AtomicNode->getOperand(i)); 10327 Ops[2] = NewCmpOp; 10328 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10329 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10330 auto NodeTy = 10331 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10332 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10333 } 10334 10335 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10336 SelectionDAG &DAG) const { 10337 SDLoc dl(Op); 10338 // Create a stack slot that is 16-byte aligned. 10339 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10340 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10341 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10342 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10343 10344 // Store the input value into Value#0 of the stack slot. 10345 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10346 MachinePointerInfo()); 10347 // Load it out. 10348 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10349 } 10350 10351 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10352 SelectionDAG &DAG) const { 10353 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10354 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10355 10356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10357 // We have legal lowering for constant indices but not for variable ones. 10358 if (!C) 10359 return SDValue(); 10360 10361 EVT VT = Op.getValueType(); 10362 SDLoc dl(Op); 10363 SDValue V1 = Op.getOperand(0); 10364 SDValue V2 = Op.getOperand(1); 10365 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10366 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10367 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10368 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10369 unsigned InsertAtElement = C->getZExtValue(); 10370 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10371 if (Subtarget.isLittleEndian()) { 10372 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10373 } 10374 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10375 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10376 } 10377 return Op; 10378 } 10379 10380 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10381 SelectionDAG &DAG) const { 10382 SDLoc dl(Op); 10383 SDNode *N = Op.getNode(); 10384 10385 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10386 "Unknown extract_vector_elt type"); 10387 10388 SDValue Value = N->getOperand(0); 10389 10390 // The first part of this is like the store lowering except that we don't 10391 // need to track the chain. 10392 10393 // The values are now known to be -1 (false) or 1 (true). To convert this 10394 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10395 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10396 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10397 10398 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10399 // understand how to form the extending load. 10400 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10401 10402 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10403 10404 // Now convert to an integer and store. 10405 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10406 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10407 Value); 10408 10409 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10410 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10411 MachinePointerInfo PtrInfo = 10412 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10413 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10414 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10415 10416 SDValue StoreChain = DAG.getEntryNode(); 10417 SDValue Ops[] = {StoreChain, 10418 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10419 Value, FIdx}; 10420 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10421 10422 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10423 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10424 10425 // Extract the value requested. 10426 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10427 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10428 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10429 10430 SDValue IntVal = 10431 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10432 10433 if (!Subtarget.useCRBits()) 10434 return IntVal; 10435 10436 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10437 } 10438 10439 /// Lowering for QPX v4i1 loads 10440 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10441 SelectionDAG &DAG) const { 10442 SDLoc dl(Op); 10443 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10444 SDValue LoadChain = LN->getChain(); 10445 SDValue BasePtr = LN->getBasePtr(); 10446 10447 if (Op.getValueType() == MVT::v4f64 || 10448 Op.getValueType() == MVT::v4f32) { 10449 EVT MemVT = LN->getMemoryVT(); 10450 unsigned Alignment = LN->getAlignment(); 10451 10452 // If this load is properly aligned, then it is legal. 10453 if (Alignment >= MemVT.getStoreSize()) 10454 return Op; 10455 10456 EVT ScalarVT = Op.getValueType().getScalarType(), 10457 ScalarMemVT = MemVT.getScalarType(); 10458 unsigned Stride = ScalarMemVT.getStoreSize(); 10459 10460 SDValue Vals[4], LoadChains[4]; 10461 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10462 SDValue Load; 10463 if (ScalarVT != ScalarMemVT) 10464 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10465 BasePtr, 10466 LN->getPointerInfo().getWithOffset(Idx * Stride), 10467 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10468 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10469 else 10470 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10471 LN->getPointerInfo().getWithOffset(Idx * Stride), 10472 MinAlign(Alignment, Idx * Stride), 10473 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10474 10475 if (Idx == 0 && LN->isIndexed()) { 10476 assert(LN->getAddressingMode() == ISD::PRE_INC && 10477 "Unknown addressing mode on vector load"); 10478 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10479 LN->getAddressingMode()); 10480 } 10481 10482 Vals[Idx] = Load; 10483 LoadChains[Idx] = Load.getValue(1); 10484 10485 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10486 DAG.getConstant(Stride, dl, 10487 BasePtr.getValueType())); 10488 } 10489 10490 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10491 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10492 10493 if (LN->isIndexed()) { 10494 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10495 return DAG.getMergeValues(RetOps, dl); 10496 } 10497 10498 SDValue RetOps[] = { Value, TF }; 10499 return DAG.getMergeValues(RetOps, dl); 10500 } 10501 10502 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10503 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10504 10505 // To lower v4i1 from a byte array, we load the byte elements of the 10506 // vector and then reuse the BUILD_VECTOR logic. 10507 10508 SDValue VectElmts[4], VectElmtChains[4]; 10509 for (unsigned i = 0; i < 4; ++i) { 10510 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10511 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10512 10513 VectElmts[i] = DAG.getExtLoad( 10514 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10515 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10516 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10517 VectElmtChains[i] = VectElmts[i].getValue(1); 10518 } 10519 10520 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10521 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10522 10523 SDValue RVals[] = { Value, LoadChain }; 10524 return DAG.getMergeValues(RVals, dl); 10525 } 10526 10527 /// Lowering for QPX v4i1 stores 10528 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10529 SelectionDAG &DAG) const { 10530 SDLoc dl(Op); 10531 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10532 SDValue StoreChain = SN->getChain(); 10533 SDValue BasePtr = SN->getBasePtr(); 10534 SDValue Value = SN->getValue(); 10535 10536 if (Value.getValueType() == MVT::v4f64 || 10537 Value.getValueType() == MVT::v4f32) { 10538 EVT MemVT = SN->getMemoryVT(); 10539 unsigned Alignment = SN->getAlignment(); 10540 10541 // If this store is properly aligned, then it is legal. 10542 if (Alignment >= MemVT.getStoreSize()) 10543 return Op; 10544 10545 EVT ScalarVT = Value.getValueType().getScalarType(), 10546 ScalarMemVT = MemVT.getScalarType(); 10547 unsigned Stride = ScalarMemVT.getStoreSize(); 10548 10549 SDValue Stores[4]; 10550 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10551 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10552 DAG.getVectorIdxConstant(Idx, dl)); 10553 SDValue Store; 10554 if (ScalarVT != ScalarMemVT) 10555 Store = 10556 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10557 SN->getPointerInfo().getWithOffset(Idx * Stride), 10558 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10559 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10560 else 10561 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10562 SN->getPointerInfo().getWithOffset(Idx * Stride), 10563 MinAlign(Alignment, Idx * Stride), 10564 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10565 10566 if (Idx == 0 && SN->isIndexed()) { 10567 assert(SN->getAddressingMode() == ISD::PRE_INC && 10568 "Unknown addressing mode on vector store"); 10569 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10570 SN->getAddressingMode()); 10571 } 10572 10573 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10574 DAG.getConstant(Stride, dl, 10575 BasePtr.getValueType())); 10576 Stores[Idx] = Store; 10577 } 10578 10579 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10580 10581 if (SN->isIndexed()) { 10582 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10583 return DAG.getMergeValues(RetOps, dl); 10584 } 10585 10586 return TF; 10587 } 10588 10589 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10590 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10591 10592 // The values are now known to be -1 (false) or 1 (true). To convert this 10593 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10594 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10595 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10596 10597 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10598 // understand how to form the extending load. 10599 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10600 10601 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10602 10603 // Now convert to an integer and store. 10604 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10605 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10606 Value); 10607 10608 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10609 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10610 MachinePointerInfo PtrInfo = 10611 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10612 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10613 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10614 10615 SDValue Ops[] = {StoreChain, 10616 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10617 Value, FIdx}; 10618 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10619 10620 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10621 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10622 10623 // Move data into the byte array. 10624 SDValue Loads[4], LoadChains[4]; 10625 for (unsigned i = 0; i < 4; ++i) { 10626 unsigned Offset = 4*i; 10627 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10628 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10629 10630 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10631 PtrInfo.getWithOffset(Offset)); 10632 LoadChains[i] = Loads[i].getValue(1); 10633 } 10634 10635 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10636 10637 SDValue Stores[4]; 10638 for (unsigned i = 0; i < 4; ++i) { 10639 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10640 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10641 10642 Stores[i] = DAG.getTruncStore( 10643 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10644 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10645 SN->getAAInfo()); 10646 } 10647 10648 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10649 10650 return StoreChain; 10651 } 10652 10653 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10654 SDLoc dl(Op); 10655 if (Op.getValueType() == MVT::v4i32) { 10656 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10657 10658 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10659 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10660 10661 SDValue RHSSwap = // = vrlw RHS, 16 10662 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10663 10664 // Shrinkify inputs to v8i16. 10665 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10666 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10667 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10668 10669 // Low parts multiplied together, generating 32-bit results (we ignore the 10670 // top parts). 10671 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10672 LHS, RHS, DAG, dl, MVT::v4i32); 10673 10674 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10675 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10676 // Shift the high parts up 16 bits. 10677 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10678 Neg16, DAG, dl); 10679 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10680 } else if (Op.getValueType() == MVT::v16i8) { 10681 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10682 bool isLittleEndian = Subtarget.isLittleEndian(); 10683 10684 // Multiply the even 8-bit parts, producing 16-bit sums. 10685 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10686 LHS, RHS, DAG, dl, MVT::v8i16); 10687 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10688 10689 // Multiply the odd 8-bit parts, producing 16-bit sums. 10690 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10691 LHS, RHS, DAG, dl, MVT::v8i16); 10692 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10693 10694 // Merge the results together. Because vmuleub and vmuloub are 10695 // instructions with a big-endian bias, we must reverse the 10696 // element numbering and reverse the meaning of "odd" and "even" 10697 // when generating little endian code. 10698 int Ops[16]; 10699 for (unsigned i = 0; i != 8; ++i) { 10700 if (isLittleEndian) { 10701 Ops[i*2 ] = 2*i; 10702 Ops[i*2+1] = 2*i+16; 10703 } else { 10704 Ops[i*2 ] = 2*i+1; 10705 Ops[i*2+1] = 2*i+1+16; 10706 } 10707 } 10708 if (isLittleEndian) 10709 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10710 else 10711 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10712 } else { 10713 llvm_unreachable("Unknown mul to lower!"); 10714 } 10715 } 10716 10717 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10718 10719 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10720 10721 EVT VT = Op.getValueType(); 10722 assert(VT.isVector() && 10723 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10724 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10725 VT == MVT::v16i8) && 10726 "Unexpected vector element type!"); 10727 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10728 "Current subtarget doesn't support smax v2i64!"); 10729 10730 // For vector abs, it can be lowered to: 10731 // abs x 10732 // ==> 10733 // y = -x 10734 // smax(x, y) 10735 10736 SDLoc dl(Op); 10737 SDValue X = Op.getOperand(0); 10738 SDValue Zero = DAG.getConstant(0, dl, VT); 10739 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10740 10741 // SMAX patch https://reviews.llvm.org/D47332 10742 // hasn't landed yet, so use intrinsic first here. 10743 // TODO: Should use SMAX directly once SMAX patch landed 10744 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10745 if (VT == MVT::v2i64) 10746 BifID = Intrinsic::ppc_altivec_vmaxsd; 10747 else if (VT == MVT::v8i16) 10748 BifID = Intrinsic::ppc_altivec_vmaxsh; 10749 else if (VT == MVT::v16i8) 10750 BifID = Intrinsic::ppc_altivec_vmaxsb; 10751 10752 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10753 } 10754 10755 // Custom lowering for fpext vf32 to v2f64 10756 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10757 10758 assert(Op.getOpcode() == ISD::FP_EXTEND && 10759 "Should only be called for ISD::FP_EXTEND"); 10760 10761 // We only want to custom lower an extend from v2f32 to v2f64. 10762 if (Op.getValueType() != MVT::v2f64 || 10763 Op.getOperand(0).getValueType() != MVT::v2f32) 10764 return SDValue(); 10765 10766 SDLoc dl(Op); 10767 SDValue Op0 = Op.getOperand(0); 10768 10769 switch (Op0.getOpcode()) { 10770 default: 10771 return SDValue(); 10772 case ISD::EXTRACT_SUBVECTOR: { 10773 assert(Op0.getNumOperands() == 2 && 10774 isa<ConstantSDNode>(Op0->getOperand(1)) && 10775 "Node should have 2 operands with second one being a constant!"); 10776 10777 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10778 return SDValue(); 10779 10780 // Custom lower is only done for high or low doubleword. 10781 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10782 if (Idx % 2 != 0) 10783 return SDValue(); 10784 10785 // Since input is v4f32, at this point Idx is either 0 or 2. 10786 // Shift to get the doubleword position we want. 10787 int DWord = Idx >> 1; 10788 10789 // High and low word positions are different on little endian. 10790 if (Subtarget.isLittleEndian()) 10791 DWord ^= 0x1; 10792 10793 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10794 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10795 } 10796 case ISD::FADD: 10797 case ISD::FMUL: 10798 case ISD::FSUB: { 10799 SDValue NewLoad[2]; 10800 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10801 // Ensure both input are loads. 10802 SDValue LdOp = Op0.getOperand(i); 10803 if (LdOp.getOpcode() != ISD::LOAD) 10804 return SDValue(); 10805 // Generate new load node. 10806 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10807 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10808 NewLoad[i] = DAG.getMemIntrinsicNode( 10809 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10810 LD->getMemoryVT(), LD->getMemOperand()); 10811 } 10812 SDValue NewOp = 10813 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10814 NewLoad[1], Op0.getNode()->getFlags()); 10815 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10816 DAG.getConstant(0, dl, MVT::i32)); 10817 } 10818 case ISD::LOAD: { 10819 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10820 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10821 SDValue NewLd = DAG.getMemIntrinsicNode( 10822 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10823 LD->getMemoryVT(), LD->getMemOperand()); 10824 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10825 DAG.getConstant(0, dl, MVT::i32)); 10826 } 10827 } 10828 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10829 } 10830 10831 /// LowerOperation - Provide custom lowering hooks for some operations. 10832 /// 10833 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10834 switch (Op.getOpcode()) { 10835 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10836 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10837 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10838 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10839 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10840 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10841 case ISD::SETCC: return LowerSETCC(Op, DAG); 10842 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10843 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10844 10845 // Variable argument lowering. 10846 case ISD::VASTART: return LowerVASTART(Op, DAG); 10847 case ISD::VAARG: return LowerVAARG(Op, DAG); 10848 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10849 10850 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10851 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10852 case ISD::GET_DYNAMIC_AREA_OFFSET: 10853 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10854 10855 // Exception handling lowering. 10856 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10857 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10858 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10859 10860 case ISD::LOAD: return LowerLOAD(Op, DAG); 10861 case ISD::STORE: return LowerSTORE(Op, DAG); 10862 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10863 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10864 case ISD::FP_TO_UINT: 10865 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10866 case ISD::UINT_TO_FP: 10867 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10868 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10869 10870 // Lower 64-bit shifts. 10871 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10872 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10873 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10874 10875 // Vector-related lowering. 10876 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10877 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10878 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10879 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10880 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10881 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10882 case ISD::MUL: return LowerMUL(Op, DAG); 10883 case ISD::ABS: return LowerABS(Op, DAG); 10884 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10885 10886 // For counter-based loop handling. 10887 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10888 10889 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10890 10891 // Frame & Return address. 10892 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10893 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10894 10895 case ISD::INTRINSIC_VOID: 10896 return LowerINTRINSIC_VOID(Op, DAG); 10897 case ISD::SREM: 10898 case ISD::UREM: 10899 return LowerREM(Op, DAG); 10900 case ISD::BSWAP: 10901 return LowerBSWAP(Op, DAG); 10902 case ISD::ATOMIC_CMP_SWAP: 10903 return LowerATOMIC_CMP_SWAP(Op, DAG); 10904 } 10905 } 10906 10907 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10908 SmallVectorImpl<SDValue>&Results, 10909 SelectionDAG &DAG) const { 10910 SDLoc dl(N); 10911 switch (N->getOpcode()) { 10912 default: 10913 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10914 case ISD::READCYCLECOUNTER: { 10915 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10916 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10917 10918 Results.push_back( 10919 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10920 Results.push_back(RTB.getValue(2)); 10921 break; 10922 } 10923 case ISD::INTRINSIC_W_CHAIN: { 10924 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10925 Intrinsic::loop_decrement) 10926 break; 10927 10928 assert(N->getValueType(0) == MVT::i1 && 10929 "Unexpected result type for CTR decrement intrinsic"); 10930 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10931 N->getValueType(0)); 10932 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10933 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10934 N->getOperand(1)); 10935 10936 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10937 Results.push_back(NewInt.getValue(1)); 10938 break; 10939 } 10940 case ISD::VAARG: { 10941 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10942 return; 10943 10944 EVT VT = N->getValueType(0); 10945 10946 if (VT == MVT::i64) { 10947 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10948 10949 Results.push_back(NewNode); 10950 Results.push_back(NewNode.getValue(1)); 10951 } 10952 return; 10953 } 10954 case ISD::FP_TO_SINT: 10955 case ISD::FP_TO_UINT: 10956 // LowerFP_TO_INT() can only handle f32 and f64. 10957 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10958 return; 10959 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10960 return; 10961 case ISD::TRUNCATE: { 10962 EVT TrgVT = N->getValueType(0); 10963 EVT OpVT = N->getOperand(0).getValueType(); 10964 if (TrgVT.isVector() && 10965 isOperationCustom(N->getOpcode(), TrgVT) && 10966 OpVT.getSizeInBits() <= 128 && 10967 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10968 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10969 return; 10970 } 10971 case ISD::BITCAST: 10972 // Don't handle bitcast here. 10973 return; 10974 } 10975 } 10976 10977 //===----------------------------------------------------------------------===// 10978 // Other Lowering Code 10979 //===----------------------------------------------------------------------===// 10980 10981 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10982 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10983 Function *Func = Intrinsic::getDeclaration(M, Id); 10984 return Builder.CreateCall(Func, {}); 10985 } 10986 10987 // The mappings for emitLeading/TrailingFence is taken from 10988 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10989 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10990 Instruction *Inst, 10991 AtomicOrdering Ord) const { 10992 if (Ord == AtomicOrdering::SequentiallyConsistent) 10993 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10994 if (isReleaseOrStronger(Ord)) 10995 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10996 return nullptr; 10997 } 10998 10999 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11000 Instruction *Inst, 11001 AtomicOrdering Ord) const { 11002 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11003 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11004 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11005 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11006 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11007 return Builder.CreateCall( 11008 Intrinsic::getDeclaration( 11009 Builder.GetInsertBlock()->getParent()->getParent(), 11010 Intrinsic::ppc_cfence, {Inst->getType()}), 11011 {Inst}); 11012 // FIXME: Can use isync for rmw operation. 11013 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11014 } 11015 return nullptr; 11016 } 11017 11018 MachineBasicBlock * 11019 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11020 unsigned AtomicSize, 11021 unsigned BinOpcode, 11022 unsigned CmpOpcode, 11023 unsigned CmpPred) const { 11024 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11025 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11026 11027 auto LoadMnemonic = PPC::LDARX; 11028 auto StoreMnemonic = PPC::STDCX; 11029 switch (AtomicSize) { 11030 default: 11031 llvm_unreachable("Unexpected size of atomic entity"); 11032 case 1: 11033 LoadMnemonic = PPC::LBARX; 11034 StoreMnemonic = PPC::STBCX; 11035 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11036 break; 11037 case 2: 11038 LoadMnemonic = PPC::LHARX; 11039 StoreMnemonic = PPC::STHCX; 11040 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11041 break; 11042 case 4: 11043 LoadMnemonic = PPC::LWARX; 11044 StoreMnemonic = PPC::STWCX; 11045 break; 11046 case 8: 11047 LoadMnemonic = PPC::LDARX; 11048 StoreMnemonic = PPC::STDCX; 11049 break; 11050 } 11051 11052 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11053 MachineFunction *F = BB->getParent(); 11054 MachineFunction::iterator It = ++BB->getIterator(); 11055 11056 Register dest = MI.getOperand(0).getReg(); 11057 Register ptrA = MI.getOperand(1).getReg(); 11058 Register ptrB = MI.getOperand(2).getReg(); 11059 Register incr = MI.getOperand(3).getReg(); 11060 DebugLoc dl = MI.getDebugLoc(); 11061 11062 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11063 MachineBasicBlock *loop2MBB = 11064 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11065 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11066 F->insert(It, loopMBB); 11067 if (CmpOpcode) 11068 F->insert(It, loop2MBB); 11069 F->insert(It, exitMBB); 11070 exitMBB->splice(exitMBB->begin(), BB, 11071 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11072 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11073 11074 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11075 Register TmpReg = (!BinOpcode) ? incr : 11076 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11077 : &PPC::GPRCRegClass); 11078 11079 // thisMBB: 11080 // ... 11081 // fallthrough --> loopMBB 11082 BB->addSuccessor(loopMBB); 11083 11084 // loopMBB: 11085 // l[wd]arx dest, ptr 11086 // add r0, dest, incr 11087 // st[wd]cx. r0, ptr 11088 // bne- loopMBB 11089 // fallthrough --> exitMBB 11090 11091 // For max/min... 11092 // loopMBB: 11093 // l[wd]arx dest, ptr 11094 // cmpl?[wd] incr, dest 11095 // bgt exitMBB 11096 // loop2MBB: 11097 // st[wd]cx. dest, ptr 11098 // bne- loopMBB 11099 // fallthrough --> exitMBB 11100 11101 BB = loopMBB; 11102 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11103 .addReg(ptrA).addReg(ptrB); 11104 if (BinOpcode) 11105 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11106 if (CmpOpcode) { 11107 // Signed comparisons of byte or halfword values must be sign-extended. 11108 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11109 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11110 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11111 ExtReg).addReg(dest); 11112 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11113 .addReg(incr).addReg(ExtReg); 11114 } else 11115 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11116 .addReg(incr).addReg(dest); 11117 11118 BuildMI(BB, dl, TII->get(PPC::BCC)) 11119 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11120 BB->addSuccessor(loop2MBB); 11121 BB->addSuccessor(exitMBB); 11122 BB = loop2MBB; 11123 } 11124 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11125 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11126 BuildMI(BB, dl, TII->get(PPC::BCC)) 11127 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11128 BB->addSuccessor(loopMBB); 11129 BB->addSuccessor(exitMBB); 11130 11131 // exitMBB: 11132 // ... 11133 BB = exitMBB; 11134 return BB; 11135 } 11136 11137 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11138 MachineInstr &MI, MachineBasicBlock *BB, 11139 bool is8bit, // operation 11140 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11141 // If we support part-word atomic mnemonics, just use them 11142 if (Subtarget.hasPartwordAtomics()) 11143 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11144 CmpPred); 11145 11146 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11147 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11148 // In 64 bit mode we have to use 64 bits for addresses, even though the 11149 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11150 // registers without caring whether they're 32 or 64, but here we're 11151 // doing actual arithmetic on the addresses. 11152 bool is64bit = Subtarget.isPPC64(); 11153 bool isLittleEndian = Subtarget.isLittleEndian(); 11154 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11155 11156 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11157 MachineFunction *F = BB->getParent(); 11158 MachineFunction::iterator It = ++BB->getIterator(); 11159 11160 Register dest = MI.getOperand(0).getReg(); 11161 Register ptrA = MI.getOperand(1).getReg(); 11162 Register ptrB = MI.getOperand(2).getReg(); 11163 Register incr = MI.getOperand(3).getReg(); 11164 DebugLoc dl = MI.getDebugLoc(); 11165 11166 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11167 MachineBasicBlock *loop2MBB = 11168 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11169 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11170 F->insert(It, loopMBB); 11171 if (CmpOpcode) 11172 F->insert(It, loop2MBB); 11173 F->insert(It, exitMBB); 11174 exitMBB->splice(exitMBB->begin(), BB, 11175 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11176 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11177 11178 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11179 const TargetRegisterClass *RC = 11180 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11181 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11182 11183 Register PtrReg = RegInfo.createVirtualRegister(RC); 11184 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11185 Register ShiftReg = 11186 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11187 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11188 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11189 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11190 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11191 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11192 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11193 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11194 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11195 Register Ptr1Reg; 11196 Register TmpReg = 11197 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11198 11199 // thisMBB: 11200 // ... 11201 // fallthrough --> loopMBB 11202 BB->addSuccessor(loopMBB); 11203 11204 // The 4-byte load must be aligned, while a char or short may be 11205 // anywhere in the word. Hence all this nasty bookkeeping code. 11206 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11207 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11208 // xori shift, shift1, 24 [16] 11209 // rlwinm ptr, ptr1, 0, 0, 29 11210 // slw incr2, incr, shift 11211 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11212 // slw mask, mask2, shift 11213 // loopMBB: 11214 // lwarx tmpDest, ptr 11215 // add tmp, tmpDest, incr2 11216 // andc tmp2, tmpDest, mask 11217 // and tmp3, tmp, mask 11218 // or tmp4, tmp3, tmp2 11219 // stwcx. tmp4, ptr 11220 // bne- loopMBB 11221 // fallthrough --> exitMBB 11222 // srw dest, tmpDest, shift 11223 if (ptrA != ZeroReg) { 11224 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11225 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11226 .addReg(ptrA) 11227 .addReg(ptrB); 11228 } else { 11229 Ptr1Reg = ptrB; 11230 } 11231 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11232 // mode. 11233 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11234 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11235 .addImm(3) 11236 .addImm(27) 11237 .addImm(is8bit ? 28 : 27); 11238 if (!isLittleEndian) 11239 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11240 .addReg(Shift1Reg) 11241 .addImm(is8bit ? 24 : 16); 11242 if (is64bit) 11243 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11244 .addReg(Ptr1Reg) 11245 .addImm(0) 11246 .addImm(61); 11247 else 11248 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11249 .addReg(Ptr1Reg) 11250 .addImm(0) 11251 .addImm(0) 11252 .addImm(29); 11253 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11254 if (is8bit) 11255 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11256 else { 11257 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11258 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11259 .addReg(Mask3Reg) 11260 .addImm(65535); 11261 } 11262 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11263 .addReg(Mask2Reg) 11264 .addReg(ShiftReg); 11265 11266 BB = loopMBB; 11267 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11268 .addReg(ZeroReg) 11269 .addReg(PtrReg); 11270 if (BinOpcode) 11271 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11272 .addReg(Incr2Reg) 11273 .addReg(TmpDestReg); 11274 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11275 .addReg(TmpDestReg) 11276 .addReg(MaskReg); 11277 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11278 if (CmpOpcode) { 11279 // For unsigned comparisons, we can directly compare the shifted values. 11280 // For signed comparisons we shift and sign extend. 11281 Register SReg = RegInfo.createVirtualRegister(GPRC); 11282 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11283 .addReg(TmpDestReg) 11284 .addReg(MaskReg); 11285 unsigned ValueReg = SReg; 11286 unsigned CmpReg = Incr2Reg; 11287 if (CmpOpcode == PPC::CMPW) { 11288 ValueReg = RegInfo.createVirtualRegister(GPRC); 11289 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11290 .addReg(SReg) 11291 .addReg(ShiftReg); 11292 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11293 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11294 .addReg(ValueReg); 11295 ValueReg = ValueSReg; 11296 CmpReg = incr; 11297 } 11298 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11299 .addReg(CmpReg) 11300 .addReg(ValueReg); 11301 BuildMI(BB, dl, TII->get(PPC::BCC)) 11302 .addImm(CmpPred) 11303 .addReg(PPC::CR0) 11304 .addMBB(exitMBB); 11305 BB->addSuccessor(loop2MBB); 11306 BB->addSuccessor(exitMBB); 11307 BB = loop2MBB; 11308 } 11309 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11310 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11311 .addReg(Tmp4Reg) 11312 .addReg(ZeroReg) 11313 .addReg(PtrReg); 11314 BuildMI(BB, dl, TII->get(PPC::BCC)) 11315 .addImm(PPC::PRED_NE) 11316 .addReg(PPC::CR0) 11317 .addMBB(loopMBB); 11318 BB->addSuccessor(loopMBB); 11319 BB->addSuccessor(exitMBB); 11320 11321 // exitMBB: 11322 // ... 11323 BB = exitMBB; 11324 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11325 .addReg(TmpDestReg) 11326 .addReg(ShiftReg); 11327 return BB; 11328 } 11329 11330 llvm::MachineBasicBlock * 11331 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11332 MachineBasicBlock *MBB) const { 11333 DebugLoc DL = MI.getDebugLoc(); 11334 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11335 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11336 11337 MachineFunction *MF = MBB->getParent(); 11338 MachineRegisterInfo &MRI = MF->getRegInfo(); 11339 11340 const BasicBlock *BB = MBB->getBasicBlock(); 11341 MachineFunction::iterator I = ++MBB->getIterator(); 11342 11343 Register DstReg = MI.getOperand(0).getReg(); 11344 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11345 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11346 Register mainDstReg = MRI.createVirtualRegister(RC); 11347 Register restoreDstReg = MRI.createVirtualRegister(RC); 11348 11349 MVT PVT = getPointerTy(MF->getDataLayout()); 11350 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11351 "Invalid Pointer Size!"); 11352 // For v = setjmp(buf), we generate 11353 // 11354 // thisMBB: 11355 // SjLjSetup mainMBB 11356 // bl mainMBB 11357 // v_restore = 1 11358 // b sinkMBB 11359 // 11360 // mainMBB: 11361 // buf[LabelOffset] = LR 11362 // v_main = 0 11363 // 11364 // sinkMBB: 11365 // v = phi(main, restore) 11366 // 11367 11368 MachineBasicBlock *thisMBB = MBB; 11369 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11370 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11371 MF->insert(I, mainMBB); 11372 MF->insert(I, sinkMBB); 11373 11374 MachineInstrBuilder MIB; 11375 11376 // Transfer the remainder of BB and its successor edges to sinkMBB. 11377 sinkMBB->splice(sinkMBB->begin(), MBB, 11378 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11379 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11380 11381 // Note that the structure of the jmp_buf used here is not compatible 11382 // with that used by libc, and is not designed to be. Specifically, it 11383 // stores only those 'reserved' registers that LLVM does not otherwise 11384 // understand how to spill. Also, by convention, by the time this 11385 // intrinsic is called, Clang has already stored the frame address in the 11386 // first slot of the buffer and stack address in the third. Following the 11387 // X86 target code, we'll store the jump address in the second slot. We also 11388 // need to save the TOC pointer (R2) to handle jumps between shared 11389 // libraries, and that will be stored in the fourth slot. The thread 11390 // identifier (R13) is not affected. 11391 11392 // thisMBB: 11393 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11394 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11395 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11396 11397 // Prepare IP either in reg. 11398 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11399 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11400 Register BufReg = MI.getOperand(1).getReg(); 11401 11402 if (Subtarget.is64BitELFABI()) { 11403 setUsesTOCBasePtr(*MBB->getParent()); 11404 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11405 .addReg(PPC::X2) 11406 .addImm(TOCOffset) 11407 .addReg(BufReg) 11408 .cloneMemRefs(MI); 11409 } 11410 11411 // Naked functions never have a base pointer, and so we use r1. For all 11412 // other functions, this decision must be delayed until during PEI. 11413 unsigned BaseReg; 11414 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11415 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11416 else 11417 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11418 11419 MIB = BuildMI(*thisMBB, MI, DL, 11420 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11421 .addReg(BaseReg) 11422 .addImm(BPOffset) 11423 .addReg(BufReg) 11424 .cloneMemRefs(MI); 11425 11426 // Setup 11427 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11428 MIB.addRegMask(TRI->getNoPreservedMask()); 11429 11430 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11431 11432 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11433 .addMBB(mainMBB); 11434 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11435 11436 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11437 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11438 11439 // mainMBB: 11440 // mainDstReg = 0 11441 MIB = 11442 BuildMI(mainMBB, DL, 11443 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11444 11445 // Store IP 11446 if (Subtarget.isPPC64()) { 11447 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11448 .addReg(LabelReg) 11449 .addImm(LabelOffset) 11450 .addReg(BufReg); 11451 } else { 11452 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11453 .addReg(LabelReg) 11454 .addImm(LabelOffset) 11455 .addReg(BufReg); 11456 } 11457 MIB.cloneMemRefs(MI); 11458 11459 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11460 mainMBB->addSuccessor(sinkMBB); 11461 11462 // sinkMBB: 11463 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11464 TII->get(PPC::PHI), DstReg) 11465 .addReg(mainDstReg).addMBB(mainMBB) 11466 .addReg(restoreDstReg).addMBB(thisMBB); 11467 11468 MI.eraseFromParent(); 11469 return sinkMBB; 11470 } 11471 11472 MachineBasicBlock * 11473 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11474 MachineBasicBlock *MBB) const { 11475 DebugLoc DL = MI.getDebugLoc(); 11476 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11477 11478 MachineFunction *MF = MBB->getParent(); 11479 MachineRegisterInfo &MRI = MF->getRegInfo(); 11480 11481 MVT PVT = getPointerTy(MF->getDataLayout()); 11482 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11483 "Invalid Pointer Size!"); 11484 11485 const TargetRegisterClass *RC = 11486 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11487 Register Tmp = MRI.createVirtualRegister(RC); 11488 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11489 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11490 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11491 unsigned BP = 11492 (PVT == MVT::i64) 11493 ? PPC::X30 11494 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11495 : PPC::R30); 11496 11497 MachineInstrBuilder MIB; 11498 11499 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11500 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11501 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11502 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11503 11504 Register BufReg = MI.getOperand(0).getReg(); 11505 11506 // Reload FP (the jumped-to function may not have had a 11507 // frame pointer, and if so, then its r31 will be restored 11508 // as necessary). 11509 if (PVT == MVT::i64) { 11510 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11511 .addImm(0) 11512 .addReg(BufReg); 11513 } else { 11514 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11515 .addImm(0) 11516 .addReg(BufReg); 11517 } 11518 MIB.cloneMemRefs(MI); 11519 11520 // Reload IP 11521 if (PVT == MVT::i64) { 11522 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11523 .addImm(LabelOffset) 11524 .addReg(BufReg); 11525 } else { 11526 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11527 .addImm(LabelOffset) 11528 .addReg(BufReg); 11529 } 11530 MIB.cloneMemRefs(MI); 11531 11532 // Reload SP 11533 if (PVT == MVT::i64) { 11534 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11535 .addImm(SPOffset) 11536 .addReg(BufReg); 11537 } else { 11538 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11539 .addImm(SPOffset) 11540 .addReg(BufReg); 11541 } 11542 MIB.cloneMemRefs(MI); 11543 11544 // Reload BP 11545 if (PVT == MVT::i64) { 11546 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11547 .addImm(BPOffset) 11548 .addReg(BufReg); 11549 } else { 11550 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11551 .addImm(BPOffset) 11552 .addReg(BufReg); 11553 } 11554 MIB.cloneMemRefs(MI); 11555 11556 // Reload TOC 11557 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11558 setUsesTOCBasePtr(*MBB->getParent()); 11559 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11560 .addImm(TOCOffset) 11561 .addReg(BufReg) 11562 .cloneMemRefs(MI); 11563 } 11564 11565 // Jump 11566 BuildMI(*MBB, MI, DL, 11567 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11568 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11569 11570 MI.eraseFromParent(); 11571 return MBB; 11572 } 11573 11574 MachineBasicBlock * 11575 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11576 MachineBasicBlock *BB) const { 11577 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11578 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11579 if (Subtarget.is64BitELFABI() && 11580 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11581 !Subtarget.isUsingPCRelativeCalls()) { 11582 // Call lowering should have added an r2 operand to indicate a dependence 11583 // on the TOC base pointer value. It can't however, because there is no 11584 // way to mark the dependence as implicit there, and so the stackmap code 11585 // will confuse it with a regular operand. Instead, add the dependence 11586 // here. 11587 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11588 } 11589 11590 return emitPatchPoint(MI, BB); 11591 } 11592 11593 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11594 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11595 return emitEHSjLjSetJmp(MI, BB); 11596 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11597 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11598 return emitEHSjLjLongJmp(MI, BB); 11599 } 11600 11601 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11602 11603 // To "insert" these instructions we actually have to insert their 11604 // control-flow patterns. 11605 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11606 MachineFunction::iterator It = ++BB->getIterator(); 11607 11608 MachineFunction *F = BB->getParent(); 11609 11610 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11611 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11612 MI.getOpcode() == PPC::SELECT_I8) { 11613 SmallVector<MachineOperand, 2> Cond; 11614 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11615 MI.getOpcode() == PPC::SELECT_CC_I8) 11616 Cond.push_back(MI.getOperand(4)); 11617 else 11618 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11619 Cond.push_back(MI.getOperand(1)); 11620 11621 DebugLoc dl = MI.getDebugLoc(); 11622 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11623 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11624 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11625 MI.getOpcode() == PPC::SELECT_CC_F8 || 11626 MI.getOpcode() == PPC::SELECT_CC_F16 || 11627 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11628 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11629 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11630 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11631 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11632 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11633 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11634 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11635 MI.getOpcode() == PPC::SELECT_CC_SPE || 11636 MI.getOpcode() == PPC::SELECT_F4 || 11637 MI.getOpcode() == PPC::SELECT_F8 || 11638 MI.getOpcode() == PPC::SELECT_F16 || 11639 MI.getOpcode() == PPC::SELECT_QFRC || 11640 MI.getOpcode() == PPC::SELECT_QSRC || 11641 MI.getOpcode() == PPC::SELECT_QBRC || 11642 MI.getOpcode() == PPC::SELECT_SPE || 11643 MI.getOpcode() == PPC::SELECT_SPE4 || 11644 MI.getOpcode() == PPC::SELECT_VRRC || 11645 MI.getOpcode() == PPC::SELECT_VSFRC || 11646 MI.getOpcode() == PPC::SELECT_VSSRC || 11647 MI.getOpcode() == PPC::SELECT_VSRC) { 11648 // The incoming instruction knows the destination vreg to set, the 11649 // condition code register to branch on, the true/false values to 11650 // select between, and a branch opcode to use. 11651 11652 // thisMBB: 11653 // ... 11654 // TrueVal = ... 11655 // cmpTY ccX, r1, r2 11656 // bCC copy1MBB 11657 // fallthrough --> copy0MBB 11658 MachineBasicBlock *thisMBB = BB; 11659 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11660 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11661 DebugLoc dl = MI.getDebugLoc(); 11662 F->insert(It, copy0MBB); 11663 F->insert(It, sinkMBB); 11664 11665 // Transfer the remainder of BB and its successor edges to sinkMBB. 11666 sinkMBB->splice(sinkMBB->begin(), BB, 11667 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11668 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11669 11670 // Next, add the true and fallthrough blocks as its successors. 11671 BB->addSuccessor(copy0MBB); 11672 BB->addSuccessor(sinkMBB); 11673 11674 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11675 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11676 MI.getOpcode() == PPC::SELECT_F16 || 11677 MI.getOpcode() == PPC::SELECT_SPE4 || 11678 MI.getOpcode() == PPC::SELECT_SPE || 11679 MI.getOpcode() == PPC::SELECT_QFRC || 11680 MI.getOpcode() == PPC::SELECT_QSRC || 11681 MI.getOpcode() == PPC::SELECT_QBRC || 11682 MI.getOpcode() == PPC::SELECT_VRRC || 11683 MI.getOpcode() == PPC::SELECT_VSFRC || 11684 MI.getOpcode() == PPC::SELECT_VSSRC || 11685 MI.getOpcode() == PPC::SELECT_VSRC) { 11686 BuildMI(BB, dl, TII->get(PPC::BC)) 11687 .addReg(MI.getOperand(1).getReg()) 11688 .addMBB(sinkMBB); 11689 } else { 11690 unsigned SelectPred = MI.getOperand(4).getImm(); 11691 BuildMI(BB, dl, TII->get(PPC::BCC)) 11692 .addImm(SelectPred) 11693 .addReg(MI.getOperand(1).getReg()) 11694 .addMBB(sinkMBB); 11695 } 11696 11697 // copy0MBB: 11698 // %FalseValue = ... 11699 // # fallthrough to sinkMBB 11700 BB = copy0MBB; 11701 11702 // Update machine-CFG edges 11703 BB->addSuccessor(sinkMBB); 11704 11705 // sinkMBB: 11706 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11707 // ... 11708 BB = sinkMBB; 11709 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11710 .addReg(MI.getOperand(3).getReg()) 11711 .addMBB(copy0MBB) 11712 .addReg(MI.getOperand(2).getReg()) 11713 .addMBB(thisMBB); 11714 } else if (MI.getOpcode() == PPC::ReadTB) { 11715 // To read the 64-bit time-base register on a 32-bit target, we read the 11716 // two halves. Should the counter have wrapped while it was being read, we 11717 // need to try again. 11718 // ... 11719 // readLoop: 11720 // mfspr Rx,TBU # load from TBU 11721 // mfspr Ry,TB # load from TB 11722 // mfspr Rz,TBU # load from TBU 11723 // cmpw crX,Rx,Rz # check if 'old'='new' 11724 // bne readLoop # branch if they're not equal 11725 // ... 11726 11727 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11728 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11729 DebugLoc dl = MI.getDebugLoc(); 11730 F->insert(It, readMBB); 11731 F->insert(It, sinkMBB); 11732 11733 // Transfer the remainder of BB and its successor edges to sinkMBB. 11734 sinkMBB->splice(sinkMBB->begin(), BB, 11735 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11736 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11737 11738 BB->addSuccessor(readMBB); 11739 BB = readMBB; 11740 11741 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11742 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11743 Register LoReg = MI.getOperand(0).getReg(); 11744 Register HiReg = MI.getOperand(1).getReg(); 11745 11746 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11747 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11748 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11749 11750 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11751 11752 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11753 .addReg(HiReg) 11754 .addReg(ReadAgainReg); 11755 BuildMI(BB, dl, TII->get(PPC::BCC)) 11756 .addImm(PPC::PRED_NE) 11757 .addReg(CmpReg) 11758 .addMBB(readMBB); 11759 11760 BB->addSuccessor(readMBB); 11761 BB->addSuccessor(sinkMBB); 11762 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11763 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11764 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11765 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11766 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11767 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11768 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11769 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11770 11771 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11772 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11773 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11774 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11775 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11776 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11777 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11778 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11779 11780 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11781 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11782 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11783 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11784 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11785 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11787 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11788 11789 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11790 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11791 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11792 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11793 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11794 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11796 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11797 11798 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11799 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11800 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11801 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11802 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11803 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11805 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11806 11807 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11808 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11809 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11810 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11811 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11812 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11814 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11815 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11817 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11819 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11821 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11822 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11823 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11824 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11826 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11828 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11830 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11831 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11832 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11833 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11835 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11837 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11839 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11840 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11841 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11842 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11844 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11846 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11848 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11849 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11850 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11851 11852 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11853 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11854 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11855 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11856 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11857 BB = EmitAtomicBinary(MI, BB, 4, 0); 11858 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11859 BB = EmitAtomicBinary(MI, BB, 8, 0); 11860 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11861 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11862 (Subtarget.hasPartwordAtomics() && 11863 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11864 (Subtarget.hasPartwordAtomics() && 11865 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11866 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11867 11868 auto LoadMnemonic = PPC::LDARX; 11869 auto StoreMnemonic = PPC::STDCX; 11870 switch (MI.getOpcode()) { 11871 default: 11872 llvm_unreachable("Compare and swap of unknown size"); 11873 case PPC::ATOMIC_CMP_SWAP_I8: 11874 LoadMnemonic = PPC::LBARX; 11875 StoreMnemonic = PPC::STBCX; 11876 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11877 break; 11878 case PPC::ATOMIC_CMP_SWAP_I16: 11879 LoadMnemonic = PPC::LHARX; 11880 StoreMnemonic = PPC::STHCX; 11881 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11882 break; 11883 case PPC::ATOMIC_CMP_SWAP_I32: 11884 LoadMnemonic = PPC::LWARX; 11885 StoreMnemonic = PPC::STWCX; 11886 break; 11887 case PPC::ATOMIC_CMP_SWAP_I64: 11888 LoadMnemonic = PPC::LDARX; 11889 StoreMnemonic = PPC::STDCX; 11890 break; 11891 } 11892 Register dest = MI.getOperand(0).getReg(); 11893 Register ptrA = MI.getOperand(1).getReg(); 11894 Register ptrB = MI.getOperand(2).getReg(); 11895 Register oldval = MI.getOperand(3).getReg(); 11896 Register newval = MI.getOperand(4).getReg(); 11897 DebugLoc dl = MI.getDebugLoc(); 11898 11899 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11900 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11901 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11902 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11903 F->insert(It, loop1MBB); 11904 F->insert(It, loop2MBB); 11905 F->insert(It, midMBB); 11906 F->insert(It, exitMBB); 11907 exitMBB->splice(exitMBB->begin(), BB, 11908 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11909 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11910 11911 // thisMBB: 11912 // ... 11913 // fallthrough --> loopMBB 11914 BB->addSuccessor(loop1MBB); 11915 11916 // loop1MBB: 11917 // l[bhwd]arx dest, ptr 11918 // cmp[wd] dest, oldval 11919 // bne- midMBB 11920 // loop2MBB: 11921 // st[bhwd]cx. newval, ptr 11922 // bne- loopMBB 11923 // b exitBB 11924 // midMBB: 11925 // st[bhwd]cx. dest, ptr 11926 // exitBB: 11927 BB = loop1MBB; 11928 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11929 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11930 .addReg(oldval) 11931 .addReg(dest); 11932 BuildMI(BB, dl, TII->get(PPC::BCC)) 11933 .addImm(PPC::PRED_NE) 11934 .addReg(PPC::CR0) 11935 .addMBB(midMBB); 11936 BB->addSuccessor(loop2MBB); 11937 BB->addSuccessor(midMBB); 11938 11939 BB = loop2MBB; 11940 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11941 .addReg(newval) 11942 .addReg(ptrA) 11943 .addReg(ptrB); 11944 BuildMI(BB, dl, TII->get(PPC::BCC)) 11945 .addImm(PPC::PRED_NE) 11946 .addReg(PPC::CR0) 11947 .addMBB(loop1MBB); 11948 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11949 BB->addSuccessor(loop1MBB); 11950 BB->addSuccessor(exitMBB); 11951 11952 BB = midMBB; 11953 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11954 .addReg(dest) 11955 .addReg(ptrA) 11956 .addReg(ptrB); 11957 BB->addSuccessor(exitMBB); 11958 11959 // exitMBB: 11960 // ... 11961 BB = exitMBB; 11962 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11963 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11964 // We must use 64-bit registers for addresses when targeting 64-bit, 11965 // since we're actually doing arithmetic on them. Other registers 11966 // can be 32-bit. 11967 bool is64bit = Subtarget.isPPC64(); 11968 bool isLittleEndian = Subtarget.isLittleEndian(); 11969 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11970 11971 Register dest = MI.getOperand(0).getReg(); 11972 Register ptrA = MI.getOperand(1).getReg(); 11973 Register ptrB = MI.getOperand(2).getReg(); 11974 Register oldval = MI.getOperand(3).getReg(); 11975 Register newval = MI.getOperand(4).getReg(); 11976 DebugLoc dl = MI.getDebugLoc(); 11977 11978 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11979 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11980 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11981 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11982 F->insert(It, loop1MBB); 11983 F->insert(It, loop2MBB); 11984 F->insert(It, midMBB); 11985 F->insert(It, exitMBB); 11986 exitMBB->splice(exitMBB->begin(), BB, 11987 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11988 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11989 11990 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11991 const TargetRegisterClass *RC = 11992 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11993 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11994 11995 Register PtrReg = RegInfo.createVirtualRegister(RC); 11996 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11997 Register ShiftReg = 11998 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11999 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12000 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12001 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12002 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12003 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12004 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12005 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12006 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12007 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12008 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12009 Register Ptr1Reg; 12010 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12011 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12012 // thisMBB: 12013 // ... 12014 // fallthrough --> loopMBB 12015 BB->addSuccessor(loop1MBB); 12016 12017 // The 4-byte load must be aligned, while a char or short may be 12018 // anywhere in the word. Hence all this nasty bookkeeping code. 12019 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12020 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12021 // xori shift, shift1, 24 [16] 12022 // rlwinm ptr, ptr1, 0, 0, 29 12023 // slw newval2, newval, shift 12024 // slw oldval2, oldval,shift 12025 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12026 // slw mask, mask2, shift 12027 // and newval3, newval2, mask 12028 // and oldval3, oldval2, mask 12029 // loop1MBB: 12030 // lwarx tmpDest, ptr 12031 // and tmp, tmpDest, mask 12032 // cmpw tmp, oldval3 12033 // bne- midMBB 12034 // loop2MBB: 12035 // andc tmp2, tmpDest, mask 12036 // or tmp4, tmp2, newval3 12037 // stwcx. tmp4, ptr 12038 // bne- loop1MBB 12039 // b exitBB 12040 // midMBB: 12041 // stwcx. tmpDest, ptr 12042 // exitBB: 12043 // srw dest, tmpDest, shift 12044 if (ptrA != ZeroReg) { 12045 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12046 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12047 .addReg(ptrA) 12048 .addReg(ptrB); 12049 } else { 12050 Ptr1Reg = ptrB; 12051 } 12052 12053 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12054 // mode. 12055 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12056 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12057 .addImm(3) 12058 .addImm(27) 12059 .addImm(is8bit ? 28 : 27); 12060 if (!isLittleEndian) 12061 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12062 .addReg(Shift1Reg) 12063 .addImm(is8bit ? 24 : 16); 12064 if (is64bit) 12065 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12066 .addReg(Ptr1Reg) 12067 .addImm(0) 12068 .addImm(61); 12069 else 12070 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12071 .addReg(Ptr1Reg) 12072 .addImm(0) 12073 .addImm(0) 12074 .addImm(29); 12075 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12076 .addReg(newval) 12077 .addReg(ShiftReg); 12078 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12079 .addReg(oldval) 12080 .addReg(ShiftReg); 12081 if (is8bit) 12082 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12083 else { 12084 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12085 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12086 .addReg(Mask3Reg) 12087 .addImm(65535); 12088 } 12089 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12090 .addReg(Mask2Reg) 12091 .addReg(ShiftReg); 12092 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12093 .addReg(NewVal2Reg) 12094 .addReg(MaskReg); 12095 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12096 .addReg(OldVal2Reg) 12097 .addReg(MaskReg); 12098 12099 BB = loop1MBB; 12100 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12101 .addReg(ZeroReg) 12102 .addReg(PtrReg); 12103 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12104 .addReg(TmpDestReg) 12105 .addReg(MaskReg); 12106 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12107 .addReg(TmpReg) 12108 .addReg(OldVal3Reg); 12109 BuildMI(BB, dl, TII->get(PPC::BCC)) 12110 .addImm(PPC::PRED_NE) 12111 .addReg(PPC::CR0) 12112 .addMBB(midMBB); 12113 BB->addSuccessor(loop2MBB); 12114 BB->addSuccessor(midMBB); 12115 12116 BB = loop2MBB; 12117 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12118 .addReg(TmpDestReg) 12119 .addReg(MaskReg); 12120 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12121 .addReg(Tmp2Reg) 12122 .addReg(NewVal3Reg); 12123 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12124 .addReg(Tmp4Reg) 12125 .addReg(ZeroReg) 12126 .addReg(PtrReg); 12127 BuildMI(BB, dl, TII->get(PPC::BCC)) 12128 .addImm(PPC::PRED_NE) 12129 .addReg(PPC::CR0) 12130 .addMBB(loop1MBB); 12131 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12132 BB->addSuccessor(loop1MBB); 12133 BB->addSuccessor(exitMBB); 12134 12135 BB = midMBB; 12136 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12137 .addReg(TmpDestReg) 12138 .addReg(ZeroReg) 12139 .addReg(PtrReg); 12140 BB->addSuccessor(exitMBB); 12141 12142 // exitMBB: 12143 // ... 12144 BB = exitMBB; 12145 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12146 .addReg(TmpReg) 12147 .addReg(ShiftReg); 12148 } else if (MI.getOpcode() == PPC::FADDrtz) { 12149 // This pseudo performs an FADD with rounding mode temporarily forced 12150 // to round-to-zero. We emit this via custom inserter since the FPSCR 12151 // is not modeled at the SelectionDAG level. 12152 Register Dest = MI.getOperand(0).getReg(); 12153 Register Src1 = MI.getOperand(1).getReg(); 12154 Register Src2 = MI.getOperand(2).getReg(); 12155 DebugLoc dl = MI.getDebugLoc(); 12156 12157 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12158 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12159 12160 // Save FPSCR value. 12161 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12162 12163 // Set rounding mode to round-to-zero. 12164 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12165 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12166 12167 // Perform addition. 12168 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12169 12170 // Restore FPSCR value. 12171 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12172 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12173 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12174 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12175 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12176 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12177 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12178 ? PPC::ANDI8_rec 12179 : PPC::ANDI_rec; 12180 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12181 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12182 12183 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12184 Register Dest = RegInfo.createVirtualRegister( 12185 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12186 12187 DebugLoc Dl = MI.getDebugLoc(); 12188 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12189 .addReg(MI.getOperand(1).getReg()) 12190 .addImm(1); 12191 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12192 MI.getOperand(0).getReg()) 12193 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12194 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12195 DebugLoc Dl = MI.getDebugLoc(); 12196 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12197 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12198 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12199 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12200 MI.getOperand(0).getReg()) 12201 .addReg(CRReg); 12202 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12203 DebugLoc Dl = MI.getDebugLoc(); 12204 unsigned Imm = MI.getOperand(1).getImm(); 12205 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12206 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12207 MI.getOperand(0).getReg()) 12208 .addReg(PPC::CR0EQ); 12209 } else if (MI.getOpcode() == PPC::SETRNDi) { 12210 DebugLoc dl = MI.getDebugLoc(); 12211 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12212 12213 // Save FPSCR value. 12214 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12215 12216 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12217 // the following settings: 12218 // 00 Round to nearest 12219 // 01 Round to 0 12220 // 10 Round to +inf 12221 // 11 Round to -inf 12222 12223 // When the operand is immediate, using the two least significant bits of 12224 // the immediate to set the bits 62:63 of FPSCR. 12225 unsigned Mode = MI.getOperand(1).getImm(); 12226 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12227 .addImm(31); 12228 12229 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12230 .addImm(30); 12231 } else if (MI.getOpcode() == PPC::SETRND) { 12232 DebugLoc dl = MI.getDebugLoc(); 12233 12234 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12235 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12236 // If the target doesn't have DirectMove, we should use stack to do the 12237 // conversion, because the target doesn't have the instructions like mtvsrd 12238 // or mfvsrd to do this conversion directly. 12239 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12240 if (Subtarget.hasDirectMove()) { 12241 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12242 .addReg(SrcReg); 12243 } else { 12244 // Use stack to do the register copy. 12245 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12246 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12247 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12248 if (RC == &PPC::F8RCRegClass) { 12249 // Copy register from F8RCRegClass to G8RCRegclass. 12250 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12251 "Unsupported RegClass."); 12252 12253 StoreOp = PPC::STFD; 12254 LoadOp = PPC::LD; 12255 } else { 12256 // Copy register from G8RCRegClass to F8RCRegclass. 12257 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12258 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12259 "Unsupported RegClass."); 12260 } 12261 12262 MachineFrameInfo &MFI = F->getFrameInfo(); 12263 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12264 12265 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12266 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12267 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12268 MFI.getObjectAlign(FrameIdx)); 12269 12270 // Store the SrcReg into the stack. 12271 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12272 .addReg(SrcReg) 12273 .addImm(0) 12274 .addFrameIndex(FrameIdx) 12275 .addMemOperand(MMOStore); 12276 12277 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12278 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12279 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12280 MFI.getObjectAlign(FrameIdx)); 12281 12282 // Load from the stack where SrcReg is stored, and save to DestReg, 12283 // so we have done the RegClass conversion from RegClass::SrcReg to 12284 // RegClass::DestReg. 12285 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12286 .addImm(0) 12287 .addFrameIndex(FrameIdx) 12288 .addMemOperand(MMOLoad); 12289 } 12290 }; 12291 12292 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12293 12294 // Save FPSCR value. 12295 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12296 12297 // When the operand is gprc register, use two least significant bits of the 12298 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12299 // 12300 // copy OldFPSCRTmpReg, OldFPSCRReg 12301 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12302 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12303 // copy NewFPSCRReg, NewFPSCRTmpReg 12304 // mtfsf 255, NewFPSCRReg 12305 MachineOperand SrcOp = MI.getOperand(1); 12306 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12307 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12308 12309 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12310 12311 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12312 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12313 12314 // The first operand of INSERT_SUBREG should be a register which has 12315 // subregisters, we only care about its RegClass, so we should use an 12316 // IMPLICIT_DEF register. 12317 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12318 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12319 .addReg(ImDefReg) 12320 .add(SrcOp) 12321 .addImm(1); 12322 12323 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12324 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12325 .addReg(OldFPSCRTmpReg) 12326 .addReg(ExtSrcReg) 12327 .addImm(0) 12328 .addImm(62); 12329 12330 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12331 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12332 12333 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12334 // bits of FPSCR. 12335 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12336 .addImm(255) 12337 .addReg(NewFPSCRReg) 12338 .addImm(0) 12339 .addImm(0); 12340 } else { 12341 llvm_unreachable("Unexpected instr type to insert"); 12342 } 12343 12344 MI.eraseFromParent(); // The pseudo instruction is gone now. 12345 return BB; 12346 } 12347 12348 //===----------------------------------------------------------------------===// 12349 // Target Optimization Hooks 12350 //===----------------------------------------------------------------------===// 12351 12352 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12353 // For the estimates, convergence is quadratic, so we essentially double the 12354 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12355 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12356 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12357 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12358 if (VT.getScalarType() == MVT::f64) 12359 RefinementSteps++; 12360 return RefinementSteps; 12361 } 12362 12363 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12364 int Enabled, int &RefinementSteps, 12365 bool &UseOneConstNR, 12366 bool Reciprocal) const { 12367 EVT VT = Operand.getValueType(); 12368 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12369 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12370 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12371 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12372 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12373 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12374 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12375 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12376 12377 // The Newton-Raphson computation with a single constant does not provide 12378 // enough accuracy on some CPUs. 12379 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12380 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12381 } 12382 return SDValue(); 12383 } 12384 12385 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12386 int Enabled, 12387 int &RefinementSteps) const { 12388 EVT VT = Operand.getValueType(); 12389 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12390 (VT == MVT::f64 && Subtarget.hasFRE()) || 12391 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12392 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12393 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12394 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12395 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12396 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12397 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12398 } 12399 return SDValue(); 12400 } 12401 12402 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12403 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12404 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12405 // enabled for division), this functionality is redundant with the default 12406 // combiner logic (once the division -> reciprocal/multiply transformation 12407 // has taken place). As a result, this matters more for older cores than for 12408 // newer ones. 12409 12410 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12411 // reciprocal if there are two or more FDIVs (for embedded cores with only 12412 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12413 switch (Subtarget.getCPUDirective()) { 12414 default: 12415 return 3; 12416 case PPC::DIR_440: 12417 case PPC::DIR_A2: 12418 case PPC::DIR_E500: 12419 case PPC::DIR_E500mc: 12420 case PPC::DIR_E5500: 12421 return 2; 12422 } 12423 } 12424 12425 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12426 // collapsed, and so we need to look through chains of them. 12427 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12428 int64_t& Offset, SelectionDAG &DAG) { 12429 if (DAG.isBaseWithConstantOffset(Loc)) { 12430 Base = Loc.getOperand(0); 12431 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12432 12433 // The base might itself be a base plus an offset, and if so, accumulate 12434 // that as well. 12435 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12436 } 12437 } 12438 12439 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12440 unsigned Bytes, int Dist, 12441 SelectionDAG &DAG) { 12442 if (VT.getSizeInBits() / 8 != Bytes) 12443 return false; 12444 12445 SDValue BaseLoc = Base->getBasePtr(); 12446 if (Loc.getOpcode() == ISD::FrameIndex) { 12447 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12448 return false; 12449 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12450 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12451 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12452 int FS = MFI.getObjectSize(FI); 12453 int BFS = MFI.getObjectSize(BFI); 12454 if (FS != BFS || FS != (int)Bytes) return false; 12455 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12456 } 12457 12458 SDValue Base1 = Loc, Base2 = BaseLoc; 12459 int64_t Offset1 = 0, Offset2 = 0; 12460 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12461 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12462 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12463 return true; 12464 12465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12466 const GlobalValue *GV1 = nullptr; 12467 const GlobalValue *GV2 = nullptr; 12468 Offset1 = 0; 12469 Offset2 = 0; 12470 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12471 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12472 if (isGA1 && isGA2 && GV1 == GV2) 12473 return Offset1 == (Offset2 + Dist*Bytes); 12474 return false; 12475 } 12476 12477 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12478 // not enforce equality of the chain operands. 12479 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12480 unsigned Bytes, int Dist, 12481 SelectionDAG &DAG) { 12482 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12483 EVT VT = LS->getMemoryVT(); 12484 SDValue Loc = LS->getBasePtr(); 12485 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12486 } 12487 12488 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12489 EVT VT; 12490 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12491 default: return false; 12492 case Intrinsic::ppc_qpx_qvlfd: 12493 case Intrinsic::ppc_qpx_qvlfda: 12494 VT = MVT::v4f64; 12495 break; 12496 case Intrinsic::ppc_qpx_qvlfs: 12497 case Intrinsic::ppc_qpx_qvlfsa: 12498 VT = MVT::v4f32; 12499 break; 12500 case Intrinsic::ppc_qpx_qvlfcd: 12501 case Intrinsic::ppc_qpx_qvlfcda: 12502 VT = MVT::v2f64; 12503 break; 12504 case Intrinsic::ppc_qpx_qvlfcs: 12505 case Intrinsic::ppc_qpx_qvlfcsa: 12506 VT = MVT::v2f32; 12507 break; 12508 case Intrinsic::ppc_qpx_qvlfiwa: 12509 case Intrinsic::ppc_qpx_qvlfiwz: 12510 case Intrinsic::ppc_altivec_lvx: 12511 case Intrinsic::ppc_altivec_lvxl: 12512 case Intrinsic::ppc_vsx_lxvw4x: 12513 case Intrinsic::ppc_vsx_lxvw4x_be: 12514 VT = MVT::v4i32; 12515 break; 12516 case Intrinsic::ppc_vsx_lxvd2x: 12517 case Intrinsic::ppc_vsx_lxvd2x_be: 12518 VT = MVT::v2f64; 12519 break; 12520 case Intrinsic::ppc_altivec_lvebx: 12521 VT = MVT::i8; 12522 break; 12523 case Intrinsic::ppc_altivec_lvehx: 12524 VT = MVT::i16; 12525 break; 12526 case Intrinsic::ppc_altivec_lvewx: 12527 VT = MVT::i32; 12528 break; 12529 } 12530 12531 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12532 } 12533 12534 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12535 EVT VT; 12536 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12537 default: return false; 12538 case Intrinsic::ppc_qpx_qvstfd: 12539 case Intrinsic::ppc_qpx_qvstfda: 12540 VT = MVT::v4f64; 12541 break; 12542 case Intrinsic::ppc_qpx_qvstfs: 12543 case Intrinsic::ppc_qpx_qvstfsa: 12544 VT = MVT::v4f32; 12545 break; 12546 case Intrinsic::ppc_qpx_qvstfcd: 12547 case Intrinsic::ppc_qpx_qvstfcda: 12548 VT = MVT::v2f64; 12549 break; 12550 case Intrinsic::ppc_qpx_qvstfcs: 12551 case Intrinsic::ppc_qpx_qvstfcsa: 12552 VT = MVT::v2f32; 12553 break; 12554 case Intrinsic::ppc_qpx_qvstfiw: 12555 case Intrinsic::ppc_qpx_qvstfiwa: 12556 case Intrinsic::ppc_altivec_stvx: 12557 case Intrinsic::ppc_altivec_stvxl: 12558 case Intrinsic::ppc_vsx_stxvw4x: 12559 VT = MVT::v4i32; 12560 break; 12561 case Intrinsic::ppc_vsx_stxvd2x: 12562 VT = MVT::v2f64; 12563 break; 12564 case Intrinsic::ppc_vsx_stxvw4x_be: 12565 VT = MVT::v4i32; 12566 break; 12567 case Intrinsic::ppc_vsx_stxvd2x_be: 12568 VT = MVT::v2f64; 12569 break; 12570 case Intrinsic::ppc_altivec_stvebx: 12571 VT = MVT::i8; 12572 break; 12573 case Intrinsic::ppc_altivec_stvehx: 12574 VT = MVT::i16; 12575 break; 12576 case Intrinsic::ppc_altivec_stvewx: 12577 VT = MVT::i32; 12578 break; 12579 } 12580 12581 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12582 } 12583 12584 return false; 12585 } 12586 12587 // Return true is there is a nearyby consecutive load to the one provided 12588 // (regardless of alignment). We search up and down the chain, looking though 12589 // token factors and other loads (but nothing else). As a result, a true result 12590 // indicates that it is safe to create a new consecutive load adjacent to the 12591 // load provided. 12592 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12593 SDValue Chain = LD->getChain(); 12594 EVT VT = LD->getMemoryVT(); 12595 12596 SmallSet<SDNode *, 16> LoadRoots; 12597 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12598 SmallSet<SDNode *, 16> Visited; 12599 12600 // First, search up the chain, branching to follow all token-factor operands. 12601 // If we find a consecutive load, then we're done, otherwise, record all 12602 // nodes just above the top-level loads and token factors. 12603 while (!Queue.empty()) { 12604 SDNode *ChainNext = Queue.pop_back_val(); 12605 if (!Visited.insert(ChainNext).second) 12606 continue; 12607 12608 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12609 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12610 return true; 12611 12612 if (!Visited.count(ChainLD->getChain().getNode())) 12613 Queue.push_back(ChainLD->getChain().getNode()); 12614 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12615 for (const SDUse &O : ChainNext->ops()) 12616 if (!Visited.count(O.getNode())) 12617 Queue.push_back(O.getNode()); 12618 } else 12619 LoadRoots.insert(ChainNext); 12620 } 12621 12622 // Second, search down the chain, starting from the top-level nodes recorded 12623 // in the first phase. These top-level nodes are the nodes just above all 12624 // loads and token factors. Starting with their uses, recursively look though 12625 // all loads (just the chain uses) and token factors to find a consecutive 12626 // load. 12627 Visited.clear(); 12628 Queue.clear(); 12629 12630 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12631 IE = LoadRoots.end(); I != IE; ++I) { 12632 Queue.push_back(*I); 12633 12634 while (!Queue.empty()) { 12635 SDNode *LoadRoot = Queue.pop_back_val(); 12636 if (!Visited.insert(LoadRoot).second) 12637 continue; 12638 12639 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12640 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12641 return true; 12642 12643 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12644 UE = LoadRoot->use_end(); UI != UE; ++UI) 12645 if (((isa<MemSDNode>(*UI) && 12646 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12647 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12648 Queue.push_back(*UI); 12649 } 12650 } 12651 12652 return false; 12653 } 12654 12655 /// This function is called when we have proved that a SETCC node can be replaced 12656 /// by subtraction (and other supporting instructions) so that the result of 12657 /// comparison is kept in a GPR instead of CR. This function is purely for 12658 /// codegen purposes and has some flags to guide the codegen process. 12659 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12660 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12661 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12662 12663 // Zero extend the operands to the largest legal integer. Originally, they 12664 // must be of a strictly smaller size. 12665 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12666 DAG.getConstant(Size, DL, MVT::i32)); 12667 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12668 DAG.getConstant(Size, DL, MVT::i32)); 12669 12670 // Swap if needed. Depends on the condition code. 12671 if (Swap) 12672 std::swap(Op0, Op1); 12673 12674 // Subtract extended integers. 12675 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12676 12677 // Move the sign bit to the least significant position and zero out the rest. 12678 // Now the least significant bit carries the result of original comparison. 12679 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12680 DAG.getConstant(Size - 1, DL, MVT::i32)); 12681 auto Final = Shifted; 12682 12683 // Complement the result if needed. Based on the condition code. 12684 if (Complement) 12685 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12686 DAG.getConstant(1, DL, MVT::i64)); 12687 12688 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12689 } 12690 12691 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12692 DAGCombinerInfo &DCI) const { 12693 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12694 12695 SelectionDAG &DAG = DCI.DAG; 12696 SDLoc DL(N); 12697 12698 // Size of integers being compared has a critical role in the following 12699 // analysis, so we prefer to do this when all types are legal. 12700 if (!DCI.isAfterLegalizeDAG()) 12701 return SDValue(); 12702 12703 // If all users of SETCC extend its value to a legal integer type 12704 // then we replace SETCC with a subtraction 12705 for (SDNode::use_iterator UI = N->use_begin(), 12706 UE = N->use_end(); UI != UE; ++UI) { 12707 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12708 return SDValue(); 12709 } 12710 12711 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12712 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12713 12714 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12715 12716 if (OpSize < Size) { 12717 switch (CC) { 12718 default: break; 12719 case ISD::SETULT: 12720 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12721 case ISD::SETULE: 12722 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12723 case ISD::SETUGT: 12724 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12725 case ISD::SETUGE: 12726 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12727 } 12728 } 12729 12730 return SDValue(); 12731 } 12732 12733 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12734 DAGCombinerInfo &DCI) const { 12735 SelectionDAG &DAG = DCI.DAG; 12736 SDLoc dl(N); 12737 12738 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12739 // If we're tracking CR bits, we need to be careful that we don't have: 12740 // trunc(binary-ops(zext(x), zext(y))) 12741 // or 12742 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12743 // such that we're unnecessarily moving things into GPRs when it would be 12744 // better to keep them in CR bits. 12745 12746 // Note that trunc here can be an actual i1 trunc, or can be the effective 12747 // truncation that comes from a setcc or select_cc. 12748 if (N->getOpcode() == ISD::TRUNCATE && 12749 N->getValueType(0) != MVT::i1) 12750 return SDValue(); 12751 12752 if (N->getOperand(0).getValueType() != MVT::i32 && 12753 N->getOperand(0).getValueType() != MVT::i64) 12754 return SDValue(); 12755 12756 if (N->getOpcode() == ISD::SETCC || 12757 N->getOpcode() == ISD::SELECT_CC) { 12758 // If we're looking at a comparison, then we need to make sure that the 12759 // high bits (all except for the first) don't matter the result. 12760 ISD::CondCode CC = 12761 cast<CondCodeSDNode>(N->getOperand( 12762 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12763 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12764 12765 if (ISD::isSignedIntSetCC(CC)) { 12766 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12767 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12768 return SDValue(); 12769 } else if (ISD::isUnsignedIntSetCC(CC)) { 12770 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12771 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12772 !DAG.MaskedValueIsZero(N->getOperand(1), 12773 APInt::getHighBitsSet(OpBits, OpBits-1))) 12774 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12775 : SDValue()); 12776 } else { 12777 // This is neither a signed nor an unsigned comparison, just make sure 12778 // that the high bits are equal. 12779 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12780 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12781 12782 // We don't really care about what is known about the first bit (if 12783 // anything), so clear it in all masks prior to comparing them. 12784 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12785 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12786 12787 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12788 return SDValue(); 12789 } 12790 } 12791 12792 // We now know that the higher-order bits are irrelevant, we just need to 12793 // make sure that all of the intermediate operations are bit operations, and 12794 // all inputs are extensions. 12795 if (N->getOperand(0).getOpcode() != ISD::AND && 12796 N->getOperand(0).getOpcode() != ISD::OR && 12797 N->getOperand(0).getOpcode() != ISD::XOR && 12798 N->getOperand(0).getOpcode() != ISD::SELECT && 12799 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12800 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12801 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12802 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12803 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12804 return SDValue(); 12805 12806 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12807 N->getOperand(1).getOpcode() != ISD::AND && 12808 N->getOperand(1).getOpcode() != ISD::OR && 12809 N->getOperand(1).getOpcode() != ISD::XOR && 12810 N->getOperand(1).getOpcode() != ISD::SELECT && 12811 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12812 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12813 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12814 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12815 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12816 return SDValue(); 12817 12818 SmallVector<SDValue, 4> Inputs; 12819 SmallVector<SDValue, 8> BinOps, PromOps; 12820 SmallPtrSet<SDNode *, 16> Visited; 12821 12822 for (unsigned i = 0; i < 2; ++i) { 12823 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12824 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12825 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12826 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12827 isa<ConstantSDNode>(N->getOperand(i))) 12828 Inputs.push_back(N->getOperand(i)); 12829 else 12830 BinOps.push_back(N->getOperand(i)); 12831 12832 if (N->getOpcode() == ISD::TRUNCATE) 12833 break; 12834 } 12835 12836 // Visit all inputs, collect all binary operations (and, or, xor and 12837 // select) that are all fed by extensions. 12838 while (!BinOps.empty()) { 12839 SDValue BinOp = BinOps.back(); 12840 BinOps.pop_back(); 12841 12842 if (!Visited.insert(BinOp.getNode()).second) 12843 continue; 12844 12845 PromOps.push_back(BinOp); 12846 12847 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12848 // The condition of the select is not promoted. 12849 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12850 continue; 12851 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12852 continue; 12853 12854 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12855 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12856 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12857 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12858 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12859 Inputs.push_back(BinOp.getOperand(i)); 12860 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12861 BinOp.getOperand(i).getOpcode() == ISD::OR || 12862 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12863 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12864 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12865 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12866 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12867 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12868 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12869 BinOps.push_back(BinOp.getOperand(i)); 12870 } else { 12871 // We have an input that is not an extension or another binary 12872 // operation; we'll abort this transformation. 12873 return SDValue(); 12874 } 12875 } 12876 } 12877 12878 // Make sure that this is a self-contained cluster of operations (which 12879 // is not quite the same thing as saying that everything has only one 12880 // use). 12881 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12882 if (isa<ConstantSDNode>(Inputs[i])) 12883 continue; 12884 12885 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12886 UE = Inputs[i].getNode()->use_end(); 12887 UI != UE; ++UI) { 12888 SDNode *User = *UI; 12889 if (User != N && !Visited.count(User)) 12890 return SDValue(); 12891 12892 // Make sure that we're not going to promote the non-output-value 12893 // operand(s) or SELECT or SELECT_CC. 12894 // FIXME: Although we could sometimes handle this, and it does occur in 12895 // practice that one of the condition inputs to the select is also one of 12896 // the outputs, we currently can't deal with this. 12897 if (User->getOpcode() == ISD::SELECT) { 12898 if (User->getOperand(0) == Inputs[i]) 12899 return SDValue(); 12900 } else if (User->getOpcode() == ISD::SELECT_CC) { 12901 if (User->getOperand(0) == Inputs[i] || 12902 User->getOperand(1) == Inputs[i]) 12903 return SDValue(); 12904 } 12905 } 12906 } 12907 12908 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12909 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12910 UE = PromOps[i].getNode()->use_end(); 12911 UI != UE; ++UI) { 12912 SDNode *User = *UI; 12913 if (User != N && !Visited.count(User)) 12914 return SDValue(); 12915 12916 // Make sure that we're not going to promote the non-output-value 12917 // operand(s) or SELECT or SELECT_CC. 12918 // FIXME: Although we could sometimes handle this, and it does occur in 12919 // practice that one of the condition inputs to the select is also one of 12920 // the outputs, we currently can't deal with this. 12921 if (User->getOpcode() == ISD::SELECT) { 12922 if (User->getOperand(0) == PromOps[i]) 12923 return SDValue(); 12924 } else if (User->getOpcode() == ISD::SELECT_CC) { 12925 if (User->getOperand(0) == PromOps[i] || 12926 User->getOperand(1) == PromOps[i]) 12927 return SDValue(); 12928 } 12929 } 12930 } 12931 12932 // Replace all inputs with the extension operand. 12933 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12934 // Constants may have users outside the cluster of to-be-promoted nodes, 12935 // and so we need to replace those as we do the promotions. 12936 if (isa<ConstantSDNode>(Inputs[i])) 12937 continue; 12938 else 12939 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12940 } 12941 12942 std::list<HandleSDNode> PromOpHandles; 12943 for (auto &PromOp : PromOps) 12944 PromOpHandles.emplace_back(PromOp); 12945 12946 // Replace all operations (these are all the same, but have a different 12947 // (i1) return type). DAG.getNode will validate that the types of 12948 // a binary operator match, so go through the list in reverse so that 12949 // we've likely promoted both operands first. Any intermediate truncations or 12950 // extensions disappear. 12951 while (!PromOpHandles.empty()) { 12952 SDValue PromOp = PromOpHandles.back().getValue(); 12953 PromOpHandles.pop_back(); 12954 12955 if (PromOp.getOpcode() == ISD::TRUNCATE || 12956 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12957 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12958 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12959 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12960 PromOp.getOperand(0).getValueType() != MVT::i1) { 12961 // The operand is not yet ready (see comment below). 12962 PromOpHandles.emplace_front(PromOp); 12963 continue; 12964 } 12965 12966 SDValue RepValue = PromOp.getOperand(0); 12967 if (isa<ConstantSDNode>(RepValue)) 12968 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12969 12970 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12971 continue; 12972 } 12973 12974 unsigned C; 12975 switch (PromOp.getOpcode()) { 12976 default: C = 0; break; 12977 case ISD::SELECT: C = 1; break; 12978 case ISD::SELECT_CC: C = 2; break; 12979 } 12980 12981 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12982 PromOp.getOperand(C).getValueType() != MVT::i1) || 12983 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12984 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12985 // The to-be-promoted operands of this node have not yet been 12986 // promoted (this should be rare because we're going through the 12987 // list backward, but if one of the operands has several users in 12988 // this cluster of to-be-promoted nodes, it is possible). 12989 PromOpHandles.emplace_front(PromOp); 12990 continue; 12991 } 12992 12993 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12994 PromOp.getNode()->op_end()); 12995 12996 // If there are any constant inputs, make sure they're replaced now. 12997 for (unsigned i = 0; i < 2; ++i) 12998 if (isa<ConstantSDNode>(Ops[C+i])) 12999 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13000 13001 DAG.ReplaceAllUsesOfValueWith(PromOp, 13002 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13003 } 13004 13005 // Now we're left with the initial truncation itself. 13006 if (N->getOpcode() == ISD::TRUNCATE) 13007 return N->getOperand(0); 13008 13009 // Otherwise, this is a comparison. The operands to be compared have just 13010 // changed type (to i1), but everything else is the same. 13011 return SDValue(N, 0); 13012 } 13013 13014 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13015 DAGCombinerInfo &DCI) const { 13016 SelectionDAG &DAG = DCI.DAG; 13017 SDLoc dl(N); 13018 13019 // If we're tracking CR bits, we need to be careful that we don't have: 13020 // zext(binary-ops(trunc(x), trunc(y))) 13021 // or 13022 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13023 // such that we're unnecessarily moving things into CR bits that can more 13024 // efficiently stay in GPRs. Note that if we're not certain that the high 13025 // bits are set as required by the final extension, we still may need to do 13026 // some masking to get the proper behavior. 13027 13028 // This same functionality is important on PPC64 when dealing with 13029 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13030 // the return values of functions. Because it is so similar, it is handled 13031 // here as well. 13032 13033 if (N->getValueType(0) != MVT::i32 && 13034 N->getValueType(0) != MVT::i64) 13035 return SDValue(); 13036 13037 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13038 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13039 return SDValue(); 13040 13041 if (N->getOperand(0).getOpcode() != ISD::AND && 13042 N->getOperand(0).getOpcode() != ISD::OR && 13043 N->getOperand(0).getOpcode() != ISD::XOR && 13044 N->getOperand(0).getOpcode() != ISD::SELECT && 13045 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13046 return SDValue(); 13047 13048 SmallVector<SDValue, 4> Inputs; 13049 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13050 SmallPtrSet<SDNode *, 16> Visited; 13051 13052 // Visit all inputs, collect all binary operations (and, or, xor and 13053 // select) that are all fed by truncations. 13054 while (!BinOps.empty()) { 13055 SDValue BinOp = BinOps.back(); 13056 BinOps.pop_back(); 13057 13058 if (!Visited.insert(BinOp.getNode()).second) 13059 continue; 13060 13061 PromOps.push_back(BinOp); 13062 13063 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13064 // The condition of the select is not promoted. 13065 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13066 continue; 13067 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13068 continue; 13069 13070 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13071 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13072 Inputs.push_back(BinOp.getOperand(i)); 13073 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13074 BinOp.getOperand(i).getOpcode() == ISD::OR || 13075 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13076 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13077 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13078 BinOps.push_back(BinOp.getOperand(i)); 13079 } else { 13080 // We have an input that is not a truncation or another binary 13081 // operation; we'll abort this transformation. 13082 return SDValue(); 13083 } 13084 } 13085 } 13086 13087 // The operands of a select that must be truncated when the select is 13088 // promoted because the operand is actually part of the to-be-promoted set. 13089 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13090 13091 // Make sure that this is a self-contained cluster of operations (which 13092 // is not quite the same thing as saying that everything has only one 13093 // use). 13094 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13095 if (isa<ConstantSDNode>(Inputs[i])) 13096 continue; 13097 13098 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13099 UE = Inputs[i].getNode()->use_end(); 13100 UI != UE; ++UI) { 13101 SDNode *User = *UI; 13102 if (User != N && !Visited.count(User)) 13103 return SDValue(); 13104 13105 // If we're going to promote the non-output-value operand(s) or SELECT or 13106 // SELECT_CC, record them for truncation. 13107 if (User->getOpcode() == ISD::SELECT) { 13108 if (User->getOperand(0) == Inputs[i]) 13109 SelectTruncOp[0].insert(std::make_pair(User, 13110 User->getOperand(0).getValueType())); 13111 } else if (User->getOpcode() == ISD::SELECT_CC) { 13112 if (User->getOperand(0) == Inputs[i]) 13113 SelectTruncOp[0].insert(std::make_pair(User, 13114 User->getOperand(0).getValueType())); 13115 if (User->getOperand(1) == Inputs[i]) 13116 SelectTruncOp[1].insert(std::make_pair(User, 13117 User->getOperand(1).getValueType())); 13118 } 13119 } 13120 } 13121 13122 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13123 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13124 UE = PromOps[i].getNode()->use_end(); 13125 UI != UE; ++UI) { 13126 SDNode *User = *UI; 13127 if (User != N && !Visited.count(User)) 13128 return SDValue(); 13129 13130 // If we're going to promote the non-output-value operand(s) or SELECT or 13131 // SELECT_CC, record them for truncation. 13132 if (User->getOpcode() == ISD::SELECT) { 13133 if (User->getOperand(0) == PromOps[i]) 13134 SelectTruncOp[0].insert(std::make_pair(User, 13135 User->getOperand(0).getValueType())); 13136 } else if (User->getOpcode() == ISD::SELECT_CC) { 13137 if (User->getOperand(0) == PromOps[i]) 13138 SelectTruncOp[0].insert(std::make_pair(User, 13139 User->getOperand(0).getValueType())); 13140 if (User->getOperand(1) == PromOps[i]) 13141 SelectTruncOp[1].insert(std::make_pair(User, 13142 User->getOperand(1).getValueType())); 13143 } 13144 } 13145 } 13146 13147 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13148 bool ReallyNeedsExt = false; 13149 if (N->getOpcode() != ISD::ANY_EXTEND) { 13150 // If all of the inputs are not already sign/zero extended, then 13151 // we'll still need to do that at the end. 13152 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13153 if (isa<ConstantSDNode>(Inputs[i])) 13154 continue; 13155 13156 unsigned OpBits = 13157 Inputs[i].getOperand(0).getValueSizeInBits(); 13158 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13159 13160 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13161 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13162 APInt::getHighBitsSet(OpBits, 13163 OpBits-PromBits))) || 13164 (N->getOpcode() == ISD::SIGN_EXTEND && 13165 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13166 (OpBits-(PromBits-1)))) { 13167 ReallyNeedsExt = true; 13168 break; 13169 } 13170 } 13171 } 13172 13173 // Replace all inputs, either with the truncation operand, or a 13174 // truncation or extension to the final output type. 13175 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13176 // Constant inputs need to be replaced with the to-be-promoted nodes that 13177 // use them because they might have users outside of the cluster of 13178 // promoted nodes. 13179 if (isa<ConstantSDNode>(Inputs[i])) 13180 continue; 13181 13182 SDValue InSrc = Inputs[i].getOperand(0); 13183 if (Inputs[i].getValueType() == N->getValueType(0)) 13184 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13185 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13186 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13187 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13188 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13189 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13190 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13191 else 13192 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13193 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13194 } 13195 13196 std::list<HandleSDNode> PromOpHandles; 13197 for (auto &PromOp : PromOps) 13198 PromOpHandles.emplace_back(PromOp); 13199 13200 // Replace all operations (these are all the same, but have a different 13201 // (promoted) return type). DAG.getNode will validate that the types of 13202 // a binary operator match, so go through the list in reverse so that 13203 // we've likely promoted both operands first. 13204 while (!PromOpHandles.empty()) { 13205 SDValue PromOp = PromOpHandles.back().getValue(); 13206 PromOpHandles.pop_back(); 13207 13208 unsigned C; 13209 switch (PromOp.getOpcode()) { 13210 default: C = 0; break; 13211 case ISD::SELECT: C = 1; break; 13212 case ISD::SELECT_CC: C = 2; break; 13213 } 13214 13215 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13216 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13217 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13218 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13219 // The to-be-promoted operands of this node have not yet been 13220 // promoted (this should be rare because we're going through the 13221 // list backward, but if one of the operands has several users in 13222 // this cluster of to-be-promoted nodes, it is possible). 13223 PromOpHandles.emplace_front(PromOp); 13224 continue; 13225 } 13226 13227 // For SELECT and SELECT_CC nodes, we do a similar check for any 13228 // to-be-promoted comparison inputs. 13229 if (PromOp.getOpcode() == ISD::SELECT || 13230 PromOp.getOpcode() == ISD::SELECT_CC) { 13231 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13232 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13233 (SelectTruncOp[1].count(PromOp.getNode()) && 13234 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13235 PromOpHandles.emplace_front(PromOp); 13236 continue; 13237 } 13238 } 13239 13240 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13241 PromOp.getNode()->op_end()); 13242 13243 // If this node has constant inputs, then they'll need to be promoted here. 13244 for (unsigned i = 0; i < 2; ++i) { 13245 if (!isa<ConstantSDNode>(Ops[C+i])) 13246 continue; 13247 if (Ops[C+i].getValueType() == N->getValueType(0)) 13248 continue; 13249 13250 if (N->getOpcode() == ISD::SIGN_EXTEND) 13251 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13252 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13253 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13254 else 13255 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13256 } 13257 13258 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13259 // truncate them again to the original value type. 13260 if (PromOp.getOpcode() == ISD::SELECT || 13261 PromOp.getOpcode() == ISD::SELECT_CC) { 13262 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13263 if (SI0 != SelectTruncOp[0].end()) 13264 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13265 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13266 if (SI1 != SelectTruncOp[1].end()) 13267 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13268 } 13269 13270 DAG.ReplaceAllUsesOfValueWith(PromOp, 13271 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13272 } 13273 13274 // Now we're left with the initial extension itself. 13275 if (!ReallyNeedsExt) 13276 return N->getOperand(0); 13277 13278 // To zero extend, just mask off everything except for the first bit (in the 13279 // i1 case). 13280 if (N->getOpcode() == ISD::ZERO_EXTEND) 13281 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13282 DAG.getConstant(APInt::getLowBitsSet( 13283 N->getValueSizeInBits(0), PromBits), 13284 dl, N->getValueType(0))); 13285 13286 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13287 "Invalid extension type"); 13288 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13289 SDValue ShiftCst = 13290 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13291 return DAG.getNode( 13292 ISD::SRA, dl, N->getValueType(0), 13293 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13294 ShiftCst); 13295 } 13296 13297 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13298 DAGCombinerInfo &DCI) const { 13299 assert(N->getOpcode() == ISD::SETCC && 13300 "Should be called with a SETCC node"); 13301 13302 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13303 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13304 SDValue LHS = N->getOperand(0); 13305 SDValue RHS = N->getOperand(1); 13306 13307 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13308 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13309 LHS.hasOneUse()) 13310 std::swap(LHS, RHS); 13311 13312 // x == 0-y --> x+y == 0 13313 // x != 0-y --> x+y != 0 13314 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13315 RHS.hasOneUse()) { 13316 SDLoc DL(N); 13317 SelectionDAG &DAG = DCI.DAG; 13318 EVT VT = N->getValueType(0); 13319 EVT OpVT = LHS.getValueType(); 13320 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13321 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13322 } 13323 } 13324 13325 return DAGCombineTruncBoolExt(N, DCI); 13326 } 13327 13328 // Is this an extending load from an f32 to an f64? 13329 static bool isFPExtLoad(SDValue Op) { 13330 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13331 return LD->getExtensionType() == ISD::EXTLOAD && 13332 Op.getValueType() == MVT::f64; 13333 return false; 13334 } 13335 13336 /// Reduces the number of fp-to-int conversion when building a vector. 13337 /// 13338 /// If this vector is built out of floating to integer conversions, 13339 /// transform it to a vector built out of floating point values followed by a 13340 /// single floating to integer conversion of the vector. 13341 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13342 /// becomes (fptosi (build_vector ($A, $B, ...))) 13343 SDValue PPCTargetLowering:: 13344 combineElementTruncationToVectorTruncation(SDNode *N, 13345 DAGCombinerInfo &DCI) const { 13346 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13347 "Should be called with a BUILD_VECTOR node"); 13348 13349 SelectionDAG &DAG = DCI.DAG; 13350 SDLoc dl(N); 13351 13352 SDValue FirstInput = N->getOperand(0); 13353 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13354 "The input operand must be an fp-to-int conversion."); 13355 13356 // This combine happens after legalization so the fp_to_[su]i nodes are 13357 // already converted to PPCSISD nodes. 13358 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13359 if (FirstConversion == PPCISD::FCTIDZ || 13360 FirstConversion == PPCISD::FCTIDUZ || 13361 FirstConversion == PPCISD::FCTIWZ || 13362 FirstConversion == PPCISD::FCTIWUZ) { 13363 bool IsSplat = true; 13364 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13365 FirstConversion == PPCISD::FCTIWUZ; 13366 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13367 SmallVector<SDValue, 4> Ops; 13368 EVT TargetVT = N->getValueType(0); 13369 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13370 SDValue NextOp = N->getOperand(i); 13371 if (NextOp.getOpcode() != PPCISD::MFVSR) 13372 return SDValue(); 13373 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13374 if (NextConversion != FirstConversion) 13375 return SDValue(); 13376 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13377 // This is not valid if the input was originally double precision. It is 13378 // also not profitable to do unless this is an extending load in which 13379 // case doing this combine will allow us to combine consecutive loads. 13380 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13381 return SDValue(); 13382 if (N->getOperand(i) != FirstInput) 13383 IsSplat = false; 13384 } 13385 13386 // If this is a splat, we leave it as-is since there will be only a single 13387 // fp-to-int conversion followed by a splat of the integer. This is better 13388 // for 32-bit and smaller ints and neutral for 64-bit ints. 13389 if (IsSplat) 13390 return SDValue(); 13391 13392 // Now that we know we have the right type of node, get its operands 13393 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13394 SDValue In = N->getOperand(i).getOperand(0); 13395 if (Is32Bit) { 13396 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13397 // here, we know that all inputs are extending loads so this is safe). 13398 if (In.isUndef()) 13399 Ops.push_back(DAG.getUNDEF(SrcVT)); 13400 else { 13401 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13402 MVT::f32, In.getOperand(0), 13403 DAG.getIntPtrConstant(1, dl)); 13404 Ops.push_back(Trunc); 13405 } 13406 } else 13407 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13408 } 13409 13410 unsigned Opcode; 13411 if (FirstConversion == PPCISD::FCTIDZ || 13412 FirstConversion == PPCISD::FCTIWZ) 13413 Opcode = ISD::FP_TO_SINT; 13414 else 13415 Opcode = ISD::FP_TO_UINT; 13416 13417 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13418 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13419 return DAG.getNode(Opcode, dl, TargetVT, BV); 13420 } 13421 return SDValue(); 13422 } 13423 13424 /// Reduce the number of loads when building a vector. 13425 /// 13426 /// Building a vector out of multiple loads can be converted to a load 13427 /// of the vector type if the loads are consecutive. If the loads are 13428 /// consecutive but in descending order, a shuffle is added at the end 13429 /// to reorder the vector. 13430 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13431 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13432 "Should be called with a BUILD_VECTOR node"); 13433 13434 SDLoc dl(N); 13435 13436 // Return early for non byte-sized type, as they can't be consecutive. 13437 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13438 return SDValue(); 13439 13440 bool InputsAreConsecutiveLoads = true; 13441 bool InputsAreReverseConsecutive = true; 13442 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13443 SDValue FirstInput = N->getOperand(0); 13444 bool IsRoundOfExtLoad = false; 13445 13446 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13447 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13448 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13449 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13450 } 13451 // Not a build vector of (possibly fp_rounded) loads. 13452 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13453 N->getNumOperands() == 1) 13454 return SDValue(); 13455 13456 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13457 // If any inputs are fp_round(extload), they all must be. 13458 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13459 return SDValue(); 13460 13461 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13462 N->getOperand(i); 13463 if (NextInput.getOpcode() != ISD::LOAD) 13464 return SDValue(); 13465 13466 SDValue PreviousInput = 13467 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13468 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13469 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13470 13471 // If any inputs are fp_round(extload), they all must be. 13472 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13473 return SDValue(); 13474 13475 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13476 InputsAreConsecutiveLoads = false; 13477 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13478 InputsAreReverseConsecutive = false; 13479 13480 // Exit early if the loads are neither consecutive nor reverse consecutive. 13481 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13482 return SDValue(); 13483 } 13484 13485 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13486 "The loads cannot be both consecutive and reverse consecutive."); 13487 13488 SDValue FirstLoadOp = 13489 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13490 SDValue LastLoadOp = 13491 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13492 N->getOperand(N->getNumOperands()-1); 13493 13494 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13495 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13496 if (InputsAreConsecutiveLoads) { 13497 assert(LD1 && "Input needs to be a LoadSDNode."); 13498 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13499 LD1->getBasePtr(), LD1->getPointerInfo(), 13500 LD1->getAlignment()); 13501 } 13502 if (InputsAreReverseConsecutive) { 13503 assert(LDL && "Input needs to be a LoadSDNode."); 13504 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13505 LDL->getBasePtr(), LDL->getPointerInfo(), 13506 LDL->getAlignment()); 13507 SmallVector<int, 16> Ops; 13508 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13509 Ops.push_back(i); 13510 13511 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13512 DAG.getUNDEF(N->getValueType(0)), Ops); 13513 } 13514 return SDValue(); 13515 } 13516 13517 // This function adds the required vector_shuffle needed to get 13518 // the elements of the vector extract in the correct position 13519 // as specified by the CorrectElems encoding. 13520 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13521 SDValue Input, uint64_t Elems, 13522 uint64_t CorrectElems) { 13523 SDLoc dl(N); 13524 13525 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13526 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13527 13528 // Knowing the element indices being extracted from the original 13529 // vector and the order in which they're being inserted, just put 13530 // them at element indices required for the instruction. 13531 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13532 if (DAG.getDataLayout().isLittleEndian()) 13533 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13534 else 13535 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13536 CorrectElems = CorrectElems >> 8; 13537 Elems = Elems >> 8; 13538 } 13539 13540 SDValue Shuffle = 13541 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13542 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13543 13544 EVT VT = N->getValueType(0); 13545 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13546 13547 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13548 Input.getValueType().getVectorElementType(), 13549 VT.getVectorNumElements()); 13550 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13551 DAG.getValueType(ExtVT)); 13552 } 13553 13554 // Look for build vector patterns where input operands come from sign 13555 // extended vector_extract elements of specific indices. If the correct indices 13556 // aren't used, add a vector shuffle to fix up the indices and create 13557 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13558 // during instruction selection. 13559 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13560 // This array encodes the indices that the vector sign extend instructions 13561 // extract from when extending from one type to another for both BE and LE. 13562 // The right nibble of each byte corresponds to the LE incides. 13563 // and the left nibble of each byte corresponds to the BE incides. 13564 // For example: 0x3074B8FC byte->word 13565 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13566 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13567 // For example: 0x000070F8 byte->double word 13568 // For LE: the allowed indices are: 0x0,0x8 13569 // For BE: the allowed indices are: 0x7,0xF 13570 uint64_t TargetElems[] = { 13571 0x3074B8FC, // b->w 13572 0x000070F8, // b->d 13573 0x10325476, // h->w 13574 0x00003074, // h->d 13575 0x00001032, // w->d 13576 }; 13577 13578 uint64_t Elems = 0; 13579 int Index; 13580 SDValue Input; 13581 13582 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13583 if (!Op) 13584 return false; 13585 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13586 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13587 return false; 13588 13589 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13590 // of the right width. 13591 SDValue Extract = Op.getOperand(0); 13592 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13593 Extract = Extract.getOperand(0); 13594 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13595 return false; 13596 13597 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13598 if (!ExtOp) 13599 return false; 13600 13601 Index = ExtOp->getZExtValue(); 13602 if (Input && Input != Extract.getOperand(0)) 13603 return false; 13604 13605 if (!Input) 13606 Input = Extract.getOperand(0); 13607 13608 Elems = Elems << 8; 13609 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13610 Elems |= Index; 13611 13612 return true; 13613 }; 13614 13615 // If the build vector operands aren't sign extended vector extracts, 13616 // of the same input vector, then return. 13617 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13618 if (!isSExtOfVecExtract(N->getOperand(i))) { 13619 return SDValue(); 13620 } 13621 } 13622 13623 // If the vector extract indicies are not correct, add the appropriate 13624 // vector_shuffle. 13625 int TgtElemArrayIdx; 13626 int InputSize = Input.getValueType().getScalarSizeInBits(); 13627 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13628 if (InputSize + OutputSize == 40) 13629 TgtElemArrayIdx = 0; 13630 else if (InputSize + OutputSize == 72) 13631 TgtElemArrayIdx = 1; 13632 else if (InputSize + OutputSize == 48) 13633 TgtElemArrayIdx = 2; 13634 else if (InputSize + OutputSize == 80) 13635 TgtElemArrayIdx = 3; 13636 else if (InputSize + OutputSize == 96) 13637 TgtElemArrayIdx = 4; 13638 else 13639 return SDValue(); 13640 13641 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13642 CorrectElems = DAG.getDataLayout().isLittleEndian() 13643 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13644 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13645 if (Elems != CorrectElems) { 13646 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13647 } 13648 13649 // Regular lowering will catch cases where a shuffle is not needed. 13650 return SDValue(); 13651 } 13652 13653 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13654 DAGCombinerInfo &DCI) const { 13655 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13656 "Should be called with a BUILD_VECTOR node"); 13657 13658 SelectionDAG &DAG = DCI.DAG; 13659 SDLoc dl(N); 13660 13661 if (!Subtarget.hasVSX()) 13662 return SDValue(); 13663 13664 // The target independent DAG combiner will leave a build_vector of 13665 // float-to-int conversions intact. We can generate MUCH better code for 13666 // a float-to-int conversion of a vector of floats. 13667 SDValue FirstInput = N->getOperand(0); 13668 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13669 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13670 if (Reduced) 13671 return Reduced; 13672 } 13673 13674 // If we're building a vector out of consecutive loads, just load that 13675 // vector type. 13676 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13677 if (Reduced) 13678 return Reduced; 13679 13680 // If we're building a vector out of extended elements from another vector 13681 // we have P9 vector integer extend instructions. The code assumes legal 13682 // input types (i.e. it can't handle things like v4i16) so do not run before 13683 // legalization. 13684 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13685 Reduced = combineBVOfVecSExt(N, DAG); 13686 if (Reduced) 13687 return Reduced; 13688 } 13689 13690 13691 if (N->getValueType(0) != MVT::v2f64) 13692 return SDValue(); 13693 13694 // Looking for: 13695 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13696 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13697 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13698 return SDValue(); 13699 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13700 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13701 return SDValue(); 13702 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13703 return SDValue(); 13704 13705 SDValue Ext1 = FirstInput.getOperand(0); 13706 SDValue Ext2 = N->getOperand(1).getOperand(0); 13707 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13708 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13709 return SDValue(); 13710 13711 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13712 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13713 if (!Ext1Op || !Ext2Op) 13714 return SDValue(); 13715 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13716 Ext1.getOperand(0) != Ext2.getOperand(0)) 13717 return SDValue(); 13718 13719 int FirstElem = Ext1Op->getZExtValue(); 13720 int SecondElem = Ext2Op->getZExtValue(); 13721 int SubvecIdx; 13722 if (FirstElem == 0 && SecondElem == 1) 13723 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13724 else if (FirstElem == 2 && SecondElem == 3) 13725 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13726 else 13727 return SDValue(); 13728 13729 SDValue SrcVec = Ext1.getOperand(0); 13730 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13731 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13732 return DAG.getNode(NodeType, dl, MVT::v2f64, 13733 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13734 } 13735 13736 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13737 DAGCombinerInfo &DCI) const { 13738 assert((N->getOpcode() == ISD::SINT_TO_FP || 13739 N->getOpcode() == ISD::UINT_TO_FP) && 13740 "Need an int -> FP conversion node here"); 13741 13742 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13743 return SDValue(); 13744 13745 SelectionDAG &DAG = DCI.DAG; 13746 SDLoc dl(N); 13747 SDValue Op(N, 0); 13748 13749 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13750 // from the hardware. 13751 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13752 return SDValue(); 13753 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13754 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13755 return SDValue(); 13756 13757 SDValue FirstOperand(Op.getOperand(0)); 13758 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13759 (FirstOperand.getValueType() == MVT::i8 || 13760 FirstOperand.getValueType() == MVT::i16); 13761 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13762 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13763 bool DstDouble = Op.getValueType() == MVT::f64; 13764 unsigned ConvOp = Signed ? 13765 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13766 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13767 SDValue WidthConst = 13768 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13769 dl, false); 13770 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13771 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13772 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13773 DAG.getVTList(MVT::f64, MVT::Other), 13774 Ops, MVT::i8, LDN->getMemOperand()); 13775 13776 // For signed conversion, we need to sign-extend the value in the VSR 13777 if (Signed) { 13778 SDValue ExtOps[] = { Ld, WidthConst }; 13779 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13780 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13781 } else 13782 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13783 } 13784 13785 13786 // For i32 intermediate values, unfortunately, the conversion functions 13787 // leave the upper 32 bits of the value are undefined. Within the set of 13788 // scalar instructions, we have no method for zero- or sign-extending the 13789 // value. Thus, we cannot handle i32 intermediate values here. 13790 if (Op.getOperand(0).getValueType() == MVT::i32) 13791 return SDValue(); 13792 13793 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13794 "UINT_TO_FP is supported only with FPCVT"); 13795 13796 // If we have FCFIDS, then use it when converting to single-precision. 13797 // Otherwise, convert to double-precision and then round. 13798 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13799 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13800 : PPCISD::FCFIDS) 13801 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13802 : PPCISD::FCFID); 13803 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13804 ? MVT::f32 13805 : MVT::f64; 13806 13807 // If we're converting from a float, to an int, and back to a float again, 13808 // then we don't need the store/load pair at all. 13809 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13810 Subtarget.hasFPCVT()) || 13811 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13812 SDValue Src = Op.getOperand(0).getOperand(0); 13813 if (Src.getValueType() == MVT::f32) { 13814 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13815 DCI.AddToWorklist(Src.getNode()); 13816 } else if (Src.getValueType() != MVT::f64) { 13817 // Make sure that we don't pick up a ppc_fp128 source value. 13818 return SDValue(); 13819 } 13820 13821 unsigned FCTOp = 13822 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13823 PPCISD::FCTIDUZ; 13824 13825 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13826 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13827 13828 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13829 FP = DAG.getNode(ISD::FP_ROUND, dl, 13830 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13831 DCI.AddToWorklist(FP.getNode()); 13832 } 13833 13834 return FP; 13835 } 13836 13837 return SDValue(); 13838 } 13839 13840 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13841 // builtins) into loads with swaps. 13842 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13843 DAGCombinerInfo &DCI) const { 13844 SelectionDAG &DAG = DCI.DAG; 13845 SDLoc dl(N); 13846 SDValue Chain; 13847 SDValue Base; 13848 MachineMemOperand *MMO; 13849 13850 switch (N->getOpcode()) { 13851 default: 13852 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13853 case ISD::LOAD: { 13854 LoadSDNode *LD = cast<LoadSDNode>(N); 13855 Chain = LD->getChain(); 13856 Base = LD->getBasePtr(); 13857 MMO = LD->getMemOperand(); 13858 // If the MMO suggests this isn't a load of a full vector, leave 13859 // things alone. For a built-in, we have to make the change for 13860 // correctness, so if there is a size problem that will be a bug. 13861 if (MMO->getSize() < 16) 13862 return SDValue(); 13863 break; 13864 } 13865 case ISD::INTRINSIC_W_CHAIN: { 13866 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13867 Chain = Intrin->getChain(); 13868 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13869 // us what we want. Get operand 2 instead. 13870 Base = Intrin->getOperand(2); 13871 MMO = Intrin->getMemOperand(); 13872 break; 13873 } 13874 } 13875 13876 MVT VecTy = N->getValueType(0).getSimpleVT(); 13877 13878 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13879 // aligned and the type is a vector with elements up to 4 bytes 13880 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13881 VecTy.getScalarSizeInBits() <= 32) { 13882 return SDValue(); 13883 } 13884 13885 SDValue LoadOps[] = { Chain, Base }; 13886 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13887 DAG.getVTList(MVT::v2f64, MVT::Other), 13888 LoadOps, MVT::v2f64, MMO); 13889 13890 DCI.AddToWorklist(Load.getNode()); 13891 Chain = Load.getValue(1); 13892 SDValue Swap = DAG.getNode( 13893 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13894 DCI.AddToWorklist(Swap.getNode()); 13895 13896 // Add a bitcast if the resulting load type doesn't match v2f64. 13897 if (VecTy != MVT::v2f64) { 13898 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13899 DCI.AddToWorklist(N.getNode()); 13900 // Package {bitcast value, swap's chain} to match Load's shape. 13901 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13902 N, Swap.getValue(1)); 13903 } 13904 13905 return Swap; 13906 } 13907 13908 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13909 // builtins) into stores with swaps. 13910 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13911 DAGCombinerInfo &DCI) const { 13912 SelectionDAG &DAG = DCI.DAG; 13913 SDLoc dl(N); 13914 SDValue Chain; 13915 SDValue Base; 13916 unsigned SrcOpnd; 13917 MachineMemOperand *MMO; 13918 13919 switch (N->getOpcode()) { 13920 default: 13921 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13922 case ISD::STORE: { 13923 StoreSDNode *ST = cast<StoreSDNode>(N); 13924 Chain = ST->getChain(); 13925 Base = ST->getBasePtr(); 13926 MMO = ST->getMemOperand(); 13927 SrcOpnd = 1; 13928 // If the MMO suggests this isn't a store of a full vector, leave 13929 // things alone. For a built-in, we have to make the change for 13930 // correctness, so if there is a size problem that will be a bug. 13931 if (MMO->getSize() < 16) 13932 return SDValue(); 13933 break; 13934 } 13935 case ISD::INTRINSIC_VOID: { 13936 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13937 Chain = Intrin->getChain(); 13938 // Intrin->getBasePtr() oddly does not get what we want. 13939 Base = Intrin->getOperand(3); 13940 MMO = Intrin->getMemOperand(); 13941 SrcOpnd = 2; 13942 break; 13943 } 13944 } 13945 13946 SDValue Src = N->getOperand(SrcOpnd); 13947 MVT VecTy = Src.getValueType().getSimpleVT(); 13948 13949 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13950 // aligned and the type is a vector with elements up to 4 bytes 13951 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13952 VecTy.getScalarSizeInBits() <= 32) { 13953 return SDValue(); 13954 } 13955 13956 // All stores are done as v2f64 and possible bit cast. 13957 if (VecTy != MVT::v2f64) { 13958 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13959 DCI.AddToWorklist(Src.getNode()); 13960 } 13961 13962 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13963 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13964 DCI.AddToWorklist(Swap.getNode()); 13965 Chain = Swap.getValue(1); 13966 SDValue StoreOps[] = { Chain, Swap, Base }; 13967 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13968 DAG.getVTList(MVT::Other), 13969 StoreOps, VecTy, MMO); 13970 DCI.AddToWorklist(Store.getNode()); 13971 return Store; 13972 } 13973 13974 // Handle DAG combine for STORE (FP_TO_INT F). 13975 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13976 DAGCombinerInfo &DCI) const { 13977 13978 SelectionDAG &DAG = DCI.DAG; 13979 SDLoc dl(N); 13980 unsigned Opcode = N->getOperand(1).getOpcode(); 13981 13982 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13983 && "Not a FP_TO_INT Instruction!"); 13984 13985 SDValue Val = N->getOperand(1).getOperand(0); 13986 EVT Op1VT = N->getOperand(1).getValueType(); 13987 EVT ResVT = Val.getValueType(); 13988 13989 // Floating point types smaller than 32 bits are not legal on Power. 13990 if (ResVT.getScalarSizeInBits() < 32) 13991 return SDValue(); 13992 13993 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13994 bool ValidTypeForStoreFltAsInt = 13995 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13996 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13997 13998 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13999 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14000 return SDValue(); 14001 14002 // Extend f32 values to f64 14003 if (ResVT.getScalarSizeInBits() == 32) { 14004 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14005 DCI.AddToWorklist(Val.getNode()); 14006 } 14007 14008 // Set signed or unsigned conversion opcode. 14009 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14010 PPCISD::FP_TO_SINT_IN_VSR : 14011 PPCISD::FP_TO_UINT_IN_VSR; 14012 14013 Val = DAG.getNode(ConvOpcode, 14014 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14015 DCI.AddToWorklist(Val.getNode()); 14016 14017 // Set number of bytes being converted. 14018 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14019 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14020 DAG.getIntPtrConstant(ByteSize, dl, false), 14021 DAG.getValueType(Op1VT) }; 14022 14023 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14024 DAG.getVTList(MVT::Other), Ops, 14025 cast<StoreSDNode>(N)->getMemoryVT(), 14026 cast<StoreSDNode>(N)->getMemOperand()); 14027 14028 DCI.AddToWorklist(Val.getNode()); 14029 return Val; 14030 } 14031 14032 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14033 LSBaseSDNode *LSBase, 14034 DAGCombinerInfo &DCI) const { 14035 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14036 "Not a reverse memop pattern!"); 14037 14038 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14039 auto Mask = SVN->getMask(); 14040 int i = 0; 14041 auto I = Mask.rbegin(); 14042 auto E = Mask.rend(); 14043 14044 for (; I != E; ++I) { 14045 if (*I != i) 14046 return false; 14047 i++; 14048 } 14049 return true; 14050 }; 14051 14052 SelectionDAG &DAG = DCI.DAG; 14053 EVT VT = SVN->getValueType(0); 14054 14055 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14056 return SDValue(); 14057 14058 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14059 // See comment in PPCVSXSwapRemoval.cpp. 14060 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14061 if (!Subtarget.hasP9Vector()) 14062 return SDValue(); 14063 14064 if(!IsElementReverse(SVN)) 14065 return SDValue(); 14066 14067 if (LSBase->getOpcode() == ISD::LOAD) { 14068 SDLoc dl(SVN); 14069 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14070 return DAG.getMemIntrinsicNode( 14071 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14072 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14073 } 14074 14075 if (LSBase->getOpcode() == ISD::STORE) { 14076 SDLoc dl(LSBase); 14077 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14078 LSBase->getBasePtr()}; 14079 return DAG.getMemIntrinsicNode( 14080 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14081 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14082 } 14083 14084 llvm_unreachable("Expected a load or store node here"); 14085 } 14086 14087 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14088 DAGCombinerInfo &DCI) const { 14089 SelectionDAG &DAG = DCI.DAG; 14090 SDLoc dl(N); 14091 switch (N->getOpcode()) { 14092 default: break; 14093 case ISD::ADD: 14094 return combineADD(N, DCI); 14095 case ISD::SHL: 14096 return combineSHL(N, DCI); 14097 case ISD::SRA: 14098 return combineSRA(N, DCI); 14099 case ISD::SRL: 14100 return combineSRL(N, DCI); 14101 case ISD::MUL: 14102 return combineMUL(N, DCI); 14103 case PPCISD::SHL: 14104 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14105 return N->getOperand(0); 14106 break; 14107 case PPCISD::SRL: 14108 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14109 return N->getOperand(0); 14110 break; 14111 case PPCISD::SRA: 14112 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14113 if (C->isNullValue() || // 0 >>s V -> 0. 14114 C->isAllOnesValue()) // -1 >>s V -> -1. 14115 return N->getOperand(0); 14116 } 14117 break; 14118 case ISD::SIGN_EXTEND: 14119 case ISD::ZERO_EXTEND: 14120 case ISD::ANY_EXTEND: 14121 return DAGCombineExtBoolTrunc(N, DCI); 14122 case ISD::TRUNCATE: 14123 return combineTRUNCATE(N, DCI); 14124 case ISD::SETCC: 14125 if (SDValue CSCC = combineSetCC(N, DCI)) 14126 return CSCC; 14127 LLVM_FALLTHROUGH; 14128 case ISD::SELECT_CC: 14129 return DAGCombineTruncBoolExt(N, DCI); 14130 case ISD::SINT_TO_FP: 14131 case ISD::UINT_TO_FP: 14132 return combineFPToIntToFP(N, DCI); 14133 case ISD::VECTOR_SHUFFLE: 14134 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14135 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14136 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14137 } 14138 break; 14139 case ISD::STORE: { 14140 14141 EVT Op1VT = N->getOperand(1).getValueType(); 14142 unsigned Opcode = N->getOperand(1).getOpcode(); 14143 14144 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14145 SDValue Val= combineStoreFPToInt(N, DCI); 14146 if (Val) 14147 return Val; 14148 } 14149 14150 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14151 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14152 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14153 if (Val) 14154 return Val; 14155 } 14156 14157 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14158 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14159 N->getOperand(1).getNode()->hasOneUse() && 14160 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14161 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14162 14163 // STBRX can only handle simple types and it makes no sense to store less 14164 // two bytes in byte-reversed order. 14165 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14166 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14167 break; 14168 14169 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14170 // Do an any-extend to 32-bits if this is a half-word input. 14171 if (BSwapOp.getValueType() == MVT::i16) 14172 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14173 14174 // If the type of BSWAP operand is wider than stored memory width 14175 // it need to be shifted to the right side before STBRX. 14176 if (Op1VT.bitsGT(mVT)) { 14177 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14178 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14179 DAG.getConstant(Shift, dl, MVT::i32)); 14180 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14181 if (Op1VT == MVT::i64) 14182 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14183 } 14184 14185 SDValue Ops[] = { 14186 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14187 }; 14188 return 14189 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14190 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14191 cast<StoreSDNode>(N)->getMemOperand()); 14192 } 14193 14194 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14195 // So it can increase the chance of CSE constant construction. 14196 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14197 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14198 // Need to sign-extended to 64-bits to handle negative values. 14199 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14200 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14201 MemVT.getSizeInBits()); 14202 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14203 14204 // DAG.getTruncStore() can't be used here because it doesn't accept 14205 // the general (base + offset) addressing mode. 14206 // So we use UpdateNodeOperands and setTruncatingStore instead. 14207 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14208 N->getOperand(3)); 14209 cast<StoreSDNode>(N)->setTruncatingStore(true); 14210 return SDValue(N, 0); 14211 } 14212 14213 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14214 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14215 if (Op1VT.isSimple()) { 14216 MVT StoreVT = Op1VT.getSimpleVT(); 14217 if (Subtarget.needsSwapsForVSXMemOps() && 14218 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14219 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14220 return expandVSXStoreForLE(N, DCI); 14221 } 14222 break; 14223 } 14224 case ISD::LOAD: { 14225 LoadSDNode *LD = cast<LoadSDNode>(N); 14226 EVT VT = LD->getValueType(0); 14227 14228 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14229 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14230 if (VT.isSimple()) { 14231 MVT LoadVT = VT.getSimpleVT(); 14232 if (Subtarget.needsSwapsForVSXMemOps() && 14233 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14234 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14235 return expandVSXLoadForLE(N, DCI); 14236 } 14237 14238 // We sometimes end up with a 64-bit integer load, from which we extract 14239 // two single-precision floating-point numbers. This happens with 14240 // std::complex<float>, and other similar structures, because of the way we 14241 // canonicalize structure copies. However, if we lack direct moves, 14242 // then the final bitcasts from the extracted integer values to the 14243 // floating-point numbers turn into store/load pairs. Even with direct moves, 14244 // just loading the two floating-point numbers is likely better. 14245 auto ReplaceTwoFloatLoad = [&]() { 14246 if (VT != MVT::i64) 14247 return false; 14248 14249 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14250 LD->isVolatile()) 14251 return false; 14252 14253 // We're looking for a sequence like this: 14254 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14255 // t16: i64 = srl t13, Constant:i32<32> 14256 // t17: i32 = truncate t16 14257 // t18: f32 = bitcast t17 14258 // t19: i32 = truncate t13 14259 // t20: f32 = bitcast t19 14260 14261 if (!LD->hasNUsesOfValue(2, 0)) 14262 return false; 14263 14264 auto UI = LD->use_begin(); 14265 while (UI.getUse().getResNo() != 0) ++UI; 14266 SDNode *Trunc = *UI++; 14267 while (UI.getUse().getResNo() != 0) ++UI; 14268 SDNode *RightShift = *UI; 14269 if (Trunc->getOpcode() != ISD::TRUNCATE) 14270 std::swap(Trunc, RightShift); 14271 14272 if (Trunc->getOpcode() != ISD::TRUNCATE || 14273 Trunc->getValueType(0) != MVT::i32 || 14274 !Trunc->hasOneUse()) 14275 return false; 14276 if (RightShift->getOpcode() != ISD::SRL || 14277 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14278 RightShift->getConstantOperandVal(1) != 32 || 14279 !RightShift->hasOneUse()) 14280 return false; 14281 14282 SDNode *Trunc2 = *RightShift->use_begin(); 14283 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14284 Trunc2->getValueType(0) != MVT::i32 || 14285 !Trunc2->hasOneUse()) 14286 return false; 14287 14288 SDNode *Bitcast = *Trunc->use_begin(); 14289 SDNode *Bitcast2 = *Trunc2->use_begin(); 14290 14291 if (Bitcast->getOpcode() != ISD::BITCAST || 14292 Bitcast->getValueType(0) != MVT::f32) 14293 return false; 14294 if (Bitcast2->getOpcode() != ISD::BITCAST || 14295 Bitcast2->getValueType(0) != MVT::f32) 14296 return false; 14297 14298 if (Subtarget.isLittleEndian()) 14299 std::swap(Bitcast, Bitcast2); 14300 14301 // Bitcast has the second float (in memory-layout order) and Bitcast2 14302 // has the first one. 14303 14304 SDValue BasePtr = LD->getBasePtr(); 14305 if (LD->isIndexed()) { 14306 assert(LD->getAddressingMode() == ISD::PRE_INC && 14307 "Non-pre-inc AM on PPC?"); 14308 BasePtr = 14309 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14310 LD->getOffset()); 14311 } 14312 14313 auto MMOFlags = 14314 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14315 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14316 LD->getPointerInfo(), LD->getAlignment(), 14317 MMOFlags, LD->getAAInfo()); 14318 SDValue AddPtr = 14319 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14320 BasePtr, DAG.getIntPtrConstant(4, dl)); 14321 SDValue FloatLoad2 = DAG.getLoad( 14322 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14323 LD->getPointerInfo().getWithOffset(4), 14324 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14325 14326 if (LD->isIndexed()) { 14327 // Note that DAGCombine should re-form any pre-increment load(s) from 14328 // what is produced here if that makes sense. 14329 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14330 } 14331 14332 DCI.CombineTo(Bitcast2, FloatLoad); 14333 DCI.CombineTo(Bitcast, FloatLoad2); 14334 14335 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14336 SDValue(FloatLoad2.getNode(), 1)); 14337 return true; 14338 }; 14339 14340 if (ReplaceTwoFloatLoad()) 14341 return SDValue(N, 0); 14342 14343 EVT MemVT = LD->getMemoryVT(); 14344 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14345 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14346 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14347 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14348 if (LD->isUnindexed() && VT.isVector() && 14349 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14350 // P8 and later hardware should just use LOAD. 14351 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14352 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14353 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14354 LD->getAlignment() >= ScalarABIAlignment)) && 14355 LD->getAlignment() < ABIAlignment) { 14356 // This is a type-legal unaligned Altivec or QPX load. 14357 SDValue Chain = LD->getChain(); 14358 SDValue Ptr = LD->getBasePtr(); 14359 bool isLittleEndian = Subtarget.isLittleEndian(); 14360 14361 // This implements the loading of unaligned vectors as described in 14362 // the venerable Apple Velocity Engine overview. Specifically: 14363 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14364 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14365 // 14366 // The general idea is to expand a sequence of one or more unaligned 14367 // loads into an alignment-based permutation-control instruction (lvsl 14368 // or lvsr), a series of regular vector loads (which always truncate 14369 // their input address to an aligned address), and a series of 14370 // permutations. The results of these permutations are the requested 14371 // loaded values. The trick is that the last "extra" load is not taken 14372 // from the address you might suspect (sizeof(vector) bytes after the 14373 // last requested load), but rather sizeof(vector) - 1 bytes after the 14374 // last requested vector. The point of this is to avoid a page fault if 14375 // the base address happened to be aligned. This works because if the 14376 // base address is aligned, then adding less than a full vector length 14377 // will cause the last vector in the sequence to be (re)loaded. 14378 // Otherwise, the next vector will be fetched as you might suspect was 14379 // necessary. 14380 14381 // We might be able to reuse the permutation generation from 14382 // a different base address offset from this one by an aligned amount. 14383 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14384 // optimization later. 14385 Intrinsic::ID Intr, IntrLD, IntrPerm; 14386 MVT PermCntlTy, PermTy, LDTy; 14387 if (Subtarget.hasAltivec()) { 14388 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14389 Intrinsic::ppc_altivec_lvsl; 14390 IntrLD = Intrinsic::ppc_altivec_lvx; 14391 IntrPerm = Intrinsic::ppc_altivec_vperm; 14392 PermCntlTy = MVT::v16i8; 14393 PermTy = MVT::v4i32; 14394 LDTy = MVT::v4i32; 14395 } else { 14396 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14397 Intrinsic::ppc_qpx_qvlpcls; 14398 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14399 Intrinsic::ppc_qpx_qvlfs; 14400 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14401 PermCntlTy = MVT::v4f64; 14402 PermTy = MVT::v4f64; 14403 LDTy = MemVT.getSimpleVT(); 14404 } 14405 14406 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14407 14408 // Create the new MMO for the new base load. It is like the original MMO, 14409 // but represents an area in memory almost twice the vector size centered 14410 // on the original address. If the address is unaligned, we might start 14411 // reading up to (sizeof(vector)-1) bytes below the address of the 14412 // original unaligned load. 14413 MachineFunction &MF = DAG.getMachineFunction(); 14414 MachineMemOperand *BaseMMO = 14415 MF.getMachineMemOperand(LD->getMemOperand(), 14416 -(long)MemVT.getStoreSize()+1, 14417 2*MemVT.getStoreSize()-1); 14418 14419 // Create the new base load. 14420 SDValue LDXIntID = 14421 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14422 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14423 SDValue BaseLoad = 14424 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14425 DAG.getVTList(PermTy, MVT::Other), 14426 BaseLoadOps, LDTy, BaseMMO); 14427 14428 // Note that the value of IncOffset (which is provided to the next 14429 // load's pointer info offset value, and thus used to calculate the 14430 // alignment), and the value of IncValue (which is actually used to 14431 // increment the pointer value) are different! This is because we 14432 // require the next load to appear to be aligned, even though it 14433 // is actually offset from the base pointer by a lesser amount. 14434 int IncOffset = VT.getSizeInBits() / 8; 14435 int IncValue = IncOffset; 14436 14437 // Walk (both up and down) the chain looking for another load at the real 14438 // (aligned) offset (the alignment of the other load does not matter in 14439 // this case). If found, then do not use the offset reduction trick, as 14440 // that will prevent the loads from being later combined (as they would 14441 // otherwise be duplicates). 14442 if (!findConsecutiveLoad(LD, DAG)) 14443 --IncValue; 14444 14445 SDValue Increment = 14446 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14447 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14448 14449 MachineMemOperand *ExtraMMO = 14450 MF.getMachineMemOperand(LD->getMemOperand(), 14451 1, 2*MemVT.getStoreSize()-1); 14452 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14453 SDValue ExtraLoad = 14454 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14455 DAG.getVTList(PermTy, MVT::Other), 14456 ExtraLoadOps, LDTy, ExtraMMO); 14457 14458 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14459 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14460 14461 // Because vperm has a big-endian bias, we must reverse the order 14462 // of the input vectors and complement the permute control vector 14463 // when generating little endian code. We have already handled the 14464 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14465 // and ExtraLoad here. 14466 SDValue Perm; 14467 if (isLittleEndian) 14468 Perm = BuildIntrinsicOp(IntrPerm, 14469 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14470 else 14471 Perm = BuildIntrinsicOp(IntrPerm, 14472 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14473 14474 if (VT != PermTy) 14475 Perm = Subtarget.hasAltivec() ? 14476 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14477 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14478 DAG.getTargetConstant(1, dl, MVT::i64)); 14479 // second argument is 1 because this rounding 14480 // is always exact. 14481 14482 // The output of the permutation is our loaded result, the TokenFactor is 14483 // our new chain. 14484 DCI.CombineTo(N, Perm, TF); 14485 return SDValue(N, 0); 14486 } 14487 } 14488 break; 14489 case ISD::INTRINSIC_WO_CHAIN: { 14490 bool isLittleEndian = Subtarget.isLittleEndian(); 14491 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14492 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14493 : Intrinsic::ppc_altivec_lvsl); 14494 if ((IID == Intr || 14495 IID == Intrinsic::ppc_qpx_qvlpcld || 14496 IID == Intrinsic::ppc_qpx_qvlpcls) && 14497 N->getOperand(1)->getOpcode() == ISD::ADD) { 14498 SDValue Add = N->getOperand(1); 14499 14500 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14501 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14502 14503 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14504 APInt::getAllOnesValue(Bits /* alignment */) 14505 .zext(Add.getScalarValueSizeInBits()))) { 14506 SDNode *BasePtr = Add->getOperand(0).getNode(); 14507 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14508 UE = BasePtr->use_end(); 14509 UI != UE; ++UI) { 14510 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14511 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14512 // We've found another LVSL/LVSR, and this address is an aligned 14513 // multiple of that one. The results will be the same, so use the 14514 // one we've just found instead. 14515 14516 return SDValue(*UI, 0); 14517 } 14518 } 14519 } 14520 14521 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14522 SDNode *BasePtr = Add->getOperand(0).getNode(); 14523 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14524 UE = BasePtr->use_end(); UI != UE; ++UI) { 14525 if (UI->getOpcode() == ISD::ADD && 14526 isa<ConstantSDNode>(UI->getOperand(1)) && 14527 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14528 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14529 (1ULL << Bits) == 0) { 14530 SDNode *OtherAdd = *UI; 14531 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14532 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14533 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14534 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14535 return SDValue(*VI, 0); 14536 } 14537 } 14538 } 14539 } 14540 } 14541 } 14542 14543 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14544 // Expose the vabsduw/h/b opportunity for down stream 14545 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14546 (IID == Intrinsic::ppc_altivec_vmaxsw || 14547 IID == Intrinsic::ppc_altivec_vmaxsh || 14548 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14549 SDValue V1 = N->getOperand(1); 14550 SDValue V2 = N->getOperand(2); 14551 if ((V1.getSimpleValueType() == MVT::v4i32 || 14552 V1.getSimpleValueType() == MVT::v8i16 || 14553 V1.getSimpleValueType() == MVT::v16i8) && 14554 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14555 // (0-a, a) 14556 if (V1.getOpcode() == ISD::SUB && 14557 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14558 V1.getOperand(1) == V2) { 14559 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14560 } 14561 // (a, 0-a) 14562 if (V2.getOpcode() == ISD::SUB && 14563 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14564 V2.getOperand(1) == V1) { 14565 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14566 } 14567 // (x-y, y-x) 14568 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14569 V1.getOperand(0) == V2.getOperand(1) && 14570 V1.getOperand(1) == V2.getOperand(0)) { 14571 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14572 } 14573 } 14574 } 14575 } 14576 14577 break; 14578 case ISD::INTRINSIC_W_CHAIN: 14579 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14580 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14581 if (Subtarget.needsSwapsForVSXMemOps()) { 14582 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14583 default: 14584 break; 14585 case Intrinsic::ppc_vsx_lxvw4x: 14586 case Intrinsic::ppc_vsx_lxvd2x: 14587 return expandVSXLoadForLE(N, DCI); 14588 } 14589 } 14590 break; 14591 case ISD::INTRINSIC_VOID: 14592 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14593 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14594 if (Subtarget.needsSwapsForVSXMemOps()) { 14595 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14596 default: 14597 break; 14598 case Intrinsic::ppc_vsx_stxvw4x: 14599 case Intrinsic::ppc_vsx_stxvd2x: 14600 return expandVSXStoreForLE(N, DCI); 14601 } 14602 } 14603 break; 14604 case ISD::BSWAP: 14605 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14606 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14607 N->getOperand(0).hasOneUse() && 14608 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14609 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14610 N->getValueType(0) == MVT::i64))) { 14611 SDValue Load = N->getOperand(0); 14612 LoadSDNode *LD = cast<LoadSDNode>(Load); 14613 // Create the byte-swapping load. 14614 SDValue Ops[] = { 14615 LD->getChain(), // Chain 14616 LD->getBasePtr(), // Ptr 14617 DAG.getValueType(N->getValueType(0)) // VT 14618 }; 14619 SDValue BSLoad = 14620 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14621 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14622 MVT::i64 : MVT::i32, MVT::Other), 14623 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14624 14625 // If this is an i16 load, insert the truncate. 14626 SDValue ResVal = BSLoad; 14627 if (N->getValueType(0) == MVT::i16) 14628 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14629 14630 // First, combine the bswap away. This makes the value produced by the 14631 // load dead. 14632 DCI.CombineTo(N, ResVal); 14633 14634 // Next, combine the load away, we give it a bogus result value but a real 14635 // chain result. The result value is dead because the bswap is dead. 14636 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14637 14638 // Return N so it doesn't get rechecked! 14639 return SDValue(N, 0); 14640 } 14641 break; 14642 case PPCISD::VCMP: 14643 // If a VCMPo node already exists with exactly the same operands as this 14644 // node, use its result instead of this node (VCMPo computes both a CR6 and 14645 // a normal output). 14646 // 14647 if (!N->getOperand(0).hasOneUse() && 14648 !N->getOperand(1).hasOneUse() && 14649 !N->getOperand(2).hasOneUse()) { 14650 14651 // Scan all of the users of the LHS, looking for VCMPo's that match. 14652 SDNode *VCMPoNode = nullptr; 14653 14654 SDNode *LHSN = N->getOperand(0).getNode(); 14655 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14656 UI != E; ++UI) 14657 if (UI->getOpcode() == PPCISD::VCMPo && 14658 UI->getOperand(1) == N->getOperand(1) && 14659 UI->getOperand(2) == N->getOperand(2) && 14660 UI->getOperand(0) == N->getOperand(0)) { 14661 VCMPoNode = *UI; 14662 break; 14663 } 14664 14665 // If there is no VCMPo node, or if the flag value has a single use, don't 14666 // transform this. 14667 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14668 break; 14669 14670 // Look at the (necessarily single) use of the flag value. If it has a 14671 // chain, this transformation is more complex. Note that multiple things 14672 // could use the value result, which we should ignore. 14673 SDNode *FlagUser = nullptr; 14674 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14675 FlagUser == nullptr; ++UI) { 14676 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14677 SDNode *User = *UI; 14678 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14679 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14680 FlagUser = User; 14681 break; 14682 } 14683 } 14684 } 14685 14686 // If the user is a MFOCRF instruction, we know this is safe. 14687 // Otherwise we give up for right now. 14688 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14689 return SDValue(VCMPoNode, 0); 14690 } 14691 break; 14692 case ISD::BRCOND: { 14693 SDValue Cond = N->getOperand(1); 14694 SDValue Target = N->getOperand(2); 14695 14696 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14697 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14698 Intrinsic::loop_decrement) { 14699 14700 // We now need to make the intrinsic dead (it cannot be instruction 14701 // selected). 14702 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14703 assert(Cond.getNode()->hasOneUse() && 14704 "Counter decrement has more than one use"); 14705 14706 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14707 N->getOperand(0), Target); 14708 } 14709 } 14710 break; 14711 case ISD::BR_CC: { 14712 // If this is a branch on an altivec predicate comparison, lower this so 14713 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14714 // lowering is done pre-legalize, because the legalizer lowers the predicate 14715 // compare down to code that is difficult to reassemble. 14716 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14717 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14718 14719 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14720 // value. If so, pass-through the AND to get to the intrinsic. 14721 if (LHS.getOpcode() == ISD::AND && 14722 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14723 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14724 Intrinsic::loop_decrement && 14725 isa<ConstantSDNode>(LHS.getOperand(1)) && 14726 !isNullConstant(LHS.getOperand(1))) 14727 LHS = LHS.getOperand(0); 14728 14729 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14730 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14731 Intrinsic::loop_decrement && 14732 isa<ConstantSDNode>(RHS)) { 14733 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14734 "Counter decrement comparison is not EQ or NE"); 14735 14736 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14737 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14738 (CC == ISD::SETNE && !Val); 14739 14740 // We now need to make the intrinsic dead (it cannot be instruction 14741 // selected). 14742 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14743 assert(LHS.getNode()->hasOneUse() && 14744 "Counter decrement has more than one use"); 14745 14746 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14747 N->getOperand(0), N->getOperand(4)); 14748 } 14749 14750 int CompareOpc; 14751 bool isDot; 14752 14753 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14754 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14755 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14756 assert(isDot && "Can't compare against a vector result!"); 14757 14758 // If this is a comparison against something other than 0/1, then we know 14759 // that the condition is never/always true. 14760 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14761 if (Val != 0 && Val != 1) { 14762 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14763 return N->getOperand(0); 14764 // Always !=, turn it into an unconditional branch. 14765 return DAG.getNode(ISD::BR, dl, MVT::Other, 14766 N->getOperand(0), N->getOperand(4)); 14767 } 14768 14769 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14770 14771 // Create the PPCISD altivec 'dot' comparison node. 14772 SDValue Ops[] = { 14773 LHS.getOperand(2), // LHS of compare 14774 LHS.getOperand(3), // RHS of compare 14775 DAG.getConstant(CompareOpc, dl, MVT::i32) 14776 }; 14777 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14778 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14779 14780 // Unpack the result based on how the target uses it. 14781 PPC::Predicate CompOpc; 14782 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14783 default: // Can't happen, don't crash on invalid number though. 14784 case 0: // Branch on the value of the EQ bit of CR6. 14785 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14786 break; 14787 case 1: // Branch on the inverted value of the EQ bit of CR6. 14788 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14789 break; 14790 case 2: // Branch on the value of the LT bit of CR6. 14791 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14792 break; 14793 case 3: // Branch on the inverted value of the LT bit of CR6. 14794 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14795 break; 14796 } 14797 14798 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14799 DAG.getConstant(CompOpc, dl, MVT::i32), 14800 DAG.getRegister(PPC::CR6, MVT::i32), 14801 N->getOperand(4), CompNode.getValue(1)); 14802 } 14803 break; 14804 } 14805 case ISD::BUILD_VECTOR: 14806 return DAGCombineBuildVector(N, DCI); 14807 case ISD::ABS: 14808 return combineABS(N, DCI); 14809 case ISD::VSELECT: 14810 return combineVSelect(N, DCI); 14811 } 14812 14813 return SDValue(); 14814 } 14815 14816 SDValue 14817 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14818 SelectionDAG &DAG, 14819 SmallVectorImpl<SDNode *> &Created) const { 14820 // fold (sdiv X, pow2) 14821 EVT VT = N->getValueType(0); 14822 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14823 return SDValue(); 14824 if ((VT != MVT::i32 && VT != MVT::i64) || 14825 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14826 return SDValue(); 14827 14828 SDLoc DL(N); 14829 SDValue N0 = N->getOperand(0); 14830 14831 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14832 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14833 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14834 14835 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14836 Created.push_back(Op.getNode()); 14837 14838 if (IsNegPow2) { 14839 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14840 Created.push_back(Op.getNode()); 14841 } 14842 14843 return Op; 14844 } 14845 14846 //===----------------------------------------------------------------------===// 14847 // Inline Assembly Support 14848 //===----------------------------------------------------------------------===// 14849 14850 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14851 KnownBits &Known, 14852 const APInt &DemandedElts, 14853 const SelectionDAG &DAG, 14854 unsigned Depth) const { 14855 Known.resetAll(); 14856 switch (Op.getOpcode()) { 14857 default: break; 14858 case PPCISD::LBRX: { 14859 // lhbrx is known to have the top bits cleared out. 14860 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14861 Known.Zero = 0xFFFF0000; 14862 break; 14863 } 14864 case ISD::INTRINSIC_WO_CHAIN: { 14865 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14866 default: break; 14867 case Intrinsic::ppc_altivec_vcmpbfp_p: 14868 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14869 case Intrinsic::ppc_altivec_vcmpequb_p: 14870 case Intrinsic::ppc_altivec_vcmpequh_p: 14871 case Intrinsic::ppc_altivec_vcmpequw_p: 14872 case Intrinsic::ppc_altivec_vcmpequd_p: 14873 case Intrinsic::ppc_altivec_vcmpgefp_p: 14874 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14875 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14876 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14877 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14878 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14879 case Intrinsic::ppc_altivec_vcmpgtub_p: 14880 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14881 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14882 case Intrinsic::ppc_altivec_vcmpgtud_p: 14883 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14884 break; 14885 } 14886 } 14887 } 14888 } 14889 14890 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14891 switch (Subtarget.getCPUDirective()) { 14892 default: break; 14893 case PPC::DIR_970: 14894 case PPC::DIR_PWR4: 14895 case PPC::DIR_PWR5: 14896 case PPC::DIR_PWR5X: 14897 case PPC::DIR_PWR6: 14898 case PPC::DIR_PWR6X: 14899 case PPC::DIR_PWR7: 14900 case PPC::DIR_PWR8: 14901 case PPC::DIR_PWR9: 14902 case PPC::DIR_PWR_FUTURE: { 14903 if (!ML) 14904 break; 14905 14906 if (!DisableInnermostLoopAlign32) { 14907 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14908 // so that we can decrease cache misses and branch-prediction misses. 14909 // Actual alignment of the loop will depend on the hotness check and other 14910 // logic in alignBlocks. 14911 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14912 return Align(32); 14913 } 14914 14915 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14916 14917 // For small loops (between 5 and 8 instructions), align to a 32-byte 14918 // boundary so that the entire loop fits in one instruction-cache line. 14919 uint64_t LoopSize = 0; 14920 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14921 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14922 LoopSize += TII->getInstSizeInBytes(*J); 14923 if (LoopSize > 32) 14924 break; 14925 } 14926 14927 if (LoopSize > 16 && LoopSize <= 32) 14928 return Align(32); 14929 14930 break; 14931 } 14932 } 14933 14934 return TargetLowering::getPrefLoopAlignment(ML); 14935 } 14936 14937 /// getConstraintType - Given a constraint, return the type of 14938 /// constraint it is for this target. 14939 PPCTargetLowering::ConstraintType 14940 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14941 if (Constraint.size() == 1) { 14942 switch (Constraint[0]) { 14943 default: break; 14944 case 'b': 14945 case 'r': 14946 case 'f': 14947 case 'd': 14948 case 'v': 14949 case 'y': 14950 return C_RegisterClass; 14951 case 'Z': 14952 // FIXME: While Z does indicate a memory constraint, it specifically 14953 // indicates an r+r address (used in conjunction with the 'y' modifier 14954 // in the replacement string). Currently, we're forcing the base 14955 // register to be r0 in the asm printer (which is interpreted as zero) 14956 // and forming the complete address in the second register. This is 14957 // suboptimal. 14958 return C_Memory; 14959 } 14960 } else if (Constraint == "wc") { // individual CR bits. 14961 return C_RegisterClass; 14962 } else if (Constraint == "wa" || Constraint == "wd" || 14963 Constraint == "wf" || Constraint == "ws" || 14964 Constraint == "wi" || Constraint == "ww") { 14965 return C_RegisterClass; // VSX registers. 14966 } 14967 return TargetLowering::getConstraintType(Constraint); 14968 } 14969 14970 /// Examine constraint type and operand type and determine a weight value. 14971 /// This object must already have been set up with the operand type 14972 /// and the current alternative constraint selected. 14973 TargetLowering::ConstraintWeight 14974 PPCTargetLowering::getSingleConstraintMatchWeight( 14975 AsmOperandInfo &info, const char *constraint) const { 14976 ConstraintWeight weight = CW_Invalid; 14977 Value *CallOperandVal = info.CallOperandVal; 14978 // If we don't have a value, we can't do a match, 14979 // but allow it at the lowest weight. 14980 if (!CallOperandVal) 14981 return CW_Default; 14982 Type *type = CallOperandVal->getType(); 14983 14984 // Look at the constraint type. 14985 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14986 return CW_Register; // an individual CR bit. 14987 else if ((StringRef(constraint) == "wa" || 14988 StringRef(constraint) == "wd" || 14989 StringRef(constraint) == "wf") && 14990 type->isVectorTy()) 14991 return CW_Register; 14992 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14993 return CW_Register; // just hold 64-bit integers data. 14994 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14995 return CW_Register; 14996 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14997 return CW_Register; 14998 14999 switch (*constraint) { 15000 default: 15001 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15002 break; 15003 case 'b': 15004 if (type->isIntegerTy()) 15005 weight = CW_Register; 15006 break; 15007 case 'f': 15008 if (type->isFloatTy()) 15009 weight = CW_Register; 15010 break; 15011 case 'd': 15012 if (type->isDoubleTy()) 15013 weight = CW_Register; 15014 break; 15015 case 'v': 15016 if (type->isVectorTy()) 15017 weight = CW_Register; 15018 break; 15019 case 'y': 15020 weight = CW_Register; 15021 break; 15022 case 'Z': 15023 weight = CW_Memory; 15024 break; 15025 } 15026 return weight; 15027 } 15028 15029 std::pair<unsigned, const TargetRegisterClass *> 15030 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15031 StringRef Constraint, 15032 MVT VT) const { 15033 if (Constraint.size() == 1) { 15034 // GCC RS6000 Constraint Letters 15035 switch (Constraint[0]) { 15036 case 'b': // R1-R31 15037 if (VT == MVT::i64 && Subtarget.isPPC64()) 15038 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15039 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15040 case 'r': // R0-R31 15041 if (VT == MVT::i64 && Subtarget.isPPC64()) 15042 return std::make_pair(0U, &PPC::G8RCRegClass); 15043 return std::make_pair(0U, &PPC::GPRCRegClass); 15044 // 'd' and 'f' constraints are both defined to be "the floating point 15045 // registers", where one is for 32-bit and the other for 64-bit. We don't 15046 // really care overly much here so just give them all the same reg classes. 15047 case 'd': 15048 case 'f': 15049 if (Subtarget.hasSPE()) { 15050 if (VT == MVT::f32 || VT == MVT::i32) 15051 return std::make_pair(0U, &PPC::GPRCRegClass); 15052 if (VT == MVT::f64 || VT == MVT::i64) 15053 return std::make_pair(0U, &PPC::SPERCRegClass); 15054 } else { 15055 if (VT == MVT::f32 || VT == MVT::i32) 15056 return std::make_pair(0U, &PPC::F4RCRegClass); 15057 if (VT == MVT::f64 || VT == MVT::i64) 15058 return std::make_pair(0U, &PPC::F8RCRegClass); 15059 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15060 return std::make_pair(0U, &PPC::QFRCRegClass); 15061 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15062 return std::make_pair(0U, &PPC::QSRCRegClass); 15063 } 15064 break; 15065 case 'v': 15066 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15067 return std::make_pair(0U, &PPC::QFRCRegClass); 15068 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15069 return std::make_pair(0U, &PPC::QSRCRegClass); 15070 if (Subtarget.hasAltivec()) 15071 return std::make_pair(0U, &PPC::VRRCRegClass); 15072 break; 15073 case 'y': // crrc 15074 return std::make_pair(0U, &PPC::CRRCRegClass); 15075 } 15076 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15077 // An individual CR bit. 15078 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15079 } else if ((Constraint == "wa" || Constraint == "wd" || 15080 Constraint == "wf" || Constraint == "wi") && 15081 Subtarget.hasVSX()) { 15082 return std::make_pair(0U, &PPC::VSRCRegClass); 15083 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15084 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15085 return std::make_pair(0U, &PPC::VSSRCRegClass); 15086 else 15087 return std::make_pair(0U, &PPC::VSFRCRegClass); 15088 } 15089 15090 // If we name a VSX register, we can't defer to the base class because it 15091 // will not recognize the correct register (their names will be VSL{0-31} 15092 // and V{0-31} so they won't match). So we match them here. 15093 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15094 int VSNum = atoi(Constraint.data() + 3); 15095 assert(VSNum >= 0 && VSNum <= 63 && 15096 "Attempted to access a vsr out of range"); 15097 if (VSNum < 32) 15098 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15099 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15100 } 15101 std::pair<unsigned, const TargetRegisterClass *> R = 15102 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15103 15104 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15105 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15106 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15107 // register. 15108 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15109 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15110 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15111 PPC::GPRCRegClass.contains(R.first)) 15112 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15113 PPC::sub_32, &PPC::G8RCRegClass), 15114 &PPC::G8RCRegClass); 15115 15116 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15117 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15118 R.first = PPC::CR0; 15119 R.second = &PPC::CRRCRegClass; 15120 } 15121 15122 return R; 15123 } 15124 15125 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15126 /// vector. If it is invalid, don't add anything to Ops. 15127 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15128 std::string &Constraint, 15129 std::vector<SDValue>&Ops, 15130 SelectionDAG &DAG) const { 15131 SDValue Result; 15132 15133 // Only support length 1 constraints. 15134 if (Constraint.length() > 1) return; 15135 15136 char Letter = Constraint[0]; 15137 switch (Letter) { 15138 default: break; 15139 case 'I': 15140 case 'J': 15141 case 'K': 15142 case 'L': 15143 case 'M': 15144 case 'N': 15145 case 'O': 15146 case 'P': { 15147 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15148 if (!CST) return; // Must be an immediate to match. 15149 SDLoc dl(Op); 15150 int64_t Value = CST->getSExtValue(); 15151 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15152 // numbers are printed as such. 15153 switch (Letter) { 15154 default: llvm_unreachable("Unknown constraint letter!"); 15155 case 'I': // "I" is a signed 16-bit constant. 15156 if (isInt<16>(Value)) 15157 Result = DAG.getTargetConstant(Value, dl, TCVT); 15158 break; 15159 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15160 if (isShiftedUInt<16, 16>(Value)) 15161 Result = DAG.getTargetConstant(Value, dl, TCVT); 15162 break; 15163 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15164 if (isShiftedInt<16, 16>(Value)) 15165 Result = DAG.getTargetConstant(Value, dl, TCVT); 15166 break; 15167 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15168 if (isUInt<16>(Value)) 15169 Result = DAG.getTargetConstant(Value, dl, TCVT); 15170 break; 15171 case 'M': // "M" is a constant that is greater than 31. 15172 if (Value > 31) 15173 Result = DAG.getTargetConstant(Value, dl, TCVT); 15174 break; 15175 case 'N': // "N" is a positive constant that is an exact power of two. 15176 if (Value > 0 && isPowerOf2_64(Value)) 15177 Result = DAG.getTargetConstant(Value, dl, TCVT); 15178 break; 15179 case 'O': // "O" is the constant zero. 15180 if (Value == 0) 15181 Result = DAG.getTargetConstant(Value, dl, TCVT); 15182 break; 15183 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15184 if (isInt<16>(-Value)) 15185 Result = DAG.getTargetConstant(Value, dl, TCVT); 15186 break; 15187 } 15188 break; 15189 } 15190 } 15191 15192 if (Result.getNode()) { 15193 Ops.push_back(Result); 15194 return; 15195 } 15196 15197 // Handle standard constraint letters. 15198 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15199 } 15200 15201 // isLegalAddressingMode - Return true if the addressing mode represented 15202 // by AM is legal for this target, for a load/store of the specified type. 15203 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15204 const AddrMode &AM, Type *Ty, 15205 unsigned AS, Instruction *I) const { 15206 // PPC does not allow r+i addressing modes for vectors! 15207 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15208 return false; 15209 15210 // PPC allows a sign-extended 16-bit immediate field. 15211 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15212 return false; 15213 15214 // No global is ever allowed as a base. 15215 if (AM.BaseGV) 15216 return false; 15217 15218 // PPC only support r+r, 15219 switch (AM.Scale) { 15220 case 0: // "r+i" or just "i", depending on HasBaseReg. 15221 break; 15222 case 1: 15223 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15224 return false; 15225 // Otherwise we have r+r or r+i. 15226 break; 15227 case 2: 15228 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15229 return false; 15230 // Allow 2*r as r+r. 15231 break; 15232 default: 15233 // No other scales are supported. 15234 return false; 15235 } 15236 15237 return true; 15238 } 15239 15240 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15241 SelectionDAG &DAG) const { 15242 MachineFunction &MF = DAG.getMachineFunction(); 15243 MachineFrameInfo &MFI = MF.getFrameInfo(); 15244 MFI.setReturnAddressIsTaken(true); 15245 15246 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15247 return SDValue(); 15248 15249 SDLoc dl(Op); 15250 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15251 15252 // Make sure the function does not optimize away the store of the RA to 15253 // the stack. 15254 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15255 FuncInfo->setLRStoreRequired(); 15256 bool isPPC64 = Subtarget.isPPC64(); 15257 auto PtrVT = getPointerTy(MF.getDataLayout()); 15258 15259 if (Depth > 0) { 15260 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15261 SDValue Offset = 15262 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15263 isPPC64 ? MVT::i64 : MVT::i32); 15264 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15265 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15266 MachinePointerInfo()); 15267 } 15268 15269 // Just load the return address off the stack. 15270 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15271 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15272 MachinePointerInfo()); 15273 } 15274 15275 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15276 SelectionDAG &DAG) const { 15277 SDLoc dl(Op); 15278 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15279 15280 MachineFunction &MF = DAG.getMachineFunction(); 15281 MachineFrameInfo &MFI = MF.getFrameInfo(); 15282 MFI.setFrameAddressIsTaken(true); 15283 15284 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15285 bool isPPC64 = PtrVT == MVT::i64; 15286 15287 // Naked functions never have a frame pointer, and so we use r1. For all 15288 // other functions, this decision must be delayed until during PEI. 15289 unsigned FrameReg; 15290 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15291 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15292 else 15293 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15294 15295 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15296 PtrVT); 15297 while (Depth--) 15298 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15299 FrameAddr, MachinePointerInfo()); 15300 return FrameAddr; 15301 } 15302 15303 // FIXME? Maybe this could be a TableGen attribute on some registers and 15304 // this table could be generated automatically from RegInfo. 15305 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15306 const MachineFunction &MF) const { 15307 bool isPPC64 = Subtarget.isPPC64(); 15308 15309 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15310 if (!is64Bit && VT != LLT::scalar(32)) 15311 report_fatal_error("Invalid register global variable type"); 15312 15313 Register Reg = StringSwitch<Register>(RegName) 15314 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15315 .Case("r2", isPPC64 ? Register() : PPC::R2) 15316 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15317 .Default(Register()); 15318 15319 if (Reg) 15320 return Reg; 15321 report_fatal_error("Invalid register name global variable"); 15322 } 15323 15324 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15325 // 32-bit SVR4 ABI access everything as got-indirect. 15326 if (Subtarget.is32BitELFABI()) 15327 return true; 15328 15329 // AIX accesses everything indirectly through the TOC, which is similar to 15330 // the GOT. 15331 if (Subtarget.isAIXABI()) 15332 return true; 15333 15334 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15335 // If it is small or large code model, module locals are accessed 15336 // indirectly by loading their address from .toc/.got. 15337 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15338 return true; 15339 15340 // JumpTable and BlockAddress are accessed as got-indirect. 15341 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15342 return true; 15343 15344 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15345 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15346 15347 return false; 15348 } 15349 15350 bool 15351 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15352 // The PowerPC target isn't yet aware of offsets. 15353 return false; 15354 } 15355 15356 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15357 const CallInst &I, 15358 MachineFunction &MF, 15359 unsigned Intrinsic) const { 15360 switch (Intrinsic) { 15361 case Intrinsic::ppc_qpx_qvlfd: 15362 case Intrinsic::ppc_qpx_qvlfs: 15363 case Intrinsic::ppc_qpx_qvlfcd: 15364 case Intrinsic::ppc_qpx_qvlfcs: 15365 case Intrinsic::ppc_qpx_qvlfiwa: 15366 case Intrinsic::ppc_qpx_qvlfiwz: 15367 case Intrinsic::ppc_altivec_lvx: 15368 case Intrinsic::ppc_altivec_lvxl: 15369 case Intrinsic::ppc_altivec_lvebx: 15370 case Intrinsic::ppc_altivec_lvehx: 15371 case Intrinsic::ppc_altivec_lvewx: 15372 case Intrinsic::ppc_vsx_lxvd2x: 15373 case Intrinsic::ppc_vsx_lxvw4x: { 15374 EVT VT; 15375 switch (Intrinsic) { 15376 case Intrinsic::ppc_altivec_lvebx: 15377 VT = MVT::i8; 15378 break; 15379 case Intrinsic::ppc_altivec_lvehx: 15380 VT = MVT::i16; 15381 break; 15382 case Intrinsic::ppc_altivec_lvewx: 15383 VT = MVT::i32; 15384 break; 15385 case Intrinsic::ppc_vsx_lxvd2x: 15386 VT = MVT::v2f64; 15387 break; 15388 case Intrinsic::ppc_qpx_qvlfd: 15389 VT = MVT::v4f64; 15390 break; 15391 case Intrinsic::ppc_qpx_qvlfs: 15392 VT = MVT::v4f32; 15393 break; 15394 case Intrinsic::ppc_qpx_qvlfcd: 15395 VT = MVT::v2f64; 15396 break; 15397 case Intrinsic::ppc_qpx_qvlfcs: 15398 VT = MVT::v2f32; 15399 break; 15400 default: 15401 VT = MVT::v4i32; 15402 break; 15403 } 15404 15405 Info.opc = ISD::INTRINSIC_W_CHAIN; 15406 Info.memVT = VT; 15407 Info.ptrVal = I.getArgOperand(0); 15408 Info.offset = -VT.getStoreSize()+1; 15409 Info.size = 2*VT.getStoreSize()-1; 15410 Info.align = Align(1); 15411 Info.flags = MachineMemOperand::MOLoad; 15412 return true; 15413 } 15414 case Intrinsic::ppc_qpx_qvlfda: 15415 case Intrinsic::ppc_qpx_qvlfsa: 15416 case Intrinsic::ppc_qpx_qvlfcda: 15417 case Intrinsic::ppc_qpx_qvlfcsa: 15418 case Intrinsic::ppc_qpx_qvlfiwaa: 15419 case Intrinsic::ppc_qpx_qvlfiwza: { 15420 EVT VT; 15421 switch (Intrinsic) { 15422 case Intrinsic::ppc_qpx_qvlfda: 15423 VT = MVT::v4f64; 15424 break; 15425 case Intrinsic::ppc_qpx_qvlfsa: 15426 VT = MVT::v4f32; 15427 break; 15428 case Intrinsic::ppc_qpx_qvlfcda: 15429 VT = MVT::v2f64; 15430 break; 15431 case Intrinsic::ppc_qpx_qvlfcsa: 15432 VT = MVT::v2f32; 15433 break; 15434 default: 15435 VT = MVT::v4i32; 15436 break; 15437 } 15438 15439 Info.opc = ISD::INTRINSIC_W_CHAIN; 15440 Info.memVT = VT; 15441 Info.ptrVal = I.getArgOperand(0); 15442 Info.offset = 0; 15443 Info.size = VT.getStoreSize(); 15444 Info.align = Align(1); 15445 Info.flags = MachineMemOperand::MOLoad; 15446 return true; 15447 } 15448 case Intrinsic::ppc_qpx_qvstfd: 15449 case Intrinsic::ppc_qpx_qvstfs: 15450 case Intrinsic::ppc_qpx_qvstfcd: 15451 case Intrinsic::ppc_qpx_qvstfcs: 15452 case Intrinsic::ppc_qpx_qvstfiw: 15453 case Intrinsic::ppc_altivec_stvx: 15454 case Intrinsic::ppc_altivec_stvxl: 15455 case Intrinsic::ppc_altivec_stvebx: 15456 case Intrinsic::ppc_altivec_stvehx: 15457 case Intrinsic::ppc_altivec_stvewx: 15458 case Intrinsic::ppc_vsx_stxvd2x: 15459 case Intrinsic::ppc_vsx_stxvw4x: { 15460 EVT VT; 15461 switch (Intrinsic) { 15462 case Intrinsic::ppc_altivec_stvebx: 15463 VT = MVT::i8; 15464 break; 15465 case Intrinsic::ppc_altivec_stvehx: 15466 VT = MVT::i16; 15467 break; 15468 case Intrinsic::ppc_altivec_stvewx: 15469 VT = MVT::i32; 15470 break; 15471 case Intrinsic::ppc_vsx_stxvd2x: 15472 VT = MVT::v2f64; 15473 break; 15474 case Intrinsic::ppc_qpx_qvstfd: 15475 VT = MVT::v4f64; 15476 break; 15477 case Intrinsic::ppc_qpx_qvstfs: 15478 VT = MVT::v4f32; 15479 break; 15480 case Intrinsic::ppc_qpx_qvstfcd: 15481 VT = MVT::v2f64; 15482 break; 15483 case Intrinsic::ppc_qpx_qvstfcs: 15484 VT = MVT::v2f32; 15485 break; 15486 default: 15487 VT = MVT::v4i32; 15488 break; 15489 } 15490 15491 Info.opc = ISD::INTRINSIC_VOID; 15492 Info.memVT = VT; 15493 Info.ptrVal = I.getArgOperand(1); 15494 Info.offset = -VT.getStoreSize()+1; 15495 Info.size = 2*VT.getStoreSize()-1; 15496 Info.align = Align(1); 15497 Info.flags = MachineMemOperand::MOStore; 15498 return true; 15499 } 15500 case Intrinsic::ppc_qpx_qvstfda: 15501 case Intrinsic::ppc_qpx_qvstfsa: 15502 case Intrinsic::ppc_qpx_qvstfcda: 15503 case Intrinsic::ppc_qpx_qvstfcsa: 15504 case Intrinsic::ppc_qpx_qvstfiwa: { 15505 EVT VT; 15506 switch (Intrinsic) { 15507 case Intrinsic::ppc_qpx_qvstfda: 15508 VT = MVT::v4f64; 15509 break; 15510 case Intrinsic::ppc_qpx_qvstfsa: 15511 VT = MVT::v4f32; 15512 break; 15513 case Intrinsic::ppc_qpx_qvstfcda: 15514 VT = MVT::v2f64; 15515 break; 15516 case Intrinsic::ppc_qpx_qvstfcsa: 15517 VT = MVT::v2f32; 15518 break; 15519 default: 15520 VT = MVT::v4i32; 15521 break; 15522 } 15523 15524 Info.opc = ISD::INTRINSIC_VOID; 15525 Info.memVT = VT; 15526 Info.ptrVal = I.getArgOperand(1); 15527 Info.offset = 0; 15528 Info.size = VT.getStoreSize(); 15529 Info.align = Align(1); 15530 Info.flags = MachineMemOperand::MOStore; 15531 return true; 15532 } 15533 default: 15534 break; 15535 } 15536 15537 return false; 15538 } 15539 15540 /// It returns EVT::Other if the type should be determined using generic 15541 /// target-independent logic. 15542 EVT PPCTargetLowering::getOptimalMemOpType( 15543 const MemOp &Op, const AttributeList &FuncAttributes) const { 15544 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15545 // When expanding a memset, require at least two QPX instructions to cover 15546 // the cost of loading the value to be stored from the constant pool. 15547 if (Subtarget.hasQPX() && Op.size() >= 32 && 15548 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15549 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15550 return MVT::v4f64; 15551 } 15552 15553 // We should use Altivec/VSX loads and stores when available. For unaligned 15554 // addresses, unaligned VSX loads are only fast starting with the P8. 15555 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15556 (Op.isAligned(Align(16)) || 15557 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15558 return MVT::v4i32; 15559 } 15560 15561 if (Subtarget.isPPC64()) { 15562 return MVT::i64; 15563 } 15564 15565 return MVT::i32; 15566 } 15567 15568 /// Returns true if it is beneficial to convert a load of a constant 15569 /// to just the constant itself. 15570 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15571 Type *Ty) const { 15572 assert(Ty->isIntegerTy()); 15573 15574 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15575 return !(BitSize == 0 || BitSize > 64); 15576 } 15577 15578 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15579 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15580 return false; 15581 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15582 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15583 return NumBits1 == 64 && NumBits2 == 32; 15584 } 15585 15586 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15587 if (!VT1.isInteger() || !VT2.isInteger()) 15588 return false; 15589 unsigned NumBits1 = VT1.getSizeInBits(); 15590 unsigned NumBits2 = VT2.getSizeInBits(); 15591 return NumBits1 == 64 && NumBits2 == 32; 15592 } 15593 15594 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15595 // Generally speaking, zexts are not free, but they are free when they can be 15596 // folded with other operations. 15597 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15598 EVT MemVT = LD->getMemoryVT(); 15599 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15600 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15601 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15602 LD->getExtensionType() == ISD::ZEXTLOAD)) 15603 return true; 15604 } 15605 15606 // FIXME: Add other cases... 15607 // - 32-bit shifts with a zext to i64 15608 // - zext after ctlz, bswap, etc. 15609 // - zext after and by a constant mask 15610 15611 return TargetLowering::isZExtFree(Val, VT2); 15612 } 15613 15614 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15615 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15616 "invalid fpext types"); 15617 // Extending to float128 is not free. 15618 if (DestVT == MVT::f128) 15619 return false; 15620 return true; 15621 } 15622 15623 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15624 return isInt<16>(Imm) || isUInt<16>(Imm); 15625 } 15626 15627 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15628 return isInt<16>(Imm) || isUInt<16>(Imm); 15629 } 15630 15631 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15632 unsigned, 15633 unsigned, 15634 MachineMemOperand::Flags, 15635 bool *Fast) const { 15636 if (DisablePPCUnaligned) 15637 return false; 15638 15639 // PowerPC supports unaligned memory access for simple non-vector types. 15640 // Although accessing unaligned addresses is not as efficient as accessing 15641 // aligned addresses, it is generally more efficient than manual expansion, 15642 // and generally only traps for software emulation when crossing page 15643 // boundaries. 15644 15645 if (!VT.isSimple()) 15646 return false; 15647 15648 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15649 return false; 15650 15651 if (VT.getSimpleVT().isVector()) { 15652 if (Subtarget.hasVSX()) { 15653 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15654 VT != MVT::v4f32 && VT != MVT::v4i32) 15655 return false; 15656 } else { 15657 return false; 15658 } 15659 } 15660 15661 if (VT == MVT::ppcf128) 15662 return false; 15663 15664 if (Fast) 15665 *Fast = true; 15666 15667 return true; 15668 } 15669 15670 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15671 EVT VT) const { 15672 return isFMAFasterThanFMulAndFAdd( 15673 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15674 } 15675 15676 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15677 Type *Ty) const { 15678 switch (Ty->getScalarType()->getTypeID()) { 15679 case Type::FloatTyID: 15680 case Type::DoubleTyID: 15681 return true; 15682 case Type::FP128TyID: 15683 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15684 default: 15685 return false; 15686 } 15687 } 15688 15689 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15690 // FIXME: add more patterns which are profitable to hoist. 15691 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15692 if (I->getOpcode() != Instruction::FMul) 15693 return true; 15694 15695 if (!I->hasOneUse()) 15696 return true; 15697 15698 Instruction *User = I->user_back(); 15699 assert(User && "A single use instruction with no uses."); 15700 15701 if (User->getOpcode() != Instruction::FSub && 15702 User->getOpcode() != Instruction::FAdd) 15703 return true; 15704 15705 const TargetOptions &Options = getTargetMachine().Options; 15706 const Function *F = I->getFunction(); 15707 const DataLayout &DL = F->getParent()->getDataLayout(); 15708 Type *Ty = User->getOperand(0)->getType(); 15709 15710 return !( 15711 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15712 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15713 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15714 } 15715 15716 const MCPhysReg * 15717 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15718 // LR is a callee-save register, but we must treat it as clobbered by any call 15719 // site. Hence we include LR in the scratch registers, which are in turn added 15720 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15721 // to CTR, which is used by any indirect call. 15722 static const MCPhysReg ScratchRegs[] = { 15723 PPC::X12, PPC::LR8, PPC::CTR8, 0 15724 }; 15725 15726 return ScratchRegs; 15727 } 15728 15729 Register PPCTargetLowering::getExceptionPointerRegister( 15730 const Constant *PersonalityFn) const { 15731 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15732 } 15733 15734 Register PPCTargetLowering::getExceptionSelectorRegister( 15735 const Constant *PersonalityFn) const { 15736 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15737 } 15738 15739 bool 15740 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15741 EVT VT , unsigned DefinedValues) const { 15742 if (VT == MVT::v2i64) 15743 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15744 15745 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15746 return true; 15747 15748 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15749 } 15750 15751 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15752 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15753 return TargetLowering::getSchedulingPreference(N); 15754 15755 return Sched::ILP; 15756 } 15757 15758 // Create a fast isel object. 15759 FastISel * 15760 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15761 const TargetLibraryInfo *LibInfo) const { 15762 return PPC::createFastISel(FuncInfo, LibInfo); 15763 } 15764 15765 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15766 if (!Subtarget.isPPC64()) return; 15767 15768 // Update IsSplitCSR in PPCFunctionInfo 15769 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15770 PFI->setIsSplitCSR(true); 15771 } 15772 15773 void PPCTargetLowering::insertCopiesSplitCSR( 15774 MachineBasicBlock *Entry, 15775 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15776 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15777 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15778 if (!IStart) 15779 return; 15780 15781 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15782 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15783 MachineBasicBlock::iterator MBBI = Entry->begin(); 15784 for (const MCPhysReg *I = IStart; *I; ++I) { 15785 const TargetRegisterClass *RC = nullptr; 15786 if (PPC::G8RCRegClass.contains(*I)) 15787 RC = &PPC::G8RCRegClass; 15788 else if (PPC::F8RCRegClass.contains(*I)) 15789 RC = &PPC::F8RCRegClass; 15790 else if (PPC::CRRCRegClass.contains(*I)) 15791 RC = &PPC::CRRCRegClass; 15792 else if (PPC::VRRCRegClass.contains(*I)) 15793 RC = &PPC::VRRCRegClass; 15794 else 15795 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15796 15797 Register NewVR = MRI->createVirtualRegister(RC); 15798 // Create copy from CSR to a virtual register. 15799 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15800 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15801 // nounwind. If we want to generalize this later, we may need to emit 15802 // CFI pseudo-instructions. 15803 assert(Entry->getParent()->getFunction().hasFnAttribute( 15804 Attribute::NoUnwind) && 15805 "Function should be nounwind in insertCopiesSplitCSR!"); 15806 Entry->addLiveIn(*I); 15807 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15808 .addReg(*I); 15809 15810 // Insert the copy-back instructions right before the terminator. 15811 for (auto *Exit : Exits) 15812 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15813 TII->get(TargetOpcode::COPY), *I) 15814 .addReg(NewVR); 15815 } 15816 } 15817 15818 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15819 bool PPCTargetLowering::useLoadStackGuardNode() const { 15820 if (!Subtarget.isTargetLinux()) 15821 return TargetLowering::useLoadStackGuardNode(); 15822 return true; 15823 } 15824 15825 // Override to disable global variable loading on Linux. 15826 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15827 if (!Subtarget.isTargetLinux()) 15828 return TargetLowering::insertSSPDeclarations(M); 15829 } 15830 15831 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15832 bool ForCodeSize) const { 15833 if (!VT.isSimple() || !Subtarget.hasVSX()) 15834 return false; 15835 15836 switch(VT.getSimpleVT().SimpleTy) { 15837 default: 15838 // For FP types that are currently not supported by PPC backend, return 15839 // false. Examples: f16, f80. 15840 return false; 15841 case MVT::f32: 15842 case MVT::f64: 15843 case MVT::ppcf128: 15844 return Imm.isPosZero(); 15845 } 15846 } 15847 15848 // For vector shift operation op, fold 15849 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15850 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15851 SelectionDAG &DAG) { 15852 SDValue N0 = N->getOperand(0); 15853 SDValue N1 = N->getOperand(1); 15854 EVT VT = N0.getValueType(); 15855 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15856 unsigned Opcode = N->getOpcode(); 15857 unsigned TargetOpcode; 15858 15859 switch (Opcode) { 15860 default: 15861 llvm_unreachable("Unexpected shift operation"); 15862 case ISD::SHL: 15863 TargetOpcode = PPCISD::SHL; 15864 break; 15865 case ISD::SRL: 15866 TargetOpcode = PPCISD::SRL; 15867 break; 15868 case ISD::SRA: 15869 TargetOpcode = PPCISD::SRA; 15870 break; 15871 } 15872 15873 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15874 N1->getOpcode() == ISD::AND) 15875 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15876 if (Mask->getZExtValue() == OpSizeInBits - 1) 15877 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15878 15879 return SDValue(); 15880 } 15881 15882 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15883 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15884 return Value; 15885 15886 SDValue N0 = N->getOperand(0); 15887 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15888 if (!Subtarget.isISA3_0() || 15889 N0.getOpcode() != ISD::SIGN_EXTEND || 15890 N0.getOperand(0).getValueType() != MVT::i32 || 15891 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15892 return SDValue(); 15893 15894 // We can't save an operation here if the value is already extended, and 15895 // the existing shift is easier to combine. 15896 SDValue ExtsSrc = N0.getOperand(0); 15897 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15898 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15899 return SDValue(); 15900 15901 SDLoc DL(N0); 15902 SDValue ShiftBy = SDValue(CN1, 0); 15903 // We want the shift amount to be i32 on the extswli, but the shift could 15904 // have an i64. 15905 if (ShiftBy.getValueType() == MVT::i64) 15906 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15907 15908 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15909 ShiftBy); 15910 } 15911 15912 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15913 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15914 return Value; 15915 15916 return SDValue(); 15917 } 15918 15919 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15920 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15921 return Value; 15922 15923 return SDValue(); 15924 } 15925 15926 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15927 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15928 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15929 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15930 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15931 const PPCSubtarget &Subtarget) { 15932 if (!Subtarget.isPPC64()) 15933 return SDValue(); 15934 15935 SDValue LHS = N->getOperand(0); 15936 SDValue RHS = N->getOperand(1); 15937 15938 auto isZextOfCompareWithConstant = [](SDValue Op) { 15939 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15940 Op.getValueType() != MVT::i64) 15941 return false; 15942 15943 SDValue Cmp = Op.getOperand(0); 15944 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15945 Cmp.getOperand(0).getValueType() != MVT::i64) 15946 return false; 15947 15948 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15949 int64_t NegConstant = 0 - Constant->getSExtValue(); 15950 // Due to the limitations of the addi instruction, 15951 // -C is required to be [-32768, 32767]. 15952 return isInt<16>(NegConstant); 15953 } 15954 15955 return false; 15956 }; 15957 15958 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15959 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15960 15961 // If there is a pattern, canonicalize a zext operand to the RHS. 15962 if (LHSHasPattern && !RHSHasPattern) 15963 std::swap(LHS, RHS); 15964 else if (!LHSHasPattern && !RHSHasPattern) 15965 return SDValue(); 15966 15967 SDLoc DL(N); 15968 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15969 SDValue Cmp = RHS.getOperand(0); 15970 SDValue Z = Cmp.getOperand(0); 15971 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15972 15973 assert(Constant && "Constant Should not be a null pointer."); 15974 int64_t NegConstant = 0 - Constant->getSExtValue(); 15975 15976 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15977 default: break; 15978 case ISD::SETNE: { 15979 // when C == 0 15980 // --> addze X, (addic Z, -1).carry 15981 // / 15982 // add X, (zext(setne Z, C))-- 15983 // \ when -32768 <= -C <= 32767 && C != 0 15984 // --> addze X, (addic (addi Z, -C), -1).carry 15985 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15986 DAG.getConstant(NegConstant, DL, MVT::i64)); 15987 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15988 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15989 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15990 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15991 SDValue(Addc.getNode(), 1)); 15992 } 15993 case ISD::SETEQ: { 15994 // when C == 0 15995 // --> addze X, (subfic Z, 0).carry 15996 // / 15997 // add X, (zext(sete Z, C))-- 15998 // \ when -32768 <= -C <= 32767 && C != 0 15999 // --> addze X, (subfic (addi Z, -C), 0).carry 16000 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16001 DAG.getConstant(NegConstant, DL, MVT::i64)); 16002 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16003 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16004 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16005 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16006 SDValue(Subc.getNode(), 1)); 16007 } 16008 } 16009 16010 return SDValue(); 16011 } 16012 16013 // Transform 16014 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16015 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16016 // In this case both C1 and C2 must be known constants. 16017 // C1+C2 must fit into a 34 bit signed integer. 16018 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16019 const PPCSubtarget &Subtarget) { 16020 if (!Subtarget.isUsingPCRelativeCalls()) 16021 return SDValue(); 16022 16023 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16024 // If we find that node try to cast the Global Address and the Constant. 16025 SDValue LHS = N->getOperand(0); 16026 SDValue RHS = N->getOperand(1); 16027 16028 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16029 std::swap(LHS, RHS); 16030 16031 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16032 return SDValue(); 16033 16034 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16035 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16036 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16037 16038 // Check that both casts succeeded. 16039 if (!GSDN || !ConstNode) 16040 return SDValue(); 16041 16042 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16043 SDLoc DL(GSDN); 16044 16045 // The signed int offset needs to fit in 34 bits. 16046 if (!isInt<34>(NewOffset)) 16047 return SDValue(); 16048 16049 // The new global address is a copy of the old global address except 16050 // that it has the updated Offset. 16051 SDValue GA = 16052 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16053 NewOffset, GSDN->getTargetFlags()); 16054 SDValue MatPCRel = 16055 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16056 return MatPCRel; 16057 } 16058 16059 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16060 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16061 return Value; 16062 16063 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16064 return Value; 16065 16066 return SDValue(); 16067 } 16068 16069 // Detect TRUNCATE operations on bitcasts of float128 values. 16070 // What we are looking for here is the situtation where we extract a subset 16071 // of bits from a 128 bit float. 16072 // This can be of two forms: 16073 // 1) BITCAST of f128 feeding TRUNCATE 16074 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16075 // The reason this is required is because we do not have a legal i128 type 16076 // and so we want to prevent having to store the f128 and then reload part 16077 // of it. 16078 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16079 DAGCombinerInfo &DCI) const { 16080 // If we are using CRBits then try that first. 16081 if (Subtarget.useCRBits()) { 16082 // Check if CRBits did anything and return that if it did. 16083 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16084 return CRTruncValue; 16085 } 16086 16087 SDLoc dl(N); 16088 SDValue Op0 = N->getOperand(0); 16089 16090 // Looking for a truncate of i128 to i64. 16091 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16092 return SDValue(); 16093 16094 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16095 16096 // SRL feeding TRUNCATE. 16097 if (Op0.getOpcode() == ISD::SRL) { 16098 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16099 // The right shift has to be by 64 bits. 16100 if (!ConstNode || ConstNode->getZExtValue() != 64) 16101 return SDValue(); 16102 16103 // Switch the element number to extract. 16104 EltToExtract = EltToExtract ? 0 : 1; 16105 // Update Op0 past the SRL. 16106 Op0 = Op0.getOperand(0); 16107 } 16108 16109 // BITCAST feeding a TRUNCATE possibly via SRL. 16110 if (Op0.getOpcode() == ISD::BITCAST && 16111 Op0.getValueType() == MVT::i128 && 16112 Op0.getOperand(0).getValueType() == MVT::f128) { 16113 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16114 return DCI.DAG.getNode( 16115 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16116 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16117 } 16118 return SDValue(); 16119 } 16120 16121 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16122 SelectionDAG &DAG = DCI.DAG; 16123 16124 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16125 if (!ConstOpOrElement) 16126 return SDValue(); 16127 16128 // An imul is usually smaller than the alternative sequence for legal type. 16129 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16130 isOperationLegal(ISD::MUL, N->getValueType(0))) 16131 return SDValue(); 16132 16133 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16134 switch (this->Subtarget.getCPUDirective()) { 16135 default: 16136 // TODO: enhance the condition for subtarget before pwr8 16137 return false; 16138 case PPC::DIR_PWR8: 16139 // type mul add shl 16140 // scalar 4 1 1 16141 // vector 7 2 2 16142 return true; 16143 case PPC::DIR_PWR9: 16144 case PPC::DIR_PWR_FUTURE: 16145 // type mul add shl 16146 // scalar 5 2 2 16147 // vector 7 2 2 16148 16149 // The cycle RATIO of related operations are showed as a table above. 16150 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16151 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16152 // are 4, it is always profitable; but for 3 instrs patterns 16153 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16154 // So we should only do it for vector type. 16155 return IsAddOne && IsNeg ? VT.isVector() : true; 16156 } 16157 }; 16158 16159 EVT VT = N->getValueType(0); 16160 SDLoc DL(N); 16161 16162 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16163 bool IsNeg = MulAmt.isNegative(); 16164 APInt MulAmtAbs = MulAmt.abs(); 16165 16166 if ((MulAmtAbs - 1).isPowerOf2()) { 16167 // (mul x, 2^N + 1) => (add (shl x, N), x) 16168 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16169 16170 if (!IsProfitable(IsNeg, true, VT)) 16171 return SDValue(); 16172 16173 SDValue Op0 = N->getOperand(0); 16174 SDValue Op1 = 16175 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16176 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16177 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16178 16179 if (!IsNeg) 16180 return Res; 16181 16182 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16183 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16184 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16185 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16186 16187 if (!IsProfitable(IsNeg, false, VT)) 16188 return SDValue(); 16189 16190 SDValue Op0 = N->getOperand(0); 16191 SDValue Op1 = 16192 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16193 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16194 16195 if (!IsNeg) 16196 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16197 else 16198 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16199 16200 } else { 16201 return SDValue(); 16202 } 16203 } 16204 16205 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16206 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16207 if (!Subtarget.is64BitELFABI()) 16208 return false; 16209 16210 // If not a tail call then no need to proceed. 16211 if (!CI->isTailCall()) 16212 return false; 16213 16214 // If sibling calls have been disabled and tail-calls aren't guaranteed 16215 // there is no reason to duplicate. 16216 auto &TM = getTargetMachine(); 16217 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16218 return false; 16219 16220 // Can't tail call a function called indirectly, or if it has variadic args. 16221 const Function *Callee = CI->getCalledFunction(); 16222 if (!Callee || Callee->isVarArg()) 16223 return false; 16224 16225 // Make sure the callee and caller calling conventions are eligible for tco. 16226 const Function *Caller = CI->getParent()->getParent(); 16227 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16228 CI->getCallingConv())) 16229 return false; 16230 16231 // If the function is local then we have a good chance at tail-calling it 16232 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16233 } 16234 16235 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16236 if (!Subtarget.hasVSX()) 16237 return false; 16238 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16239 return true; 16240 return VT == MVT::f32 || VT == MVT::f64 || 16241 VT == MVT::v4f32 || VT == MVT::v2f64; 16242 } 16243 16244 bool PPCTargetLowering:: 16245 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16246 const Value *Mask = AndI.getOperand(1); 16247 // If the mask is suitable for andi. or andis. we should sink the and. 16248 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16249 // Can't handle constants wider than 64-bits. 16250 if (CI->getBitWidth() > 64) 16251 return false; 16252 int64_t ConstVal = CI->getZExtValue(); 16253 return isUInt<16>(ConstVal) || 16254 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16255 } 16256 16257 // For non-constant masks, we can always use the record-form and. 16258 return true; 16259 } 16260 16261 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16262 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16263 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16264 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16265 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16266 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16267 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16268 assert(Subtarget.hasP9Altivec() && 16269 "Only combine this when P9 altivec supported!"); 16270 EVT VT = N->getValueType(0); 16271 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16272 return SDValue(); 16273 16274 SelectionDAG &DAG = DCI.DAG; 16275 SDLoc dl(N); 16276 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16277 // Even for signed integers, if it's known to be positive (as signed 16278 // integer) due to zero-extended inputs. 16279 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16280 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16281 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16282 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16283 (SubOpcd1 == ISD::ZERO_EXTEND || 16284 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16285 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16286 N->getOperand(0)->getOperand(0), 16287 N->getOperand(0)->getOperand(1), 16288 DAG.getTargetConstant(0, dl, MVT::i32)); 16289 } 16290 16291 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16292 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16293 N->getOperand(0).hasOneUse()) { 16294 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16295 N->getOperand(0)->getOperand(0), 16296 N->getOperand(0)->getOperand(1), 16297 DAG.getTargetConstant(1, dl, MVT::i32)); 16298 } 16299 } 16300 16301 return SDValue(); 16302 } 16303 16304 // For type v4i32/v8ii16/v16i8, transform 16305 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16306 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16307 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16308 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16309 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16310 DAGCombinerInfo &DCI) const { 16311 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16312 assert(Subtarget.hasP9Altivec() && 16313 "Only combine this when P9 altivec supported!"); 16314 16315 SelectionDAG &DAG = DCI.DAG; 16316 SDLoc dl(N); 16317 SDValue Cond = N->getOperand(0); 16318 SDValue TrueOpnd = N->getOperand(1); 16319 SDValue FalseOpnd = N->getOperand(2); 16320 EVT VT = N->getOperand(1).getValueType(); 16321 16322 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16323 FalseOpnd.getOpcode() != ISD::SUB) 16324 return SDValue(); 16325 16326 // ABSD only available for type v4i32/v8i16/v16i8 16327 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16328 return SDValue(); 16329 16330 // At least to save one more dependent computation 16331 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16332 return SDValue(); 16333 16334 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16335 16336 // Can only handle unsigned comparison here 16337 switch (CC) { 16338 default: 16339 return SDValue(); 16340 case ISD::SETUGT: 16341 case ISD::SETUGE: 16342 break; 16343 case ISD::SETULT: 16344 case ISD::SETULE: 16345 std::swap(TrueOpnd, FalseOpnd); 16346 break; 16347 } 16348 16349 SDValue CmpOpnd1 = Cond.getOperand(0); 16350 SDValue CmpOpnd2 = Cond.getOperand(1); 16351 16352 // SETCC CmpOpnd1 CmpOpnd2 cond 16353 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16354 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16355 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16356 TrueOpnd.getOperand(1) == CmpOpnd2 && 16357 FalseOpnd.getOperand(0) == CmpOpnd2 && 16358 FalseOpnd.getOperand(1) == CmpOpnd1) { 16359 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16360 CmpOpnd1, CmpOpnd2, 16361 DAG.getTargetConstant(0, dl, MVT::i32)); 16362 } 16363 16364 return SDValue(); 16365 } 16366