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 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 129 130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 131 132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 133 134 // FIXME: Remove this once the bug has been fixed! 135 extern cl::opt<bool> ANDIGlueBug; 136 137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 138 const PPCSubtarget &STI) 139 : TargetLowering(TM), Subtarget(STI) { 140 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 141 // arguments are at least 4/8 bytes aligned. 142 bool isPPC64 = Subtarget.isPPC64(); 143 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 144 145 // Set up the register classes. 146 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 147 if (!useSoftFloat()) { 148 if (hasSPE()) { 149 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 150 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 151 } else { 152 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 153 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 154 } 155 } 156 157 // Match BITREVERSE to customized fast code sequence in the td file. 158 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 159 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 160 161 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 162 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 163 164 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 165 for (MVT VT : MVT::integer_valuetypes()) { 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 168 } 169 170 if (Subtarget.isISA3_0()) { 171 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 172 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 174 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 175 } else { 176 // No extending loads from f16 or HW conversions back and forth. 177 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 178 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 179 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 180 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 181 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 182 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 183 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 184 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 185 } 186 187 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 188 189 // PowerPC has pre-inc load and store's. 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 200 if (!Subtarget.hasSPE()) { 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 202 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 204 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 205 } 206 207 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 208 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 209 for (MVT VT : ScalarIntVTs) { 210 setOperationAction(ISD::ADDC, VT, Legal); 211 setOperationAction(ISD::ADDE, VT, Legal); 212 setOperationAction(ISD::SUBC, VT, Legal); 213 setOperationAction(ISD::SUBE, VT, Legal); 214 } 215 216 if (Subtarget.useCRBits()) { 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 218 219 if (isPPC64 || Subtarget.hasFPCVT()) { 220 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 221 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 222 isPPC64 ? MVT::i64 : MVT::i32); 223 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 224 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 225 isPPC64 ? MVT::i64 : MVT::i32); 226 } else { 227 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 228 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 229 } 230 231 // PowerPC does not support direct load/store of condition registers. 232 setOperationAction(ISD::LOAD, MVT::i1, Custom); 233 setOperationAction(ISD::STORE, MVT::i1, Custom); 234 235 // FIXME: Remove this once the ANDI glue bug is fixed: 236 if (ANDIGlueBug) 237 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 238 239 for (MVT VT : MVT::integer_valuetypes()) { 240 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 241 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 242 setTruncStoreAction(VT, MVT::i1, Expand); 243 } 244 245 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 246 } 247 248 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 249 // PPC (the libcall is not available). 250 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 251 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 252 253 // We do not currently implement these libm ops for PowerPC. 254 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 259 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 260 261 // PowerPC has no SREM/UREM instructions unless we are on P9 262 // On P9 we may use a hardware instruction to compute the remainder. 263 // The instructions are not legalized directly because in the cases where the 264 // result of both the remainder and the division is required it is more 265 // efficient to compute the remainder from the result of the division rather 266 // than use the remainder instruction. 267 if (Subtarget.isISA3_0()) { 268 setOperationAction(ISD::SREM, MVT::i32, Custom); 269 setOperationAction(ISD::UREM, MVT::i32, Custom); 270 setOperationAction(ISD::SREM, MVT::i64, Custom); 271 setOperationAction(ISD::UREM, MVT::i64, Custom); 272 } else { 273 setOperationAction(ISD::SREM, MVT::i32, Expand); 274 setOperationAction(ISD::UREM, MVT::i32, Expand); 275 setOperationAction(ISD::SREM, MVT::i64, Expand); 276 setOperationAction(ISD::UREM, MVT::i64, Expand); 277 } 278 279 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 280 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 282 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 284 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 286 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 287 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 288 289 // Handle constrained floating-point operations of scalar. 290 // TODO: Handle SPE specific operation. 291 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 294 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 295 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 296 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 297 298 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 300 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 301 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 302 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 303 if (Subtarget.hasVSX()) 304 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 305 306 if (Subtarget.hasFSQRT()) { 307 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 309 } 310 311 if (Subtarget.hasFPRND()) { 312 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 313 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 314 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 315 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 316 317 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 318 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 319 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 320 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 321 } 322 323 // We don't support sin/cos/sqrt/fmod/pow 324 setOperationAction(ISD::FSIN , MVT::f64, Expand); 325 setOperationAction(ISD::FCOS , MVT::f64, Expand); 326 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 327 setOperationAction(ISD::FREM , MVT::f64, Expand); 328 setOperationAction(ISD::FPOW , MVT::f64, Expand); 329 setOperationAction(ISD::FSIN , MVT::f32, Expand); 330 setOperationAction(ISD::FCOS , MVT::f32, Expand); 331 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 332 setOperationAction(ISD::FREM , MVT::f32, Expand); 333 setOperationAction(ISD::FPOW , MVT::f32, Expand); 334 if (Subtarget.hasSPE()) { 335 setOperationAction(ISD::FMA , MVT::f64, Expand); 336 setOperationAction(ISD::FMA , MVT::f32, Expand); 337 } else { 338 setOperationAction(ISD::FMA , MVT::f64, Legal); 339 setOperationAction(ISD::FMA , MVT::f32, Legal); 340 } 341 342 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 343 344 // If we're enabling GP optimizations, use hardware square root 345 if (!Subtarget.hasFSQRT() && 346 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 347 Subtarget.hasFRE())) 348 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 349 350 if (!Subtarget.hasFSQRT() && 351 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 352 Subtarget.hasFRES())) 353 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 354 355 if (Subtarget.hasFCPSGN()) { 356 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 357 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 358 } else { 359 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 360 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 361 } 362 363 if (Subtarget.hasFPRND()) { 364 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 365 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 366 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 367 setOperationAction(ISD::FROUND, MVT::f64, Legal); 368 369 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 370 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 371 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 372 setOperationAction(ISD::FROUND, MVT::f32, Legal); 373 } 374 375 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 376 // to speed up scalar BSWAP64. 377 // CTPOP or CTTZ were introduced in P8/P9 respectively 378 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 379 if (Subtarget.hasP9Vector()) 380 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 381 else 382 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 383 if (Subtarget.isISA3_0()) { 384 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 385 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 386 } else { 387 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 388 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 389 } 390 391 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 392 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 393 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 394 } else { 395 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 396 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 397 } 398 399 // PowerPC does not have ROTR 400 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 401 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 402 403 if (!Subtarget.useCRBits()) { 404 // PowerPC does not have Select 405 setOperationAction(ISD::SELECT, MVT::i32, Expand); 406 setOperationAction(ISD::SELECT, MVT::i64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f32, Expand); 408 setOperationAction(ISD::SELECT, MVT::f64, Expand); 409 } 410 411 // PowerPC wants to turn select_cc of FP into fsel when possible. 412 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 413 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 414 415 // PowerPC wants to optimize integer setcc a bit 416 if (!Subtarget.useCRBits()) 417 setOperationAction(ISD::SETCC, MVT::i32, Custom); 418 419 // PowerPC does not have BRCOND which requires SetCC 420 if (!Subtarget.useCRBits()) 421 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 422 423 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 424 425 if (Subtarget.hasSPE()) { 426 // SPE has built-in conversions 427 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 428 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 429 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 430 } else { 431 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 432 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 433 434 // PowerPC does not have [U|S]INT_TO_FP 435 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 436 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 437 } 438 439 if (Subtarget.hasDirectMove() && isPPC64) { 440 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 441 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 442 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 443 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 444 if (TM.Options.UnsafeFPMath) { 445 setOperationAction(ISD::LRINT, MVT::f64, Legal); 446 setOperationAction(ISD::LRINT, MVT::f32, Legal); 447 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 448 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 449 setOperationAction(ISD::LROUND, MVT::f64, Legal); 450 setOperationAction(ISD::LROUND, MVT::f32, Legal); 451 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 452 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 453 } 454 } else { 455 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 456 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 457 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 458 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 459 } 460 461 // We cannot sextinreg(i1). Expand to shifts. 462 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 463 464 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 465 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 466 // support continuation, user-level threading, and etc.. As a result, no 467 // other SjLj exception interfaces are implemented and please don't build 468 // your own exception handling based on them. 469 // LLVM/Clang supports zero-cost DWARF exception handling. 470 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 471 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 472 473 // We want to legalize GlobalAddress and ConstantPool nodes into the 474 // appropriate instructions to materialize the address. 475 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 476 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 477 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 478 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 479 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 480 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 481 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 482 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 483 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 484 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 485 486 // TRAP is legal. 487 setOperationAction(ISD::TRAP, MVT::Other, Legal); 488 489 // TRAMPOLINE is custom lowered. 490 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 491 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 492 493 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 494 setOperationAction(ISD::VASTART , MVT::Other, Custom); 495 496 if (Subtarget.is64BitELFABI()) { 497 // VAARG always uses double-word chunks, so promote anything smaller. 498 setOperationAction(ISD::VAARG, MVT::i1, Promote); 499 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 500 setOperationAction(ISD::VAARG, MVT::i8, Promote); 501 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 502 setOperationAction(ISD::VAARG, MVT::i16, Promote); 503 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 504 setOperationAction(ISD::VAARG, MVT::i32, Promote); 505 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 506 setOperationAction(ISD::VAARG, MVT::Other, Expand); 507 } else if (Subtarget.is32BitELFABI()) { 508 // VAARG is custom lowered with the 32-bit SVR4 ABI. 509 setOperationAction(ISD::VAARG, MVT::Other, Custom); 510 setOperationAction(ISD::VAARG, MVT::i64, Custom); 511 } else 512 setOperationAction(ISD::VAARG, MVT::Other, Expand); 513 514 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 515 if (Subtarget.is32BitELFABI()) 516 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 517 else 518 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 519 520 // Use the default implementation. 521 setOperationAction(ISD::VAEND , MVT::Other, Expand); 522 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 523 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 524 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 525 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 526 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 527 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 528 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 529 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 530 531 // We want to custom lower some of our intrinsics. 532 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 533 534 // To handle counter-based loop conditions. 535 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 536 537 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 538 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 539 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 540 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 541 542 // Comparisons that require checking two conditions. 543 if (Subtarget.hasSPE()) { 544 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 545 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 546 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 547 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 548 } 549 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 550 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 551 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 552 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 553 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 554 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 555 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 556 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 557 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 558 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 559 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 560 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 561 562 if (Subtarget.has64BitSupport()) { 563 // They also have instructions for converting between i64 and fp. 564 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 565 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 566 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 567 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 568 // This is just the low 32 bits of a (signed) fp->i64 conversion. 569 // We cannot do this with Promote because i64 is not a legal type. 570 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 571 572 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 573 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 574 } else { 575 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 576 if (Subtarget.hasSPE()) 577 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 578 else 579 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 580 } 581 582 // With the instructions enabled under FPCVT, we can do everything. 583 if (Subtarget.hasFPCVT()) { 584 if (Subtarget.has64BitSupport()) { 585 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 586 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 587 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 588 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 589 } 590 591 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 592 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 593 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 594 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 595 } 596 597 if (Subtarget.use64BitRegs()) { 598 // 64-bit PowerPC implementations can support i64 types directly 599 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 600 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 601 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 602 // 64-bit PowerPC wants to expand i128 shifts itself. 603 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 604 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 605 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 606 } else { 607 // 32-bit PowerPC wants to expand i64 shifts itself. 608 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 609 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 610 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 611 } 612 613 if (Subtarget.hasVSX()) { 614 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 615 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 616 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 617 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 618 } 619 620 if (Subtarget.hasAltivec()) { 621 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 622 setOperationAction(ISD::SADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::UADDSAT, VT, Legal); 625 setOperationAction(ISD::USUBSAT, VT, Legal); 626 } 627 // First set operation action for all vector types to expand. Then we 628 // will selectively turn on ones that can be effectively codegen'd. 629 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 630 // add/sub are legal for all supported vector VT's. 631 setOperationAction(ISD::ADD, VT, Legal); 632 setOperationAction(ISD::SUB, VT, Legal); 633 634 // For v2i64, these are only valid with P8Vector. This is corrected after 635 // the loop. 636 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 637 setOperationAction(ISD::SMAX, VT, Legal); 638 setOperationAction(ISD::SMIN, VT, Legal); 639 setOperationAction(ISD::UMAX, VT, Legal); 640 setOperationAction(ISD::UMIN, VT, Legal); 641 } 642 else { 643 setOperationAction(ISD::SMAX, VT, Expand); 644 setOperationAction(ISD::SMIN, VT, Expand); 645 setOperationAction(ISD::UMAX, VT, Expand); 646 setOperationAction(ISD::UMIN, VT, Expand); 647 } 648 649 if (Subtarget.hasVSX()) { 650 setOperationAction(ISD::FMAXNUM, VT, Legal); 651 setOperationAction(ISD::FMINNUM, VT, Legal); 652 } 653 654 // Vector instructions introduced in P8 655 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 656 setOperationAction(ISD::CTPOP, VT, Legal); 657 setOperationAction(ISD::CTLZ, VT, Legal); 658 } 659 else { 660 setOperationAction(ISD::CTPOP, VT, Expand); 661 setOperationAction(ISD::CTLZ, VT, Expand); 662 } 663 664 // Vector instructions introduced in P9 665 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 666 setOperationAction(ISD::CTTZ, VT, Legal); 667 else 668 setOperationAction(ISD::CTTZ, VT, Expand); 669 670 // We promote all shuffles to v16i8. 671 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 672 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 673 674 // We promote all non-typed operations to v4i32. 675 setOperationAction(ISD::AND , VT, Promote); 676 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 677 setOperationAction(ISD::OR , VT, Promote); 678 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 679 setOperationAction(ISD::XOR , VT, Promote); 680 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 681 setOperationAction(ISD::LOAD , VT, Promote); 682 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 683 setOperationAction(ISD::SELECT, VT, Promote); 684 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 685 setOperationAction(ISD::VSELECT, VT, Legal); 686 setOperationAction(ISD::SELECT_CC, VT, Promote); 687 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 688 setOperationAction(ISD::STORE, VT, Promote); 689 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 690 691 // No other operations are legal. 692 setOperationAction(ISD::MUL , VT, Expand); 693 setOperationAction(ISD::SDIV, VT, Expand); 694 setOperationAction(ISD::SREM, VT, Expand); 695 setOperationAction(ISD::UDIV, VT, Expand); 696 setOperationAction(ISD::UREM, VT, Expand); 697 setOperationAction(ISD::FDIV, VT, Expand); 698 setOperationAction(ISD::FREM, VT, Expand); 699 setOperationAction(ISD::FNEG, VT, Expand); 700 setOperationAction(ISD::FSQRT, VT, Expand); 701 setOperationAction(ISD::FLOG, VT, Expand); 702 setOperationAction(ISD::FLOG10, VT, Expand); 703 setOperationAction(ISD::FLOG2, VT, Expand); 704 setOperationAction(ISD::FEXP, VT, Expand); 705 setOperationAction(ISD::FEXP2, VT, Expand); 706 setOperationAction(ISD::FSIN, VT, Expand); 707 setOperationAction(ISD::FCOS, VT, Expand); 708 setOperationAction(ISD::FABS, VT, Expand); 709 setOperationAction(ISD::FFLOOR, VT, Expand); 710 setOperationAction(ISD::FCEIL, VT, Expand); 711 setOperationAction(ISD::FTRUNC, VT, Expand); 712 setOperationAction(ISD::FRINT, VT, Expand); 713 setOperationAction(ISD::FNEARBYINT, VT, Expand); 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 715 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 716 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 717 setOperationAction(ISD::MULHU, VT, Expand); 718 setOperationAction(ISD::MULHS, VT, Expand); 719 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 720 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 721 setOperationAction(ISD::UDIVREM, VT, Expand); 722 setOperationAction(ISD::SDIVREM, VT, Expand); 723 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 724 setOperationAction(ISD::FPOW, VT, Expand); 725 setOperationAction(ISD::BSWAP, VT, Expand); 726 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 727 setOperationAction(ISD::ROTL, VT, Expand); 728 setOperationAction(ISD::ROTR, VT, Expand); 729 730 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 731 setTruncStoreAction(VT, InnerVT, Expand); 732 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 733 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 734 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 735 } 736 } 737 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 738 if (!Subtarget.hasP8Vector()) { 739 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 740 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 741 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 742 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 743 } 744 745 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 746 setOperationAction(ISD::ABS, VT, Custom); 747 748 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 749 // with merges, splats, etc. 750 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 751 752 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 753 // are cheap, so handle them before they get expanded to scalar. 754 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 755 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 756 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 757 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 758 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 759 760 setOperationAction(ISD::AND , MVT::v4i32, Legal); 761 setOperationAction(ISD::OR , MVT::v4i32, Legal); 762 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 763 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 764 setOperationAction(ISD::SELECT, MVT::v4i32, 765 Subtarget.useCRBits() ? Legal : Expand); 766 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 767 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 768 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 769 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 770 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 771 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 772 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 773 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 774 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 775 776 // Without hasP8Altivec set, v2i64 SMAX isn't available. 777 // But ABS custom lowering requires SMAX support. 778 if (!Subtarget.hasP8Altivec()) 779 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 780 781 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 782 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 783 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 784 if (Subtarget.hasAltivec()) 785 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 786 setOperationAction(ISD::ROTL, VT, Legal); 787 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 788 if (Subtarget.hasP8Altivec()) 789 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 790 791 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 792 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 793 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 794 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 795 796 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 797 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 798 799 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 800 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 801 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 802 } 803 804 if (Subtarget.hasP8Altivec()) 805 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 806 else 807 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 808 809 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 810 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 811 812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 813 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 814 815 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 816 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 817 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 819 820 // Altivec does not contain unordered floating-point compare instructions 821 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 822 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 823 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 824 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 825 826 if (Subtarget.hasVSX()) { 827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 829 if (Subtarget.hasP8Vector()) { 830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 831 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 832 } 833 if (Subtarget.hasDirectMove() && isPPC64) { 834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 836 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 839 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 840 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 841 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 842 } 843 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 844 845 // The nearbyint variants are not allowed to raise the inexact exception 846 // so we can only code-gen them with unsafe math. 847 if (TM.Options.UnsafeFPMath) { 848 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 849 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 850 } 851 852 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 853 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 854 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 855 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 856 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 857 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 858 setOperationAction(ISD::FROUND, MVT::f64, Legal); 859 setOperationAction(ISD::FRINT, MVT::f64, Legal); 860 861 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 862 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 863 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 864 setOperationAction(ISD::FROUND, MVT::f32, Legal); 865 setOperationAction(ISD::FRINT, MVT::f32, Legal); 866 867 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 868 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 869 870 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 871 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 872 873 // Share the Altivec comparison restrictions. 874 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 875 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 876 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 877 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 878 879 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 880 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 881 882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 883 884 if (Subtarget.hasP8Vector()) 885 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 886 887 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 888 889 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 890 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 891 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 892 893 if (Subtarget.hasP8Altivec()) { 894 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 895 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 896 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 897 898 // 128 bit shifts can be accomplished via 3 instructions for SHL and 899 // SRL, but not for SRA because of the instructions available: 900 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 901 // doing 902 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 903 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 904 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 905 906 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 907 } 908 else { 909 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 910 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 911 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 912 913 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 914 915 // VSX v2i64 only supports non-arithmetic operations. 916 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 917 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 918 } 919 920 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 921 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 922 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 923 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 924 925 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 926 927 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 928 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 929 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 930 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 931 932 // Custom handling for partial vectors of integers converted to 933 // floating point. We already have optimal handling for v2i32 through 934 // the DAG combine, so those aren't necessary. 935 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 936 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 937 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 938 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 939 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 940 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 941 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 942 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 943 944 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 945 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 946 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 947 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 948 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 949 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 950 951 if (Subtarget.hasDirectMove()) 952 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 953 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 954 955 // Handle constrained floating-point operations of vector. 956 // The predictor is `hasVSX` because altivec instruction has 957 // no exception but VSX vector instruction has. 958 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 959 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 960 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 961 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 962 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 963 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 964 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 965 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 966 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 967 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 968 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 969 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 970 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 971 972 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 973 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 974 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 975 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 976 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 977 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 978 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 979 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 980 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 981 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 982 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 983 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 984 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 985 986 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 987 } 988 989 if (Subtarget.hasP8Altivec()) { 990 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 991 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 992 } 993 994 if (Subtarget.hasP9Vector()) { 995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 997 998 // 128 bit shifts can be accomplished via 3 instructions for SHL and 999 // SRL, but not for SRA because of the instructions available: 1000 // VS{RL} and VS{RL}O. 1001 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1002 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1003 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1004 1005 if (EnableQuadPrecision) { 1006 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1007 setOperationAction(ISD::FADD, MVT::f128, Legal); 1008 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1009 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1010 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1011 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1012 // No extending loads to f128 on PPC. 1013 for (MVT FPT : MVT::fp_valuetypes()) 1014 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1015 setOperationAction(ISD::FMA, MVT::f128, Legal); 1016 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1017 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1018 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1019 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1020 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1021 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1022 1023 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1024 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1025 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1026 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1027 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1028 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1029 1030 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1031 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1032 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1033 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1034 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1035 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1036 // No implementation for these ops for PowerPC. 1037 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1038 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1039 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1040 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1041 setOperationAction(ISD::FREM, MVT::f128, Expand); 1042 1043 // Handle constrained floating-point operations of fp128 1044 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1045 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1046 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1047 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1048 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1049 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1050 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1051 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1052 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1053 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1054 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1055 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1056 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1057 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1058 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1059 } 1060 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1061 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1062 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1063 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1064 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1065 } 1066 1067 if (Subtarget.hasP9Altivec()) { 1068 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1069 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1070 1071 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1072 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1073 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1074 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1075 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1076 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1077 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1078 } 1079 } 1080 1081 if (Subtarget.hasQPX()) { 1082 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1083 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1084 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1085 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1086 1087 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1088 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1089 1090 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1091 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1092 1093 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1094 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1095 1096 if (!Subtarget.useCRBits()) 1097 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1098 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1099 1100 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1101 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1102 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1103 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1104 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1105 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1106 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1107 1108 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1109 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1110 1111 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1112 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1113 1114 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1115 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1116 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1117 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1118 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1119 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1120 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1121 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1122 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1123 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1124 1125 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1126 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1127 1128 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1129 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1130 1131 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1132 1133 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1134 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1135 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1136 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1137 1138 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1139 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1140 1141 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1142 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1143 1144 if (!Subtarget.useCRBits()) 1145 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1146 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1147 1148 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1149 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1150 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1151 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1152 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1153 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1154 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1155 1156 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1157 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1158 1159 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1160 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1161 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1162 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1163 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1164 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1165 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1166 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1167 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1168 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1169 1170 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1172 1173 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1174 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1175 1176 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1177 1178 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1179 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1180 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1181 1182 if (!Subtarget.useCRBits()) 1183 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1184 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1185 1186 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1187 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1188 1189 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1190 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1191 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1192 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1193 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1194 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1195 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1196 1197 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1198 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1199 1200 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1201 1202 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1203 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1204 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1205 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1206 1207 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1208 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1209 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1210 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1211 1212 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1213 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1214 1215 // These need to set FE_INEXACT, and so cannot be vectorized here. 1216 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1217 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1218 1219 if (TM.Options.UnsafeFPMath) { 1220 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1221 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1222 1223 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1224 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1225 } else { 1226 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1227 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1228 1229 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1230 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1231 } 1232 1233 // TODO: Handle constrained floating-point operations of v4f64 1234 } 1235 1236 if (Subtarget.has64BitSupport()) 1237 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1238 1239 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1240 1241 if (!isPPC64) { 1242 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1243 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1244 } 1245 1246 setBooleanContents(ZeroOrOneBooleanContent); 1247 1248 if (Subtarget.hasAltivec()) { 1249 // Altivec instructions set fields to all zeros or all ones. 1250 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1251 } 1252 1253 if (!isPPC64) { 1254 // These libcalls are not available in 32-bit. 1255 setLibcallName(RTLIB::SHL_I128, nullptr); 1256 setLibcallName(RTLIB::SRL_I128, nullptr); 1257 setLibcallName(RTLIB::SRA_I128, nullptr); 1258 } 1259 1260 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1261 1262 // We have target-specific dag combine patterns for the following nodes: 1263 setTargetDAGCombine(ISD::ADD); 1264 setTargetDAGCombine(ISD::SHL); 1265 setTargetDAGCombine(ISD::SRA); 1266 setTargetDAGCombine(ISD::SRL); 1267 setTargetDAGCombine(ISD::MUL); 1268 setTargetDAGCombine(ISD::FMA); 1269 setTargetDAGCombine(ISD::SINT_TO_FP); 1270 setTargetDAGCombine(ISD::BUILD_VECTOR); 1271 if (Subtarget.hasFPCVT()) 1272 setTargetDAGCombine(ISD::UINT_TO_FP); 1273 setTargetDAGCombine(ISD::LOAD); 1274 setTargetDAGCombine(ISD::STORE); 1275 setTargetDAGCombine(ISD::BR_CC); 1276 if (Subtarget.useCRBits()) 1277 setTargetDAGCombine(ISD::BRCOND); 1278 setTargetDAGCombine(ISD::BSWAP); 1279 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1280 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1281 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1282 1283 setTargetDAGCombine(ISD::SIGN_EXTEND); 1284 setTargetDAGCombine(ISD::ZERO_EXTEND); 1285 setTargetDAGCombine(ISD::ANY_EXTEND); 1286 1287 setTargetDAGCombine(ISD::TRUNCATE); 1288 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1289 1290 1291 if (Subtarget.useCRBits()) { 1292 setTargetDAGCombine(ISD::TRUNCATE); 1293 setTargetDAGCombine(ISD::SETCC); 1294 setTargetDAGCombine(ISD::SELECT_CC); 1295 } 1296 1297 // Use reciprocal estimates. 1298 if (TM.Options.UnsafeFPMath) { 1299 setTargetDAGCombine(ISD::FDIV); 1300 setTargetDAGCombine(ISD::FSQRT); 1301 } 1302 1303 if (Subtarget.hasP9Altivec()) { 1304 setTargetDAGCombine(ISD::ABS); 1305 setTargetDAGCombine(ISD::VSELECT); 1306 } 1307 1308 if (EnableQuadPrecision) { 1309 setLibcallName(RTLIB::LOG_F128, "logf128"); 1310 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1311 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1312 setLibcallName(RTLIB::EXP_F128, "expf128"); 1313 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1314 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1315 setLibcallName(RTLIB::COS_F128, "cosf128"); 1316 setLibcallName(RTLIB::POW_F128, "powf128"); 1317 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1318 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1319 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1320 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1321 } 1322 1323 // With 32 condition bits, we don't need to sink (and duplicate) compares 1324 // aggressively in CodeGenPrep. 1325 if (Subtarget.useCRBits()) { 1326 setHasMultipleConditionRegisters(); 1327 setJumpIsExpensive(); 1328 } 1329 1330 setMinFunctionAlignment(Align(4)); 1331 1332 switch (Subtarget.getCPUDirective()) { 1333 default: break; 1334 case PPC::DIR_970: 1335 case PPC::DIR_A2: 1336 case PPC::DIR_E500: 1337 case PPC::DIR_E500mc: 1338 case PPC::DIR_E5500: 1339 case PPC::DIR_PWR4: 1340 case PPC::DIR_PWR5: 1341 case PPC::DIR_PWR5X: 1342 case PPC::DIR_PWR6: 1343 case PPC::DIR_PWR6X: 1344 case PPC::DIR_PWR7: 1345 case PPC::DIR_PWR8: 1346 case PPC::DIR_PWR9: 1347 case PPC::DIR_PWR10: 1348 case PPC::DIR_PWR_FUTURE: 1349 setPrefLoopAlignment(Align(16)); 1350 setPrefFunctionAlignment(Align(16)); 1351 break; 1352 } 1353 1354 if (Subtarget.enableMachineScheduler()) 1355 setSchedulingPreference(Sched::Source); 1356 else 1357 setSchedulingPreference(Sched::Hybrid); 1358 1359 computeRegisterProperties(STI.getRegisterInfo()); 1360 1361 // The Freescale cores do better with aggressive inlining of memcpy and 1362 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1363 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1364 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1365 MaxStoresPerMemset = 32; 1366 MaxStoresPerMemsetOptSize = 16; 1367 MaxStoresPerMemcpy = 32; 1368 MaxStoresPerMemcpyOptSize = 8; 1369 MaxStoresPerMemmove = 32; 1370 MaxStoresPerMemmoveOptSize = 8; 1371 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1372 // The A2 also benefits from (very) aggressive inlining of memcpy and 1373 // friends. The overhead of a the function call, even when warm, can be 1374 // over one hundred cycles. 1375 MaxStoresPerMemset = 128; 1376 MaxStoresPerMemcpy = 128; 1377 MaxStoresPerMemmove = 128; 1378 MaxLoadsPerMemcmp = 128; 1379 } else { 1380 MaxLoadsPerMemcmp = 8; 1381 MaxLoadsPerMemcmpOptSize = 4; 1382 } 1383 1384 // Let the subtarget (CPU) decide if a predictable select is more expensive 1385 // than the corresponding branch. This information is used in CGP to decide 1386 // when to convert selects into branches. 1387 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1388 } 1389 1390 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1391 /// the desired ByVal argument alignment. 1392 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1393 if (MaxAlign == MaxMaxAlign) 1394 return; 1395 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1396 if (MaxMaxAlign >= 32 && 1397 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1398 MaxAlign = Align(32); 1399 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1400 MaxAlign < 16) 1401 MaxAlign = Align(16); 1402 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1403 Align EltAlign; 1404 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1405 if (EltAlign > MaxAlign) 1406 MaxAlign = EltAlign; 1407 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1408 for (auto *EltTy : STy->elements()) { 1409 Align EltAlign; 1410 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1411 if (EltAlign > MaxAlign) 1412 MaxAlign = EltAlign; 1413 if (MaxAlign == MaxMaxAlign) 1414 break; 1415 } 1416 } 1417 } 1418 1419 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1420 /// function arguments in the caller parameter area. 1421 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1422 const DataLayout &DL) const { 1423 // 16byte and wider vectors are passed on 16byte boundary. 1424 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1425 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1426 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1427 getMaxByValAlign(Ty, Alignment, Subtarget.hasQPX() ? Align(32) : Align(16)); 1428 return Alignment.value(); 1429 } 1430 1431 bool PPCTargetLowering::useSoftFloat() const { 1432 return Subtarget.useSoftFloat(); 1433 } 1434 1435 bool PPCTargetLowering::hasSPE() const { 1436 return Subtarget.hasSPE(); 1437 } 1438 1439 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1440 return VT.isScalarInteger(); 1441 } 1442 1443 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1444 /// type is cheaper than a multiply followed by a shift. 1445 /// This is true for words and doublewords on 64-bit PowerPC. 1446 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1447 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1448 isOperationLegal(ISD::MULHU, Type))) 1449 return true; 1450 return TargetLowering::isMulhCheaperThanMulShift(Type); 1451 } 1452 1453 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1454 switch ((PPCISD::NodeType)Opcode) { 1455 case PPCISD::FIRST_NUMBER: break; 1456 case PPCISD::FSEL: return "PPCISD::FSEL"; 1457 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1458 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1459 case PPCISD::FCFID: return "PPCISD::FCFID"; 1460 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1461 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1462 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1463 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1464 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1465 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1466 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1467 case PPCISD::FP_TO_UINT_IN_VSR: 1468 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1469 case PPCISD::FP_TO_SINT_IN_VSR: 1470 return "PPCISD::FP_TO_SINT_IN_VSR"; 1471 case PPCISD::FRE: return "PPCISD::FRE"; 1472 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1473 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1474 case PPCISD::VPERM: return "PPCISD::VPERM"; 1475 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1476 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1477 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1478 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1479 case PPCISD::CMPB: return "PPCISD::CMPB"; 1480 case PPCISD::Hi: return "PPCISD::Hi"; 1481 case PPCISD::Lo: return "PPCISD::Lo"; 1482 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1483 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1484 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1485 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1486 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1487 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1488 case PPCISD::SRL: return "PPCISD::SRL"; 1489 case PPCISD::SRA: return "PPCISD::SRA"; 1490 case PPCISD::SHL: return "PPCISD::SHL"; 1491 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1492 case PPCISD::CALL: return "PPCISD::CALL"; 1493 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1494 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1495 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1496 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1497 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1498 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1499 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1500 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1501 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1502 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1503 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1504 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1505 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1506 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1507 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1508 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1509 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1510 case PPCISD::ANDI_rec_1_EQ_BIT: 1511 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1512 case PPCISD::ANDI_rec_1_GT_BIT: 1513 return "PPCISD::ANDI_rec_1_GT_BIT"; 1514 case PPCISD::VCMP: return "PPCISD::VCMP"; 1515 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1516 case PPCISD::LBRX: return "PPCISD::LBRX"; 1517 case PPCISD::STBRX: return "PPCISD::STBRX"; 1518 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1519 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1520 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1521 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1522 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1523 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1524 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1525 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1526 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1527 case PPCISD::ST_VSR_SCAL_INT: 1528 return "PPCISD::ST_VSR_SCAL_INT"; 1529 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1530 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1531 case PPCISD::BDZ: return "PPCISD::BDZ"; 1532 case PPCISD::MFFS: return "PPCISD::MFFS"; 1533 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1534 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1535 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1536 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1537 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1538 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1539 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1540 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1541 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1542 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1543 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1544 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1545 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1546 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1547 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1548 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1549 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1550 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1551 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1552 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1553 case PPCISD::SC: return "PPCISD::SC"; 1554 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1555 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1556 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1557 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1558 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1559 case PPCISD::VABSD: return "PPCISD::VABSD"; 1560 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1561 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1562 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1563 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1564 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1565 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1566 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1567 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1568 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1569 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1570 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1571 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1572 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1573 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1574 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1575 } 1576 return nullptr; 1577 } 1578 1579 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1580 EVT VT) const { 1581 if (!VT.isVector()) 1582 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1583 1584 if (Subtarget.hasQPX()) 1585 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1586 1587 return VT.changeVectorElementTypeToInteger(); 1588 } 1589 1590 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1591 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1592 return true; 1593 } 1594 1595 //===----------------------------------------------------------------------===// 1596 // Node matching predicates, for use by the tblgen matching code. 1597 //===----------------------------------------------------------------------===// 1598 1599 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1600 static bool isFloatingPointZero(SDValue Op) { 1601 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1602 return CFP->getValueAPF().isZero(); 1603 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1604 // Maybe this has already been legalized into the constant pool? 1605 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1606 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1607 return CFP->getValueAPF().isZero(); 1608 } 1609 return false; 1610 } 1611 1612 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1613 /// true if Op is undef or if it matches the specified value. 1614 static bool isConstantOrUndef(int Op, int Val) { 1615 return Op < 0 || Op == Val; 1616 } 1617 1618 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1619 /// VPKUHUM instruction. 1620 /// The ShuffleKind distinguishes between big-endian operations with 1621 /// two different inputs (0), either-endian operations with two identical 1622 /// inputs (1), and little-endian operations with two different inputs (2). 1623 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1624 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1625 SelectionDAG &DAG) { 1626 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1627 if (ShuffleKind == 0) { 1628 if (IsLE) 1629 return false; 1630 for (unsigned i = 0; i != 16; ++i) 1631 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1632 return false; 1633 } else if (ShuffleKind == 2) { 1634 if (!IsLE) 1635 return false; 1636 for (unsigned i = 0; i != 16; ++i) 1637 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1638 return false; 1639 } else if (ShuffleKind == 1) { 1640 unsigned j = IsLE ? 0 : 1; 1641 for (unsigned i = 0; i != 8; ++i) 1642 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1643 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1644 return false; 1645 } 1646 return true; 1647 } 1648 1649 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1650 /// VPKUWUM instruction. 1651 /// The ShuffleKind distinguishes between big-endian operations with 1652 /// two different inputs (0), either-endian operations with two identical 1653 /// inputs (1), and little-endian operations with two different inputs (2). 1654 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1655 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1656 SelectionDAG &DAG) { 1657 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1658 if (ShuffleKind == 0) { 1659 if (IsLE) 1660 return false; 1661 for (unsigned i = 0; i != 16; i += 2) 1662 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1663 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1664 return false; 1665 } else if (ShuffleKind == 2) { 1666 if (!IsLE) 1667 return false; 1668 for (unsigned i = 0; i != 16; i += 2) 1669 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1670 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1671 return false; 1672 } else if (ShuffleKind == 1) { 1673 unsigned j = IsLE ? 0 : 2; 1674 for (unsigned i = 0; i != 8; i += 2) 1675 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1676 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1678 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1679 return false; 1680 } 1681 return true; 1682 } 1683 1684 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1685 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1686 /// current subtarget. 1687 /// 1688 /// The ShuffleKind distinguishes between big-endian operations with 1689 /// two different inputs (0), either-endian operations with two identical 1690 /// inputs (1), and little-endian operations with two different inputs (2). 1691 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1692 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1693 SelectionDAG &DAG) { 1694 const PPCSubtarget& Subtarget = 1695 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1696 if (!Subtarget.hasP8Vector()) 1697 return false; 1698 1699 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1700 if (ShuffleKind == 0) { 1701 if (IsLE) 1702 return false; 1703 for (unsigned i = 0; i != 16; i += 4) 1704 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1705 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1706 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1707 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1708 return false; 1709 } else if (ShuffleKind == 2) { 1710 if (!IsLE) 1711 return false; 1712 for (unsigned i = 0; i != 16; i += 4) 1713 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1714 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1715 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1716 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1717 return false; 1718 } else if (ShuffleKind == 1) { 1719 unsigned j = IsLE ? 0 : 4; 1720 for (unsigned i = 0; i != 8; i += 4) 1721 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1722 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1723 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1724 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1725 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1726 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1727 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1728 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1729 return false; 1730 } 1731 return true; 1732 } 1733 1734 /// isVMerge - Common function, used to match vmrg* shuffles. 1735 /// 1736 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1737 unsigned LHSStart, unsigned RHSStart) { 1738 if (N->getValueType(0) != MVT::v16i8) 1739 return false; 1740 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1741 "Unsupported merge size!"); 1742 1743 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1744 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1745 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1746 LHSStart+j+i*UnitSize) || 1747 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1748 RHSStart+j+i*UnitSize)) 1749 return false; 1750 } 1751 return true; 1752 } 1753 1754 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1755 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1756 /// The ShuffleKind distinguishes between big-endian merges with two 1757 /// different inputs (0), either-endian merges with two identical inputs (1), 1758 /// and little-endian merges with two different inputs (2). For the latter, 1759 /// the input operands are swapped (see PPCInstrAltivec.td). 1760 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1761 unsigned ShuffleKind, SelectionDAG &DAG) { 1762 if (DAG.getDataLayout().isLittleEndian()) { 1763 if (ShuffleKind == 1) // unary 1764 return isVMerge(N, UnitSize, 0, 0); 1765 else if (ShuffleKind == 2) // swapped 1766 return isVMerge(N, UnitSize, 0, 16); 1767 else 1768 return false; 1769 } else { 1770 if (ShuffleKind == 1) // unary 1771 return isVMerge(N, UnitSize, 8, 8); 1772 else if (ShuffleKind == 0) // normal 1773 return isVMerge(N, UnitSize, 8, 24); 1774 else 1775 return false; 1776 } 1777 } 1778 1779 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1780 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1781 /// The ShuffleKind distinguishes between big-endian merges with two 1782 /// different inputs (0), either-endian merges with two identical inputs (1), 1783 /// and little-endian merges with two different inputs (2). For the latter, 1784 /// the input operands are swapped (see PPCInstrAltivec.td). 1785 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1786 unsigned ShuffleKind, SelectionDAG &DAG) { 1787 if (DAG.getDataLayout().isLittleEndian()) { 1788 if (ShuffleKind == 1) // unary 1789 return isVMerge(N, UnitSize, 8, 8); 1790 else if (ShuffleKind == 2) // swapped 1791 return isVMerge(N, UnitSize, 8, 24); 1792 else 1793 return false; 1794 } else { 1795 if (ShuffleKind == 1) // unary 1796 return isVMerge(N, UnitSize, 0, 0); 1797 else if (ShuffleKind == 0) // normal 1798 return isVMerge(N, UnitSize, 0, 16); 1799 else 1800 return false; 1801 } 1802 } 1803 1804 /** 1805 * Common function used to match vmrgew and vmrgow shuffles 1806 * 1807 * The indexOffset determines whether to look for even or odd words in 1808 * the shuffle mask. This is based on the of the endianness of the target 1809 * machine. 1810 * - Little Endian: 1811 * - Use offset of 0 to check for odd elements 1812 * - Use offset of 4 to check for even elements 1813 * - Big Endian: 1814 * - Use offset of 0 to check for even elements 1815 * - Use offset of 4 to check for odd elements 1816 * A detailed description of the vector element ordering for little endian and 1817 * big endian can be found at 1818 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1819 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1820 * compiler differences mean to you 1821 * 1822 * The mask to the shuffle vector instruction specifies the indices of the 1823 * elements from the two input vectors to place in the result. The elements are 1824 * numbered in array-access order, starting with the first vector. These vectors 1825 * are always of type v16i8, thus each vector will contain 16 elements of size 1826 * 8. More info on the shuffle vector can be found in the 1827 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1828 * Language Reference. 1829 * 1830 * The RHSStartValue indicates whether the same input vectors are used (unary) 1831 * or two different input vectors are used, based on the following: 1832 * - If the instruction uses the same vector for both inputs, the range of the 1833 * indices will be 0 to 15. In this case, the RHSStart value passed should 1834 * be 0. 1835 * - If the instruction has two different vectors then the range of the 1836 * indices will be 0 to 31. In this case, the RHSStart value passed should 1837 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1838 * to 31 specify elements in the second vector). 1839 * 1840 * \param[in] N The shuffle vector SD Node to analyze 1841 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1842 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1843 * vector to the shuffle_vector instruction 1844 * \return true iff this shuffle vector represents an even or odd word merge 1845 */ 1846 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1847 unsigned RHSStartValue) { 1848 if (N->getValueType(0) != MVT::v16i8) 1849 return false; 1850 1851 for (unsigned i = 0; i < 2; ++i) 1852 for (unsigned j = 0; j < 4; ++j) 1853 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1854 i*RHSStartValue+j+IndexOffset) || 1855 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1856 i*RHSStartValue+j+IndexOffset+8)) 1857 return false; 1858 return true; 1859 } 1860 1861 /** 1862 * Determine if the specified shuffle mask is suitable for the vmrgew or 1863 * vmrgow instructions. 1864 * 1865 * \param[in] N The shuffle vector SD Node to analyze 1866 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1867 * \param[in] ShuffleKind Identify the type of merge: 1868 * - 0 = big-endian merge with two different inputs; 1869 * - 1 = either-endian merge with two identical inputs; 1870 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1871 * little-endian merges). 1872 * \param[in] DAG The current SelectionDAG 1873 * \return true iff this shuffle mask 1874 */ 1875 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1876 unsigned ShuffleKind, SelectionDAG &DAG) { 1877 if (DAG.getDataLayout().isLittleEndian()) { 1878 unsigned indexOffset = CheckEven ? 4 : 0; 1879 if (ShuffleKind == 1) // Unary 1880 return isVMerge(N, indexOffset, 0); 1881 else if (ShuffleKind == 2) // swapped 1882 return isVMerge(N, indexOffset, 16); 1883 else 1884 return false; 1885 } 1886 else { 1887 unsigned indexOffset = CheckEven ? 0 : 4; 1888 if (ShuffleKind == 1) // Unary 1889 return isVMerge(N, indexOffset, 0); 1890 else if (ShuffleKind == 0) // Normal 1891 return isVMerge(N, indexOffset, 16); 1892 else 1893 return false; 1894 } 1895 return false; 1896 } 1897 1898 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1899 /// amount, otherwise return -1. 1900 /// The ShuffleKind distinguishes between big-endian operations with two 1901 /// different inputs (0), either-endian operations with two identical inputs 1902 /// (1), and little-endian operations with two different inputs (2). For the 1903 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1904 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1905 SelectionDAG &DAG) { 1906 if (N->getValueType(0) != MVT::v16i8) 1907 return -1; 1908 1909 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1910 1911 // Find the first non-undef value in the shuffle mask. 1912 unsigned i; 1913 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1914 /*search*/; 1915 1916 if (i == 16) return -1; // all undef. 1917 1918 // Otherwise, check to see if the rest of the elements are consecutively 1919 // numbered from this value. 1920 unsigned ShiftAmt = SVOp->getMaskElt(i); 1921 if (ShiftAmt < i) return -1; 1922 1923 ShiftAmt -= i; 1924 bool isLE = DAG.getDataLayout().isLittleEndian(); 1925 1926 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1927 // Check the rest of the elements to see if they are consecutive. 1928 for (++i; i != 16; ++i) 1929 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1930 return -1; 1931 } else if (ShuffleKind == 1) { 1932 // Check the rest of the elements to see if they are consecutive. 1933 for (++i; i != 16; ++i) 1934 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1935 return -1; 1936 } else 1937 return -1; 1938 1939 if (isLE) 1940 ShiftAmt = 16 - ShiftAmt; 1941 1942 return ShiftAmt; 1943 } 1944 1945 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1946 /// specifies a splat of a single element that is suitable for input to 1947 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1948 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1949 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1950 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1951 1952 // The consecutive indices need to specify an element, not part of two 1953 // different elements. So abandon ship early if this isn't the case. 1954 if (N->getMaskElt(0) % EltSize != 0) 1955 return false; 1956 1957 // This is a splat operation if each element of the permute is the same, and 1958 // if the value doesn't reference the second vector. 1959 unsigned ElementBase = N->getMaskElt(0); 1960 1961 // FIXME: Handle UNDEF elements too! 1962 if (ElementBase >= 16) 1963 return false; 1964 1965 // Check that the indices are consecutive, in the case of a multi-byte element 1966 // splatted with a v16i8 mask. 1967 for (unsigned i = 1; i != EltSize; ++i) 1968 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1969 return false; 1970 1971 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1972 if (N->getMaskElt(i) < 0) continue; 1973 for (unsigned j = 0; j != EltSize; ++j) 1974 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1975 return false; 1976 } 1977 return true; 1978 } 1979 1980 /// Check that the mask is shuffling N byte elements. Within each N byte 1981 /// element of the mask, the indices could be either in increasing or 1982 /// decreasing order as long as they are consecutive. 1983 /// \param[in] N the shuffle vector SD Node to analyze 1984 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1985 /// Word/DoubleWord/QuadWord). 1986 /// \param[in] StepLen the delta indices number among the N byte element, if 1987 /// the mask is in increasing/decreasing order then it is 1/-1. 1988 /// \return true iff the mask is shuffling N byte elements. 1989 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1990 int StepLen) { 1991 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1992 "Unexpected element width."); 1993 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1994 1995 unsigned NumOfElem = 16 / Width; 1996 unsigned MaskVal[16]; // Width is never greater than 16 1997 for (unsigned i = 0; i < NumOfElem; ++i) { 1998 MaskVal[0] = N->getMaskElt(i * Width); 1999 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2000 return false; 2001 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2002 return false; 2003 } 2004 2005 for (unsigned int j = 1; j < Width; ++j) { 2006 MaskVal[j] = N->getMaskElt(i * Width + j); 2007 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2008 return false; 2009 } 2010 } 2011 } 2012 2013 return true; 2014 } 2015 2016 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2017 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2018 if (!isNByteElemShuffleMask(N, 4, 1)) 2019 return false; 2020 2021 // Now we look at mask elements 0,4,8,12 2022 unsigned M0 = N->getMaskElt(0) / 4; 2023 unsigned M1 = N->getMaskElt(4) / 4; 2024 unsigned M2 = N->getMaskElt(8) / 4; 2025 unsigned M3 = N->getMaskElt(12) / 4; 2026 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2027 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2028 2029 // Below, let H and L be arbitrary elements of the shuffle mask 2030 // where H is in the range [4,7] and L is in the range [0,3]. 2031 // H, 1, 2, 3 or L, 5, 6, 7 2032 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2033 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2034 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2035 InsertAtByte = IsLE ? 12 : 0; 2036 Swap = M0 < 4; 2037 return true; 2038 } 2039 // 0, H, 2, 3 or 4, L, 6, 7 2040 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2041 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2042 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2043 InsertAtByte = IsLE ? 8 : 4; 2044 Swap = M1 < 4; 2045 return true; 2046 } 2047 // 0, 1, H, 3 or 4, 5, L, 7 2048 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2049 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2050 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2051 InsertAtByte = IsLE ? 4 : 8; 2052 Swap = M2 < 4; 2053 return true; 2054 } 2055 // 0, 1, 2, H or 4, 5, 6, L 2056 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2057 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2058 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2059 InsertAtByte = IsLE ? 0 : 12; 2060 Swap = M3 < 4; 2061 return true; 2062 } 2063 2064 // If both vector operands for the shuffle are the same vector, the mask will 2065 // contain only elements from the first one and the second one will be undef. 2066 if (N->getOperand(1).isUndef()) { 2067 ShiftElts = 0; 2068 Swap = true; 2069 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2070 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2071 InsertAtByte = IsLE ? 12 : 0; 2072 return true; 2073 } 2074 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2075 InsertAtByte = IsLE ? 8 : 4; 2076 return true; 2077 } 2078 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2079 InsertAtByte = IsLE ? 4 : 8; 2080 return true; 2081 } 2082 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2083 InsertAtByte = IsLE ? 0 : 12; 2084 return true; 2085 } 2086 } 2087 2088 return false; 2089 } 2090 2091 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2092 bool &Swap, bool IsLE) { 2093 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2094 // Ensure each byte index of the word is consecutive. 2095 if (!isNByteElemShuffleMask(N, 4, 1)) 2096 return false; 2097 2098 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2099 unsigned M0 = N->getMaskElt(0) / 4; 2100 unsigned M1 = N->getMaskElt(4) / 4; 2101 unsigned M2 = N->getMaskElt(8) / 4; 2102 unsigned M3 = N->getMaskElt(12) / 4; 2103 2104 // If both vector operands for the shuffle are the same vector, the mask will 2105 // contain only elements from the first one and the second one will be undef. 2106 if (N->getOperand(1).isUndef()) { 2107 assert(M0 < 4 && "Indexing into an undef vector?"); 2108 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2109 return false; 2110 2111 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2112 Swap = false; 2113 return true; 2114 } 2115 2116 // Ensure each word index of the ShuffleVector Mask is consecutive. 2117 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2118 return false; 2119 2120 if (IsLE) { 2121 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2122 // Input vectors don't need to be swapped if the leading element 2123 // of the result is one of the 3 left elements of the second vector 2124 // (or if there is no shift to be done at all). 2125 Swap = false; 2126 ShiftElts = (8 - M0) % 8; 2127 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2128 // Input vectors need to be swapped if the leading element 2129 // of the result is one of the 3 left elements of the first vector 2130 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2131 Swap = true; 2132 ShiftElts = (4 - M0) % 4; 2133 } 2134 2135 return true; 2136 } else { // BE 2137 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2138 // Input vectors don't need to be swapped if the leading element 2139 // of the result is one of the 4 elements of the first vector. 2140 Swap = false; 2141 ShiftElts = M0; 2142 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2143 // Input vectors need to be swapped if the leading element 2144 // of the result is one of the 4 elements of the right vector. 2145 Swap = true; 2146 ShiftElts = M0 - 4; 2147 } 2148 2149 return true; 2150 } 2151 } 2152 2153 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2154 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2155 2156 if (!isNByteElemShuffleMask(N, Width, -1)) 2157 return false; 2158 2159 for (int i = 0; i < 16; i += Width) 2160 if (N->getMaskElt(i) != i + Width - 1) 2161 return false; 2162 2163 return true; 2164 } 2165 2166 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2167 return isXXBRShuffleMaskHelper(N, 2); 2168 } 2169 2170 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2171 return isXXBRShuffleMaskHelper(N, 4); 2172 } 2173 2174 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2175 return isXXBRShuffleMaskHelper(N, 8); 2176 } 2177 2178 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2179 return isXXBRShuffleMaskHelper(N, 16); 2180 } 2181 2182 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2183 /// if the inputs to the instruction should be swapped and set \p DM to the 2184 /// value for the immediate. 2185 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2186 /// AND element 0 of the result comes from the first input (LE) or second input 2187 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2188 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2189 /// mask. 2190 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2191 bool &Swap, bool IsLE) { 2192 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2193 2194 // Ensure each byte index of the double word is consecutive. 2195 if (!isNByteElemShuffleMask(N, 8, 1)) 2196 return false; 2197 2198 unsigned M0 = N->getMaskElt(0) / 8; 2199 unsigned M1 = N->getMaskElt(8) / 8; 2200 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2201 2202 // If both vector operands for the shuffle are the same vector, the mask will 2203 // contain only elements from the first one and the second one will be undef. 2204 if (N->getOperand(1).isUndef()) { 2205 if ((M0 | M1) < 2) { 2206 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2207 Swap = false; 2208 return true; 2209 } else 2210 return false; 2211 } 2212 2213 if (IsLE) { 2214 if (M0 > 1 && M1 < 2) { 2215 Swap = false; 2216 } else if (M0 < 2 && M1 > 1) { 2217 M0 = (M0 + 2) % 4; 2218 M1 = (M1 + 2) % 4; 2219 Swap = true; 2220 } else 2221 return false; 2222 2223 // Note: if control flow comes here that means Swap is already set above 2224 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2225 return true; 2226 } else { // BE 2227 if (M0 < 2 && M1 > 1) { 2228 Swap = false; 2229 } else if (M0 > 1 && M1 < 2) { 2230 M0 = (M0 + 2) % 4; 2231 M1 = (M1 + 2) % 4; 2232 Swap = true; 2233 } else 2234 return false; 2235 2236 // Note: if control flow comes here that means Swap is already set above 2237 DM = (M0 << 1) + (M1 & 1); 2238 return true; 2239 } 2240 } 2241 2242 2243 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2244 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2245 /// elements are counted from the left of the vector register). 2246 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2247 SelectionDAG &DAG) { 2248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2249 assert(isSplatShuffleMask(SVOp, EltSize)); 2250 if (DAG.getDataLayout().isLittleEndian()) 2251 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2252 else 2253 return SVOp->getMaskElt(0) / EltSize; 2254 } 2255 2256 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2257 /// by using a vspltis[bhw] instruction of the specified element size, return 2258 /// the constant being splatted. The ByteSize field indicates the number of 2259 /// bytes of each element [124] -> [bhw]. 2260 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2261 SDValue OpVal(nullptr, 0); 2262 2263 // If ByteSize of the splat is bigger than the element size of the 2264 // build_vector, then we have a case where we are checking for a splat where 2265 // multiple elements of the buildvector are folded together into a single 2266 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2267 unsigned EltSize = 16/N->getNumOperands(); 2268 if (EltSize < ByteSize) { 2269 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2270 SDValue UniquedVals[4]; 2271 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2272 2273 // See if all of the elements in the buildvector agree across. 2274 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2275 if (N->getOperand(i).isUndef()) continue; 2276 // If the element isn't a constant, bail fully out. 2277 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2278 2279 if (!UniquedVals[i&(Multiple-1)].getNode()) 2280 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2281 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2282 return SDValue(); // no match. 2283 } 2284 2285 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2286 // either constant or undef values that are identical for each chunk. See 2287 // if these chunks can form into a larger vspltis*. 2288 2289 // Check to see if all of the leading entries are either 0 or -1. If 2290 // neither, then this won't fit into the immediate field. 2291 bool LeadingZero = true; 2292 bool LeadingOnes = true; 2293 for (unsigned i = 0; i != Multiple-1; ++i) { 2294 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2295 2296 LeadingZero &= isNullConstant(UniquedVals[i]); 2297 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2298 } 2299 // Finally, check the least significant entry. 2300 if (LeadingZero) { 2301 if (!UniquedVals[Multiple-1].getNode()) 2302 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2303 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2304 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2305 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2306 } 2307 if (LeadingOnes) { 2308 if (!UniquedVals[Multiple-1].getNode()) 2309 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2310 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2311 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2312 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2313 } 2314 2315 return SDValue(); 2316 } 2317 2318 // Check to see if this buildvec has a single non-undef value in its elements. 2319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2320 if (N->getOperand(i).isUndef()) continue; 2321 if (!OpVal.getNode()) 2322 OpVal = N->getOperand(i); 2323 else if (OpVal != N->getOperand(i)) 2324 return SDValue(); 2325 } 2326 2327 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2328 2329 unsigned ValSizeInBytes = EltSize; 2330 uint64_t Value = 0; 2331 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2332 Value = CN->getZExtValue(); 2333 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2334 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2335 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2336 } 2337 2338 // If the splat value is larger than the element value, then we can never do 2339 // this splat. The only case that we could fit the replicated bits into our 2340 // immediate field for would be zero, and we prefer to use vxor for it. 2341 if (ValSizeInBytes < ByteSize) return SDValue(); 2342 2343 // If the element value is larger than the splat value, check if it consists 2344 // of a repeated bit pattern of size ByteSize. 2345 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2346 return SDValue(); 2347 2348 // Properly sign extend the value. 2349 int MaskVal = SignExtend32(Value, ByteSize * 8); 2350 2351 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2352 if (MaskVal == 0) return SDValue(); 2353 2354 // Finally, if this value fits in a 5 bit sext field, return it 2355 if (SignExtend32<5>(MaskVal) == MaskVal) 2356 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2357 return SDValue(); 2358 } 2359 2360 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2361 /// amount, otherwise return -1. 2362 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2363 EVT VT = N->getValueType(0); 2364 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2365 return -1; 2366 2367 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2368 2369 // Find the first non-undef value in the shuffle mask. 2370 unsigned i; 2371 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2372 /*search*/; 2373 2374 if (i == 4) return -1; // all undef. 2375 2376 // Otherwise, check to see if the rest of the elements are consecutively 2377 // numbered from this value. 2378 unsigned ShiftAmt = SVOp->getMaskElt(i); 2379 if (ShiftAmt < i) return -1; 2380 ShiftAmt -= i; 2381 2382 // Check the rest of the elements to see if they are consecutive. 2383 for (++i; i != 4; ++i) 2384 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2385 return -1; 2386 2387 return ShiftAmt; 2388 } 2389 2390 //===----------------------------------------------------------------------===// 2391 // Addressing Mode Selection 2392 //===----------------------------------------------------------------------===// 2393 2394 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2395 /// or 64-bit immediate, and if the value can be accurately represented as a 2396 /// sign extension from a 16-bit value. If so, this returns true and the 2397 /// immediate. 2398 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2399 if (!isa<ConstantSDNode>(N)) 2400 return false; 2401 2402 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2403 if (N->getValueType(0) == MVT::i32) 2404 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2405 else 2406 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2407 } 2408 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2409 return isIntS16Immediate(Op.getNode(), Imm); 2410 } 2411 2412 2413 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2414 /// be represented as an indexed [r+r] operation. 2415 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2416 SDValue &Index, 2417 SelectionDAG &DAG) const { 2418 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2419 UI != E; ++UI) { 2420 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2421 if (Memop->getMemoryVT() == MVT::f64) { 2422 Base = N.getOperand(0); 2423 Index = N.getOperand(1); 2424 return true; 2425 } 2426 } 2427 } 2428 return false; 2429 } 2430 2431 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2432 /// can be represented as an indexed [r+r] operation. Returns false if it 2433 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2434 /// non-zero and N can be represented by a base register plus a signed 16-bit 2435 /// displacement, make a more precise judgement by checking (displacement % \p 2436 /// EncodingAlignment). 2437 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2438 SDValue &Index, SelectionDAG &DAG, 2439 unsigned EncodingAlignment) const { 2440 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2441 // a [pc+imm]. 2442 if (SelectAddressPCRel(N, Base)) 2443 return false; 2444 2445 int16_t imm = 0; 2446 if (N.getOpcode() == ISD::ADD) { 2447 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2448 // SPE load/store can only handle 8-bit offsets. 2449 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2450 return true; 2451 if (isIntS16Immediate(N.getOperand(1), imm) && 2452 (!EncodingAlignment || !(imm % EncodingAlignment))) 2453 return false; // r+i 2454 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2455 return false; // r+i 2456 2457 Base = N.getOperand(0); 2458 Index = N.getOperand(1); 2459 return true; 2460 } else if (N.getOpcode() == ISD::OR) { 2461 if (isIntS16Immediate(N.getOperand(1), imm) && 2462 (!EncodingAlignment || !(imm % EncodingAlignment))) 2463 return false; // r+i can fold it if we can. 2464 2465 // If this is an or of disjoint bitfields, we can codegen this as an add 2466 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2467 // disjoint. 2468 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2469 2470 if (LHSKnown.Zero.getBoolValue()) { 2471 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2472 // If all of the bits are known zero on the LHS or RHS, the add won't 2473 // carry. 2474 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2475 Base = N.getOperand(0); 2476 Index = N.getOperand(1); 2477 return true; 2478 } 2479 } 2480 } 2481 2482 return false; 2483 } 2484 2485 // If we happen to be doing an i64 load or store into a stack slot that has 2486 // less than a 4-byte alignment, then the frame-index elimination may need to 2487 // use an indexed load or store instruction (because the offset may not be a 2488 // multiple of 4). The extra register needed to hold the offset comes from the 2489 // register scavenger, and it is possible that the scavenger will need to use 2490 // an emergency spill slot. As a result, we need to make sure that a spill slot 2491 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2492 // stack slot. 2493 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2494 // FIXME: This does not handle the LWA case. 2495 if (VT != MVT::i64) 2496 return; 2497 2498 // NOTE: We'll exclude negative FIs here, which come from argument 2499 // lowering, because there are no known test cases triggering this problem 2500 // using packed structures (or similar). We can remove this exclusion if 2501 // we find such a test case. The reason why this is so test-case driven is 2502 // because this entire 'fixup' is only to prevent crashes (from the 2503 // register scavenger) on not-really-valid inputs. For example, if we have: 2504 // %a = alloca i1 2505 // %b = bitcast i1* %a to i64* 2506 // store i64* a, i64 b 2507 // then the store should really be marked as 'align 1', but is not. If it 2508 // were marked as 'align 1' then the indexed form would have been 2509 // instruction-selected initially, and the problem this 'fixup' is preventing 2510 // won't happen regardless. 2511 if (FrameIdx < 0) 2512 return; 2513 2514 MachineFunction &MF = DAG.getMachineFunction(); 2515 MachineFrameInfo &MFI = MF.getFrameInfo(); 2516 2517 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2518 return; 2519 2520 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2521 FuncInfo->setHasNonRISpills(); 2522 } 2523 2524 /// Returns true if the address N can be represented by a base register plus 2525 /// a signed 16-bit displacement [r+imm], and if it is not better 2526 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2527 /// displacements that are multiples of that value. 2528 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2529 SDValue &Base, 2530 SelectionDAG &DAG, 2531 unsigned EncodingAlignment) const { 2532 // FIXME dl should come from parent load or store, not from address 2533 SDLoc dl(N); 2534 2535 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2536 // a [pc+imm]. 2537 if (SelectAddressPCRel(N, Base)) 2538 return false; 2539 2540 // If this can be more profitably realized as r+r, fail. 2541 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2542 return false; 2543 2544 if (N.getOpcode() == ISD::ADD) { 2545 int16_t imm = 0; 2546 if (isIntS16Immediate(N.getOperand(1), imm) && 2547 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2548 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2549 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2550 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2551 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2552 } else { 2553 Base = N.getOperand(0); 2554 } 2555 return true; // [r+i] 2556 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2557 // Match LOAD (ADD (X, Lo(G))). 2558 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2559 && "Cannot handle constant offsets yet!"); 2560 Disp = N.getOperand(1).getOperand(0); // The global address. 2561 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2562 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2563 Disp.getOpcode() == ISD::TargetConstantPool || 2564 Disp.getOpcode() == ISD::TargetJumpTable); 2565 Base = N.getOperand(0); 2566 return true; // [&g+r] 2567 } 2568 } else if (N.getOpcode() == ISD::OR) { 2569 int16_t imm = 0; 2570 if (isIntS16Immediate(N.getOperand(1), imm) && 2571 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2572 // If this is an or of disjoint bitfields, we can codegen this as an add 2573 // (for better address arithmetic) if the LHS and RHS of the OR are 2574 // provably disjoint. 2575 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2576 2577 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2578 // If all of the bits are known zero on the LHS or RHS, the add won't 2579 // carry. 2580 if (FrameIndexSDNode *FI = 2581 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2582 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2583 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2584 } else { 2585 Base = N.getOperand(0); 2586 } 2587 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2588 return true; 2589 } 2590 } 2591 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2592 // Loading from a constant address. 2593 2594 // If this address fits entirely in a 16-bit sext immediate field, codegen 2595 // this as "d, 0" 2596 int16_t Imm; 2597 if (isIntS16Immediate(CN, Imm) && 2598 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2599 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2600 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2601 CN->getValueType(0)); 2602 return true; 2603 } 2604 2605 // Handle 32-bit sext immediates with LIS + addr mode. 2606 if ((CN->getValueType(0) == MVT::i32 || 2607 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2608 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2609 int Addr = (int)CN->getZExtValue(); 2610 2611 // Otherwise, break this down into an LIS + disp. 2612 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2613 2614 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2615 MVT::i32); 2616 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2617 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2618 return true; 2619 } 2620 } 2621 2622 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2623 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2624 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2625 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2626 } else 2627 Base = N; 2628 return true; // [r+0] 2629 } 2630 2631 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2632 /// represented as an indexed [r+r] operation. 2633 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2634 SDValue &Index, 2635 SelectionDAG &DAG) const { 2636 // Check to see if we can easily represent this as an [r+r] address. This 2637 // will fail if it thinks that the address is more profitably represented as 2638 // reg+imm, e.g. where imm = 0. 2639 if (SelectAddressRegReg(N, Base, Index, DAG)) 2640 return true; 2641 2642 // If the address is the result of an add, we will utilize the fact that the 2643 // address calculation includes an implicit add. However, we can reduce 2644 // register pressure if we do not materialize a constant just for use as the 2645 // index register. We only get rid of the add if it is not an add of a 2646 // value and a 16-bit signed constant and both have a single use. 2647 int16_t imm = 0; 2648 if (N.getOpcode() == ISD::ADD && 2649 (!isIntS16Immediate(N.getOperand(1), imm) || 2650 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2651 Base = N.getOperand(0); 2652 Index = N.getOperand(1); 2653 return true; 2654 } 2655 2656 // Otherwise, do it the hard way, using R0 as the base register. 2657 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2658 N.getValueType()); 2659 Index = N; 2660 return true; 2661 } 2662 2663 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2664 Ty *PCRelCand = dyn_cast<Ty>(N); 2665 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2666 } 2667 2668 /// Returns true if this address is a PC Relative address. 2669 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2670 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2671 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2672 // This is a materialize PC Relative node. Always select this as PC Relative. 2673 Base = N; 2674 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2675 return true; 2676 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2677 isValidPCRelNode<GlobalAddressSDNode>(N) || 2678 isValidPCRelNode<JumpTableSDNode>(N) || 2679 isValidPCRelNode<BlockAddressSDNode>(N)) 2680 return true; 2681 return false; 2682 } 2683 2684 /// Returns true if we should use a direct load into vector instruction 2685 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2686 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2687 2688 // If there are any other uses other than scalar to vector, then we should 2689 // keep it as a scalar load -> direct move pattern to prevent multiple 2690 // loads. 2691 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2692 if (!LD) 2693 return false; 2694 2695 EVT MemVT = LD->getMemoryVT(); 2696 if (!MemVT.isSimple()) 2697 return false; 2698 switch(MemVT.getSimpleVT().SimpleTy) { 2699 case MVT::i64: 2700 break; 2701 case MVT::i32: 2702 if (!ST.hasP8Vector()) 2703 return false; 2704 break; 2705 case MVT::i16: 2706 case MVT::i8: 2707 if (!ST.hasP9Vector()) 2708 return false; 2709 break; 2710 default: 2711 return false; 2712 } 2713 2714 SDValue LoadedVal(N, 0); 2715 if (!LoadedVal.hasOneUse()) 2716 return false; 2717 2718 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2719 UI != UE; ++UI) 2720 if (UI.getUse().get().getResNo() == 0 && 2721 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2722 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2723 return false; 2724 2725 return true; 2726 } 2727 2728 /// getPreIndexedAddressParts - returns true by value, base pointer and 2729 /// offset pointer and addressing mode by reference if the node's address 2730 /// can be legally represented as pre-indexed load / store address. 2731 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2732 SDValue &Offset, 2733 ISD::MemIndexedMode &AM, 2734 SelectionDAG &DAG) const { 2735 if (DisablePPCPreinc) return false; 2736 2737 bool isLoad = true; 2738 SDValue Ptr; 2739 EVT VT; 2740 unsigned Alignment; 2741 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2742 Ptr = LD->getBasePtr(); 2743 VT = LD->getMemoryVT(); 2744 Alignment = LD->getAlignment(); 2745 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2746 Ptr = ST->getBasePtr(); 2747 VT = ST->getMemoryVT(); 2748 Alignment = ST->getAlignment(); 2749 isLoad = false; 2750 } else 2751 return false; 2752 2753 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2754 // instructions because we can fold these into a more efficient instruction 2755 // instead, (such as LXSD). 2756 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2757 return false; 2758 } 2759 2760 // PowerPC doesn't have preinc load/store instructions for vectors (except 2761 // for QPX, which does have preinc r+r forms). 2762 if (VT.isVector()) { 2763 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2764 return false; 2765 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2766 AM = ISD::PRE_INC; 2767 return true; 2768 } 2769 } 2770 2771 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2772 // Common code will reject creating a pre-inc form if the base pointer 2773 // is a frame index, or if N is a store and the base pointer is either 2774 // the same as or a predecessor of the value being stored. Check for 2775 // those situations here, and try with swapped Base/Offset instead. 2776 bool Swap = false; 2777 2778 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2779 Swap = true; 2780 else if (!isLoad) { 2781 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2782 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2783 Swap = true; 2784 } 2785 2786 if (Swap) 2787 std::swap(Base, Offset); 2788 2789 AM = ISD::PRE_INC; 2790 return true; 2791 } 2792 2793 // LDU/STU can only handle immediates that are a multiple of 4. 2794 if (VT != MVT::i64) { 2795 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2796 return false; 2797 } else { 2798 // LDU/STU need an address with at least 4-byte alignment. 2799 if (Alignment < 4) 2800 return false; 2801 2802 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2803 return false; 2804 } 2805 2806 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2807 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2808 // sext i32 to i64 when addr mode is r+i. 2809 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2810 LD->getExtensionType() == ISD::SEXTLOAD && 2811 isa<ConstantSDNode>(Offset)) 2812 return false; 2813 } 2814 2815 AM = ISD::PRE_INC; 2816 return true; 2817 } 2818 2819 //===----------------------------------------------------------------------===// 2820 // LowerOperation implementation 2821 //===----------------------------------------------------------------------===// 2822 2823 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2824 /// and LoOpFlags to the target MO flags. 2825 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2826 unsigned &HiOpFlags, unsigned &LoOpFlags, 2827 const GlobalValue *GV = nullptr) { 2828 HiOpFlags = PPCII::MO_HA; 2829 LoOpFlags = PPCII::MO_LO; 2830 2831 // Don't use the pic base if not in PIC relocation model. 2832 if (IsPIC) { 2833 HiOpFlags |= PPCII::MO_PIC_FLAG; 2834 LoOpFlags |= PPCII::MO_PIC_FLAG; 2835 } 2836 } 2837 2838 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2839 SelectionDAG &DAG) { 2840 SDLoc DL(HiPart); 2841 EVT PtrVT = HiPart.getValueType(); 2842 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2843 2844 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2845 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2846 2847 // With PIC, the first instruction is actually "GR+hi(&G)". 2848 if (isPIC) 2849 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2850 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2851 2852 // Generate non-pic code that has direct accesses to the constant pool. 2853 // The address of the global is just (hi(&g)+lo(&g)). 2854 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2855 } 2856 2857 static void setUsesTOCBasePtr(MachineFunction &MF) { 2858 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2859 FuncInfo->setUsesTOCBasePtr(); 2860 } 2861 2862 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2863 setUsesTOCBasePtr(DAG.getMachineFunction()); 2864 } 2865 2866 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2867 SDValue GA) const { 2868 const bool Is64Bit = Subtarget.isPPC64(); 2869 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2870 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2871 : Subtarget.isAIXABI() 2872 ? DAG.getRegister(PPC::R2, VT) 2873 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2874 SDValue Ops[] = { GA, Reg }; 2875 return DAG.getMemIntrinsicNode( 2876 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2877 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2878 MachineMemOperand::MOLoad); 2879 } 2880 2881 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2882 SelectionDAG &DAG) const { 2883 EVT PtrVT = Op.getValueType(); 2884 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2885 const Constant *C = CP->getConstVal(); 2886 2887 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2888 // The actual address of the GlobalValue is stored in the TOC. 2889 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2890 if (Subtarget.isUsingPCRelativeCalls()) { 2891 SDLoc DL(CP); 2892 EVT Ty = getPointerTy(DAG.getDataLayout()); 2893 SDValue ConstPool = DAG.getTargetConstantPool( 2894 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2895 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2896 } 2897 setUsesTOCBasePtr(DAG); 2898 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2899 return getTOCEntry(DAG, SDLoc(CP), GA); 2900 } 2901 2902 unsigned MOHiFlag, MOLoFlag; 2903 bool IsPIC = isPositionIndependent(); 2904 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2905 2906 if (IsPIC && Subtarget.isSVR4ABI()) { 2907 SDValue GA = 2908 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2909 return getTOCEntry(DAG, SDLoc(CP), GA); 2910 } 2911 2912 SDValue CPIHi = 2913 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2914 SDValue CPILo = 2915 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2916 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2917 } 2918 2919 // For 64-bit PowerPC, prefer the more compact relative encodings. 2920 // This trades 32 bits per jump table entry for one or two instructions 2921 // on the jump site. 2922 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2923 if (isJumpTableRelative()) 2924 return MachineJumpTableInfo::EK_LabelDifference32; 2925 2926 return TargetLowering::getJumpTableEncoding(); 2927 } 2928 2929 bool PPCTargetLowering::isJumpTableRelative() const { 2930 if (UseAbsoluteJumpTables) 2931 return false; 2932 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2933 return true; 2934 return TargetLowering::isJumpTableRelative(); 2935 } 2936 2937 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2938 SelectionDAG &DAG) const { 2939 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2940 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2941 2942 switch (getTargetMachine().getCodeModel()) { 2943 case CodeModel::Small: 2944 case CodeModel::Medium: 2945 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2946 default: 2947 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2948 getPointerTy(DAG.getDataLayout())); 2949 } 2950 } 2951 2952 const MCExpr * 2953 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2954 unsigned JTI, 2955 MCContext &Ctx) const { 2956 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2957 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2958 2959 switch (getTargetMachine().getCodeModel()) { 2960 case CodeModel::Small: 2961 case CodeModel::Medium: 2962 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2963 default: 2964 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2965 } 2966 } 2967 2968 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2969 EVT PtrVT = Op.getValueType(); 2970 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2971 2972 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2973 if (Subtarget.isUsingPCRelativeCalls()) { 2974 SDLoc DL(JT); 2975 EVT Ty = getPointerTy(DAG.getDataLayout()); 2976 SDValue GA = 2977 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2978 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2979 return MatAddr; 2980 } 2981 2982 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2983 // The actual address of the GlobalValue is stored in the TOC. 2984 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2985 setUsesTOCBasePtr(DAG); 2986 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2987 return getTOCEntry(DAG, SDLoc(JT), GA); 2988 } 2989 2990 unsigned MOHiFlag, MOLoFlag; 2991 bool IsPIC = isPositionIndependent(); 2992 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2993 2994 if (IsPIC && Subtarget.isSVR4ABI()) { 2995 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2996 PPCII::MO_PIC_FLAG); 2997 return getTOCEntry(DAG, SDLoc(GA), GA); 2998 } 2999 3000 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3001 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3002 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3003 } 3004 3005 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3006 SelectionDAG &DAG) const { 3007 EVT PtrVT = Op.getValueType(); 3008 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3009 const BlockAddress *BA = BASDN->getBlockAddress(); 3010 3011 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3012 if (Subtarget.isUsingPCRelativeCalls()) { 3013 SDLoc DL(BASDN); 3014 EVT Ty = getPointerTy(DAG.getDataLayout()); 3015 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3016 PPCII::MO_PCREL_FLAG); 3017 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3018 return MatAddr; 3019 } 3020 3021 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3022 // The actual BlockAddress is stored in the TOC. 3023 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3024 setUsesTOCBasePtr(DAG); 3025 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3026 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3027 } 3028 3029 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3030 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3031 return getTOCEntry( 3032 DAG, SDLoc(BASDN), 3033 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3034 3035 unsigned MOHiFlag, MOLoFlag; 3036 bool IsPIC = isPositionIndependent(); 3037 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3038 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3039 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3040 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3041 } 3042 3043 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3044 SelectionDAG &DAG) const { 3045 // FIXME: TLS addresses currently use medium model code sequences, 3046 // which is the most useful form. Eventually support for small and 3047 // large models could be added if users need it, at the cost of 3048 // additional complexity. 3049 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3050 if (DAG.getTarget().useEmulatedTLS()) 3051 return LowerToTLSEmulatedModel(GA, DAG); 3052 3053 SDLoc dl(GA); 3054 const GlobalValue *GV = GA->getGlobal(); 3055 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3056 bool is64bit = Subtarget.isPPC64(); 3057 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3058 PICLevel::Level picLevel = M->getPICLevel(); 3059 3060 const TargetMachine &TM = getTargetMachine(); 3061 TLSModel::Model Model = TM.getTLSModel(GV); 3062 3063 if (Model == TLSModel::LocalExec) { 3064 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3065 PPCII::MO_TPREL_HA); 3066 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3067 PPCII::MO_TPREL_LO); 3068 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3069 : DAG.getRegister(PPC::R2, MVT::i32); 3070 3071 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3072 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3073 } 3074 3075 if (Model == TLSModel::InitialExec) { 3076 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3077 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3078 PPCII::MO_TLS); 3079 SDValue GOTPtr; 3080 if (is64bit) { 3081 setUsesTOCBasePtr(DAG); 3082 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3083 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3084 PtrVT, GOTReg, TGA); 3085 } else { 3086 if (!TM.isPositionIndependent()) 3087 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3088 else if (picLevel == PICLevel::SmallPIC) 3089 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3090 else 3091 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3092 } 3093 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3094 PtrVT, TGA, GOTPtr); 3095 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3096 } 3097 3098 if (Model == TLSModel::GeneralDynamic) { 3099 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3100 SDValue GOTPtr; 3101 if (is64bit) { 3102 setUsesTOCBasePtr(DAG); 3103 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3104 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3105 GOTReg, TGA); 3106 } else { 3107 if (picLevel == PICLevel::SmallPIC) 3108 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3109 else 3110 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3111 } 3112 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3113 GOTPtr, TGA, TGA); 3114 } 3115 3116 if (Model == TLSModel::LocalDynamic) { 3117 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3118 SDValue GOTPtr; 3119 if (is64bit) { 3120 setUsesTOCBasePtr(DAG); 3121 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3122 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3123 GOTReg, TGA); 3124 } else { 3125 if (picLevel == PICLevel::SmallPIC) 3126 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3127 else 3128 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3129 } 3130 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3131 PtrVT, GOTPtr, TGA, TGA); 3132 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3133 PtrVT, TLSAddr, TGA); 3134 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3135 } 3136 3137 llvm_unreachable("Unknown TLS model!"); 3138 } 3139 3140 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3141 SelectionDAG &DAG) const { 3142 EVT PtrVT = Op.getValueType(); 3143 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3144 SDLoc DL(GSDN); 3145 const GlobalValue *GV = GSDN->getGlobal(); 3146 3147 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3148 // The actual address of the GlobalValue is stored in the TOC. 3149 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3150 if (Subtarget.isUsingPCRelativeCalls()) { 3151 EVT Ty = getPointerTy(DAG.getDataLayout()); 3152 if (isAccessedAsGotIndirect(Op)) { 3153 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3154 PPCII::MO_PCREL_FLAG | 3155 PPCII::MO_GOT_FLAG); 3156 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3157 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3158 MachinePointerInfo()); 3159 return Load; 3160 } else { 3161 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3162 PPCII::MO_PCREL_FLAG); 3163 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3164 } 3165 } 3166 setUsesTOCBasePtr(DAG); 3167 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3168 return getTOCEntry(DAG, DL, GA); 3169 } 3170 3171 unsigned MOHiFlag, MOLoFlag; 3172 bool IsPIC = isPositionIndependent(); 3173 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3174 3175 if (IsPIC && Subtarget.isSVR4ABI()) { 3176 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3177 GSDN->getOffset(), 3178 PPCII::MO_PIC_FLAG); 3179 return getTOCEntry(DAG, DL, GA); 3180 } 3181 3182 SDValue GAHi = 3183 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3184 SDValue GALo = 3185 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3186 3187 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3188 } 3189 3190 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3191 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3192 SDLoc dl(Op); 3193 3194 if (Op.getValueType() == MVT::v2i64) { 3195 // When the operands themselves are v2i64 values, we need to do something 3196 // special because VSX has no underlying comparison operations for these. 3197 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3198 // Equality can be handled by casting to the legal type for Altivec 3199 // comparisons, everything else needs to be expanded. 3200 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3201 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3202 DAG.getSetCC(dl, MVT::v4i32, 3203 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3204 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3205 CC)); 3206 } 3207 3208 return SDValue(); 3209 } 3210 3211 // We handle most of these in the usual way. 3212 return Op; 3213 } 3214 3215 // If we're comparing for equality to zero, expose the fact that this is 3216 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3217 // fold the new nodes. 3218 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3219 return V; 3220 3221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3222 // Leave comparisons against 0 and -1 alone for now, since they're usually 3223 // optimized. FIXME: revisit this when we can custom lower all setcc 3224 // optimizations. 3225 if (C->isAllOnesValue() || C->isNullValue()) 3226 return SDValue(); 3227 } 3228 3229 // If we have an integer seteq/setne, turn it into a compare against zero 3230 // by xor'ing the rhs with the lhs, which is faster than setting a 3231 // condition register, reading it back out, and masking the correct bit. The 3232 // normal approach here uses sub to do this instead of xor. Using xor exposes 3233 // the result to other bit-twiddling opportunities. 3234 EVT LHSVT = Op.getOperand(0).getValueType(); 3235 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3236 EVT VT = Op.getValueType(); 3237 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3238 Op.getOperand(1)); 3239 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3240 } 3241 return SDValue(); 3242 } 3243 3244 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3245 SDNode *Node = Op.getNode(); 3246 EVT VT = Node->getValueType(0); 3247 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3248 SDValue InChain = Node->getOperand(0); 3249 SDValue VAListPtr = Node->getOperand(1); 3250 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3251 SDLoc dl(Node); 3252 3253 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3254 3255 // gpr_index 3256 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3257 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3258 InChain = GprIndex.getValue(1); 3259 3260 if (VT == MVT::i64) { 3261 // Check if GprIndex is even 3262 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3263 DAG.getConstant(1, dl, MVT::i32)); 3264 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3265 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3266 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3267 DAG.getConstant(1, dl, MVT::i32)); 3268 // Align GprIndex to be even if it isn't 3269 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3270 GprIndex); 3271 } 3272 3273 // fpr index is 1 byte after gpr 3274 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3275 DAG.getConstant(1, dl, MVT::i32)); 3276 3277 // fpr 3278 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3279 FprPtr, MachinePointerInfo(SV), MVT::i8); 3280 InChain = FprIndex.getValue(1); 3281 3282 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3283 DAG.getConstant(8, dl, MVT::i32)); 3284 3285 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3286 DAG.getConstant(4, dl, MVT::i32)); 3287 3288 // areas 3289 SDValue OverflowArea = 3290 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3291 InChain = OverflowArea.getValue(1); 3292 3293 SDValue RegSaveArea = 3294 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3295 InChain = RegSaveArea.getValue(1); 3296 3297 // select overflow_area if index > 8 3298 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3299 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3300 3301 // adjustment constant gpr_index * 4/8 3302 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3303 VT.isInteger() ? GprIndex : FprIndex, 3304 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3305 MVT::i32)); 3306 3307 // OurReg = RegSaveArea + RegConstant 3308 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3309 RegConstant); 3310 3311 // Floating types are 32 bytes into RegSaveArea 3312 if (VT.isFloatingPoint()) 3313 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3314 DAG.getConstant(32, dl, MVT::i32)); 3315 3316 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3317 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3318 VT.isInteger() ? GprIndex : FprIndex, 3319 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3320 MVT::i32)); 3321 3322 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3323 VT.isInteger() ? VAListPtr : FprPtr, 3324 MachinePointerInfo(SV), MVT::i8); 3325 3326 // determine if we should load from reg_save_area or overflow_area 3327 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3328 3329 // increase overflow_area by 4/8 if gpr/fpr > 8 3330 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3331 DAG.getConstant(VT.isInteger() ? 4 : 8, 3332 dl, MVT::i32)); 3333 3334 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3335 OverflowAreaPlusN); 3336 3337 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3338 MachinePointerInfo(), MVT::i32); 3339 3340 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3341 } 3342 3343 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3344 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3345 3346 // We have to copy the entire va_list struct: 3347 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3348 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3349 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3350 false, true, false, MachinePointerInfo(), 3351 MachinePointerInfo()); 3352 } 3353 3354 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3355 SelectionDAG &DAG) const { 3356 if (Subtarget.isAIXABI()) 3357 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3358 3359 return Op.getOperand(0); 3360 } 3361 3362 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3363 SelectionDAG &DAG) const { 3364 if (Subtarget.isAIXABI()) 3365 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3366 3367 SDValue Chain = Op.getOperand(0); 3368 SDValue Trmp = Op.getOperand(1); // trampoline 3369 SDValue FPtr = Op.getOperand(2); // nested function 3370 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3371 SDLoc dl(Op); 3372 3373 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3374 bool isPPC64 = (PtrVT == MVT::i64); 3375 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3376 3377 TargetLowering::ArgListTy Args; 3378 TargetLowering::ArgListEntry Entry; 3379 3380 Entry.Ty = IntPtrTy; 3381 Entry.Node = Trmp; Args.push_back(Entry); 3382 3383 // TrampSize == (isPPC64 ? 48 : 40); 3384 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3385 isPPC64 ? MVT::i64 : MVT::i32); 3386 Args.push_back(Entry); 3387 3388 Entry.Node = FPtr; Args.push_back(Entry); 3389 Entry.Node = Nest; Args.push_back(Entry); 3390 3391 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3392 TargetLowering::CallLoweringInfo CLI(DAG); 3393 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3394 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3395 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3396 3397 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3398 return CallResult.second; 3399 } 3400 3401 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3402 MachineFunction &MF = DAG.getMachineFunction(); 3403 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3404 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3405 3406 SDLoc dl(Op); 3407 3408 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3409 // vastart just stores the address of the VarArgsFrameIndex slot into the 3410 // memory location argument. 3411 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3412 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3413 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3414 MachinePointerInfo(SV)); 3415 } 3416 3417 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3418 // We suppose the given va_list is already allocated. 3419 // 3420 // typedef struct { 3421 // char gpr; /* index into the array of 8 GPRs 3422 // * stored in the register save area 3423 // * gpr=0 corresponds to r3, 3424 // * gpr=1 to r4, etc. 3425 // */ 3426 // char fpr; /* index into the array of 8 FPRs 3427 // * stored in the register save area 3428 // * fpr=0 corresponds to f1, 3429 // * fpr=1 to f2, etc. 3430 // */ 3431 // char *overflow_arg_area; 3432 // /* location on stack that holds 3433 // * the next overflow argument 3434 // */ 3435 // char *reg_save_area; 3436 // /* where r3:r10 and f1:f8 (if saved) 3437 // * are stored 3438 // */ 3439 // } va_list[1]; 3440 3441 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3442 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3443 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3444 PtrVT); 3445 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3446 PtrVT); 3447 3448 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3449 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3450 3451 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3452 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3453 3454 uint64_t FPROffset = 1; 3455 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3456 3457 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3458 3459 // Store first byte : number of int regs 3460 SDValue firstStore = 3461 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3462 MachinePointerInfo(SV), MVT::i8); 3463 uint64_t nextOffset = FPROffset; 3464 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3465 ConstFPROffset); 3466 3467 // Store second byte : number of float regs 3468 SDValue secondStore = 3469 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3470 MachinePointerInfo(SV, nextOffset), MVT::i8); 3471 nextOffset += StackOffset; 3472 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3473 3474 // Store second word : arguments given on stack 3475 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3476 MachinePointerInfo(SV, nextOffset)); 3477 nextOffset += FrameOffset; 3478 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3479 3480 // Store third word : arguments given in registers 3481 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3482 MachinePointerInfo(SV, nextOffset)); 3483 } 3484 3485 /// FPR - The set of FP registers that should be allocated for arguments 3486 /// on Darwin and AIX. 3487 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3488 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3489 PPC::F11, PPC::F12, PPC::F13}; 3490 3491 /// QFPR - The set of QPX registers that should be allocated for arguments. 3492 static const MCPhysReg QFPR[] = { 3493 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3494 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3495 3496 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3497 /// the stack. 3498 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3499 unsigned PtrByteSize) { 3500 unsigned ArgSize = ArgVT.getStoreSize(); 3501 if (Flags.isByVal()) 3502 ArgSize = Flags.getByValSize(); 3503 3504 // Round up to multiples of the pointer size, except for array members, 3505 // which are always packed. 3506 if (!Flags.isInConsecutiveRegs()) 3507 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3508 3509 return ArgSize; 3510 } 3511 3512 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3513 /// on the stack. 3514 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3515 ISD::ArgFlagsTy Flags, 3516 unsigned PtrByteSize) { 3517 Align Alignment(PtrByteSize); 3518 3519 // Altivec parameters are padded to a 16 byte boundary. 3520 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3521 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3522 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3523 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3524 Alignment = Align(16); 3525 // QPX vector types stored in double-precision are padded to a 32 byte 3526 // boundary. 3527 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3528 Alignment = Align(32); 3529 3530 // ByVal parameters are aligned as requested. 3531 if (Flags.isByVal()) { 3532 auto BVAlign = Flags.getNonZeroByValAlign(); 3533 if (BVAlign > PtrByteSize) { 3534 if (BVAlign.value() % PtrByteSize != 0) 3535 llvm_unreachable( 3536 "ByVal alignment is not a multiple of the pointer size"); 3537 3538 Alignment = BVAlign; 3539 } 3540 } 3541 3542 // Array members are always packed to their original alignment. 3543 if (Flags.isInConsecutiveRegs()) { 3544 // If the array member was split into multiple registers, the first 3545 // needs to be aligned to the size of the full type. (Except for 3546 // ppcf128, which is only aligned as its f64 components.) 3547 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3548 Alignment = Align(OrigVT.getStoreSize()); 3549 else 3550 Alignment = Align(ArgVT.getStoreSize()); 3551 } 3552 3553 return Alignment; 3554 } 3555 3556 /// CalculateStackSlotUsed - Return whether this argument will use its 3557 /// stack slot (instead of being passed in registers). ArgOffset, 3558 /// AvailableFPRs, and AvailableVRs must hold the current argument 3559 /// position, and will be updated to account for this argument. 3560 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3561 ISD::ArgFlagsTy Flags, 3562 unsigned PtrByteSize, 3563 unsigned LinkageSize, 3564 unsigned ParamAreaSize, 3565 unsigned &ArgOffset, 3566 unsigned &AvailableFPRs, 3567 unsigned &AvailableVRs, bool HasQPX) { 3568 bool UseMemory = false; 3569 3570 // Respect alignment of argument on the stack. 3571 Align Alignment = 3572 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3573 ArgOffset = alignTo(ArgOffset, Alignment); 3574 // If there's no space left in the argument save area, we must 3575 // use memory (this check also catches zero-sized arguments). 3576 if (ArgOffset >= LinkageSize + ParamAreaSize) 3577 UseMemory = true; 3578 3579 // Allocate argument on the stack. 3580 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3581 if (Flags.isInConsecutiveRegsLast()) 3582 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3583 // If we overran the argument save area, we must use memory 3584 // (this check catches arguments passed partially in memory) 3585 if (ArgOffset > LinkageSize + ParamAreaSize) 3586 UseMemory = true; 3587 3588 // However, if the argument is actually passed in an FPR or a VR, 3589 // we don't use memory after all. 3590 if (!Flags.isByVal()) { 3591 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3592 // QPX registers overlap with the scalar FP registers. 3593 (HasQPX && (ArgVT == MVT::v4f32 || 3594 ArgVT == MVT::v4f64 || 3595 ArgVT == MVT::v4i1))) 3596 if (AvailableFPRs > 0) { 3597 --AvailableFPRs; 3598 return false; 3599 } 3600 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3601 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3602 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3603 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3604 if (AvailableVRs > 0) { 3605 --AvailableVRs; 3606 return false; 3607 } 3608 } 3609 3610 return UseMemory; 3611 } 3612 3613 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3614 /// ensure minimum alignment required for target. 3615 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3616 unsigned NumBytes) { 3617 return alignTo(NumBytes, Lowering->getStackAlign()); 3618 } 3619 3620 SDValue PPCTargetLowering::LowerFormalArguments( 3621 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3622 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3623 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3624 if (Subtarget.isAIXABI()) 3625 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3626 InVals); 3627 if (Subtarget.is64BitELFABI()) 3628 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3629 InVals); 3630 if (Subtarget.is32BitELFABI()) 3631 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3632 InVals); 3633 3634 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3635 InVals); 3636 } 3637 3638 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3639 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3640 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3641 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3642 3643 // 32-bit SVR4 ABI Stack Frame Layout: 3644 // +-----------------------------------+ 3645 // +--> | Back chain | 3646 // | +-----------------------------------+ 3647 // | | Floating-point register save area | 3648 // | +-----------------------------------+ 3649 // | | General register save area | 3650 // | +-----------------------------------+ 3651 // | | CR save word | 3652 // | +-----------------------------------+ 3653 // | | VRSAVE save word | 3654 // | +-----------------------------------+ 3655 // | | Alignment padding | 3656 // | +-----------------------------------+ 3657 // | | Vector register save area | 3658 // | +-----------------------------------+ 3659 // | | Local variable space | 3660 // | +-----------------------------------+ 3661 // | | Parameter list area | 3662 // | +-----------------------------------+ 3663 // | | LR save word | 3664 // | +-----------------------------------+ 3665 // SP--> +--- | Back chain | 3666 // +-----------------------------------+ 3667 // 3668 // Specifications: 3669 // System V Application Binary Interface PowerPC Processor Supplement 3670 // AltiVec Technology Programming Interface Manual 3671 3672 MachineFunction &MF = DAG.getMachineFunction(); 3673 MachineFrameInfo &MFI = MF.getFrameInfo(); 3674 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3675 3676 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3677 // Potential tail calls could cause overwriting of argument stack slots. 3678 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3679 (CallConv == CallingConv::Fast)); 3680 const Align PtrAlign(4); 3681 3682 // Assign locations to all of the incoming arguments. 3683 SmallVector<CCValAssign, 16> ArgLocs; 3684 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3685 *DAG.getContext()); 3686 3687 // Reserve space for the linkage area on the stack. 3688 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3689 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3690 if (useSoftFloat()) 3691 CCInfo.PreAnalyzeFormalArguments(Ins); 3692 3693 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3694 CCInfo.clearWasPPCF128(); 3695 3696 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3697 CCValAssign &VA = ArgLocs[i]; 3698 3699 // Arguments stored in registers. 3700 if (VA.isRegLoc()) { 3701 const TargetRegisterClass *RC; 3702 EVT ValVT = VA.getValVT(); 3703 3704 switch (ValVT.getSimpleVT().SimpleTy) { 3705 default: 3706 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3707 case MVT::i1: 3708 case MVT::i32: 3709 RC = &PPC::GPRCRegClass; 3710 break; 3711 case MVT::f32: 3712 if (Subtarget.hasP8Vector()) 3713 RC = &PPC::VSSRCRegClass; 3714 else if (Subtarget.hasSPE()) 3715 RC = &PPC::GPRCRegClass; 3716 else 3717 RC = &PPC::F4RCRegClass; 3718 break; 3719 case MVT::f64: 3720 if (Subtarget.hasVSX()) 3721 RC = &PPC::VSFRCRegClass; 3722 else if (Subtarget.hasSPE()) 3723 // SPE passes doubles in GPR pairs. 3724 RC = &PPC::GPRCRegClass; 3725 else 3726 RC = &PPC::F8RCRegClass; 3727 break; 3728 case MVT::v16i8: 3729 case MVT::v8i16: 3730 case MVT::v4i32: 3731 RC = &PPC::VRRCRegClass; 3732 break; 3733 case MVT::v4f32: 3734 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3735 break; 3736 case MVT::v2f64: 3737 case MVT::v2i64: 3738 RC = &PPC::VRRCRegClass; 3739 break; 3740 case MVT::v4f64: 3741 RC = &PPC::QFRCRegClass; 3742 break; 3743 case MVT::v4i1: 3744 RC = &PPC::QBRCRegClass; 3745 break; 3746 } 3747 3748 SDValue ArgValue; 3749 // Transform the arguments stored in physical registers into 3750 // virtual ones. 3751 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3752 assert(i + 1 < e && "No second half of double precision argument"); 3753 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3754 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3755 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3756 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3757 if (!Subtarget.isLittleEndian()) 3758 std::swap (ArgValueLo, ArgValueHi); 3759 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3760 ArgValueHi); 3761 } else { 3762 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3763 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3764 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3765 if (ValVT == MVT::i1) 3766 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3767 } 3768 3769 InVals.push_back(ArgValue); 3770 } else { 3771 // Argument stored in memory. 3772 assert(VA.isMemLoc()); 3773 3774 // Get the extended size of the argument type in stack 3775 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3776 // Get the actual size of the argument type 3777 unsigned ObjSize = VA.getValVT().getStoreSize(); 3778 unsigned ArgOffset = VA.getLocMemOffset(); 3779 // Stack objects in PPC32 are right justified. 3780 ArgOffset += ArgSize - ObjSize; 3781 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3782 3783 // Create load nodes to retrieve arguments from the stack. 3784 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3785 InVals.push_back( 3786 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3787 } 3788 } 3789 3790 // Assign locations to all of the incoming aggregate by value arguments. 3791 // Aggregates passed by value are stored in the local variable space of the 3792 // caller's stack frame, right above the parameter list area. 3793 SmallVector<CCValAssign, 16> ByValArgLocs; 3794 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3795 ByValArgLocs, *DAG.getContext()); 3796 3797 // Reserve stack space for the allocations in CCInfo. 3798 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3799 3800 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3801 3802 // Area that is at least reserved in the caller of this function. 3803 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3804 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3805 3806 // Set the size that is at least reserved in caller of this function. Tail 3807 // call optimized function's reserved stack space needs to be aligned so that 3808 // taking the difference between two stack areas will result in an aligned 3809 // stack. 3810 MinReservedArea = 3811 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3812 FuncInfo->setMinReservedArea(MinReservedArea); 3813 3814 SmallVector<SDValue, 8> MemOps; 3815 3816 // If the function takes variable number of arguments, make a frame index for 3817 // the start of the first vararg value... for expansion of llvm.va_start. 3818 if (isVarArg) { 3819 static const MCPhysReg GPArgRegs[] = { 3820 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3821 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3822 }; 3823 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3824 3825 static const MCPhysReg FPArgRegs[] = { 3826 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3827 PPC::F8 3828 }; 3829 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3830 3831 if (useSoftFloat() || hasSPE()) 3832 NumFPArgRegs = 0; 3833 3834 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3835 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3836 3837 // Make room for NumGPArgRegs and NumFPArgRegs. 3838 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3839 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3840 3841 FuncInfo->setVarArgsStackOffset( 3842 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3843 CCInfo.getNextStackOffset(), true)); 3844 3845 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3846 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3847 3848 // The fixed integer arguments of a variadic function are stored to the 3849 // VarArgsFrameIndex on the stack so that they may be loaded by 3850 // dereferencing the result of va_next. 3851 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3852 // Get an existing live-in vreg, or add a new one. 3853 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3854 if (!VReg) 3855 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3856 3857 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3858 SDValue Store = 3859 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3860 MemOps.push_back(Store); 3861 // Increment the address by four for the next argument to store 3862 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3863 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3864 } 3865 3866 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3867 // is set. 3868 // The double arguments are stored to the VarArgsFrameIndex 3869 // on the stack. 3870 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3871 // Get an existing live-in vreg, or add a new one. 3872 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3873 if (!VReg) 3874 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3875 3876 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3877 SDValue Store = 3878 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3879 MemOps.push_back(Store); 3880 // Increment the address by eight for the next argument to store 3881 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3882 PtrVT); 3883 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3884 } 3885 } 3886 3887 if (!MemOps.empty()) 3888 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3889 3890 return Chain; 3891 } 3892 3893 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3894 // value to MVT::i64 and then truncate to the correct register size. 3895 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3896 EVT ObjectVT, SelectionDAG &DAG, 3897 SDValue ArgVal, 3898 const SDLoc &dl) const { 3899 if (Flags.isSExt()) 3900 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3901 DAG.getValueType(ObjectVT)); 3902 else if (Flags.isZExt()) 3903 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3904 DAG.getValueType(ObjectVT)); 3905 3906 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3907 } 3908 3909 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3910 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3911 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3912 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3913 // TODO: add description of PPC stack frame format, or at least some docs. 3914 // 3915 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3916 bool isLittleEndian = Subtarget.isLittleEndian(); 3917 MachineFunction &MF = DAG.getMachineFunction(); 3918 MachineFrameInfo &MFI = MF.getFrameInfo(); 3919 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3920 3921 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3922 "fastcc not supported on varargs functions"); 3923 3924 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3925 // Potential tail calls could cause overwriting of argument stack slots. 3926 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3927 (CallConv == CallingConv::Fast)); 3928 unsigned PtrByteSize = 8; 3929 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3930 3931 static const MCPhysReg GPR[] = { 3932 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3933 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3934 }; 3935 static const MCPhysReg VR[] = { 3936 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3937 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3938 }; 3939 3940 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3941 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3942 const unsigned Num_VR_Regs = array_lengthof(VR); 3943 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3944 3945 // Do a first pass over the arguments to determine whether the ABI 3946 // guarantees that our caller has allocated the parameter save area 3947 // on its stack frame. In the ELFv1 ABI, this is always the case; 3948 // in the ELFv2 ABI, it is true if this is a vararg function or if 3949 // any parameter is located in a stack slot. 3950 3951 bool HasParameterArea = !isELFv2ABI || isVarArg; 3952 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3953 unsigned NumBytes = LinkageSize; 3954 unsigned AvailableFPRs = Num_FPR_Regs; 3955 unsigned AvailableVRs = Num_VR_Regs; 3956 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3957 if (Ins[i].Flags.isNest()) 3958 continue; 3959 3960 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3961 PtrByteSize, LinkageSize, ParamAreaSize, 3962 NumBytes, AvailableFPRs, AvailableVRs, 3963 Subtarget.hasQPX())) 3964 HasParameterArea = true; 3965 } 3966 3967 // Add DAG nodes to load the arguments or copy them out of registers. On 3968 // entry to a function on PPC, the arguments start after the linkage area, 3969 // although the first ones are often in registers. 3970 3971 unsigned ArgOffset = LinkageSize; 3972 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3973 unsigned &QFPR_idx = FPR_idx; 3974 SmallVector<SDValue, 8> MemOps; 3975 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3976 unsigned CurArgIdx = 0; 3977 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3978 SDValue ArgVal; 3979 bool needsLoad = false; 3980 EVT ObjectVT = Ins[ArgNo].VT; 3981 EVT OrigVT = Ins[ArgNo].ArgVT; 3982 unsigned ObjSize = ObjectVT.getStoreSize(); 3983 unsigned ArgSize = ObjSize; 3984 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3985 if (Ins[ArgNo].isOrigArg()) { 3986 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3987 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3988 } 3989 // We re-align the argument offset for each argument, except when using the 3990 // fast calling convention, when we need to make sure we do that only when 3991 // we'll actually use a stack slot. 3992 unsigned CurArgOffset; 3993 Align Alignment; 3994 auto ComputeArgOffset = [&]() { 3995 /* Respect alignment of argument on the stack. */ 3996 Alignment = 3997 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3998 ArgOffset = alignTo(ArgOffset, Alignment); 3999 CurArgOffset = ArgOffset; 4000 }; 4001 4002 if (CallConv != CallingConv::Fast) { 4003 ComputeArgOffset(); 4004 4005 /* Compute GPR index associated with argument offset. */ 4006 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4007 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4008 } 4009 4010 // FIXME the codegen can be much improved in some cases. 4011 // We do not have to keep everything in memory. 4012 if (Flags.isByVal()) { 4013 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4014 4015 if (CallConv == CallingConv::Fast) 4016 ComputeArgOffset(); 4017 4018 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4019 ObjSize = Flags.getByValSize(); 4020 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4021 // Empty aggregate parameters do not take up registers. Examples: 4022 // struct { } a; 4023 // union { } b; 4024 // int c[0]; 4025 // etc. However, we have to provide a place-holder in InVals, so 4026 // pretend we have an 8-byte item at the current address for that 4027 // purpose. 4028 if (!ObjSize) { 4029 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4030 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4031 InVals.push_back(FIN); 4032 continue; 4033 } 4034 4035 // Create a stack object covering all stack doublewords occupied 4036 // by the argument. If the argument is (fully or partially) on 4037 // the stack, or if the argument is fully in registers but the 4038 // caller has allocated the parameter save anyway, we can refer 4039 // directly to the caller's stack frame. Otherwise, create a 4040 // local copy in our own frame. 4041 int FI; 4042 if (HasParameterArea || 4043 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4044 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4045 else 4046 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4047 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4048 4049 // Handle aggregates smaller than 8 bytes. 4050 if (ObjSize < PtrByteSize) { 4051 // The value of the object is its address, which differs from the 4052 // address of the enclosing doubleword on big-endian systems. 4053 SDValue Arg = FIN; 4054 if (!isLittleEndian) { 4055 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4056 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4057 } 4058 InVals.push_back(Arg); 4059 4060 if (GPR_idx != Num_GPR_Regs) { 4061 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4062 FuncInfo->addLiveInAttr(VReg, Flags); 4063 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4064 SDValue Store; 4065 4066 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4067 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4068 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4069 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4070 MachinePointerInfo(&*FuncArg), ObjType); 4071 } else { 4072 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4073 // store the whole register as-is to the parameter save area 4074 // slot. 4075 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4076 MachinePointerInfo(&*FuncArg)); 4077 } 4078 4079 MemOps.push_back(Store); 4080 } 4081 // Whether we copied from a register or not, advance the offset 4082 // into the parameter save area by a full doubleword. 4083 ArgOffset += PtrByteSize; 4084 continue; 4085 } 4086 4087 // The value of the object is its address, which is the address of 4088 // its first stack doubleword. 4089 InVals.push_back(FIN); 4090 4091 // Store whatever pieces of the object are in registers to memory. 4092 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4093 if (GPR_idx == Num_GPR_Regs) 4094 break; 4095 4096 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4097 FuncInfo->addLiveInAttr(VReg, Flags); 4098 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4099 SDValue Addr = FIN; 4100 if (j) { 4101 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4102 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4103 } 4104 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4105 MachinePointerInfo(&*FuncArg, j)); 4106 MemOps.push_back(Store); 4107 ++GPR_idx; 4108 } 4109 ArgOffset += ArgSize; 4110 continue; 4111 } 4112 4113 switch (ObjectVT.getSimpleVT().SimpleTy) { 4114 default: llvm_unreachable("Unhandled argument type!"); 4115 case MVT::i1: 4116 case MVT::i32: 4117 case MVT::i64: 4118 if (Flags.isNest()) { 4119 // The 'nest' parameter, if any, is passed in R11. 4120 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4121 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4122 4123 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4124 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4125 4126 break; 4127 } 4128 4129 // These can be scalar arguments or elements of an integer array type 4130 // passed directly. Clang may use those instead of "byval" aggregate 4131 // types to avoid forcing arguments to memory unnecessarily. 4132 if (GPR_idx != Num_GPR_Regs) { 4133 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4134 FuncInfo->addLiveInAttr(VReg, Flags); 4135 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4136 4137 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4138 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4139 // value to MVT::i64 and then truncate to the correct register size. 4140 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4141 } else { 4142 if (CallConv == CallingConv::Fast) 4143 ComputeArgOffset(); 4144 4145 needsLoad = true; 4146 ArgSize = PtrByteSize; 4147 } 4148 if (CallConv != CallingConv::Fast || needsLoad) 4149 ArgOffset += 8; 4150 break; 4151 4152 case MVT::f32: 4153 case MVT::f64: 4154 // These can be scalar arguments or elements of a float array type 4155 // passed directly. The latter are used to implement ELFv2 homogenous 4156 // float aggregates. 4157 if (FPR_idx != Num_FPR_Regs) { 4158 unsigned VReg; 4159 4160 if (ObjectVT == MVT::f32) 4161 VReg = MF.addLiveIn(FPR[FPR_idx], 4162 Subtarget.hasP8Vector() 4163 ? &PPC::VSSRCRegClass 4164 : &PPC::F4RCRegClass); 4165 else 4166 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4167 ? &PPC::VSFRCRegClass 4168 : &PPC::F8RCRegClass); 4169 4170 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4171 ++FPR_idx; 4172 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4173 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4174 // once we support fp <-> gpr moves. 4175 4176 // This can only ever happen in the presence of f32 array types, 4177 // since otherwise we never run out of FPRs before running out 4178 // of GPRs. 4179 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4180 FuncInfo->addLiveInAttr(VReg, Flags); 4181 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4182 4183 if (ObjectVT == MVT::f32) { 4184 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4185 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4186 DAG.getConstant(32, dl, MVT::i32)); 4187 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4188 } 4189 4190 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4191 } else { 4192 if (CallConv == CallingConv::Fast) 4193 ComputeArgOffset(); 4194 4195 needsLoad = true; 4196 } 4197 4198 // When passing an array of floats, the array occupies consecutive 4199 // space in the argument area; only round up to the next doubleword 4200 // at the end of the array. Otherwise, each float takes 8 bytes. 4201 if (CallConv != CallingConv::Fast || needsLoad) { 4202 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4203 ArgOffset += ArgSize; 4204 if (Flags.isInConsecutiveRegsLast()) 4205 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4206 } 4207 break; 4208 case MVT::v4f32: 4209 case MVT::v4i32: 4210 case MVT::v8i16: 4211 case MVT::v16i8: 4212 case MVT::v2f64: 4213 case MVT::v2i64: 4214 case MVT::v1i128: 4215 case MVT::f128: 4216 if (!Subtarget.hasQPX()) { 4217 // These can be scalar arguments or elements of a vector array type 4218 // passed directly. The latter are used to implement ELFv2 homogenous 4219 // vector aggregates. 4220 if (VR_idx != Num_VR_Regs) { 4221 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4222 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4223 ++VR_idx; 4224 } else { 4225 if (CallConv == CallingConv::Fast) 4226 ComputeArgOffset(); 4227 needsLoad = true; 4228 } 4229 if (CallConv != CallingConv::Fast || needsLoad) 4230 ArgOffset += 16; 4231 break; 4232 } // not QPX 4233 4234 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4235 "Invalid QPX parameter type"); 4236 LLVM_FALLTHROUGH; 4237 4238 case MVT::v4f64: 4239 case MVT::v4i1: 4240 // QPX vectors are treated like their scalar floating-point subregisters 4241 // (except that they're larger). 4242 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4243 if (QFPR_idx != Num_QFPR_Regs) { 4244 const TargetRegisterClass *RC; 4245 switch (ObjectVT.getSimpleVT().SimpleTy) { 4246 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4247 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4248 default: RC = &PPC::QBRCRegClass; break; 4249 } 4250 4251 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4252 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4253 ++QFPR_idx; 4254 } else { 4255 if (CallConv == CallingConv::Fast) 4256 ComputeArgOffset(); 4257 needsLoad = true; 4258 } 4259 if (CallConv != CallingConv::Fast || needsLoad) 4260 ArgOffset += Sz; 4261 break; 4262 } 4263 4264 // We need to load the argument to a virtual register if we determined 4265 // above that we ran out of physical registers of the appropriate type. 4266 if (needsLoad) { 4267 if (ObjSize < ArgSize && !isLittleEndian) 4268 CurArgOffset += ArgSize - ObjSize; 4269 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4270 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4271 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4272 } 4273 4274 InVals.push_back(ArgVal); 4275 } 4276 4277 // Area that is at least reserved in the caller of this function. 4278 unsigned MinReservedArea; 4279 if (HasParameterArea) 4280 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4281 else 4282 MinReservedArea = LinkageSize; 4283 4284 // Set the size that is at least reserved in caller of this function. Tail 4285 // call optimized functions' reserved stack space needs to be aligned so that 4286 // taking the difference between two stack areas will result in an aligned 4287 // stack. 4288 MinReservedArea = 4289 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4290 FuncInfo->setMinReservedArea(MinReservedArea); 4291 4292 // If the function takes variable number of arguments, make a frame index for 4293 // the start of the first vararg value... for expansion of llvm.va_start. 4294 if (isVarArg) { 4295 int Depth = ArgOffset; 4296 4297 FuncInfo->setVarArgsFrameIndex( 4298 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4299 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4300 4301 // If this function is vararg, store any remaining integer argument regs 4302 // to their spots on the stack so that they may be loaded by dereferencing 4303 // the result of va_next. 4304 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4305 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4306 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4307 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4308 SDValue Store = 4309 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4310 MemOps.push_back(Store); 4311 // Increment the address by four for the next argument to store 4312 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4313 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4314 } 4315 } 4316 4317 if (!MemOps.empty()) 4318 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4319 4320 return Chain; 4321 } 4322 4323 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4324 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4325 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4326 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4327 // TODO: add description of PPC stack frame format, or at least some docs. 4328 // 4329 MachineFunction &MF = DAG.getMachineFunction(); 4330 MachineFrameInfo &MFI = MF.getFrameInfo(); 4331 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4332 4333 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4334 bool isPPC64 = PtrVT == MVT::i64; 4335 // Potential tail calls could cause overwriting of argument stack slots. 4336 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4337 (CallConv == CallingConv::Fast)); 4338 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4339 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4340 unsigned ArgOffset = LinkageSize; 4341 // Area that is at least reserved in caller of this function. 4342 unsigned MinReservedArea = ArgOffset; 4343 4344 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4345 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4346 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4347 }; 4348 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4349 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4350 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4351 }; 4352 static const MCPhysReg VR[] = { 4353 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4354 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4355 }; 4356 4357 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4358 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4359 const unsigned Num_VR_Regs = array_lengthof( VR); 4360 4361 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4362 4363 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4364 4365 // In 32-bit non-varargs functions, the stack space for vectors is after the 4366 // stack space for non-vectors. We do not use this space unless we have 4367 // too many vectors to fit in registers, something that only occurs in 4368 // constructed examples:), but we have to walk the arglist to figure 4369 // that out...for the pathological case, compute VecArgOffset as the 4370 // start of the vector parameter area. Computing VecArgOffset is the 4371 // entire point of the following loop. 4372 unsigned VecArgOffset = ArgOffset; 4373 if (!isVarArg && !isPPC64) { 4374 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4375 ++ArgNo) { 4376 EVT ObjectVT = Ins[ArgNo].VT; 4377 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4378 4379 if (Flags.isByVal()) { 4380 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4381 unsigned ObjSize = Flags.getByValSize(); 4382 unsigned ArgSize = 4383 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4384 VecArgOffset += ArgSize; 4385 continue; 4386 } 4387 4388 switch(ObjectVT.getSimpleVT().SimpleTy) { 4389 default: llvm_unreachable("Unhandled argument type!"); 4390 case MVT::i1: 4391 case MVT::i32: 4392 case MVT::f32: 4393 VecArgOffset += 4; 4394 break; 4395 case MVT::i64: // PPC64 4396 case MVT::f64: 4397 // FIXME: We are guaranteed to be !isPPC64 at this point. 4398 // Does MVT::i64 apply? 4399 VecArgOffset += 8; 4400 break; 4401 case MVT::v4f32: 4402 case MVT::v4i32: 4403 case MVT::v8i16: 4404 case MVT::v16i8: 4405 // Nothing to do, we're only looking at Nonvector args here. 4406 break; 4407 } 4408 } 4409 } 4410 // We've found where the vector parameter area in memory is. Skip the 4411 // first 12 parameters; these don't use that memory. 4412 VecArgOffset = ((VecArgOffset+15)/16)*16; 4413 VecArgOffset += 12*16; 4414 4415 // Add DAG nodes to load the arguments or copy them out of registers. On 4416 // entry to a function on PPC, the arguments start after the linkage area, 4417 // although the first ones are often in registers. 4418 4419 SmallVector<SDValue, 8> MemOps; 4420 unsigned nAltivecParamsAtEnd = 0; 4421 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4422 unsigned CurArgIdx = 0; 4423 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4424 SDValue ArgVal; 4425 bool needsLoad = false; 4426 EVT ObjectVT = Ins[ArgNo].VT; 4427 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4428 unsigned ArgSize = ObjSize; 4429 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4430 if (Ins[ArgNo].isOrigArg()) { 4431 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4432 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4433 } 4434 unsigned CurArgOffset = ArgOffset; 4435 4436 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4437 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4438 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4439 if (isVarArg || isPPC64) { 4440 MinReservedArea = ((MinReservedArea+15)/16)*16; 4441 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4442 Flags, 4443 PtrByteSize); 4444 } else nAltivecParamsAtEnd++; 4445 } else 4446 // Calculate min reserved area. 4447 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4448 Flags, 4449 PtrByteSize); 4450 4451 // FIXME the codegen can be much improved in some cases. 4452 // We do not have to keep everything in memory. 4453 if (Flags.isByVal()) { 4454 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4455 4456 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4457 ObjSize = Flags.getByValSize(); 4458 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4459 // Objects of size 1 and 2 are right justified, everything else is 4460 // left justified. This means the memory address is adjusted forwards. 4461 if (ObjSize==1 || ObjSize==2) { 4462 CurArgOffset = CurArgOffset + (4 - ObjSize); 4463 } 4464 // The value of the object is its address. 4465 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4466 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4467 InVals.push_back(FIN); 4468 if (ObjSize==1 || ObjSize==2) { 4469 if (GPR_idx != Num_GPR_Regs) { 4470 unsigned VReg; 4471 if (isPPC64) 4472 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4473 else 4474 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4475 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4476 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4477 SDValue Store = 4478 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4479 MachinePointerInfo(&*FuncArg), ObjType); 4480 MemOps.push_back(Store); 4481 ++GPR_idx; 4482 } 4483 4484 ArgOffset += PtrByteSize; 4485 4486 continue; 4487 } 4488 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4489 // Store whatever pieces of the object are in registers 4490 // to memory. ArgOffset will be the address of the beginning 4491 // of the object. 4492 if (GPR_idx != Num_GPR_Regs) { 4493 unsigned VReg; 4494 if (isPPC64) 4495 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4496 else 4497 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4498 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4499 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4500 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4501 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4502 MachinePointerInfo(&*FuncArg, j)); 4503 MemOps.push_back(Store); 4504 ++GPR_idx; 4505 ArgOffset += PtrByteSize; 4506 } else { 4507 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4508 break; 4509 } 4510 } 4511 continue; 4512 } 4513 4514 switch (ObjectVT.getSimpleVT().SimpleTy) { 4515 default: llvm_unreachable("Unhandled argument type!"); 4516 case MVT::i1: 4517 case MVT::i32: 4518 if (!isPPC64) { 4519 if (GPR_idx != Num_GPR_Regs) { 4520 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4521 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4522 4523 if (ObjectVT == MVT::i1) 4524 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4525 4526 ++GPR_idx; 4527 } else { 4528 needsLoad = true; 4529 ArgSize = PtrByteSize; 4530 } 4531 // All int arguments reserve stack space in the Darwin ABI. 4532 ArgOffset += PtrByteSize; 4533 break; 4534 } 4535 LLVM_FALLTHROUGH; 4536 case MVT::i64: // PPC64 4537 if (GPR_idx != Num_GPR_Regs) { 4538 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4539 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4540 4541 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4542 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4543 // value to MVT::i64 and then truncate to the correct register size. 4544 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4545 4546 ++GPR_idx; 4547 } else { 4548 needsLoad = true; 4549 ArgSize = PtrByteSize; 4550 } 4551 // All int arguments reserve stack space in the Darwin ABI. 4552 ArgOffset += 8; 4553 break; 4554 4555 case MVT::f32: 4556 case MVT::f64: 4557 // Every 4 bytes of argument space consumes one of the GPRs available for 4558 // argument passing. 4559 if (GPR_idx != Num_GPR_Regs) { 4560 ++GPR_idx; 4561 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4562 ++GPR_idx; 4563 } 4564 if (FPR_idx != Num_FPR_Regs) { 4565 unsigned VReg; 4566 4567 if (ObjectVT == MVT::f32) 4568 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4569 else 4570 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4571 4572 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4573 ++FPR_idx; 4574 } else { 4575 needsLoad = true; 4576 } 4577 4578 // All FP arguments reserve stack space in the Darwin ABI. 4579 ArgOffset += isPPC64 ? 8 : ObjSize; 4580 break; 4581 case MVT::v4f32: 4582 case MVT::v4i32: 4583 case MVT::v8i16: 4584 case MVT::v16i8: 4585 // Note that vector arguments in registers don't reserve stack space, 4586 // except in varargs functions. 4587 if (VR_idx != Num_VR_Regs) { 4588 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4589 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4590 if (isVarArg) { 4591 while ((ArgOffset % 16) != 0) { 4592 ArgOffset += PtrByteSize; 4593 if (GPR_idx != Num_GPR_Regs) 4594 GPR_idx++; 4595 } 4596 ArgOffset += 16; 4597 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4598 } 4599 ++VR_idx; 4600 } else { 4601 if (!isVarArg && !isPPC64) { 4602 // Vectors go after all the nonvectors. 4603 CurArgOffset = VecArgOffset; 4604 VecArgOffset += 16; 4605 } else { 4606 // Vectors are aligned. 4607 ArgOffset = ((ArgOffset+15)/16)*16; 4608 CurArgOffset = ArgOffset; 4609 ArgOffset += 16; 4610 } 4611 needsLoad = true; 4612 } 4613 break; 4614 } 4615 4616 // We need to load the argument to a virtual register if we determined above 4617 // that we ran out of physical registers of the appropriate type. 4618 if (needsLoad) { 4619 int FI = MFI.CreateFixedObject(ObjSize, 4620 CurArgOffset + (ArgSize - ObjSize), 4621 isImmutable); 4622 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4623 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4624 } 4625 4626 InVals.push_back(ArgVal); 4627 } 4628 4629 // Allow for Altivec parameters at the end, if needed. 4630 if (nAltivecParamsAtEnd) { 4631 MinReservedArea = ((MinReservedArea+15)/16)*16; 4632 MinReservedArea += 16*nAltivecParamsAtEnd; 4633 } 4634 4635 // Area that is at least reserved in the caller of this function. 4636 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4637 4638 // Set the size that is at least reserved in caller of this function. Tail 4639 // call optimized functions' reserved stack space needs to be aligned so that 4640 // taking the difference between two stack areas will result in an aligned 4641 // stack. 4642 MinReservedArea = 4643 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4644 FuncInfo->setMinReservedArea(MinReservedArea); 4645 4646 // If the function takes variable number of arguments, make a frame index for 4647 // the start of the first vararg value... for expansion of llvm.va_start. 4648 if (isVarArg) { 4649 int Depth = ArgOffset; 4650 4651 FuncInfo->setVarArgsFrameIndex( 4652 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4653 Depth, true)); 4654 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4655 4656 // If this function is vararg, store any remaining integer argument regs 4657 // to their spots on the stack so that they may be loaded by dereferencing 4658 // the result of va_next. 4659 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4660 unsigned VReg; 4661 4662 if (isPPC64) 4663 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4664 else 4665 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4666 4667 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4668 SDValue Store = 4669 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4670 MemOps.push_back(Store); 4671 // Increment the address by four for the next argument to store 4672 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4673 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4674 } 4675 } 4676 4677 if (!MemOps.empty()) 4678 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4679 4680 return Chain; 4681 } 4682 4683 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4684 /// adjusted to accommodate the arguments for the tailcall. 4685 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4686 unsigned ParamSize) { 4687 4688 if (!isTailCall) return 0; 4689 4690 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4691 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4692 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4693 // Remember only if the new adjustment is bigger. 4694 if (SPDiff < FI->getTailCallSPDelta()) 4695 FI->setTailCallSPDelta(SPDiff); 4696 4697 return SPDiff; 4698 } 4699 4700 static bool isFunctionGlobalAddress(SDValue Callee); 4701 4702 static bool 4703 callsShareTOCBase(const Function *Caller, SDValue Callee, 4704 const TargetMachine &TM) { 4705 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4706 // don't have enough information to determine if the caller and calle share 4707 // the same TOC base, so we have to pessimistically assume they don't for 4708 // correctness. 4709 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4710 if (!G) 4711 return false; 4712 4713 const GlobalValue *GV = G->getGlobal(); 4714 // The medium and large code models are expected to provide a sufficiently 4715 // large TOC to provide all data addressing needs of a module with a 4716 // single TOC. Since each module will be addressed with a single TOC then we 4717 // only need to check that caller and callee don't cross dso boundaries. 4718 if (CodeModel::Medium == TM.getCodeModel() || 4719 CodeModel::Large == TM.getCodeModel()) 4720 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4721 4722 // Otherwise we need to ensure callee and caller are in the same section, 4723 // since the linker may allocate multiple TOCs, and we don't know which 4724 // sections will belong to the same TOC base. 4725 4726 if (!GV->isStrongDefinitionForLinker()) 4727 return false; 4728 4729 // Any explicitly-specified sections and section prefixes must also match. 4730 // Also, if we're using -ffunction-sections, then each function is always in 4731 // a different section (the same is true for COMDAT functions). 4732 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4733 GV->getSection() != Caller->getSection()) 4734 return false; 4735 if (const auto *F = dyn_cast<Function>(GV)) { 4736 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4737 return false; 4738 } 4739 4740 // If the callee might be interposed, then we can't assume the ultimate call 4741 // target will be in the same section. Even in cases where we can assume that 4742 // interposition won't happen, in any case where the linker might insert a 4743 // stub to allow for interposition, we must generate code as though 4744 // interposition might occur. To understand why this matters, consider a 4745 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4746 // in the same section, but a is in a different module (i.e. has a different 4747 // TOC base pointer). If the linker allows for interposition between b and c, 4748 // then it will generate a stub for the call edge between b and c which will 4749 // save the TOC pointer into the designated stack slot allocated by b. If we 4750 // return true here, and therefore allow a tail call between b and c, that 4751 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4752 // pointer into the stack slot allocated by a (where the a -> b stub saved 4753 // a's TOC base pointer). If we're not considering a tail call, but rather, 4754 // whether a nop is needed after the call instruction in b, because the linker 4755 // will insert a stub, it might complain about a missing nop if we omit it 4756 // (although many don't complain in this case). 4757 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4758 return false; 4759 4760 return true; 4761 } 4762 4763 static bool 4764 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4765 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4766 assert(Subtarget.is64BitELFABI()); 4767 4768 const unsigned PtrByteSize = 8; 4769 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4770 4771 static const MCPhysReg GPR[] = { 4772 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4773 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4774 }; 4775 static const MCPhysReg VR[] = { 4776 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4777 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4778 }; 4779 4780 const unsigned NumGPRs = array_lengthof(GPR); 4781 const unsigned NumFPRs = 13; 4782 const unsigned NumVRs = array_lengthof(VR); 4783 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4784 4785 unsigned NumBytes = LinkageSize; 4786 unsigned AvailableFPRs = NumFPRs; 4787 unsigned AvailableVRs = NumVRs; 4788 4789 for (const ISD::OutputArg& Param : Outs) { 4790 if (Param.Flags.isNest()) continue; 4791 4792 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4793 PtrByteSize, LinkageSize, ParamAreaSize, 4794 NumBytes, AvailableFPRs, AvailableVRs, 4795 Subtarget.hasQPX())) 4796 return true; 4797 } 4798 return false; 4799 } 4800 4801 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4802 if (CB.arg_size() != CallerFn->arg_size()) 4803 return false; 4804 4805 auto CalleeArgIter = CB.arg_begin(); 4806 auto CalleeArgEnd = CB.arg_end(); 4807 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4808 4809 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4810 const Value* CalleeArg = *CalleeArgIter; 4811 const Value* CallerArg = &(*CallerArgIter); 4812 if (CalleeArg == CallerArg) 4813 continue; 4814 4815 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4816 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4817 // } 4818 // 1st argument of callee is undef and has the same type as caller. 4819 if (CalleeArg->getType() == CallerArg->getType() && 4820 isa<UndefValue>(CalleeArg)) 4821 continue; 4822 4823 return false; 4824 } 4825 4826 return true; 4827 } 4828 4829 // Returns true if TCO is possible between the callers and callees 4830 // calling conventions. 4831 static bool 4832 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4833 CallingConv::ID CalleeCC) { 4834 // Tail calls are possible with fastcc and ccc. 4835 auto isTailCallableCC = [] (CallingConv::ID CC){ 4836 return CC == CallingConv::C || CC == CallingConv::Fast; 4837 }; 4838 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4839 return false; 4840 4841 // We can safely tail call both fastcc and ccc callees from a c calling 4842 // convention caller. If the caller is fastcc, we may have less stack space 4843 // than a non-fastcc caller with the same signature so disable tail-calls in 4844 // that case. 4845 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4846 } 4847 4848 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4849 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4850 const SmallVectorImpl<ISD::OutputArg> &Outs, 4851 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4852 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4853 4854 if (DisableSCO && !TailCallOpt) return false; 4855 4856 // Variadic argument functions are not supported. 4857 if (isVarArg) return false; 4858 4859 auto &Caller = DAG.getMachineFunction().getFunction(); 4860 // Check that the calling conventions are compatible for tco. 4861 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4862 return false; 4863 4864 // Caller contains any byval parameter is not supported. 4865 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4866 return false; 4867 4868 // Callee contains any byval parameter is not supported, too. 4869 // Note: This is a quick work around, because in some cases, e.g. 4870 // caller's stack size > callee's stack size, we are still able to apply 4871 // sibling call optimization. For example, gcc is able to do SCO for caller1 4872 // in the following example, but not for caller2. 4873 // struct test { 4874 // long int a; 4875 // char ary[56]; 4876 // } gTest; 4877 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4878 // b->a = v.a; 4879 // return 0; 4880 // } 4881 // void caller1(struct test a, struct test c, struct test *b) { 4882 // callee(gTest, b); } 4883 // void caller2(struct test *b) { callee(gTest, b); } 4884 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4885 return false; 4886 4887 // If callee and caller use different calling conventions, we cannot pass 4888 // parameters on stack since offsets for the parameter area may be different. 4889 if (Caller.getCallingConv() != CalleeCC && 4890 needStackSlotPassParameters(Subtarget, Outs)) 4891 return false; 4892 4893 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4894 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4895 // callee potentially have different TOC bases then we cannot tail call since 4896 // we need to restore the TOC pointer after the call. 4897 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4898 // We cannot guarantee this for indirect calls or calls to external functions. 4899 // When PC-Relative addressing is used, the concept of the TOC is no longer 4900 // applicable so this check is not required. 4901 // Check first for indirect calls. 4902 if (!Subtarget.isUsingPCRelativeCalls() && 4903 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4904 return false; 4905 4906 // Check if we share the TOC base. 4907 if (!Subtarget.isUsingPCRelativeCalls() && 4908 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4909 return false; 4910 4911 // TCO allows altering callee ABI, so we don't have to check further. 4912 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4913 return true; 4914 4915 if (DisableSCO) return false; 4916 4917 // If callee use the same argument list that caller is using, then we can 4918 // apply SCO on this case. If it is not, then we need to check if callee needs 4919 // stack for passing arguments. 4920 // PC Relative tail calls may not have a CallBase. 4921 // If there is no CallBase we cannot verify if we have the same argument 4922 // list so assume that we don't have the same argument list. 4923 if (CB && !hasSameArgumentList(&Caller, *CB) && 4924 needStackSlotPassParameters(Subtarget, Outs)) 4925 return false; 4926 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4927 return false; 4928 4929 return true; 4930 } 4931 4932 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4933 /// for tail call optimization. Targets which want to do tail call 4934 /// optimization should implement this function. 4935 bool 4936 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4937 CallingConv::ID CalleeCC, 4938 bool isVarArg, 4939 const SmallVectorImpl<ISD::InputArg> &Ins, 4940 SelectionDAG& DAG) const { 4941 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4942 return false; 4943 4944 // Variable argument functions are not supported. 4945 if (isVarArg) 4946 return false; 4947 4948 MachineFunction &MF = DAG.getMachineFunction(); 4949 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4950 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4951 // Functions containing by val parameters are not supported. 4952 for (unsigned i = 0; i != Ins.size(); i++) { 4953 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4954 if (Flags.isByVal()) return false; 4955 } 4956 4957 // Non-PIC/GOT tail calls are supported. 4958 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4959 return true; 4960 4961 // At the moment we can only do local tail calls (in same module, hidden 4962 // or protected) if we are generating PIC. 4963 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4964 return G->getGlobal()->hasHiddenVisibility() 4965 || G->getGlobal()->hasProtectedVisibility(); 4966 } 4967 4968 return false; 4969 } 4970 4971 /// isCallCompatibleAddress - Return the immediate to use if the specified 4972 /// 32-bit value is representable in the immediate field of a BxA instruction. 4973 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4974 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4975 if (!C) return nullptr; 4976 4977 int Addr = C->getZExtValue(); 4978 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4979 SignExtend32<26>(Addr) != Addr) 4980 return nullptr; // Top 6 bits have to be sext of immediate. 4981 4982 return DAG 4983 .getConstant( 4984 (int)C->getZExtValue() >> 2, SDLoc(Op), 4985 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4986 .getNode(); 4987 } 4988 4989 namespace { 4990 4991 struct TailCallArgumentInfo { 4992 SDValue Arg; 4993 SDValue FrameIdxOp; 4994 int FrameIdx = 0; 4995 4996 TailCallArgumentInfo() = default; 4997 }; 4998 4999 } // end anonymous namespace 5000 5001 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 5002 static void StoreTailCallArgumentsToStackSlot( 5003 SelectionDAG &DAG, SDValue Chain, 5004 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 5005 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 5006 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 5007 SDValue Arg = TailCallArgs[i].Arg; 5008 SDValue FIN = TailCallArgs[i].FrameIdxOp; 5009 int FI = TailCallArgs[i].FrameIdx; 5010 // Store relative to framepointer. 5011 MemOpChains.push_back(DAG.getStore( 5012 Chain, dl, Arg, FIN, 5013 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 5014 } 5015 } 5016 5017 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 5018 /// the appropriate stack slot for the tail call optimized function call. 5019 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 5020 SDValue OldRetAddr, SDValue OldFP, 5021 int SPDiff, const SDLoc &dl) { 5022 if (SPDiff) { 5023 // Calculate the new stack slot for the return address. 5024 MachineFunction &MF = DAG.getMachineFunction(); 5025 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5026 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5027 bool isPPC64 = Subtarget.isPPC64(); 5028 int SlotSize = isPPC64 ? 8 : 4; 5029 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5030 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5031 NewRetAddrLoc, true); 5032 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5033 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5034 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5035 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5036 } 5037 return Chain; 5038 } 5039 5040 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5041 /// the position of the argument. 5042 static void 5043 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5044 SDValue Arg, int SPDiff, unsigned ArgOffset, 5045 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5046 int Offset = ArgOffset + SPDiff; 5047 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5048 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5049 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5050 SDValue FIN = DAG.getFrameIndex(FI, VT); 5051 TailCallArgumentInfo Info; 5052 Info.Arg = Arg; 5053 Info.FrameIdxOp = FIN; 5054 Info.FrameIdx = FI; 5055 TailCallArguments.push_back(Info); 5056 } 5057 5058 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5059 /// stack slot. Returns the chain as result and the loaded frame pointers in 5060 /// LROpOut/FPOpout. Used when tail calling. 5061 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5062 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5063 SDValue &FPOpOut, const SDLoc &dl) const { 5064 if (SPDiff) { 5065 // Load the LR and FP stack slot for later adjusting. 5066 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5067 LROpOut = getReturnAddrFrameIndex(DAG); 5068 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5069 Chain = SDValue(LROpOut.getNode(), 1); 5070 } 5071 return Chain; 5072 } 5073 5074 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5075 /// by "Src" to address "Dst" of size "Size". Alignment information is 5076 /// specified by the specific parameter attribute. The copy will be passed as 5077 /// a byval function parameter. 5078 /// Sometimes what we are copying is the end of a larger object, the part that 5079 /// does not fit in registers. 5080 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5081 SDValue Chain, ISD::ArgFlagsTy Flags, 5082 SelectionDAG &DAG, const SDLoc &dl) { 5083 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5084 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5085 Flags.getNonZeroByValAlign(), false, false, false, 5086 MachinePointerInfo(), MachinePointerInfo()); 5087 } 5088 5089 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5090 /// tail calls. 5091 static void LowerMemOpCallTo( 5092 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5093 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5094 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5095 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5096 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5097 if (!isTailCall) { 5098 if (isVector) { 5099 SDValue StackPtr; 5100 if (isPPC64) 5101 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5102 else 5103 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5104 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5105 DAG.getConstant(ArgOffset, dl, PtrVT)); 5106 } 5107 MemOpChains.push_back( 5108 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5109 // Calculate and remember argument location. 5110 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5111 TailCallArguments); 5112 } 5113 5114 static void 5115 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5116 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5117 SDValue FPOp, 5118 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5119 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5120 // might overwrite each other in case of tail call optimization. 5121 SmallVector<SDValue, 8> MemOpChains2; 5122 // Do not flag preceding copytoreg stuff together with the following stuff. 5123 InFlag = SDValue(); 5124 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5125 MemOpChains2, dl); 5126 if (!MemOpChains2.empty()) 5127 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5128 5129 // Store the return address to the appropriate stack slot. 5130 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5131 5132 // Emit callseq_end just before tailcall node. 5133 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5134 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5135 InFlag = Chain.getValue(1); 5136 } 5137 5138 // Is this global address that of a function that can be called by name? (as 5139 // opposed to something that must hold a descriptor for an indirect call). 5140 static bool isFunctionGlobalAddress(SDValue Callee) { 5141 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5142 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5143 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5144 return false; 5145 5146 return G->getGlobal()->getValueType()->isFunctionTy(); 5147 } 5148 5149 return false; 5150 } 5151 5152 SDValue PPCTargetLowering::LowerCallResult( 5153 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5154 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5155 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5156 SmallVector<CCValAssign, 16> RVLocs; 5157 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5158 *DAG.getContext()); 5159 5160 CCRetInfo.AnalyzeCallResult( 5161 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5162 ? RetCC_PPC_Cold 5163 : RetCC_PPC); 5164 5165 // Copy all of the result registers out of their specified physreg. 5166 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5167 CCValAssign &VA = RVLocs[i]; 5168 assert(VA.isRegLoc() && "Can only return in registers!"); 5169 5170 SDValue Val; 5171 5172 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5173 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5174 InFlag); 5175 Chain = Lo.getValue(1); 5176 InFlag = Lo.getValue(2); 5177 VA = RVLocs[++i]; // skip ahead to next loc 5178 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5179 InFlag); 5180 Chain = Hi.getValue(1); 5181 InFlag = Hi.getValue(2); 5182 if (!Subtarget.isLittleEndian()) 5183 std::swap (Lo, Hi); 5184 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5185 } else { 5186 Val = DAG.getCopyFromReg(Chain, dl, 5187 VA.getLocReg(), VA.getLocVT(), InFlag); 5188 Chain = Val.getValue(1); 5189 InFlag = Val.getValue(2); 5190 } 5191 5192 switch (VA.getLocInfo()) { 5193 default: llvm_unreachable("Unknown loc info!"); 5194 case CCValAssign::Full: break; 5195 case CCValAssign::AExt: 5196 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5197 break; 5198 case CCValAssign::ZExt: 5199 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5200 DAG.getValueType(VA.getValVT())); 5201 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5202 break; 5203 case CCValAssign::SExt: 5204 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5205 DAG.getValueType(VA.getValVT())); 5206 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5207 break; 5208 } 5209 5210 InVals.push_back(Val); 5211 } 5212 5213 return Chain; 5214 } 5215 5216 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5217 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5218 // PatchPoint calls are not indirect. 5219 if (isPatchPoint) 5220 return false; 5221 5222 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5223 return false; 5224 5225 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5226 // becuase the immediate function pointer points to a descriptor instead of 5227 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5228 // pointer immediate points to the global entry point, while the BLA would 5229 // need to jump to the local entry point (see rL211174). 5230 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5231 isBLACompatibleAddress(Callee, DAG)) 5232 return false; 5233 5234 return true; 5235 } 5236 5237 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5238 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5239 return Subtarget.isAIXABI() || 5240 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5241 } 5242 5243 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5244 const Function &Caller, 5245 const SDValue &Callee, 5246 const PPCSubtarget &Subtarget, 5247 const TargetMachine &TM) { 5248 if (CFlags.IsTailCall) 5249 return PPCISD::TC_RETURN; 5250 5251 // This is a call through a function pointer. 5252 if (CFlags.IsIndirect) { 5253 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5254 // indirect calls. The save of the caller's TOC pointer to the stack will be 5255 // inserted into the DAG as part of call lowering. The restore of the TOC 5256 // pointer is modeled by using a pseudo instruction for the call opcode that 5257 // represents the 2 instruction sequence of an indirect branch and link, 5258 // immediately followed by a load of the TOC pointer from the the stack save 5259 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5260 // as it is not saved or used. 5261 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5262 : PPCISD::BCTRL; 5263 } 5264 5265 if (Subtarget.isUsingPCRelativeCalls()) { 5266 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5267 return PPCISD::CALL_NOTOC; 5268 } 5269 5270 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5271 // immediately following the call instruction if the caller and callee may 5272 // have different TOC bases. At link time if the linker determines the calls 5273 // may not share a TOC base, the call is redirected to a trampoline inserted 5274 // by the linker. The trampoline will (among other things) save the callers 5275 // TOC pointer at an ABI designated offset in the linkage area and the linker 5276 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5277 // into gpr2. 5278 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5279 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5280 : PPCISD::CALL_NOP; 5281 5282 return PPCISD::CALL; 5283 } 5284 5285 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5286 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5287 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5288 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5289 return SDValue(Dest, 0); 5290 5291 // Returns true if the callee is local, and false otherwise. 5292 auto isLocalCallee = [&]() { 5293 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5294 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5295 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5296 5297 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5298 !dyn_cast_or_null<GlobalIFunc>(GV); 5299 }; 5300 5301 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5302 // a static relocation model causes some versions of GNU LD (2.17.50, at 5303 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5304 // built with secure-PLT. 5305 bool UsePlt = 5306 Subtarget.is32BitELFABI() && !isLocalCallee() && 5307 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5308 5309 // On AIX, direct function calls reference the symbol for the function's 5310 // entry point, which is named by prepending a "." before the function's 5311 // C-linkage name. 5312 const auto getAIXFuncEntryPointSymbolSDNode = 5313 [&](StringRef FuncName, bool IsDeclaration, 5314 const XCOFF::StorageClass &SC) { 5315 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5316 5317 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5318 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5319 5320 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5321 // On AIX, an undefined symbol needs to be associated with a 5322 // MCSectionXCOFF to get the correct storage mapping class. 5323 // In this case, XCOFF::XMC_PR. 5324 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5325 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5326 SectionKind::getMetadata()); 5327 S->setRepresentedCsect(Sec); 5328 } 5329 5330 MVT PtrVT = 5331 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5332 return DAG.getMCSymbol(S, PtrVT); 5333 }; 5334 5335 if (isFunctionGlobalAddress(Callee)) { 5336 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5337 const GlobalValue *GV = G->getGlobal(); 5338 5339 if (!Subtarget.isAIXABI()) 5340 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5341 UsePlt ? PPCII::MO_PLT : 0); 5342 5343 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5344 const GlobalObject *GO = cast<GlobalObject>(GV); 5345 const XCOFF::StorageClass SC = 5346 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5347 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5348 SC); 5349 } 5350 5351 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5352 const char *SymName = S->getSymbol(); 5353 if (!Subtarget.isAIXABI()) 5354 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5355 UsePlt ? PPCII::MO_PLT : 0); 5356 5357 // If there exists a user-declared function whose name is the same as the 5358 // ExternalSymbol's, then we pick up the user-declared version. 5359 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5360 if (const Function *F = 5361 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5362 const XCOFF::StorageClass SC = 5363 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5364 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5365 SC); 5366 } 5367 5368 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5369 } 5370 5371 // No transformation needed. 5372 assert(Callee.getNode() && "What no callee?"); 5373 return Callee; 5374 } 5375 5376 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5377 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5378 "Expected a CALLSEQ_STARTSDNode."); 5379 5380 // The last operand is the chain, except when the node has glue. If the node 5381 // has glue, then the last operand is the glue, and the chain is the second 5382 // last operand. 5383 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5384 if (LastValue.getValueType() != MVT::Glue) 5385 return LastValue; 5386 5387 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5388 } 5389 5390 // Creates the node that moves a functions address into the count register 5391 // to prepare for an indirect call instruction. 5392 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5393 SDValue &Glue, SDValue &Chain, 5394 const SDLoc &dl) { 5395 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5396 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5397 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5398 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5399 // The glue is the second value produced. 5400 Glue = Chain.getValue(1); 5401 } 5402 5403 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5404 SDValue &Glue, SDValue &Chain, 5405 SDValue CallSeqStart, 5406 const CallBase *CB, const SDLoc &dl, 5407 bool hasNest, 5408 const PPCSubtarget &Subtarget) { 5409 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5410 // entry point, but to the function descriptor (the function entry point 5411 // address is part of the function descriptor though). 5412 // The function descriptor is a three doubleword structure with the 5413 // following fields: function entry point, TOC base address and 5414 // environment pointer. 5415 // Thus for a call through a function pointer, the following actions need 5416 // to be performed: 5417 // 1. Save the TOC of the caller in the TOC save area of its stack 5418 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5419 // 2. Load the address of the function entry point from the function 5420 // descriptor. 5421 // 3. Load the TOC of the callee from the function descriptor into r2. 5422 // 4. Load the environment pointer from the function descriptor into 5423 // r11. 5424 // 5. Branch to the function entry point address. 5425 // 6. On return of the callee, the TOC of the caller needs to be 5426 // restored (this is done in FinishCall()). 5427 // 5428 // The loads are scheduled at the beginning of the call sequence, and the 5429 // register copies are flagged together to ensure that no other 5430 // operations can be scheduled in between. E.g. without flagging the 5431 // copies together, a TOC access in the caller could be scheduled between 5432 // the assignment of the callee TOC and the branch to the callee, which leads 5433 // to incorrect code. 5434 5435 // Start by loading the function address from the descriptor. 5436 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5437 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5438 ? (MachineMemOperand::MODereferenceable | 5439 MachineMemOperand::MOInvariant) 5440 : MachineMemOperand::MONone; 5441 5442 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5443 5444 // Registers used in building the DAG. 5445 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5446 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5447 5448 // Offsets of descriptor members. 5449 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5450 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5451 5452 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5453 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5454 5455 // One load for the functions entry point address. 5456 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5457 Alignment, MMOFlags); 5458 5459 // One for loading the TOC anchor for the module that contains the called 5460 // function. 5461 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5462 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5463 SDValue TOCPtr = 5464 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5465 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5466 5467 // One for loading the environment pointer. 5468 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5469 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5470 SDValue LoadEnvPtr = 5471 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5472 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5473 5474 5475 // Then copy the newly loaded TOC anchor to the TOC pointer. 5476 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5477 Chain = TOCVal.getValue(0); 5478 Glue = TOCVal.getValue(1); 5479 5480 // If the function call has an explicit 'nest' parameter, it takes the 5481 // place of the environment pointer. 5482 assert((!hasNest || !Subtarget.isAIXABI()) && 5483 "Nest parameter is not supported on AIX."); 5484 if (!hasNest) { 5485 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5486 Chain = EnvVal.getValue(0); 5487 Glue = EnvVal.getValue(1); 5488 } 5489 5490 // The rest of the indirect call sequence is the same as the non-descriptor 5491 // DAG. 5492 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5493 } 5494 5495 static void 5496 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5497 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5498 SelectionDAG &DAG, 5499 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5500 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5501 const PPCSubtarget &Subtarget) { 5502 const bool IsPPC64 = Subtarget.isPPC64(); 5503 // MVT for a general purpose register. 5504 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5505 5506 // First operand is always the chain. 5507 Ops.push_back(Chain); 5508 5509 // If it's a direct call pass the callee as the second operand. 5510 if (!CFlags.IsIndirect) 5511 Ops.push_back(Callee); 5512 else { 5513 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5514 5515 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5516 // on the stack (this would have been done in `LowerCall_64SVR4` or 5517 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5518 // represents both the indirect branch and a load that restores the TOC 5519 // pointer from the linkage area. The operand for the TOC restore is an add 5520 // of the TOC save offset to the stack pointer. This must be the second 5521 // operand: after the chain input but before any other variadic arguments. 5522 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5523 // saved or used. 5524 if (isTOCSaveRestoreRequired(Subtarget)) { 5525 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5526 5527 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5528 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5529 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5530 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5531 Ops.push_back(AddTOC); 5532 } 5533 5534 // Add the register used for the environment pointer. 5535 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5536 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5537 RegVT)); 5538 5539 5540 // Add CTR register as callee so a bctr can be emitted later. 5541 if (CFlags.IsTailCall) 5542 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5543 } 5544 5545 // If this is a tail call add stack pointer delta. 5546 if (CFlags.IsTailCall) 5547 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5548 5549 // Add argument registers to the end of the list so that they are known live 5550 // into the call. 5551 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5552 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5553 RegsToPass[i].second.getValueType())); 5554 5555 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5556 // no way to mark dependencies as implicit here. 5557 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5558 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5559 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5560 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5561 5562 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5563 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5564 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5565 5566 // Add a register mask operand representing the call-preserved registers. 5567 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5568 const uint32_t *Mask = 5569 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5570 assert(Mask && "Missing call preserved mask for calling convention"); 5571 Ops.push_back(DAG.getRegisterMask(Mask)); 5572 5573 // If the glue is valid, it is the last operand. 5574 if (Glue.getNode()) 5575 Ops.push_back(Glue); 5576 } 5577 5578 SDValue PPCTargetLowering::FinishCall( 5579 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5580 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5581 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5582 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5583 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5584 5585 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5586 Subtarget.isAIXABI()) 5587 setUsesTOCBasePtr(DAG); 5588 5589 unsigned CallOpc = 5590 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5591 Subtarget, DAG.getTarget()); 5592 5593 if (!CFlags.IsIndirect) 5594 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5595 else if (Subtarget.usesFunctionDescriptors()) 5596 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5597 dl, CFlags.HasNest, Subtarget); 5598 else 5599 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5600 5601 // Build the operand list for the call instruction. 5602 SmallVector<SDValue, 8> Ops; 5603 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5604 SPDiff, Subtarget); 5605 5606 // Emit tail call. 5607 if (CFlags.IsTailCall) { 5608 // Indirect tail call when using PC Relative calls do not have the same 5609 // constraints. 5610 assert(((Callee.getOpcode() == ISD::Register && 5611 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5612 Callee.getOpcode() == ISD::TargetExternalSymbol || 5613 Callee.getOpcode() == ISD::TargetGlobalAddress || 5614 isa<ConstantSDNode>(Callee) || 5615 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5616 "Expecting a global address, external symbol, absolute value, " 5617 "register or an indirect tail call when PC Relative calls are " 5618 "used."); 5619 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5620 assert(CallOpc == PPCISD::TC_RETURN && 5621 "Unexpected call opcode for a tail call."); 5622 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5623 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5624 } 5625 5626 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5627 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5628 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5629 Glue = Chain.getValue(1); 5630 5631 // When performing tail call optimization the callee pops its arguments off 5632 // the stack. Account for this here so these bytes can be pushed back on in 5633 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5634 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5635 getTargetMachine().Options.GuaranteedTailCallOpt) 5636 ? NumBytes 5637 : 0; 5638 5639 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5640 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5641 Glue, dl); 5642 Glue = Chain.getValue(1); 5643 5644 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5645 DAG, InVals); 5646 } 5647 5648 SDValue 5649 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5650 SmallVectorImpl<SDValue> &InVals) const { 5651 SelectionDAG &DAG = CLI.DAG; 5652 SDLoc &dl = CLI.DL; 5653 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5654 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5655 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5656 SDValue Chain = CLI.Chain; 5657 SDValue Callee = CLI.Callee; 5658 bool &isTailCall = CLI.IsTailCall; 5659 CallingConv::ID CallConv = CLI.CallConv; 5660 bool isVarArg = CLI.IsVarArg; 5661 bool isPatchPoint = CLI.IsPatchPoint; 5662 const CallBase *CB = CLI.CB; 5663 5664 if (isTailCall) { 5665 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5666 isTailCall = false; 5667 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5668 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5669 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5670 else 5671 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5672 Ins, DAG); 5673 if (isTailCall) { 5674 ++NumTailCalls; 5675 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5676 ++NumSiblingCalls; 5677 5678 // PC Relative calls no longer guarantee that the callee is a Global 5679 // Address Node. The callee could be an indirect tail call in which 5680 // case the SDValue for the callee could be a load (to load the address 5681 // of a function pointer) or it may be a register copy (to move the 5682 // address of the callee from a function parameter into a virtual 5683 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5684 assert((Subtarget.isUsingPCRelativeCalls() || 5685 isa<GlobalAddressSDNode>(Callee)) && 5686 "Callee should be an llvm::Function object."); 5687 5688 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5689 << "\nTCO callee: "); 5690 LLVM_DEBUG(Callee.dump()); 5691 } 5692 } 5693 5694 if (!isTailCall && CB && CB->isMustTailCall()) 5695 report_fatal_error("failed to perform tail call elimination on a call " 5696 "site marked musttail"); 5697 5698 // When long calls (i.e. indirect calls) are always used, calls are always 5699 // made via function pointer. If we have a function name, first translate it 5700 // into a pointer. 5701 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5702 !isTailCall) 5703 Callee = LowerGlobalAddress(Callee, DAG); 5704 5705 CallFlags CFlags( 5706 CallConv, isTailCall, isVarArg, isPatchPoint, 5707 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5708 // hasNest 5709 Subtarget.is64BitELFABI() && 5710 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5711 CLI.NoMerge); 5712 5713 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5714 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5715 InVals, CB); 5716 5717 if (Subtarget.isSVR4ABI()) 5718 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5719 InVals, CB); 5720 5721 if (Subtarget.isAIXABI()) 5722 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5723 InVals, CB); 5724 5725 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5726 InVals, CB); 5727 } 5728 5729 SDValue PPCTargetLowering::LowerCall_32SVR4( 5730 SDValue Chain, SDValue Callee, CallFlags CFlags, 5731 const SmallVectorImpl<ISD::OutputArg> &Outs, 5732 const SmallVectorImpl<SDValue> &OutVals, 5733 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5734 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5735 const CallBase *CB) const { 5736 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5737 // of the 32-bit SVR4 ABI stack frame layout. 5738 5739 const CallingConv::ID CallConv = CFlags.CallConv; 5740 const bool IsVarArg = CFlags.IsVarArg; 5741 const bool IsTailCall = CFlags.IsTailCall; 5742 5743 assert((CallConv == CallingConv::C || 5744 CallConv == CallingConv::Cold || 5745 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5746 5747 const Align PtrAlign(4); 5748 5749 MachineFunction &MF = DAG.getMachineFunction(); 5750 5751 // Mark this function as potentially containing a function that contains a 5752 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5753 // and restoring the callers stack pointer in this functions epilog. This is 5754 // done because by tail calling the called function might overwrite the value 5755 // in this function's (MF) stack pointer stack slot 0(SP). 5756 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5757 CallConv == CallingConv::Fast) 5758 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5759 5760 // Count how many bytes are to be pushed on the stack, including the linkage 5761 // area, parameter list area and the part of the local variable space which 5762 // contains copies of aggregates which are passed by value. 5763 5764 // Assign locations to all of the outgoing arguments. 5765 SmallVector<CCValAssign, 16> ArgLocs; 5766 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5767 5768 // Reserve space for the linkage area on the stack. 5769 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5770 PtrAlign); 5771 if (useSoftFloat()) 5772 CCInfo.PreAnalyzeCallOperands(Outs); 5773 5774 if (IsVarArg) { 5775 // Handle fixed and variable vector arguments differently. 5776 // Fixed vector arguments go into registers as long as registers are 5777 // available. Variable vector arguments always go into memory. 5778 unsigned NumArgs = Outs.size(); 5779 5780 for (unsigned i = 0; i != NumArgs; ++i) { 5781 MVT ArgVT = Outs[i].VT; 5782 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5783 bool Result; 5784 5785 if (Outs[i].IsFixed) { 5786 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5787 CCInfo); 5788 } else { 5789 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5790 ArgFlags, CCInfo); 5791 } 5792 5793 if (Result) { 5794 #ifndef NDEBUG 5795 errs() << "Call operand #" << i << " has unhandled type " 5796 << EVT(ArgVT).getEVTString() << "\n"; 5797 #endif 5798 llvm_unreachable(nullptr); 5799 } 5800 } 5801 } else { 5802 // All arguments are treated the same. 5803 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5804 } 5805 CCInfo.clearWasPPCF128(); 5806 5807 // Assign locations to all of the outgoing aggregate by value arguments. 5808 SmallVector<CCValAssign, 16> ByValArgLocs; 5809 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5810 5811 // Reserve stack space for the allocations in CCInfo. 5812 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5813 5814 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5815 5816 // Size of the linkage area, parameter list area and the part of the local 5817 // space variable where copies of aggregates which are passed by value are 5818 // stored. 5819 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5820 5821 // Calculate by how many bytes the stack has to be adjusted in case of tail 5822 // call optimization. 5823 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5824 5825 // Adjust the stack pointer for the new arguments... 5826 // These operations are automatically eliminated by the prolog/epilog pass 5827 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5828 SDValue CallSeqStart = Chain; 5829 5830 // Load the return address and frame pointer so it can be moved somewhere else 5831 // later. 5832 SDValue LROp, FPOp; 5833 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5834 5835 // Set up a copy of the stack pointer for use loading and storing any 5836 // arguments that may not fit in the registers available for argument 5837 // passing. 5838 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5839 5840 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5841 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5842 SmallVector<SDValue, 8> MemOpChains; 5843 5844 bool seenFloatArg = false; 5845 // Walk the register/memloc assignments, inserting copies/loads. 5846 // i - Tracks the index into the list of registers allocated for the call 5847 // RealArgIdx - Tracks the index into the list of actual function arguments 5848 // j - Tracks the index into the list of byval arguments 5849 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5850 i != e; 5851 ++i, ++RealArgIdx) { 5852 CCValAssign &VA = ArgLocs[i]; 5853 SDValue Arg = OutVals[RealArgIdx]; 5854 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5855 5856 if (Flags.isByVal()) { 5857 // Argument is an aggregate which is passed by value, thus we need to 5858 // create a copy of it in the local variable space of the current stack 5859 // frame (which is the stack frame of the caller) and pass the address of 5860 // this copy to the callee. 5861 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5862 CCValAssign &ByValVA = ByValArgLocs[j++]; 5863 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5864 5865 // Memory reserved in the local variable space of the callers stack frame. 5866 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5867 5868 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5869 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5870 StackPtr, PtrOff); 5871 5872 // Create a copy of the argument in the local area of the current 5873 // stack frame. 5874 SDValue MemcpyCall = 5875 CreateCopyOfByValArgument(Arg, PtrOff, 5876 CallSeqStart.getNode()->getOperand(0), 5877 Flags, DAG, dl); 5878 5879 // This must go outside the CALLSEQ_START..END. 5880 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5881 SDLoc(MemcpyCall)); 5882 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5883 NewCallSeqStart.getNode()); 5884 Chain = CallSeqStart = NewCallSeqStart; 5885 5886 // Pass the address of the aggregate copy on the stack either in a 5887 // physical register or in the parameter list area of the current stack 5888 // frame to the callee. 5889 Arg = PtrOff; 5890 } 5891 5892 // When useCRBits() is true, there can be i1 arguments. 5893 // It is because getRegisterType(MVT::i1) => MVT::i1, 5894 // and for other integer types getRegisterType() => MVT::i32. 5895 // Extend i1 and ensure callee will get i32. 5896 if (Arg.getValueType() == MVT::i1) 5897 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5898 dl, MVT::i32, Arg); 5899 5900 if (VA.isRegLoc()) { 5901 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5902 // Put argument in a physical register. 5903 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5904 bool IsLE = Subtarget.isLittleEndian(); 5905 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5906 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5907 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5908 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5909 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5910 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5911 SVal.getValue(0))); 5912 } else 5913 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5914 } else { 5915 // Put argument in the parameter list area of the current stack frame. 5916 assert(VA.isMemLoc()); 5917 unsigned LocMemOffset = VA.getLocMemOffset(); 5918 5919 if (!IsTailCall) { 5920 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5921 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5922 StackPtr, PtrOff); 5923 5924 MemOpChains.push_back( 5925 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5926 } else { 5927 // Calculate and remember argument location. 5928 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5929 TailCallArguments); 5930 } 5931 } 5932 } 5933 5934 if (!MemOpChains.empty()) 5935 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5936 5937 // Build a sequence of copy-to-reg nodes chained together with token chain 5938 // and flag operands which copy the outgoing args into the appropriate regs. 5939 SDValue InFlag; 5940 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5941 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5942 RegsToPass[i].second, InFlag); 5943 InFlag = Chain.getValue(1); 5944 } 5945 5946 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5947 // registers. 5948 if (IsVarArg) { 5949 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5950 SDValue Ops[] = { Chain, InFlag }; 5951 5952 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5953 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5954 5955 InFlag = Chain.getValue(1); 5956 } 5957 5958 if (IsTailCall) 5959 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5960 TailCallArguments); 5961 5962 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5963 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5964 } 5965 5966 // Copy an argument into memory, being careful to do this outside the 5967 // call sequence for the call to which the argument belongs. 5968 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5969 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5970 SelectionDAG &DAG, const SDLoc &dl) const { 5971 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5972 CallSeqStart.getNode()->getOperand(0), 5973 Flags, DAG, dl); 5974 // The MEMCPY must go outside the CALLSEQ_START..END. 5975 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5976 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5977 SDLoc(MemcpyCall)); 5978 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5979 NewCallSeqStart.getNode()); 5980 return NewCallSeqStart; 5981 } 5982 5983 SDValue PPCTargetLowering::LowerCall_64SVR4( 5984 SDValue Chain, SDValue Callee, CallFlags CFlags, 5985 const SmallVectorImpl<ISD::OutputArg> &Outs, 5986 const SmallVectorImpl<SDValue> &OutVals, 5987 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5988 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5989 const CallBase *CB) const { 5990 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5991 bool isLittleEndian = Subtarget.isLittleEndian(); 5992 unsigned NumOps = Outs.size(); 5993 bool IsSibCall = false; 5994 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5995 5996 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5997 unsigned PtrByteSize = 8; 5998 5999 MachineFunction &MF = DAG.getMachineFunction(); 6000 6001 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 6002 IsSibCall = true; 6003 6004 // Mark this function as potentially containing a function that contains a 6005 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6006 // and restoring the callers stack pointer in this functions epilog. This is 6007 // done because by tail calling the called function might overwrite the value 6008 // in this function's (MF) stack pointer stack slot 0(SP). 6009 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6010 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6011 6012 assert(!(IsFastCall && CFlags.IsVarArg) && 6013 "fastcc not supported on varargs functions"); 6014 6015 // Count how many bytes are to be pushed on the stack, including the linkage 6016 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 6017 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 6018 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 6019 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6020 unsigned NumBytes = LinkageSize; 6021 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6022 unsigned &QFPR_idx = FPR_idx; 6023 6024 static const MCPhysReg GPR[] = { 6025 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6026 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6027 }; 6028 static const MCPhysReg VR[] = { 6029 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6030 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6031 }; 6032 6033 const unsigned NumGPRs = array_lengthof(GPR); 6034 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6035 const unsigned NumVRs = array_lengthof(VR); 6036 const unsigned NumQFPRs = NumFPRs; 6037 6038 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6039 // can be passed to the callee in registers. 6040 // For the fast calling convention, there is another check below. 6041 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6042 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6043 if (!HasParameterArea) { 6044 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6045 unsigned AvailableFPRs = NumFPRs; 6046 unsigned AvailableVRs = NumVRs; 6047 unsigned NumBytesTmp = NumBytes; 6048 for (unsigned i = 0; i != NumOps; ++i) { 6049 if (Outs[i].Flags.isNest()) continue; 6050 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6051 PtrByteSize, LinkageSize, ParamAreaSize, 6052 NumBytesTmp, AvailableFPRs, AvailableVRs, 6053 Subtarget.hasQPX())) 6054 HasParameterArea = true; 6055 } 6056 } 6057 6058 // When using the fast calling convention, we don't provide backing for 6059 // arguments that will be in registers. 6060 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6061 6062 // Avoid allocating parameter area for fastcc functions if all the arguments 6063 // can be passed in the registers. 6064 if (IsFastCall) 6065 HasParameterArea = false; 6066 6067 // Add up all the space actually used. 6068 for (unsigned i = 0; i != NumOps; ++i) { 6069 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6070 EVT ArgVT = Outs[i].VT; 6071 EVT OrigVT = Outs[i].ArgVT; 6072 6073 if (Flags.isNest()) 6074 continue; 6075 6076 if (IsFastCall) { 6077 if (Flags.isByVal()) { 6078 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6079 if (NumGPRsUsed > NumGPRs) 6080 HasParameterArea = true; 6081 } else { 6082 switch (ArgVT.getSimpleVT().SimpleTy) { 6083 default: llvm_unreachable("Unexpected ValueType for argument!"); 6084 case MVT::i1: 6085 case MVT::i32: 6086 case MVT::i64: 6087 if (++NumGPRsUsed <= NumGPRs) 6088 continue; 6089 break; 6090 case MVT::v4i32: 6091 case MVT::v8i16: 6092 case MVT::v16i8: 6093 case MVT::v2f64: 6094 case MVT::v2i64: 6095 case MVT::v1i128: 6096 case MVT::f128: 6097 if (++NumVRsUsed <= NumVRs) 6098 continue; 6099 break; 6100 case MVT::v4f32: 6101 // When using QPX, this is handled like a FP register, otherwise, it 6102 // is an Altivec register. 6103 if (Subtarget.hasQPX()) { 6104 if (++NumFPRsUsed <= NumFPRs) 6105 continue; 6106 } else { 6107 if (++NumVRsUsed <= NumVRs) 6108 continue; 6109 } 6110 break; 6111 case MVT::f32: 6112 case MVT::f64: 6113 case MVT::v4f64: // QPX 6114 case MVT::v4i1: // QPX 6115 if (++NumFPRsUsed <= NumFPRs) 6116 continue; 6117 break; 6118 } 6119 HasParameterArea = true; 6120 } 6121 } 6122 6123 /* Respect alignment of argument on the stack. */ 6124 auto Alignement = 6125 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6126 NumBytes = alignTo(NumBytes, Alignement); 6127 6128 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6129 if (Flags.isInConsecutiveRegsLast()) 6130 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6131 } 6132 6133 unsigned NumBytesActuallyUsed = NumBytes; 6134 6135 // In the old ELFv1 ABI, 6136 // the prolog code of the callee may store up to 8 GPR argument registers to 6137 // the stack, allowing va_start to index over them in memory if its varargs. 6138 // Because we cannot tell if this is needed on the caller side, we have to 6139 // conservatively assume that it is needed. As such, make sure we have at 6140 // least enough stack space for the caller to store the 8 GPRs. 6141 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6142 // really requires memory operands, e.g. a vararg function. 6143 if (HasParameterArea) 6144 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6145 else 6146 NumBytes = LinkageSize; 6147 6148 // Tail call needs the stack to be aligned. 6149 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6150 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6151 6152 int SPDiff = 0; 6153 6154 // Calculate by how many bytes the stack has to be adjusted in case of tail 6155 // call optimization. 6156 if (!IsSibCall) 6157 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6158 6159 // To protect arguments on the stack from being clobbered in a tail call, 6160 // force all the loads to happen before doing any other lowering. 6161 if (CFlags.IsTailCall) 6162 Chain = DAG.getStackArgumentTokenFactor(Chain); 6163 6164 // Adjust the stack pointer for the new arguments... 6165 // These operations are automatically eliminated by the prolog/epilog pass 6166 if (!IsSibCall) 6167 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6168 SDValue CallSeqStart = Chain; 6169 6170 // Load the return address and frame pointer so it can be move somewhere else 6171 // later. 6172 SDValue LROp, FPOp; 6173 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6174 6175 // Set up a copy of the stack pointer for use loading and storing any 6176 // arguments that may not fit in the registers available for argument 6177 // passing. 6178 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6179 6180 // Figure out which arguments are going to go in registers, and which in 6181 // memory. Also, if this is a vararg function, floating point operations 6182 // must be stored to our stack, and loaded into integer regs as well, if 6183 // any integer regs are available for argument passing. 6184 unsigned ArgOffset = LinkageSize; 6185 6186 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6187 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6188 6189 SmallVector<SDValue, 8> MemOpChains; 6190 for (unsigned i = 0; i != NumOps; ++i) { 6191 SDValue Arg = OutVals[i]; 6192 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6193 EVT ArgVT = Outs[i].VT; 6194 EVT OrigVT = Outs[i].ArgVT; 6195 6196 // PtrOff will be used to store the current argument to the stack if a 6197 // register cannot be found for it. 6198 SDValue PtrOff; 6199 6200 // We re-align the argument offset for each argument, except when using the 6201 // fast calling convention, when we need to make sure we do that only when 6202 // we'll actually use a stack slot. 6203 auto ComputePtrOff = [&]() { 6204 /* Respect alignment of argument on the stack. */ 6205 auto Alignment = 6206 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6207 ArgOffset = alignTo(ArgOffset, Alignment); 6208 6209 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6210 6211 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6212 }; 6213 6214 if (!IsFastCall) { 6215 ComputePtrOff(); 6216 6217 /* Compute GPR index associated with argument offset. */ 6218 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6219 GPR_idx = std::min(GPR_idx, NumGPRs); 6220 } 6221 6222 // Promote integers to 64-bit values. 6223 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6224 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6225 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6226 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6227 } 6228 6229 // FIXME memcpy is used way more than necessary. Correctness first. 6230 // Note: "by value" is code for passing a structure by value, not 6231 // basic types. 6232 if (Flags.isByVal()) { 6233 // Note: Size includes alignment padding, so 6234 // struct x { short a; char b; } 6235 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6236 // These are the proper values we need for right-justifying the 6237 // aggregate in a parameter register. 6238 unsigned Size = Flags.getByValSize(); 6239 6240 // An empty aggregate parameter takes up no storage and no 6241 // registers. 6242 if (Size == 0) 6243 continue; 6244 6245 if (IsFastCall) 6246 ComputePtrOff(); 6247 6248 // All aggregates smaller than 8 bytes must be passed right-justified. 6249 if (Size==1 || Size==2 || Size==4) { 6250 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6251 if (GPR_idx != NumGPRs) { 6252 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6253 MachinePointerInfo(), VT); 6254 MemOpChains.push_back(Load.getValue(1)); 6255 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6256 6257 ArgOffset += PtrByteSize; 6258 continue; 6259 } 6260 } 6261 6262 if (GPR_idx == NumGPRs && Size < 8) { 6263 SDValue AddPtr = PtrOff; 6264 if (!isLittleEndian) { 6265 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6266 PtrOff.getValueType()); 6267 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6268 } 6269 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6270 CallSeqStart, 6271 Flags, DAG, dl); 6272 ArgOffset += PtrByteSize; 6273 continue; 6274 } 6275 // Copy entire object into memory. There are cases where gcc-generated 6276 // code assumes it is there, even if it could be put entirely into 6277 // registers. (This is not what the doc says.) 6278 6279 // FIXME: The above statement is likely due to a misunderstanding of the 6280 // documents. All arguments must be copied into the parameter area BY 6281 // THE CALLEE in the event that the callee takes the address of any 6282 // formal argument. That has not yet been implemented. However, it is 6283 // reasonable to use the stack area as a staging area for the register 6284 // load. 6285 6286 // Skip this for small aggregates, as we will use the same slot for a 6287 // right-justified copy, below. 6288 if (Size >= 8) 6289 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6290 CallSeqStart, 6291 Flags, DAG, dl); 6292 6293 // When a register is available, pass a small aggregate right-justified. 6294 if (Size < 8 && GPR_idx != NumGPRs) { 6295 // The easiest way to get this right-justified in a register 6296 // is to copy the structure into the rightmost portion of a 6297 // local variable slot, then load the whole slot into the 6298 // register. 6299 // FIXME: The memcpy seems to produce pretty awful code for 6300 // small aggregates, particularly for packed ones. 6301 // FIXME: It would be preferable to use the slot in the 6302 // parameter save area instead of a new local variable. 6303 SDValue AddPtr = PtrOff; 6304 if (!isLittleEndian) { 6305 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6306 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6307 } 6308 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6309 CallSeqStart, 6310 Flags, DAG, dl); 6311 6312 // Load the slot into the register. 6313 SDValue Load = 6314 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6315 MemOpChains.push_back(Load.getValue(1)); 6316 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6317 6318 // Done with this argument. 6319 ArgOffset += PtrByteSize; 6320 continue; 6321 } 6322 6323 // For aggregates larger than PtrByteSize, copy the pieces of the 6324 // object that fit into registers from the parameter save area. 6325 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6326 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6327 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6328 if (GPR_idx != NumGPRs) { 6329 SDValue Load = 6330 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6331 MemOpChains.push_back(Load.getValue(1)); 6332 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6333 ArgOffset += PtrByteSize; 6334 } else { 6335 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6336 break; 6337 } 6338 } 6339 continue; 6340 } 6341 6342 switch (Arg.getSimpleValueType().SimpleTy) { 6343 default: llvm_unreachable("Unexpected ValueType for argument!"); 6344 case MVT::i1: 6345 case MVT::i32: 6346 case MVT::i64: 6347 if (Flags.isNest()) { 6348 // The 'nest' parameter, if any, is passed in R11. 6349 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6350 break; 6351 } 6352 6353 // These can be scalar arguments or elements of an integer array type 6354 // passed directly. Clang may use those instead of "byval" aggregate 6355 // types to avoid forcing arguments to memory unnecessarily. 6356 if (GPR_idx != NumGPRs) { 6357 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6358 } else { 6359 if (IsFastCall) 6360 ComputePtrOff(); 6361 6362 assert(HasParameterArea && 6363 "Parameter area must exist to pass an argument in memory."); 6364 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6365 true, CFlags.IsTailCall, false, MemOpChains, 6366 TailCallArguments, dl); 6367 if (IsFastCall) 6368 ArgOffset += PtrByteSize; 6369 } 6370 if (!IsFastCall) 6371 ArgOffset += PtrByteSize; 6372 break; 6373 case MVT::f32: 6374 case MVT::f64: { 6375 // These can be scalar arguments or elements of a float array type 6376 // passed directly. The latter are used to implement ELFv2 homogenous 6377 // float aggregates. 6378 6379 // Named arguments go into FPRs first, and once they overflow, the 6380 // remaining arguments go into GPRs and then the parameter save area. 6381 // Unnamed arguments for vararg functions always go to GPRs and 6382 // then the parameter save area. For now, put all arguments to vararg 6383 // routines always in both locations (FPR *and* GPR or stack slot). 6384 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6385 bool NeededLoad = false; 6386 6387 // First load the argument into the next available FPR. 6388 if (FPR_idx != NumFPRs) 6389 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6390 6391 // Next, load the argument into GPR or stack slot if needed. 6392 if (!NeedGPROrStack) 6393 ; 6394 else if (GPR_idx != NumGPRs && !IsFastCall) { 6395 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6396 // once we support fp <-> gpr moves. 6397 6398 // In the non-vararg case, this can only ever happen in the 6399 // presence of f32 array types, since otherwise we never run 6400 // out of FPRs before running out of GPRs. 6401 SDValue ArgVal; 6402 6403 // Double values are always passed in a single GPR. 6404 if (Arg.getValueType() != MVT::f32) { 6405 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6406 6407 // Non-array float values are extended and passed in a GPR. 6408 } else if (!Flags.isInConsecutiveRegs()) { 6409 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6410 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6411 6412 // If we have an array of floats, we collect every odd element 6413 // together with its predecessor into one GPR. 6414 } else if (ArgOffset % PtrByteSize != 0) { 6415 SDValue Lo, Hi; 6416 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6417 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6418 if (!isLittleEndian) 6419 std::swap(Lo, Hi); 6420 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6421 6422 // The final element, if even, goes into the first half of a GPR. 6423 } else if (Flags.isInConsecutiveRegsLast()) { 6424 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6425 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6426 if (!isLittleEndian) 6427 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6428 DAG.getConstant(32, dl, MVT::i32)); 6429 6430 // Non-final even elements are skipped; they will be handled 6431 // together the with subsequent argument on the next go-around. 6432 } else 6433 ArgVal = SDValue(); 6434 6435 if (ArgVal.getNode()) 6436 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6437 } else { 6438 if (IsFastCall) 6439 ComputePtrOff(); 6440 6441 // Single-precision floating-point values are mapped to the 6442 // second (rightmost) word of the stack doubleword. 6443 if (Arg.getValueType() == MVT::f32 && 6444 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6445 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6446 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6447 } 6448 6449 assert(HasParameterArea && 6450 "Parameter area must exist to pass an argument in memory."); 6451 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6452 true, CFlags.IsTailCall, false, MemOpChains, 6453 TailCallArguments, dl); 6454 6455 NeededLoad = true; 6456 } 6457 // When passing an array of floats, the array occupies consecutive 6458 // space in the argument area; only round up to the next doubleword 6459 // at the end of the array. Otherwise, each float takes 8 bytes. 6460 if (!IsFastCall || NeededLoad) { 6461 ArgOffset += (Arg.getValueType() == MVT::f32 && 6462 Flags.isInConsecutiveRegs()) ? 4 : 8; 6463 if (Flags.isInConsecutiveRegsLast()) 6464 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6465 } 6466 break; 6467 } 6468 case MVT::v4f32: 6469 case MVT::v4i32: 6470 case MVT::v8i16: 6471 case MVT::v16i8: 6472 case MVT::v2f64: 6473 case MVT::v2i64: 6474 case MVT::v1i128: 6475 case MVT::f128: 6476 if (!Subtarget.hasQPX()) { 6477 // These can be scalar arguments or elements of a vector array type 6478 // passed directly. The latter are used to implement ELFv2 homogenous 6479 // vector aggregates. 6480 6481 // For a varargs call, named arguments go into VRs or on the stack as 6482 // usual; unnamed arguments always go to the stack or the corresponding 6483 // GPRs when within range. For now, we always put the value in both 6484 // locations (or even all three). 6485 if (CFlags.IsVarArg) { 6486 assert(HasParameterArea && 6487 "Parameter area must exist if we have a varargs call."); 6488 // We could elide this store in the case where the object fits 6489 // entirely in R registers. Maybe later. 6490 SDValue Store = 6491 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6492 MemOpChains.push_back(Store); 6493 if (VR_idx != NumVRs) { 6494 SDValue Load = 6495 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6496 MemOpChains.push_back(Load.getValue(1)); 6497 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6498 } 6499 ArgOffset += 16; 6500 for (unsigned i=0; i<16; i+=PtrByteSize) { 6501 if (GPR_idx == NumGPRs) 6502 break; 6503 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6504 DAG.getConstant(i, dl, PtrVT)); 6505 SDValue Load = 6506 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6507 MemOpChains.push_back(Load.getValue(1)); 6508 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6509 } 6510 break; 6511 } 6512 6513 // Non-varargs Altivec params go into VRs or on the stack. 6514 if (VR_idx != NumVRs) { 6515 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6516 } else { 6517 if (IsFastCall) 6518 ComputePtrOff(); 6519 6520 assert(HasParameterArea && 6521 "Parameter area must exist to pass an argument in memory."); 6522 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6523 true, CFlags.IsTailCall, true, MemOpChains, 6524 TailCallArguments, dl); 6525 if (IsFastCall) 6526 ArgOffset += 16; 6527 } 6528 6529 if (!IsFastCall) 6530 ArgOffset += 16; 6531 break; 6532 } // not QPX 6533 6534 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6535 "Invalid QPX parameter type"); 6536 6537 LLVM_FALLTHROUGH; 6538 case MVT::v4f64: 6539 case MVT::v4i1: { 6540 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6541 if (CFlags.IsVarArg) { 6542 assert(HasParameterArea && 6543 "Parameter area must exist if we have a varargs call."); 6544 // We could elide this store in the case where the object fits 6545 // entirely in R registers. Maybe later. 6546 SDValue Store = 6547 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6548 MemOpChains.push_back(Store); 6549 if (QFPR_idx != NumQFPRs) { 6550 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6551 PtrOff, MachinePointerInfo()); 6552 MemOpChains.push_back(Load.getValue(1)); 6553 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6554 } 6555 ArgOffset += (IsF32 ? 16 : 32); 6556 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6557 if (GPR_idx == NumGPRs) 6558 break; 6559 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6560 DAG.getConstant(i, dl, PtrVT)); 6561 SDValue Load = 6562 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6563 MemOpChains.push_back(Load.getValue(1)); 6564 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6565 } 6566 break; 6567 } 6568 6569 // Non-varargs QPX params go into registers or on the stack. 6570 if (QFPR_idx != NumQFPRs) { 6571 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6572 } else { 6573 if (IsFastCall) 6574 ComputePtrOff(); 6575 6576 assert(HasParameterArea && 6577 "Parameter area must exist to pass an argument in memory."); 6578 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6579 true, CFlags.IsTailCall, true, MemOpChains, 6580 TailCallArguments, dl); 6581 if (IsFastCall) 6582 ArgOffset += (IsF32 ? 16 : 32); 6583 } 6584 6585 if (!IsFastCall) 6586 ArgOffset += (IsF32 ? 16 : 32); 6587 break; 6588 } 6589 } 6590 } 6591 6592 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6593 "mismatch in size of parameter area"); 6594 (void)NumBytesActuallyUsed; 6595 6596 if (!MemOpChains.empty()) 6597 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6598 6599 // Check if this is an indirect call (MTCTR/BCTRL). 6600 // See prepareDescriptorIndirectCall and buildCallOperands for more 6601 // information about calls through function pointers in the 64-bit SVR4 ABI. 6602 if (CFlags.IsIndirect) { 6603 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6604 // caller in the TOC save area. 6605 if (isTOCSaveRestoreRequired(Subtarget)) { 6606 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6607 // Load r2 into a virtual register and store it to the TOC save area. 6608 setUsesTOCBasePtr(DAG); 6609 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6610 // TOC save area offset. 6611 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6612 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6613 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6614 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6615 MachinePointerInfo::getStack( 6616 DAG.getMachineFunction(), TOCSaveOffset)); 6617 } 6618 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6619 // This does not mean the MTCTR instruction must use R12; it's easier 6620 // to model this as an extra parameter, so do that. 6621 if (isELFv2ABI && !CFlags.IsPatchPoint) 6622 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6623 } 6624 6625 // Build a sequence of copy-to-reg nodes chained together with token chain 6626 // and flag operands which copy the outgoing args into the appropriate regs. 6627 SDValue InFlag; 6628 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6629 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6630 RegsToPass[i].second, InFlag); 6631 InFlag = Chain.getValue(1); 6632 } 6633 6634 if (CFlags.IsTailCall && !IsSibCall) 6635 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6636 TailCallArguments); 6637 6638 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6639 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6640 } 6641 6642 SDValue PPCTargetLowering::LowerCall_Darwin( 6643 SDValue Chain, SDValue Callee, CallFlags CFlags, 6644 const SmallVectorImpl<ISD::OutputArg> &Outs, 6645 const SmallVectorImpl<SDValue> &OutVals, 6646 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6647 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6648 const CallBase *CB) const { 6649 unsigned NumOps = Outs.size(); 6650 6651 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6652 bool isPPC64 = PtrVT == MVT::i64; 6653 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6654 6655 MachineFunction &MF = DAG.getMachineFunction(); 6656 6657 // Mark this function as potentially containing a function that contains a 6658 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6659 // and restoring the callers stack pointer in this functions epilog. This is 6660 // done because by tail calling the called function might overwrite the value 6661 // in this function's (MF) stack pointer stack slot 0(SP). 6662 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6663 CFlags.CallConv == CallingConv::Fast) 6664 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6665 6666 // Count how many bytes are to be pushed on the stack, including the linkage 6667 // area, and parameter passing area. We start with 24/48 bytes, which is 6668 // prereserved space for [SP][CR][LR][3 x unused]. 6669 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6670 unsigned NumBytes = LinkageSize; 6671 6672 // Add up all the space actually used. 6673 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6674 // they all go in registers, but we must reserve stack space for them for 6675 // possible use by the caller. In varargs or 64-bit calls, parameters are 6676 // assigned stack space in order, with padding so Altivec parameters are 6677 // 16-byte aligned. 6678 unsigned nAltivecParamsAtEnd = 0; 6679 for (unsigned i = 0; i != NumOps; ++i) { 6680 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6681 EVT ArgVT = Outs[i].VT; 6682 // Varargs Altivec parameters are padded to a 16 byte boundary. 6683 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6684 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6685 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6686 if (!CFlags.IsVarArg && !isPPC64) { 6687 // Non-varargs Altivec parameters go after all the non-Altivec 6688 // parameters; handle those later so we know how much padding we need. 6689 nAltivecParamsAtEnd++; 6690 continue; 6691 } 6692 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6693 NumBytes = ((NumBytes+15)/16)*16; 6694 } 6695 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6696 } 6697 6698 // Allow for Altivec parameters at the end, if needed. 6699 if (nAltivecParamsAtEnd) { 6700 NumBytes = ((NumBytes+15)/16)*16; 6701 NumBytes += 16*nAltivecParamsAtEnd; 6702 } 6703 6704 // The prolog code of the callee may store up to 8 GPR argument registers to 6705 // the stack, allowing va_start to index over them in memory if its varargs. 6706 // Because we cannot tell if this is needed on the caller side, we have to 6707 // conservatively assume that it is needed. As such, make sure we have at 6708 // least enough stack space for the caller to store the 8 GPRs. 6709 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6710 6711 // Tail call needs the stack to be aligned. 6712 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6713 CFlags.CallConv == CallingConv::Fast) 6714 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6715 6716 // Calculate by how many bytes the stack has to be adjusted in case of tail 6717 // call optimization. 6718 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6719 6720 // To protect arguments on the stack from being clobbered in a tail call, 6721 // force all the loads to happen before doing any other lowering. 6722 if (CFlags.IsTailCall) 6723 Chain = DAG.getStackArgumentTokenFactor(Chain); 6724 6725 // Adjust the stack pointer for the new arguments... 6726 // These operations are automatically eliminated by the prolog/epilog pass 6727 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6728 SDValue CallSeqStart = Chain; 6729 6730 // Load the return address and frame pointer so it can be move somewhere else 6731 // later. 6732 SDValue LROp, FPOp; 6733 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6734 6735 // Set up a copy of the stack pointer for use loading and storing any 6736 // arguments that may not fit in the registers available for argument 6737 // passing. 6738 SDValue StackPtr; 6739 if (isPPC64) 6740 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6741 else 6742 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6743 6744 // Figure out which arguments are going to go in registers, and which in 6745 // memory. Also, if this is a vararg function, floating point operations 6746 // must be stored to our stack, and loaded into integer regs as well, if 6747 // any integer regs are available for argument passing. 6748 unsigned ArgOffset = LinkageSize; 6749 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6750 6751 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6752 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6753 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6754 }; 6755 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6756 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6757 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6758 }; 6759 static const MCPhysReg VR[] = { 6760 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6761 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6762 }; 6763 const unsigned NumGPRs = array_lengthof(GPR_32); 6764 const unsigned NumFPRs = 13; 6765 const unsigned NumVRs = array_lengthof(VR); 6766 6767 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6768 6769 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6770 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6771 6772 SmallVector<SDValue, 8> MemOpChains; 6773 for (unsigned i = 0; i != NumOps; ++i) { 6774 SDValue Arg = OutVals[i]; 6775 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6776 6777 // PtrOff will be used to store the current argument to the stack if a 6778 // register cannot be found for it. 6779 SDValue PtrOff; 6780 6781 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6782 6783 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6784 6785 // On PPC64, promote integers to 64-bit values. 6786 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6787 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6788 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6789 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6790 } 6791 6792 // FIXME memcpy is used way more than necessary. Correctness first. 6793 // Note: "by value" is code for passing a structure by value, not 6794 // basic types. 6795 if (Flags.isByVal()) { 6796 unsigned Size = Flags.getByValSize(); 6797 // Very small objects are passed right-justified. Everything else is 6798 // passed left-justified. 6799 if (Size==1 || Size==2) { 6800 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6801 if (GPR_idx != NumGPRs) { 6802 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6803 MachinePointerInfo(), VT); 6804 MemOpChains.push_back(Load.getValue(1)); 6805 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6806 6807 ArgOffset += PtrByteSize; 6808 } else { 6809 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6810 PtrOff.getValueType()); 6811 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6812 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6813 CallSeqStart, 6814 Flags, DAG, dl); 6815 ArgOffset += PtrByteSize; 6816 } 6817 continue; 6818 } 6819 // Copy entire object into memory. There are cases where gcc-generated 6820 // code assumes it is there, even if it could be put entirely into 6821 // registers. (This is not what the doc says.) 6822 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6823 CallSeqStart, 6824 Flags, DAG, dl); 6825 6826 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6827 // copy the pieces of the object that fit into registers from the 6828 // parameter save area. 6829 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6830 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6831 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6832 if (GPR_idx != NumGPRs) { 6833 SDValue Load = 6834 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6835 MemOpChains.push_back(Load.getValue(1)); 6836 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6837 ArgOffset += PtrByteSize; 6838 } else { 6839 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6840 break; 6841 } 6842 } 6843 continue; 6844 } 6845 6846 switch (Arg.getSimpleValueType().SimpleTy) { 6847 default: llvm_unreachable("Unexpected ValueType for argument!"); 6848 case MVT::i1: 6849 case MVT::i32: 6850 case MVT::i64: 6851 if (GPR_idx != NumGPRs) { 6852 if (Arg.getValueType() == MVT::i1) 6853 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6854 6855 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6856 } else { 6857 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6858 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6859 TailCallArguments, dl); 6860 } 6861 ArgOffset += PtrByteSize; 6862 break; 6863 case MVT::f32: 6864 case MVT::f64: 6865 if (FPR_idx != NumFPRs) { 6866 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6867 6868 if (CFlags.IsVarArg) { 6869 SDValue Store = 6870 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6871 MemOpChains.push_back(Store); 6872 6873 // Float varargs are always shadowed in available integer registers 6874 if (GPR_idx != NumGPRs) { 6875 SDValue Load = 6876 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6877 MemOpChains.push_back(Load.getValue(1)); 6878 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6879 } 6880 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6881 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6882 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6883 SDValue Load = 6884 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6885 MemOpChains.push_back(Load.getValue(1)); 6886 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6887 } 6888 } else { 6889 // If we have any FPRs remaining, we may also have GPRs remaining. 6890 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6891 // GPRs. 6892 if (GPR_idx != NumGPRs) 6893 ++GPR_idx; 6894 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6895 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6896 ++GPR_idx; 6897 } 6898 } else 6899 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6900 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6901 TailCallArguments, dl); 6902 if (isPPC64) 6903 ArgOffset += 8; 6904 else 6905 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6906 break; 6907 case MVT::v4f32: 6908 case MVT::v4i32: 6909 case MVT::v8i16: 6910 case MVT::v16i8: 6911 if (CFlags.IsVarArg) { 6912 // These go aligned on the stack, or in the corresponding R registers 6913 // when within range. The Darwin PPC ABI doc claims they also go in 6914 // V registers; in fact gcc does this only for arguments that are 6915 // prototyped, not for those that match the ... We do it for all 6916 // arguments, seems to work. 6917 while (ArgOffset % 16 !=0) { 6918 ArgOffset += PtrByteSize; 6919 if (GPR_idx != NumGPRs) 6920 GPR_idx++; 6921 } 6922 // We could elide this store in the case where the object fits 6923 // entirely in R registers. Maybe later. 6924 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6925 DAG.getConstant(ArgOffset, dl, PtrVT)); 6926 SDValue Store = 6927 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6928 MemOpChains.push_back(Store); 6929 if (VR_idx != NumVRs) { 6930 SDValue Load = 6931 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6932 MemOpChains.push_back(Load.getValue(1)); 6933 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6934 } 6935 ArgOffset += 16; 6936 for (unsigned i=0; i<16; i+=PtrByteSize) { 6937 if (GPR_idx == NumGPRs) 6938 break; 6939 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6940 DAG.getConstant(i, dl, PtrVT)); 6941 SDValue Load = 6942 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6943 MemOpChains.push_back(Load.getValue(1)); 6944 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6945 } 6946 break; 6947 } 6948 6949 // Non-varargs Altivec params generally go in registers, but have 6950 // stack space allocated at the end. 6951 if (VR_idx != NumVRs) { 6952 // Doesn't have GPR space allocated. 6953 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6954 } else if (nAltivecParamsAtEnd==0) { 6955 // We are emitting Altivec params in order. 6956 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6957 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6958 TailCallArguments, dl); 6959 ArgOffset += 16; 6960 } 6961 break; 6962 } 6963 } 6964 // If all Altivec parameters fit in registers, as they usually do, 6965 // they get stack space following the non-Altivec parameters. We 6966 // don't track this here because nobody below needs it. 6967 // If there are more Altivec parameters than fit in registers emit 6968 // the stores here. 6969 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6970 unsigned j = 0; 6971 // Offset is aligned; skip 1st 12 params which go in V registers. 6972 ArgOffset = ((ArgOffset+15)/16)*16; 6973 ArgOffset += 12*16; 6974 for (unsigned i = 0; i != NumOps; ++i) { 6975 SDValue Arg = OutVals[i]; 6976 EVT ArgType = Outs[i].VT; 6977 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6978 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6979 if (++j > NumVRs) { 6980 SDValue PtrOff; 6981 // We are emitting Altivec params in order. 6982 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6983 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6984 TailCallArguments, dl); 6985 ArgOffset += 16; 6986 } 6987 } 6988 } 6989 } 6990 6991 if (!MemOpChains.empty()) 6992 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6993 6994 // On Darwin, R12 must contain the address of an indirect callee. This does 6995 // not mean the MTCTR instruction must use R12; it's easier to model this as 6996 // an extra parameter, so do that. 6997 if (CFlags.IsIndirect) { 6998 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6999 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 7000 PPC::R12), Callee)); 7001 } 7002 7003 // Build a sequence of copy-to-reg nodes chained together with token chain 7004 // and flag operands which copy the outgoing args into the appropriate regs. 7005 SDValue InFlag; 7006 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 7007 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 7008 RegsToPass[i].second, InFlag); 7009 InFlag = Chain.getValue(1); 7010 } 7011 7012 if (CFlags.IsTailCall) 7013 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 7014 TailCallArguments); 7015 7016 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7017 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7018 } 7019 7020 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 7021 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 7022 CCState &State) { 7023 7024 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 7025 State.getMachineFunction().getSubtarget()); 7026 const bool IsPPC64 = Subtarget.isPPC64(); 7027 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 7028 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 7029 7030 assert((!ValVT.isInteger() || 7031 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 7032 "Integer argument exceeds register size: should have been legalized"); 7033 7034 if (ValVT == MVT::f128) 7035 report_fatal_error("f128 is unimplemented on AIX."); 7036 7037 if (ArgFlags.isNest()) 7038 report_fatal_error("Nest arguments are unimplemented."); 7039 7040 if (ValVT.isVector() || LocVT.isVector()) 7041 report_fatal_error("Vector arguments are unimplemented on AIX."); 7042 7043 static const MCPhysReg GPR_32[] = {// 32-bit registers. 7044 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7045 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7046 static const MCPhysReg GPR_64[] = {// 64-bit registers. 7047 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7048 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7049 7050 if (ArgFlags.isByVal()) { 7051 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 7052 report_fatal_error("Pass-by-value arguments with alignment greater than " 7053 "register width are not supported."); 7054 7055 const unsigned ByValSize = ArgFlags.getByValSize(); 7056 7057 // An empty aggregate parameter takes up no storage and no registers, 7058 // but needs a MemLoc for a stack slot for the formal arguments side. 7059 if (ByValSize == 0) { 7060 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7061 State.getNextStackOffset(), RegVT, 7062 LocInfo)); 7063 return false; 7064 } 7065 7066 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 7067 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 7068 for (const unsigned E = Offset + StackSize; Offset < E; 7069 Offset += PtrAlign.value()) { 7070 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7071 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7072 else { 7073 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7074 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7075 LocInfo)); 7076 break; 7077 } 7078 } 7079 return false; 7080 } 7081 7082 // Arguments always reserve parameter save area. 7083 switch (ValVT.SimpleTy) { 7084 default: 7085 report_fatal_error("Unhandled value type for argument."); 7086 case MVT::i64: 7087 // i64 arguments should have been split to i32 for PPC32. 7088 assert(IsPPC64 && "PPC32 should have split i64 values."); 7089 LLVM_FALLTHROUGH; 7090 case MVT::i1: 7091 case MVT::i32: { 7092 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 7093 // AIX integer arguments are always passed in register width. 7094 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7095 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7096 : CCValAssign::LocInfo::ZExt; 7097 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7098 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7099 else 7100 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7101 7102 return false; 7103 } 7104 case MVT::f32: 7105 case MVT::f64: { 7106 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7107 const unsigned StoreSize = LocVT.getStoreSize(); 7108 // Floats are always 4-byte aligned in the PSA on AIX. 7109 // This includes f64 in 64-bit mode for ABI compatibility. 7110 const unsigned Offset = 7111 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 7112 unsigned FReg = State.AllocateReg(FPR); 7113 if (FReg) 7114 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7115 7116 // Reserve and initialize GPRs or initialize the PSA as required. 7117 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 7118 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7119 assert(FReg && "An FPR should be available when a GPR is reserved."); 7120 if (State.isVarArg()) { 7121 // Successfully reserved GPRs are only initialized for vararg calls. 7122 // Custom handling is required for: 7123 // f64 in PPC32 needs to be split into 2 GPRs. 7124 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7125 State.addLoc( 7126 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7127 } 7128 } else { 7129 // If there are insufficient GPRs, the PSA needs to be initialized. 7130 // Initialization occurs even if an FPR was initialized for 7131 // compatibility with the AIX XL compiler. The full memory for the 7132 // argument will be initialized even if a prior word is saved in GPR. 7133 // A custom memLoc is used when the argument also passes in FPR so 7134 // that the callee handling can skip over it easily. 7135 State.addLoc( 7136 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7137 LocInfo) 7138 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7139 break; 7140 } 7141 } 7142 7143 return false; 7144 } 7145 } 7146 return true; 7147 } 7148 7149 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7150 bool IsPPC64) { 7151 assert((IsPPC64 || SVT != MVT::i64) && 7152 "i64 should have been split for 32-bit codegen."); 7153 7154 switch (SVT) { 7155 default: 7156 report_fatal_error("Unexpected value type for formal argument"); 7157 case MVT::i1: 7158 case MVT::i32: 7159 case MVT::i64: 7160 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7161 case MVT::f32: 7162 return &PPC::F4RCRegClass; 7163 case MVT::f64: 7164 return &PPC::F8RCRegClass; 7165 } 7166 } 7167 7168 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7169 SelectionDAG &DAG, SDValue ArgValue, 7170 MVT LocVT, const SDLoc &dl) { 7171 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7172 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7173 7174 if (Flags.isSExt()) 7175 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7176 DAG.getValueType(ValVT)); 7177 else if (Flags.isZExt()) 7178 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7179 DAG.getValueType(ValVT)); 7180 7181 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7182 } 7183 7184 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7185 const unsigned LASize = FL->getLinkageSize(); 7186 7187 if (PPC::GPRCRegClass.contains(Reg)) { 7188 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7189 "Reg must be a valid argument register!"); 7190 return LASize + 4 * (Reg - PPC::R3); 7191 } 7192 7193 if (PPC::G8RCRegClass.contains(Reg)) { 7194 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7195 "Reg must be a valid argument register!"); 7196 return LASize + 8 * (Reg - PPC::X3); 7197 } 7198 7199 llvm_unreachable("Only general purpose registers expected."); 7200 } 7201 7202 // AIX ABI Stack Frame Layout: 7203 // 7204 // Low Memory +--------------------------------------------+ 7205 // SP +---> | Back chain | ---+ 7206 // | +--------------------------------------------+ | 7207 // | | Saved Condition Register | | 7208 // | +--------------------------------------------+ | 7209 // | | Saved Linkage Register | | 7210 // | +--------------------------------------------+ | Linkage Area 7211 // | | Reserved for compilers | | 7212 // | +--------------------------------------------+ | 7213 // | | Reserved for binders | | 7214 // | +--------------------------------------------+ | 7215 // | | Saved TOC pointer | ---+ 7216 // | +--------------------------------------------+ 7217 // | | Parameter save area | 7218 // | +--------------------------------------------+ 7219 // | | Alloca space | 7220 // | +--------------------------------------------+ 7221 // | | Local variable space | 7222 // | +--------------------------------------------+ 7223 // | | Float/int conversion temporary | 7224 // | +--------------------------------------------+ 7225 // | | Save area for AltiVec registers | 7226 // | +--------------------------------------------+ 7227 // | | AltiVec alignment padding | 7228 // | +--------------------------------------------+ 7229 // | | Save area for VRSAVE register | 7230 // | +--------------------------------------------+ 7231 // | | Save area for General Purpose registers | 7232 // | +--------------------------------------------+ 7233 // | | Save area for Floating Point registers | 7234 // | +--------------------------------------------+ 7235 // +---- | Back chain | 7236 // High Memory +--------------------------------------------+ 7237 // 7238 // Specifications: 7239 // AIX 7.2 Assembler Language Reference 7240 // Subroutine linkage convention 7241 7242 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7243 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7244 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7245 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7246 7247 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7248 CallConv == CallingConv::Fast) && 7249 "Unexpected calling convention!"); 7250 7251 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7252 report_fatal_error("Tail call support is unimplemented on AIX."); 7253 7254 if (useSoftFloat()) 7255 report_fatal_error("Soft float support is unimplemented on AIX."); 7256 7257 const PPCSubtarget &Subtarget = 7258 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7259 if (Subtarget.hasQPX()) 7260 report_fatal_error("QPX support is not supported on AIX."); 7261 7262 const bool IsPPC64 = Subtarget.isPPC64(); 7263 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7264 7265 // Assign locations to all of the incoming arguments. 7266 SmallVector<CCValAssign, 16> ArgLocs; 7267 MachineFunction &MF = DAG.getMachineFunction(); 7268 MachineFrameInfo &MFI = MF.getFrameInfo(); 7269 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7270 7271 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7272 // Reserve space for the linkage area on the stack. 7273 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7274 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7275 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7276 7277 SmallVector<SDValue, 8> MemOps; 7278 7279 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7280 CCValAssign &VA = ArgLocs[I++]; 7281 MVT LocVT = VA.getLocVT(); 7282 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7283 7284 // For compatibility with the AIX XL compiler, the float args in the 7285 // parameter save area are initialized even if the argument is available 7286 // in register. The caller is required to initialize both the register 7287 // and memory, however, the callee can choose to expect it in either. 7288 // The memloc is dismissed here because the argument is retrieved from 7289 // the register. 7290 if (VA.isMemLoc() && VA.needsCustom()) 7291 continue; 7292 7293 if (Flags.isByVal() && VA.isMemLoc()) { 7294 const unsigned Size = 7295 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7296 PtrByteSize); 7297 const int FI = MF.getFrameInfo().CreateFixedObject( 7298 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7299 /* IsAliased */ true); 7300 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7301 InVals.push_back(FIN); 7302 7303 continue; 7304 } 7305 7306 if (Flags.isByVal()) { 7307 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7308 7309 const MCPhysReg ArgReg = VA.getLocReg(); 7310 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7311 7312 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7313 report_fatal_error("Over aligned byvals not supported yet."); 7314 7315 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7316 const int FI = MF.getFrameInfo().CreateFixedObject( 7317 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7318 /* IsAliased */ true); 7319 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7320 InVals.push_back(FIN); 7321 7322 // Add live ins for all the RegLocs for the same ByVal. 7323 const TargetRegisterClass *RegClass = 7324 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7325 7326 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7327 unsigned Offset) { 7328 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7329 // Since the callers side has left justified the aggregate in the 7330 // register, we can simply store the entire register into the stack 7331 // slot. 7332 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7333 // The store to the fixedstack object is needed becuase accessing a 7334 // field of the ByVal will use a gep and load. Ideally we will optimize 7335 // to extracting the value from the register directly, and elide the 7336 // stores when the arguments address is not taken, but that will need to 7337 // be future work. 7338 SDValue Store = 7339 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7340 DAG.getObjectPtrOffset(dl, FIN, Offset), 7341 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7342 7343 MemOps.push_back(Store); 7344 }; 7345 7346 unsigned Offset = 0; 7347 HandleRegLoc(VA.getLocReg(), Offset); 7348 Offset += PtrByteSize; 7349 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7350 Offset += PtrByteSize) { 7351 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7352 "RegLocs should be for ByVal argument."); 7353 7354 const CCValAssign RL = ArgLocs[I++]; 7355 HandleRegLoc(RL.getLocReg(), Offset); 7356 } 7357 7358 if (Offset != StackSize) { 7359 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7360 "Expected MemLoc for remaining bytes."); 7361 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7362 // Consume the MemLoc.The InVal has already been emitted, so nothing 7363 // more needs to be done. 7364 ++I; 7365 } 7366 7367 continue; 7368 } 7369 7370 EVT ValVT = VA.getValVT(); 7371 if (VA.isRegLoc() && !VA.needsCustom()) { 7372 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7373 unsigned VReg = 7374 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7375 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7376 if (ValVT.isScalarInteger() && 7377 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7378 ArgValue = 7379 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7380 } 7381 InVals.push_back(ArgValue); 7382 continue; 7383 } 7384 if (VA.isMemLoc()) { 7385 const unsigned LocSize = LocVT.getStoreSize(); 7386 const unsigned ValSize = ValVT.getStoreSize(); 7387 assert((ValSize <= LocSize) && 7388 "Object size is larger than size of MemLoc"); 7389 int CurArgOffset = VA.getLocMemOffset(); 7390 // Objects are right-justified because AIX is big-endian. 7391 if (LocSize > ValSize) 7392 CurArgOffset += LocSize - ValSize; 7393 // Potential tail calls could cause overwriting of argument stack slots. 7394 const bool IsImmutable = 7395 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7396 (CallConv == CallingConv::Fast)); 7397 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7398 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7399 SDValue ArgValue = 7400 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7401 InVals.push_back(ArgValue); 7402 continue; 7403 } 7404 } 7405 7406 // On AIX a minimum of 8 words is saved to the parameter save area. 7407 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7408 // Area that is at least reserved in the caller of this function. 7409 unsigned CallerReservedArea = 7410 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7411 7412 // Set the size that is at least reserved in caller of this function. Tail 7413 // call optimized function's reserved stack space needs to be aligned so 7414 // that taking the difference between two stack areas will result in an 7415 // aligned stack. 7416 CallerReservedArea = 7417 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7418 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7419 FuncInfo->setMinReservedArea(CallerReservedArea); 7420 7421 if (isVarArg) { 7422 FuncInfo->setVarArgsFrameIndex( 7423 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7424 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7425 7426 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7427 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7428 7429 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7430 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7431 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7432 7433 // The fixed integer arguments of a variadic function are stored to the 7434 // VarArgsFrameIndex on the stack so that they may be loaded by 7435 // dereferencing the result of va_next. 7436 for (unsigned GPRIndex = 7437 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7438 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7439 7440 const unsigned VReg = 7441 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7442 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7443 7444 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7445 SDValue Store = 7446 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7447 MemOps.push_back(Store); 7448 // Increment the address for the next argument to store. 7449 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7450 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7451 } 7452 } 7453 7454 if (!MemOps.empty()) 7455 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7456 7457 return Chain; 7458 } 7459 7460 SDValue PPCTargetLowering::LowerCall_AIX( 7461 SDValue Chain, SDValue Callee, CallFlags CFlags, 7462 const SmallVectorImpl<ISD::OutputArg> &Outs, 7463 const SmallVectorImpl<SDValue> &OutVals, 7464 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7465 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7466 const CallBase *CB) const { 7467 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7468 // AIX ABI stack frame layout. 7469 7470 assert((CFlags.CallConv == CallingConv::C || 7471 CFlags.CallConv == CallingConv::Cold || 7472 CFlags.CallConv == CallingConv::Fast) && 7473 "Unexpected calling convention!"); 7474 7475 if (CFlags.IsPatchPoint) 7476 report_fatal_error("This call type is unimplemented on AIX."); 7477 7478 const PPCSubtarget& Subtarget = 7479 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7480 if (Subtarget.hasQPX()) 7481 report_fatal_error("QPX is not supported on AIX."); 7482 if (Subtarget.hasAltivec()) 7483 report_fatal_error("Altivec support is unimplemented on AIX."); 7484 7485 MachineFunction &MF = DAG.getMachineFunction(); 7486 SmallVector<CCValAssign, 16> ArgLocs; 7487 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7488 *DAG.getContext()); 7489 7490 // Reserve space for the linkage save area (LSA) on the stack. 7491 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7492 // [SP][CR][LR][2 x reserved][TOC]. 7493 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7494 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7495 const bool IsPPC64 = Subtarget.isPPC64(); 7496 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7497 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7498 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7499 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7500 7501 // The prolog code of the callee may store up to 8 GPR argument registers to 7502 // the stack, allowing va_start to index over them in memory if the callee 7503 // is variadic. 7504 // Because we cannot tell if this is needed on the caller side, we have to 7505 // conservatively assume that it is needed. As such, make sure we have at 7506 // least enough stack space for the caller to store the 8 GPRs. 7507 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7508 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7509 CCInfo.getNextStackOffset()); 7510 7511 // Adjust the stack pointer for the new arguments... 7512 // These operations are automatically eliminated by the prolog/epilog pass. 7513 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7514 SDValue CallSeqStart = Chain; 7515 7516 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7517 SmallVector<SDValue, 8> MemOpChains; 7518 7519 // Set up a copy of the stack pointer for loading and storing any 7520 // arguments that may not fit in the registers available for argument 7521 // passing. 7522 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7523 : DAG.getRegister(PPC::R1, MVT::i32); 7524 7525 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7526 const unsigned ValNo = ArgLocs[I].getValNo(); 7527 SDValue Arg = OutVals[ValNo]; 7528 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7529 7530 if (Flags.isByVal()) { 7531 const unsigned ByValSize = Flags.getByValSize(); 7532 7533 // Nothing to do for zero-sized ByVals on the caller side. 7534 if (!ByValSize) { 7535 ++I; 7536 continue; 7537 } 7538 7539 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7540 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7541 (LoadOffset != 0) 7542 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7543 : Arg, 7544 MachinePointerInfo(), VT); 7545 }; 7546 7547 unsigned LoadOffset = 0; 7548 7549 // Initialize registers, which are fully occupied by the by-val argument. 7550 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7551 SDValue Load = GetLoad(PtrVT, LoadOffset); 7552 MemOpChains.push_back(Load.getValue(1)); 7553 LoadOffset += PtrByteSize; 7554 const CCValAssign &ByValVA = ArgLocs[I++]; 7555 assert(ByValVA.getValNo() == ValNo && 7556 "Unexpected location for pass-by-value argument."); 7557 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7558 } 7559 7560 if (LoadOffset == ByValSize) 7561 continue; 7562 7563 // There must be one more loc to handle the remainder. 7564 assert(ArgLocs[I].getValNo() == ValNo && 7565 "Expected additional location for by-value argument."); 7566 7567 if (ArgLocs[I].isMemLoc()) { 7568 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7569 const CCValAssign &ByValVA = ArgLocs[I++]; 7570 ISD::ArgFlagsTy MemcpyFlags = Flags; 7571 // Only memcpy the bytes that don't pass in register. 7572 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7573 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7574 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7575 : Arg, 7576 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7577 CallSeqStart, MemcpyFlags, DAG, dl); 7578 continue; 7579 } 7580 7581 // Initialize the final register residue. 7582 // Any residue that occupies the final by-val arg register must be 7583 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7584 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7585 // 2 and 1 byte loads. 7586 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7587 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7588 "Unexpected register residue for by-value argument."); 7589 SDValue ResidueVal; 7590 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7591 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7592 const MVT VT = 7593 N == 1 ? MVT::i8 7594 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7595 SDValue Load = GetLoad(VT, LoadOffset); 7596 MemOpChains.push_back(Load.getValue(1)); 7597 LoadOffset += N; 7598 Bytes += N; 7599 7600 // By-val arguments are passed left-justfied in register. 7601 // Every load here needs to be shifted, otherwise a full register load 7602 // should have been used. 7603 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7604 "Unexpected load emitted during handling of pass-by-value " 7605 "argument."); 7606 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7607 EVT ShiftAmountTy = 7608 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7609 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7610 SDValue ShiftedLoad = 7611 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7612 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7613 ShiftedLoad) 7614 : ShiftedLoad; 7615 } 7616 7617 const CCValAssign &ByValVA = ArgLocs[I++]; 7618 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7619 continue; 7620 } 7621 7622 CCValAssign &VA = ArgLocs[I++]; 7623 const MVT LocVT = VA.getLocVT(); 7624 const MVT ValVT = VA.getValVT(); 7625 7626 switch (VA.getLocInfo()) { 7627 default: 7628 report_fatal_error("Unexpected argument extension type."); 7629 case CCValAssign::Full: 7630 break; 7631 case CCValAssign::ZExt: 7632 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7633 break; 7634 case CCValAssign::SExt: 7635 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7636 break; 7637 } 7638 7639 if (VA.isRegLoc() && !VA.needsCustom()) { 7640 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7641 continue; 7642 } 7643 7644 if (VA.isMemLoc()) { 7645 SDValue PtrOff = 7646 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7647 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7648 MemOpChains.push_back( 7649 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7650 7651 continue; 7652 } 7653 7654 // Custom handling is used for GPR initializations for vararg float 7655 // arguments. 7656 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7657 ValVT.isFloatingPoint() && LocVT.isInteger() && 7658 "Unexpected register handling for calling convention."); 7659 7660 SDValue ArgAsInt = 7661 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7662 7663 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7664 // f32 in 32-bit GPR 7665 // f64 in 64-bit GPR 7666 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7667 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7668 // f32 in 64-bit GPR. 7669 RegsToPass.push_back(std::make_pair( 7670 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7671 else { 7672 // f64 in two 32-bit GPRs 7673 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7674 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7675 "Unexpected custom register for argument!"); 7676 CCValAssign &GPR1 = VA; 7677 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7678 DAG.getConstant(32, dl, MVT::i8)); 7679 RegsToPass.push_back(std::make_pair( 7680 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7681 7682 if (I != E) { 7683 // If only 1 GPR was available, there will only be one custom GPR and 7684 // the argument will also pass in memory. 7685 CCValAssign &PeekArg = ArgLocs[I]; 7686 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7687 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7688 CCValAssign &GPR2 = ArgLocs[I++]; 7689 RegsToPass.push_back(std::make_pair( 7690 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7691 } 7692 } 7693 } 7694 } 7695 7696 if (!MemOpChains.empty()) 7697 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7698 7699 // For indirect calls, we need to save the TOC base to the stack for 7700 // restoration after the call. 7701 if (CFlags.IsIndirect) { 7702 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7703 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7704 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7705 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7706 const unsigned TOCSaveOffset = 7707 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7708 7709 setUsesTOCBasePtr(DAG); 7710 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7711 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7712 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7713 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7714 Chain = DAG.getStore( 7715 Val.getValue(1), dl, Val, AddPtr, 7716 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7717 } 7718 7719 // Build a sequence of copy-to-reg nodes chained together with token chain 7720 // and flag operands which copy the outgoing args into the appropriate regs. 7721 SDValue InFlag; 7722 for (auto Reg : RegsToPass) { 7723 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7724 InFlag = Chain.getValue(1); 7725 } 7726 7727 const int SPDiff = 0; 7728 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7729 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7730 } 7731 7732 bool 7733 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7734 MachineFunction &MF, bool isVarArg, 7735 const SmallVectorImpl<ISD::OutputArg> &Outs, 7736 LLVMContext &Context) const { 7737 SmallVector<CCValAssign, 16> RVLocs; 7738 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7739 return CCInfo.CheckReturn( 7740 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7741 ? RetCC_PPC_Cold 7742 : RetCC_PPC); 7743 } 7744 7745 SDValue 7746 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7747 bool isVarArg, 7748 const SmallVectorImpl<ISD::OutputArg> &Outs, 7749 const SmallVectorImpl<SDValue> &OutVals, 7750 const SDLoc &dl, SelectionDAG &DAG) const { 7751 SmallVector<CCValAssign, 16> RVLocs; 7752 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7753 *DAG.getContext()); 7754 CCInfo.AnalyzeReturn(Outs, 7755 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7756 ? RetCC_PPC_Cold 7757 : RetCC_PPC); 7758 7759 SDValue Flag; 7760 SmallVector<SDValue, 4> RetOps(1, Chain); 7761 7762 // Copy the result values into the output registers. 7763 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7764 CCValAssign &VA = RVLocs[i]; 7765 assert(VA.isRegLoc() && "Can only return in registers!"); 7766 7767 SDValue Arg = OutVals[RealResIdx]; 7768 7769 switch (VA.getLocInfo()) { 7770 default: llvm_unreachable("Unknown loc info!"); 7771 case CCValAssign::Full: break; 7772 case CCValAssign::AExt: 7773 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7774 break; 7775 case CCValAssign::ZExt: 7776 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7777 break; 7778 case CCValAssign::SExt: 7779 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7780 break; 7781 } 7782 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7783 bool isLittleEndian = Subtarget.isLittleEndian(); 7784 // Legalize ret f64 -> ret 2 x i32. 7785 SDValue SVal = 7786 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7787 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7788 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7789 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7790 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7791 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7792 Flag = Chain.getValue(1); 7793 VA = RVLocs[++i]; // skip ahead to next loc 7794 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7795 } else 7796 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7797 Flag = Chain.getValue(1); 7798 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7799 } 7800 7801 RetOps[0] = Chain; // Update chain. 7802 7803 // Add the flag if we have it. 7804 if (Flag.getNode()) 7805 RetOps.push_back(Flag); 7806 7807 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7808 } 7809 7810 SDValue 7811 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7812 SelectionDAG &DAG) const { 7813 SDLoc dl(Op); 7814 7815 // Get the correct type for integers. 7816 EVT IntVT = Op.getValueType(); 7817 7818 // Get the inputs. 7819 SDValue Chain = Op.getOperand(0); 7820 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7821 // Build a DYNAREAOFFSET node. 7822 SDValue Ops[2] = {Chain, FPSIdx}; 7823 SDVTList VTs = DAG.getVTList(IntVT); 7824 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7825 } 7826 7827 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7828 SelectionDAG &DAG) const { 7829 // When we pop the dynamic allocation we need to restore the SP link. 7830 SDLoc dl(Op); 7831 7832 // Get the correct type for pointers. 7833 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7834 7835 // Construct the stack pointer operand. 7836 bool isPPC64 = Subtarget.isPPC64(); 7837 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7838 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7839 7840 // Get the operands for the STACKRESTORE. 7841 SDValue Chain = Op.getOperand(0); 7842 SDValue SaveSP = Op.getOperand(1); 7843 7844 // Load the old link SP. 7845 SDValue LoadLinkSP = 7846 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7847 7848 // Restore the stack pointer. 7849 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7850 7851 // Store the old link SP. 7852 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7853 } 7854 7855 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7856 MachineFunction &MF = DAG.getMachineFunction(); 7857 bool isPPC64 = Subtarget.isPPC64(); 7858 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7859 7860 // Get current frame pointer save index. The users of this index will be 7861 // primarily DYNALLOC instructions. 7862 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7863 int RASI = FI->getReturnAddrSaveIndex(); 7864 7865 // If the frame pointer save index hasn't been defined yet. 7866 if (!RASI) { 7867 // Find out what the fix offset of the frame pointer save area. 7868 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7869 // Allocate the frame index for frame pointer save area. 7870 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7871 // Save the result. 7872 FI->setReturnAddrSaveIndex(RASI); 7873 } 7874 return DAG.getFrameIndex(RASI, PtrVT); 7875 } 7876 7877 SDValue 7878 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7879 MachineFunction &MF = DAG.getMachineFunction(); 7880 bool isPPC64 = Subtarget.isPPC64(); 7881 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7882 7883 // Get current frame pointer save index. The users of this index will be 7884 // primarily DYNALLOC instructions. 7885 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7886 int FPSI = FI->getFramePointerSaveIndex(); 7887 7888 // If the frame pointer save index hasn't been defined yet. 7889 if (!FPSI) { 7890 // Find out what the fix offset of the frame pointer save area. 7891 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7892 // Allocate the frame index for frame pointer save area. 7893 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7894 // Save the result. 7895 FI->setFramePointerSaveIndex(FPSI); 7896 } 7897 return DAG.getFrameIndex(FPSI, PtrVT); 7898 } 7899 7900 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7901 SelectionDAG &DAG) const { 7902 // Get the inputs. 7903 SDValue Chain = Op.getOperand(0); 7904 SDValue Size = Op.getOperand(1); 7905 SDLoc dl(Op); 7906 7907 // Get the correct type for pointers. 7908 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7909 // Negate the size. 7910 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7911 DAG.getConstant(0, dl, PtrVT), Size); 7912 // Construct a node for the frame pointer save index. 7913 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7914 // Build a DYNALLOC node. 7915 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7916 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7917 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7918 } 7919 7920 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7921 SelectionDAG &DAG) const { 7922 MachineFunction &MF = DAG.getMachineFunction(); 7923 7924 bool isPPC64 = Subtarget.isPPC64(); 7925 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7926 7927 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7928 return DAG.getFrameIndex(FI, PtrVT); 7929 } 7930 7931 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7932 SelectionDAG &DAG) const { 7933 SDLoc DL(Op); 7934 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7935 DAG.getVTList(MVT::i32, MVT::Other), 7936 Op.getOperand(0), Op.getOperand(1)); 7937 } 7938 7939 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7940 SelectionDAG &DAG) const { 7941 SDLoc DL(Op); 7942 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7943 Op.getOperand(0), Op.getOperand(1)); 7944 } 7945 7946 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7947 if (Op.getValueType().isVector()) 7948 return LowerVectorLoad(Op, DAG); 7949 7950 assert(Op.getValueType() == MVT::i1 && 7951 "Custom lowering only for i1 loads"); 7952 7953 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7954 7955 SDLoc dl(Op); 7956 LoadSDNode *LD = cast<LoadSDNode>(Op); 7957 7958 SDValue Chain = LD->getChain(); 7959 SDValue BasePtr = LD->getBasePtr(); 7960 MachineMemOperand *MMO = LD->getMemOperand(); 7961 7962 SDValue NewLD = 7963 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7964 BasePtr, MVT::i8, MMO); 7965 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7966 7967 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7968 return DAG.getMergeValues(Ops, dl); 7969 } 7970 7971 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7972 if (Op.getOperand(1).getValueType().isVector()) 7973 return LowerVectorStore(Op, DAG); 7974 7975 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7976 "Custom lowering only for i1 stores"); 7977 7978 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7979 7980 SDLoc dl(Op); 7981 StoreSDNode *ST = cast<StoreSDNode>(Op); 7982 7983 SDValue Chain = ST->getChain(); 7984 SDValue BasePtr = ST->getBasePtr(); 7985 SDValue Value = ST->getValue(); 7986 MachineMemOperand *MMO = ST->getMemOperand(); 7987 7988 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7989 Value); 7990 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7991 } 7992 7993 // FIXME: Remove this once the ANDI glue bug is fixed: 7994 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7995 assert(Op.getValueType() == MVT::i1 && 7996 "Custom lowering only for i1 results"); 7997 7998 SDLoc DL(Op); 7999 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 8000 } 8001 8002 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 8003 SelectionDAG &DAG) const { 8004 8005 // Implements a vector truncate that fits in a vector register as a shuffle. 8006 // We want to legalize vector truncates down to where the source fits in 8007 // a vector register (and target is therefore smaller than vector register 8008 // size). At that point legalization will try to custom lower the sub-legal 8009 // result and get here - where we can contain the truncate as a single target 8010 // operation. 8011 8012 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 8013 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 8014 // 8015 // We will implement it for big-endian ordering as this (where x denotes 8016 // undefined): 8017 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 8018 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 8019 // 8020 // The same operation in little-endian ordering will be: 8021 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 8022 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 8023 8024 assert(Op.getValueType().isVector() && "Vector type expected."); 8025 8026 SDLoc DL(Op); 8027 SDValue N1 = Op.getOperand(0); 8028 unsigned SrcSize = N1.getValueType().getSizeInBits(); 8029 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 8030 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 8031 8032 EVT TrgVT = Op.getValueType(); 8033 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 8034 EVT EltVT = TrgVT.getVectorElementType(); 8035 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8036 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8037 8038 // First list the elements we want to keep. 8039 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 8040 SmallVector<int, 16> ShuffV; 8041 if (Subtarget.isLittleEndian()) 8042 for (unsigned i = 0; i < TrgNumElts; ++i) 8043 ShuffV.push_back(i * SizeMult); 8044 else 8045 for (unsigned i = 1; i <= TrgNumElts; ++i) 8046 ShuffV.push_back(i * SizeMult - 1); 8047 8048 // Populate the remaining elements with undefs. 8049 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 8050 // ShuffV.push_back(i + WideNumElts); 8051 ShuffV.push_back(WideNumElts + 1); 8052 8053 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 8054 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 8055 } 8056 8057 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 8058 /// possible. 8059 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 8060 // Not FP? Not a fsel. 8061 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 8062 !Op.getOperand(2).getValueType().isFloatingPoint()) 8063 return Op; 8064 8065 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 8066 8067 EVT ResVT = Op.getValueType(); 8068 EVT CmpVT = Op.getOperand(0).getValueType(); 8069 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8070 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 8071 SDLoc dl(Op); 8072 SDNodeFlags Flags = Op.getNode()->getFlags(); 8073 8074 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 8075 // presence of infinities. 8076 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 8077 switch (CC) { 8078 default: 8079 break; 8080 case ISD::SETOGT: 8081 case ISD::SETGT: 8082 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8083 case ISD::SETOLT: 8084 case ISD::SETLT: 8085 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8086 } 8087 } 8088 8089 // We might be able to do better than this under some circumstances, but in 8090 // general, fsel-based lowering of select is a finite-math-only optimization. 8091 // For more information, see section F.3 of the 2.06 ISA specification. 8092 // With ISA 3.0 8093 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8094 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8095 return Op; 8096 8097 // If the RHS of the comparison is a 0.0, we don't need to do the 8098 // subtraction at all. 8099 SDValue Sel1; 8100 if (isFloatingPointZero(RHS)) 8101 switch (CC) { 8102 default: break; // SETUO etc aren't handled by fsel. 8103 case ISD::SETNE: 8104 std::swap(TV, FV); 8105 LLVM_FALLTHROUGH; 8106 case ISD::SETEQ: 8107 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8108 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8109 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8110 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8111 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8112 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8113 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8114 case ISD::SETULT: 8115 case ISD::SETLT: 8116 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8117 LLVM_FALLTHROUGH; 8118 case ISD::SETOGE: 8119 case ISD::SETGE: 8120 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8121 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8122 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8123 case ISD::SETUGT: 8124 case ISD::SETGT: 8125 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8126 LLVM_FALLTHROUGH; 8127 case ISD::SETOLE: 8128 case ISD::SETLE: 8129 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8130 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8131 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8132 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8133 } 8134 8135 SDValue Cmp; 8136 switch (CC) { 8137 default: break; // SETUO etc aren't handled by fsel. 8138 case ISD::SETNE: 8139 std::swap(TV, FV); 8140 LLVM_FALLTHROUGH; 8141 case ISD::SETEQ: 8142 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8143 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8144 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8145 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8146 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8147 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8148 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8149 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8150 case ISD::SETULT: 8151 case ISD::SETLT: 8152 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8153 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8154 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8155 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8156 case ISD::SETOGE: 8157 case ISD::SETGE: 8158 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8159 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8160 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8161 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8162 case ISD::SETUGT: 8163 case ISD::SETGT: 8164 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8165 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8166 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8167 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8168 case ISD::SETOLE: 8169 case ISD::SETLE: 8170 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8171 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8172 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8173 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8174 } 8175 return Op; 8176 } 8177 8178 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8179 SelectionDAG &DAG, 8180 const SDLoc &dl) const { 8181 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8182 SDValue Src = Op.getOperand(0); 8183 if (Src.getValueType() == MVT::f32) 8184 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8185 8186 SDValue Tmp; 8187 switch (Op.getSimpleValueType().SimpleTy) { 8188 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8189 case MVT::i32: 8190 Tmp = DAG.getNode( 8191 Op.getOpcode() == ISD::FP_TO_SINT 8192 ? PPCISD::FCTIWZ 8193 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8194 dl, MVT::f64, Src); 8195 break; 8196 case MVT::i64: 8197 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8198 "i64 FP_TO_UINT is supported only with FPCVT"); 8199 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8200 PPCISD::FCTIDUZ, 8201 dl, MVT::f64, Src); 8202 break; 8203 } 8204 8205 // Convert the FP value to an int value through memory. 8206 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8207 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8208 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8209 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8210 MachinePointerInfo MPI = 8211 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8212 8213 // Emit a store to the stack slot. 8214 SDValue Chain; 8215 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8216 if (i32Stack) { 8217 MachineFunction &MF = DAG.getMachineFunction(); 8218 Alignment = Align(4); 8219 MachineMemOperand *MMO = 8220 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8221 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8222 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8223 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8224 } else 8225 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8226 8227 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8228 // add in a bias on big endian. 8229 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8230 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8231 DAG.getConstant(4, dl, FIPtr.getValueType())); 8232 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8233 } 8234 8235 RLI.Chain = Chain; 8236 RLI.Ptr = FIPtr; 8237 RLI.MPI = MPI; 8238 RLI.Alignment = Alignment; 8239 } 8240 8241 /// Custom lowers floating point to integer conversions to use 8242 /// the direct move instructions available in ISA 2.07 to avoid the 8243 /// need for load/store combinations. 8244 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8245 SelectionDAG &DAG, 8246 const SDLoc &dl) const { 8247 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8248 SDValue Src = Op.getOperand(0); 8249 8250 if (Src.getValueType() == MVT::f32) 8251 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8252 8253 SDValue Tmp; 8254 switch (Op.getSimpleValueType().SimpleTy) { 8255 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8256 case MVT::i32: 8257 Tmp = DAG.getNode( 8258 Op.getOpcode() == ISD::FP_TO_SINT 8259 ? PPCISD::FCTIWZ 8260 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8261 dl, MVT::f64, Src); 8262 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8263 break; 8264 case MVT::i64: 8265 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8266 "i64 FP_TO_UINT is supported only with FPCVT"); 8267 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8268 PPCISD::FCTIDUZ, 8269 dl, MVT::f64, Src); 8270 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8271 break; 8272 } 8273 return Tmp; 8274 } 8275 8276 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8277 const SDLoc &dl) const { 8278 8279 // FP to INT conversions are legal for f128. 8280 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8281 return Op; 8282 8283 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8284 // PPC (the libcall is not available). 8285 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8286 if (Op.getValueType() == MVT::i32) { 8287 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8288 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8289 MVT::f64, Op.getOperand(0), 8290 DAG.getIntPtrConstant(0, dl)); 8291 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8292 MVT::f64, Op.getOperand(0), 8293 DAG.getIntPtrConstant(1, dl)); 8294 8295 // Add the two halves of the long double in round-to-zero mode. 8296 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8297 8298 // Now use a smaller FP_TO_SINT. 8299 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8300 } 8301 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8302 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8303 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8304 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8305 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8306 // FIXME: generated code sucks. 8307 // TODO: Are there fast-math-flags to propagate to this FSUB? 8308 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8309 Op.getOperand(0), Tmp); 8310 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8311 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8312 DAG.getConstant(0x80000000, dl, MVT::i32)); 8313 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8314 Op.getOperand(0)); 8315 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8316 ISD::SETGE); 8317 } 8318 } 8319 8320 return SDValue(); 8321 } 8322 8323 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8324 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8325 8326 ReuseLoadInfo RLI; 8327 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8328 8329 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8330 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8331 } 8332 8333 // We're trying to insert a regular store, S, and then a load, L. If the 8334 // incoming value, O, is a load, we might just be able to have our load use the 8335 // address used by O. However, we don't know if anything else will store to 8336 // that address before we can load from it. To prevent this situation, we need 8337 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8338 // the same chain operand as O, we create a token factor from the chain results 8339 // of O and L, and we replace all uses of O's chain result with that token 8340 // factor (see spliceIntoChain below for this last part). 8341 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8342 ReuseLoadInfo &RLI, 8343 SelectionDAG &DAG, 8344 ISD::LoadExtType ET) const { 8345 SDLoc dl(Op); 8346 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8347 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8348 if (ET == ISD::NON_EXTLOAD && 8349 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8350 isOperationLegalOrCustom(Op.getOpcode(), 8351 Op.getOperand(0).getValueType())) { 8352 8353 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8354 return true; 8355 } 8356 8357 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8358 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8359 LD->isNonTemporal()) 8360 return false; 8361 if (LD->getMemoryVT() != MemVT) 8362 return false; 8363 8364 RLI.Ptr = LD->getBasePtr(); 8365 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8366 assert(LD->getAddressingMode() == ISD::PRE_INC && 8367 "Non-pre-inc AM on PPC?"); 8368 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8369 LD->getOffset()); 8370 } 8371 8372 RLI.Chain = LD->getChain(); 8373 RLI.MPI = LD->getPointerInfo(); 8374 RLI.IsDereferenceable = LD->isDereferenceable(); 8375 RLI.IsInvariant = LD->isInvariant(); 8376 RLI.Alignment = LD->getAlign(); 8377 RLI.AAInfo = LD->getAAInfo(); 8378 RLI.Ranges = LD->getRanges(); 8379 8380 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8381 return true; 8382 } 8383 8384 // Given the head of the old chain, ResChain, insert a token factor containing 8385 // it and NewResChain, and make users of ResChain now be users of that token 8386 // factor. 8387 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8388 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8389 SDValue NewResChain, 8390 SelectionDAG &DAG) const { 8391 if (!ResChain) 8392 return; 8393 8394 SDLoc dl(NewResChain); 8395 8396 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8397 NewResChain, DAG.getUNDEF(MVT::Other)); 8398 assert(TF.getNode() != NewResChain.getNode() && 8399 "A new TF really is required here"); 8400 8401 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8402 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8403 } 8404 8405 /// Analyze profitability of direct move 8406 /// prefer float load to int load plus direct move 8407 /// when there is no integer use of int load 8408 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8409 SDNode *Origin = Op.getOperand(0).getNode(); 8410 if (Origin->getOpcode() != ISD::LOAD) 8411 return true; 8412 8413 // If there is no LXSIBZX/LXSIHZX, like Power8, 8414 // prefer direct move if the memory size is 1 or 2 bytes. 8415 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8416 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8417 return true; 8418 8419 for (SDNode::use_iterator UI = Origin->use_begin(), 8420 UE = Origin->use_end(); 8421 UI != UE; ++UI) { 8422 8423 // Only look at the users of the loaded value. 8424 if (UI.getUse().get().getResNo() != 0) 8425 continue; 8426 8427 if (UI->getOpcode() != ISD::SINT_TO_FP && 8428 UI->getOpcode() != ISD::UINT_TO_FP) 8429 return true; 8430 } 8431 8432 return false; 8433 } 8434 8435 /// Custom lowers integer to floating point conversions to use 8436 /// the direct move instructions available in ISA 2.07 to avoid the 8437 /// need for load/store combinations. 8438 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8439 SelectionDAG &DAG, 8440 const SDLoc &dl) const { 8441 assert((Op.getValueType() == MVT::f32 || 8442 Op.getValueType() == MVT::f64) && 8443 "Invalid floating point type as target of conversion"); 8444 assert(Subtarget.hasFPCVT() && 8445 "Int to FP conversions with direct moves require FPCVT"); 8446 SDValue FP; 8447 SDValue Src = Op.getOperand(0); 8448 bool SinglePrec = Op.getValueType() == MVT::f32; 8449 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8450 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8451 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8452 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8453 8454 if (WordInt) { 8455 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8456 dl, MVT::f64, Src); 8457 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8458 } 8459 else { 8460 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8461 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8462 } 8463 8464 return FP; 8465 } 8466 8467 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8468 8469 EVT VecVT = Vec.getValueType(); 8470 assert(VecVT.isVector() && "Expected a vector type."); 8471 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8472 8473 EVT EltVT = VecVT.getVectorElementType(); 8474 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8475 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8476 8477 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8478 SmallVector<SDValue, 16> Ops(NumConcat); 8479 Ops[0] = Vec; 8480 SDValue UndefVec = DAG.getUNDEF(VecVT); 8481 for (unsigned i = 1; i < NumConcat; ++i) 8482 Ops[i] = UndefVec; 8483 8484 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8485 } 8486 8487 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8488 const SDLoc &dl) const { 8489 8490 unsigned Opc = Op.getOpcode(); 8491 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8492 "Unexpected conversion type"); 8493 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8494 "Supports conversions to v2f64/v4f32 only."); 8495 8496 bool SignedConv = Opc == ISD::SINT_TO_FP; 8497 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8498 8499 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8500 EVT WideVT = Wide.getValueType(); 8501 unsigned WideNumElts = WideVT.getVectorNumElements(); 8502 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8503 8504 SmallVector<int, 16> ShuffV; 8505 for (unsigned i = 0; i < WideNumElts; ++i) 8506 ShuffV.push_back(i + WideNumElts); 8507 8508 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8509 int SaveElts = FourEltRes ? 4 : 2; 8510 if (Subtarget.isLittleEndian()) 8511 for (int i = 0; i < SaveElts; i++) 8512 ShuffV[i * Stride] = i; 8513 else 8514 for (int i = 1; i <= SaveElts; i++) 8515 ShuffV[i * Stride - 1] = i - 1; 8516 8517 SDValue ShuffleSrc2 = 8518 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8519 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8520 8521 SDValue Extend; 8522 if (SignedConv) { 8523 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8524 EVT ExtVT = Op.getOperand(0).getValueType(); 8525 if (Subtarget.hasP9Altivec()) 8526 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8527 IntermediateVT.getVectorNumElements()); 8528 8529 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8530 DAG.getValueType(ExtVT)); 8531 } else 8532 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8533 8534 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8535 } 8536 8537 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8538 SelectionDAG &DAG) const { 8539 SDLoc dl(Op); 8540 8541 EVT InVT = Op.getOperand(0).getValueType(); 8542 EVT OutVT = Op.getValueType(); 8543 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8544 isOperationCustom(Op.getOpcode(), InVT)) 8545 return LowerINT_TO_FPVector(Op, DAG, dl); 8546 8547 // Conversions to f128 are legal. 8548 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8549 return Op; 8550 8551 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8552 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8553 return SDValue(); 8554 8555 SDValue Value = Op.getOperand(0); 8556 // The values are now known to be -1 (false) or 1 (true). To convert this 8557 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8558 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8559 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8560 8561 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8562 8563 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8564 8565 if (Op.getValueType() != MVT::v4f64) 8566 Value = DAG.getNode(ISD::FP_ROUND, dl, 8567 Op.getValueType(), Value, 8568 DAG.getIntPtrConstant(1, dl)); 8569 return Value; 8570 } 8571 8572 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8573 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8574 return SDValue(); 8575 8576 if (Op.getOperand(0).getValueType() == MVT::i1) 8577 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8578 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8579 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8580 8581 // If we have direct moves, we can do all the conversion, skip the store/load 8582 // however, without FPCVT we can't do most conversions. 8583 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8584 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8585 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8586 8587 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8588 "UINT_TO_FP is supported only with FPCVT"); 8589 8590 // If we have FCFIDS, then use it when converting to single-precision. 8591 // Otherwise, convert to double-precision and then round. 8592 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8593 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8594 : PPCISD::FCFIDS) 8595 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8596 : PPCISD::FCFID); 8597 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8598 ? MVT::f32 8599 : MVT::f64; 8600 8601 if (Op.getOperand(0).getValueType() == MVT::i64) { 8602 SDValue SINT = Op.getOperand(0); 8603 // When converting to single-precision, we actually need to convert 8604 // to double-precision first and then round to single-precision. 8605 // To avoid double-rounding effects during that operation, we have 8606 // to prepare the input operand. Bits that might be truncated when 8607 // converting to double-precision are replaced by a bit that won't 8608 // be lost at this stage, but is below the single-precision rounding 8609 // position. 8610 // 8611 // However, if -enable-unsafe-fp-math is in effect, accept double 8612 // rounding to avoid the extra overhead. 8613 if (Op.getValueType() == MVT::f32 && 8614 !Subtarget.hasFPCVT() && 8615 !DAG.getTarget().Options.UnsafeFPMath) { 8616 8617 // Twiddle input to make sure the low 11 bits are zero. (If this 8618 // is the case, we are guaranteed the value will fit into the 53 bit 8619 // mantissa of an IEEE double-precision value without rounding.) 8620 // If any of those low 11 bits were not zero originally, make sure 8621 // bit 12 (value 2048) is set instead, so that the final rounding 8622 // to single-precision gets the correct result. 8623 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8624 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8625 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8626 Round, DAG.getConstant(2047, dl, MVT::i64)); 8627 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8628 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8629 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8630 8631 // However, we cannot use that value unconditionally: if the magnitude 8632 // of the input value is small, the bit-twiddling we did above might 8633 // end up visibly changing the output. Fortunately, in that case, we 8634 // don't need to twiddle bits since the original input will convert 8635 // exactly to double-precision floating-point already. Therefore, 8636 // construct a conditional to use the original value if the top 11 8637 // bits are all sign-bit copies, and use the rounded value computed 8638 // above otherwise. 8639 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8640 SINT, DAG.getConstant(53, dl, MVT::i32)); 8641 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8642 Cond, DAG.getConstant(1, dl, MVT::i64)); 8643 Cond = DAG.getSetCC( 8644 dl, 8645 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8646 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8647 8648 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8649 } 8650 8651 ReuseLoadInfo RLI; 8652 SDValue Bits; 8653 8654 MachineFunction &MF = DAG.getMachineFunction(); 8655 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8656 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8657 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8658 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8659 } else if (Subtarget.hasLFIWAX() && 8660 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8661 MachineMemOperand *MMO = 8662 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8663 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8664 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8665 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8666 DAG.getVTList(MVT::f64, MVT::Other), 8667 Ops, MVT::i32, MMO); 8668 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8669 } else if (Subtarget.hasFPCVT() && 8670 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8671 MachineMemOperand *MMO = 8672 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8673 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8674 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8675 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8676 DAG.getVTList(MVT::f64, MVT::Other), 8677 Ops, MVT::i32, MMO); 8678 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8679 } else if (((Subtarget.hasLFIWAX() && 8680 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8681 (Subtarget.hasFPCVT() && 8682 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8683 SINT.getOperand(0).getValueType() == MVT::i32) { 8684 MachineFrameInfo &MFI = MF.getFrameInfo(); 8685 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8686 8687 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8688 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8689 8690 SDValue Store = 8691 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8692 MachinePointerInfo::getFixedStack( 8693 DAG.getMachineFunction(), FrameIdx)); 8694 8695 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8696 "Expected an i32 store"); 8697 8698 RLI.Ptr = FIdx; 8699 RLI.Chain = Store; 8700 RLI.MPI = 8701 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8702 RLI.Alignment = Align(4); 8703 8704 MachineMemOperand *MMO = 8705 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8706 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8707 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8708 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8709 PPCISD::LFIWZX : PPCISD::LFIWAX, 8710 dl, DAG.getVTList(MVT::f64, MVT::Other), 8711 Ops, MVT::i32, MMO); 8712 } else 8713 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8714 8715 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8716 8717 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8718 FP = DAG.getNode(ISD::FP_ROUND, dl, 8719 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8720 return FP; 8721 } 8722 8723 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8724 "Unhandled INT_TO_FP type in custom expander!"); 8725 // Since we only generate this in 64-bit mode, we can take advantage of 8726 // 64-bit registers. In particular, sign extend the input value into the 8727 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8728 // then lfd it and fcfid it. 8729 MachineFunction &MF = DAG.getMachineFunction(); 8730 MachineFrameInfo &MFI = MF.getFrameInfo(); 8731 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8732 8733 SDValue Ld; 8734 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8735 ReuseLoadInfo RLI; 8736 bool ReusingLoad; 8737 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8738 DAG))) { 8739 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8740 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8741 8742 SDValue Store = 8743 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8744 MachinePointerInfo::getFixedStack( 8745 DAG.getMachineFunction(), FrameIdx)); 8746 8747 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8748 "Expected an i32 store"); 8749 8750 RLI.Ptr = FIdx; 8751 RLI.Chain = Store; 8752 RLI.MPI = 8753 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8754 RLI.Alignment = Align(4); 8755 } 8756 8757 MachineMemOperand *MMO = 8758 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8759 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8760 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8761 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8762 PPCISD::LFIWZX : PPCISD::LFIWAX, 8763 dl, DAG.getVTList(MVT::f64, MVT::Other), 8764 Ops, MVT::i32, MMO); 8765 if (ReusingLoad) 8766 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8767 } else { 8768 assert(Subtarget.isPPC64() && 8769 "i32->FP without LFIWAX supported only on PPC64"); 8770 8771 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8772 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8773 8774 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8775 Op.getOperand(0)); 8776 8777 // STD the extended value into the stack slot. 8778 SDValue Store = DAG.getStore( 8779 DAG.getEntryNode(), dl, Ext64, FIdx, 8780 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8781 8782 // Load the value as a double. 8783 Ld = DAG.getLoad( 8784 MVT::f64, dl, Store, FIdx, 8785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8786 } 8787 8788 // FCFID it and return it. 8789 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8790 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8791 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8792 DAG.getIntPtrConstant(0, dl)); 8793 return FP; 8794 } 8795 8796 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8797 SelectionDAG &DAG) const { 8798 SDLoc dl(Op); 8799 /* 8800 The rounding mode is in bits 30:31 of FPSR, and has the following 8801 settings: 8802 00 Round to nearest 8803 01 Round to 0 8804 10 Round to +inf 8805 11 Round to -inf 8806 8807 FLT_ROUNDS, on the other hand, expects the following: 8808 -1 Undefined 8809 0 Round to 0 8810 1 Round to nearest 8811 2 Round to +inf 8812 3 Round to -inf 8813 8814 To perform the conversion, we do: 8815 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8816 */ 8817 8818 MachineFunction &MF = DAG.getMachineFunction(); 8819 EVT VT = Op.getValueType(); 8820 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8821 8822 // Save FP Control Word to register 8823 SDValue Chain = Op.getOperand(0); 8824 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8825 Chain = MFFS.getValue(1); 8826 8827 // Save FP register to stack slot 8828 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8829 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8830 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8831 8832 // Load FP Control Word from low 32 bits of stack slot. 8833 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8834 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8835 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8836 Chain = CWD.getValue(1); 8837 8838 // Transform as necessary 8839 SDValue CWD1 = 8840 DAG.getNode(ISD::AND, dl, MVT::i32, 8841 CWD, DAG.getConstant(3, dl, MVT::i32)); 8842 SDValue CWD2 = 8843 DAG.getNode(ISD::SRL, dl, MVT::i32, 8844 DAG.getNode(ISD::AND, dl, MVT::i32, 8845 DAG.getNode(ISD::XOR, dl, MVT::i32, 8846 CWD, DAG.getConstant(3, dl, MVT::i32)), 8847 DAG.getConstant(3, dl, MVT::i32)), 8848 DAG.getConstant(1, dl, MVT::i32)); 8849 8850 SDValue RetVal = 8851 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8852 8853 RetVal = 8854 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8855 dl, VT, RetVal); 8856 8857 return DAG.getMergeValues({RetVal, Chain}, dl); 8858 } 8859 8860 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8861 EVT VT = Op.getValueType(); 8862 unsigned BitWidth = VT.getSizeInBits(); 8863 SDLoc dl(Op); 8864 assert(Op.getNumOperands() == 3 && 8865 VT == Op.getOperand(1).getValueType() && 8866 "Unexpected SHL!"); 8867 8868 // Expand into a bunch of logical ops. Note that these ops 8869 // depend on the PPC behavior for oversized shift amounts. 8870 SDValue Lo = Op.getOperand(0); 8871 SDValue Hi = Op.getOperand(1); 8872 SDValue Amt = Op.getOperand(2); 8873 EVT AmtVT = Amt.getValueType(); 8874 8875 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8876 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8877 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8878 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8879 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8880 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8881 DAG.getConstant(-BitWidth, dl, AmtVT)); 8882 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8883 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8884 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8885 SDValue OutOps[] = { OutLo, OutHi }; 8886 return DAG.getMergeValues(OutOps, dl); 8887 } 8888 8889 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8890 EVT VT = Op.getValueType(); 8891 SDLoc dl(Op); 8892 unsigned BitWidth = VT.getSizeInBits(); 8893 assert(Op.getNumOperands() == 3 && 8894 VT == Op.getOperand(1).getValueType() && 8895 "Unexpected SRL!"); 8896 8897 // Expand into a bunch of logical ops. Note that these ops 8898 // depend on the PPC behavior for oversized shift amounts. 8899 SDValue Lo = Op.getOperand(0); 8900 SDValue Hi = Op.getOperand(1); 8901 SDValue Amt = Op.getOperand(2); 8902 EVT AmtVT = Amt.getValueType(); 8903 8904 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8905 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8906 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8907 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8908 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8909 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8910 DAG.getConstant(-BitWidth, dl, AmtVT)); 8911 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8912 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8913 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8914 SDValue OutOps[] = { OutLo, OutHi }; 8915 return DAG.getMergeValues(OutOps, dl); 8916 } 8917 8918 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8919 SDLoc dl(Op); 8920 EVT VT = Op.getValueType(); 8921 unsigned BitWidth = VT.getSizeInBits(); 8922 assert(Op.getNumOperands() == 3 && 8923 VT == Op.getOperand(1).getValueType() && 8924 "Unexpected SRA!"); 8925 8926 // Expand into a bunch of logical ops, followed by a select_cc. 8927 SDValue Lo = Op.getOperand(0); 8928 SDValue Hi = Op.getOperand(1); 8929 SDValue Amt = Op.getOperand(2); 8930 EVT AmtVT = Amt.getValueType(); 8931 8932 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8933 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8934 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8935 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8936 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8937 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8938 DAG.getConstant(-BitWidth, dl, AmtVT)); 8939 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8940 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8941 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8942 Tmp4, Tmp6, ISD::SETLE); 8943 SDValue OutOps[] = { OutLo, OutHi }; 8944 return DAG.getMergeValues(OutOps, dl); 8945 } 8946 8947 //===----------------------------------------------------------------------===// 8948 // Vector related lowering. 8949 // 8950 8951 /// BuildSplatI - Build a canonical splati of Val with an element size of 8952 /// SplatSize. Cast the result to VT. 8953 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8954 SelectionDAG &DAG, const SDLoc &dl) { 8955 static const MVT VTys[] = { // canonical VT to use for each size. 8956 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8957 }; 8958 8959 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8960 8961 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8962 if (Val == -1) 8963 SplatSize = 1; 8964 8965 EVT CanonicalVT = VTys[SplatSize-1]; 8966 8967 // Build a canonical splat for this value. 8968 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8969 } 8970 8971 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8972 /// specified intrinsic ID. 8973 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8974 const SDLoc &dl, EVT DestVT = MVT::Other) { 8975 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8976 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8977 DAG.getConstant(IID, dl, MVT::i32), Op); 8978 } 8979 8980 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8981 /// specified intrinsic ID. 8982 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8983 SelectionDAG &DAG, const SDLoc &dl, 8984 EVT DestVT = MVT::Other) { 8985 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8986 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8987 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8988 } 8989 8990 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8991 /// specified intrinsic ID. 8992 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8993 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8994 EVT DestVT = MVT::Other) { 8995 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8996 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8997 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8998 } 8999 9000 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9001 /// amount. The result has the specified value type. 9002 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9003 SelectionDAG &DAG, const SDLoc &dl) { 9004 // Force LHS/RHS to be the right type. 9005 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9006 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9007 9008 int Ops[16]; 9009 for (unsigned i = 0; i != 16; ++i) 9010 Ops[i] = i + Amt; 9011 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9012 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9013 } 9014 9015 /// Do we have an efficient pattern in a .td file for this node? 9016 /// 9017 /// \param V - pointer to the BuildVectorSDNode being matched 9018 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9019 /// 9020 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9021 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9022 /// the opposite is true (expansion is beneficial) are: 9023 /// - The node builds a vector out of integers that are not 32 or 64-bits 9024 /// - The node builds a vector out of constants 9025 /// - The node is a "load-and-splat" 9026 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9027 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9028 bool HasDirectMove, 9029 bool HasP8Vector) { 9030 EVT VecVT = V->getValueType(0); 9031 bool RightType = VecVT == MVT::v2f64 || 9032 (HasP8Vector && VecVT == MVT::v4f32) || 9033 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9034 if (!RightType) 9035 return false; 9036 9037 bool IsSplat = true; 9038 bool IsLoad = false; 9039 SDValue Op0 = V->getOperand(0); 9040 9041 // This function is called in a block that confirms the node is not a constant 9042 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9043 // different constants. 9044 if (V->isConstant()) 9045 return false; 9046 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9047 if (V->getOperand(i).isUndef()) 9048 return false; 9049 // We want to expand nodes that represent load-and-splat even if the 9050 // loaded value is a floating point truncation or conversion to int. 9051 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9052 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9053 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9054 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9055 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9056 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9057 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9058 IsLoad = true; 9059 // If the operands are different or the input is not a load and has more 9060 // uses than just this BV node, then it isn't a splat. 9061 if (V->getOperand(i) != Op0 || 9062 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9063 IsSplat = false; 9064 } 9065 return !(IsSplat && IsLoad); 9066 } 9067 9068 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9069 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9070 9071 SDLoc dl(Op); 9072 SDValue Op0 = Op->getOperand(0); 9073 9074 if (!EnableQuadPrecision || 9075 (Op.getValueType() != MVT::f128 ) || 9076 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9077 (Op0.getOperand(0).getValueType() != MVT::i64) || 9078 (Op0.getOperand(1).getValueType() != MVT::i64)) 9079 return SDValue(); 9080 9081 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9082 Op0.getOperand(1)); 9083 } 9084 9085 static const SDValue *getNormalLoadInput(const SDValue &Op) { 9086 const SDValue *InputLoad = &Op; 9087 if (InputLoad->getOpcode() == ISD::BITCAST) 9088 InputLoad = &InputLoad->getOperand(0); 9089 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9090 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) 9091 InputLoad = &InputLoad->getOperand(0); 9092 if (InputLoad->getOpcode() != ISD::LOAD) 9093 return nullptr; 9094 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9095 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9096 } 9097 9098 // If this is a case we can't handle, return null and let the default 9099 // expansion code take care of it. If we CAN select this case, and if it 9100 // selects to a single instruction, return Op. Otherwise, if we can codegen 9101 // this case more efficiently than a constant pool load, lower it to the 9102 // sequence of ops that should be used. 9103 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9104 SelectionDAG &DAG) const { 9105 SDLoc dl(Op); 9106 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9107 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9108 9109 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9110 // We first build an i32 vector, load it into a QPX register, 9111 // then convert it to a floating-point vector and compare it 9112 // to a zero vector to get the boolean result. 9113 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9114 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9115 MachinePointerInfo PtrInfo = 9116 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9117 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9118 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9119 9120 assert(BVN->getNumOperands() == 4 && 9121 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9122 9123 bool IsConst = true; 9124 for (unsigned i = 0; i < 4; ++i) { 9125 if (BVN->getOperand(i).isUndef()) continue; 9126 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9127 IsConst = false; 9128 break; 9129 } 9130 } 9131 9132 if (IsConst) { 9133 Constant *One = 9134 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9135 Constant *NegOne = 9136 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9137 9138 Constant *CV[4]; 9139 for (unsigned i = 0; i < 4; ++i) { 9140 if (BVN->getOperand(i).isUndef()) 9141 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9142 else if (isNullConstant(BVN->getOperand(i))) 9143 CV[i] = NegOne; 9144 else 9145 CV[i] = One; 9146 } 9147 9148 Constant *CP = ConstantVector::get(CV); 9149 SDValue CPIdx = 9150 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9151 9152 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9153 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9154 return DAG.getMemIntrinsicNode( 9155 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9156 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9157 } 9158 9159 SmallVector<SDValue, 4> Stores; 9160 for (unsigned i = 0; i < 4; ++i) { 9161 if (BVN->getOperand(i).isUndef()) continue; 9162 9163 unsigned Offset = 4*i; 9164 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9165 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9166 9167 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9168 if (StoreSize > 4) { 9169 Stores.push_back( 9170 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9171 PtrInfo.getWithOffset(Offset), MVT::i32)); 9172 } else { 9173 SDValue StoreValue = BVN->getOperand(i); 9174 if (StoreSize < 4) 9175 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9176 9177 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9178 PtrInfo.getWithOffset(Offset))); 9179 } 9180 } 9181 9182 SDValue StoreChain; 9183 if (!Stores.empty()) 9184 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9185 else 9186 StoreChain = DAG.getEntryNode(); 9187 9188 // Now load from v4i32 into the QPX register; this will extend it to 9189 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9190 // is typed as v4f64 because the QPX register integer states are not 9191 // explicitly represented. 9192 9193 SDValue Ops[] = {StoreChain, 9194 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9195 FIdx}; 9196 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9197 9198 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9199 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9200 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9201 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9202 LoadedVect); 9203 9204 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9205 9206 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9207 } 9208 9209 // All other QPX vectors are handled by generic code. 9210 if (Subtarget.hasQPX()) 9211 return SDValue(); 9212 9213 // Check if this is a splat of a constant value. 9214 APInt APSplatBits, APSplatUndef; 9215 unsigned SplatBitSize; 9216 bool HasAnyUndefs; 9217 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9218 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9219 SplatBitSize > 32) { 9220 9221 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9222 // Handle load-and-splat patterns as we have instructions that will do this 9223 // in one go. 9224 if (InputLoad && DAG.isSplatValue(Op, true)) { 9225 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9226 9227 // We have handling for 4 and 8 byte elements. 9228 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9229 9230 // Checking for a single use of this load, we have to check for vector 9231 // width (128 bits) / ElementSize uses (since each operand of the 9232 // BUILD_VECTOR is a separate use of the value. 9233 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9234 ((Subtarget.hasVSX() && ElementSize == 64) || 9235 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9236 SDValue Ops[] = { 9237 LD->getChain(), // Chain 9238 LD->getBasePtr(), // Ptr 9239 DAG.getValueType(Op.getValueType()) // VT 9240 }; 9241 return 9242 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9243 DAG.getVTList(Op.getValueType(), MVT::Other), 9244 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9245 } 9246 } 9247 9248 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9249 // lowered to VSX instructions under certain conditions. 9250 // Without VSX, there is no pattern more efficient than expanding the node. 9251 if (Subtarget.hasVSX() && 9252 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9253 Subtarget.hasP8Vector())) 9254 return Op; 9255 return SDValue(); 9256 } 9257 9258 unsigned SplatBits = APSplatBits.getZExtValue(); 9259 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9260 unsigned SplatSize = SplatBitSize / 8; 9261 9262 // First, handle single instruction cases. 9263 9264 // All zeros? 9265 if (SplatBits == 0) { 9266 // Canonicalize all zero vectors to be v4i32. 9267 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9268 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9269 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9270 } 9271 return Op; 9272 } 9273 9274 // We have XXSPLTIB for constant splats one byte wide 9275 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9276 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9277 if (Subtarget.hasP9Vector() && SplatSize == 1) 9278 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9279 9280 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9281 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9282 (32-SplatBitSize)); 9283 if (SextVal >= -16 && SextVal <= 15) 9284 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9285 9286 // Two instruction sequences. 9287 9288 // If this value is in the range [-32,30] and is even, use: 9289 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9290 // If this value is in the range [17,31] and is odd, use: 9291 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9292 // If this value is in the range [-31,-17] and is odd, use: 9293 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9294 // Note the last two are three-instruction sequences. 9295 if (SextVal >= -32 && SextVal <= 31) { 9296 // To avoid having these optimizations undone by constant folding, 9297 // we convert to a pseudo that will be expanded later into one of 9298 // the above forms. 9299 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9300 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9301 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9302 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9303 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9304 if (VT == Op.getValueType()) 9305 return RetVal; 9306 else 9307 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9308 } 9309 9310 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9311 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9312 // for fneg/fabs. 9313 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9314 // Make -1 and vspltisw -1: 9315 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9316 9317 // Make the VSLW intrinsic, computing 0x8000_0000. 9318 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9319 OnesV, DAG, dl); 9320 9321 // xor by OnesV to invert it. 9322 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9323 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9324 } 9325 9326 // Check to see if this is a wide variety of vsplti*, binop self cases. 9327 static const signed char SplatCsts[] = { 9328 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9329 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9330 }; 9331 9332 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9333 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9334 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9335 int i = SplatCsts[idx]; 9336 9337 // Figure out what shift amount will be used by altivec if shifted by i in 9338 // this splat size. 9339 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9340 9341 // vsplti + shl self. 9342 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9343 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9344 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9345 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9346 Intrinsic::ppc_altivec_vslw 9347 }; 9348 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9349 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9350 } 9351 9352 // vsplti + srl self. 9353 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9354 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9355 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9356 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9357 Intrinsic::ppc_altivec_vsrw 9358 }; 9359 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9360 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9361 } 9362 9363 // vsplti + sra self. 9364 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9365 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9366 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9367 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9368 Intrinsic::ppc_altivec_vsraw 9369 }; 9370 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9371 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9372 } 9373 9374 // vsplti + rol self. 9375 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9376 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9377 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9378 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9379 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9380 Intrinsic::ppc_altivec_vrlw 9381 }; 9382 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9383 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9384 } 9385 9386 // t = vsplti c, result = vsldoi t, t, 1 9387 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9388 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9389 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9390 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9391 } 9392 // t = vsplti c, result = vsldoi t, t, 2 9393 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9394 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9395 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9396 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9397 } 9398 // t = vsplti c, result = vsldoi t, t, 3 9399 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9400 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9401 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9402 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9403 } 9404 } 9405 9406 return SDValue(); 9407 } 9408 9409 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9410 /// the specified operations to build the shuffle. 9411 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9412 SDValue RHS, SelectionDAG &DAG, 9413 const SDLoc &dl) { 9414 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9415 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9416 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9417 9418 enum { 9419 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9420 OP_VMRGHW, 9421 OP_VMRGLW, 9422 OP_VSPLTISW0, 9423 OP_VSPLTISW1, 9424 OP_VSPLTISW2, 9425 OP_VSPLTISW3, 9426 OP_VSLDOI4, 9427 OP_VSLDOI8, 9428 OP_VSLDOI12 9429 }; 9430 9431 if (OpNum == OP_COPY) { 9432 if (LHSID == (1*9+2)*9+3) return LHS; 9433 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9434 return RHS; 9435 } 9436 9437 SDValue OpLHS, OpRHS; 9438 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9439 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9440 9441 int ShufIdxs[16]; 9442 switch (OpNum) { 9443 default: llvm_unreachable("Unknown i32 permute!"); 9444 case OP_VMRGHW: 9445 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9446 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9447 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9448 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9449 break; 9450 case OP_VMRGLW: 9451 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9452 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9453 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9454 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9455 break; 9456 case OP_VSPLTISW0: 9457 for (unsigned i = 0; i != 16; ++i) 9458 ShufIdxs[i] = (i&3)+0; 9459 break; 9460 case OP_VSPLTISW1: 9461 for (unsigned i = 0; i != 16; ++i) 9462 ShufIdxs[i] = (i&3)+4; 9463 break; 9464 case OP_VSPLTISW2: 9465 for (unsigned i = 0; i != 16; ++i) 9466 ShufIdxs[i] = (i&3)+8; 9467 break; 9468 case OP_VSPLTISW3: 9469 for (unsigned i = 0; i != 16; ++i) 9470 ShufIdxs[i] = (i&3)+12; 9471 break; 9472 case OP_VSLDOI4: 9473 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9474 case OP_VSLDOI8: 9475 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9476 case OP_VSLDOI12: 9477 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9478 } 9479 EVT VT = OpLHS.getValueType(); 9480 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9481 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9482 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9483 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9484 } 9485 9486 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9487 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9488 /// SDValue. 9489 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9490 SelectionDAG &DAG) const { 9491 const unsigned BytesInVector = 16; 9492 bool IsLE = Subtarget.isLittleEndian(); 9493 SDLoc dl(N); 9494 SDValue V1 = N->getOperand(0); 9495 SDValue V2 = N->getOperand(1); 9496 unsigned ShiftElts = 0, InsertAtByte = 0; 9497 bool Swap = false; 9498 9499 // Shifts required to get the byte we want at element 7. 9500 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9501 0, 15, 14, 13, 12, 11, 10, 9}; 9502 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9503 1, 2, 3, 4, 5, 6, 7, 8}; 9504 9505 ArrayRef<int> Mask = N->getMask(); 9506 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9507 9508 // For each mask element, find out if we're just inserting something 9509 // from V2 into V1 or vice versa. 9510 // Possible permutations inserting an element from V2 into V1: 9511 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9512 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9513 // ... 9514 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9515 // Inserting from V1 into V2 will be similar, except mask range will be 9516 // [16,31]. 9517 9518 bool FoundCandidate = false; 9519 // If both vector operands for the shuffle are the same vector, the mask 9520 // will contain only elements from the first one and the second one will be 9521 // undef. 9522 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9523 // Go through the mask of half-words to find an element that's being moved 9524 // from one vector to the other. 9525 for (unsigned i = 0; i < BytesInVector; ++i) { 9526 unsigned CurrentElement = Mask[i]; 9527 // If 2nd operand is undefined, we should only look for element 7 in the 9528 // Mask. 9529 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9530 continue; 9531 9532 bool OtherElementsInOrder = true; 9533 // Examine the other elements in the Mask to see if they're in original 9534 // order. 9535 for (unsigned j = 0; j < BytesInVector; ++j) { 9536 if (j == i) 9537 continue; 9538 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9539 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9540 // in which we always assume we're always picking from the 1st operand. 9541 int MaskOffset = 9542 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9543 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9544 OtherElementsInOrder = false; 9545 break; 9546 } 9547 } 9548 // If other elements are in original order, we record the number of shifts 9549 // we need to get the element we want into element 7. Also record which byte 9550 // in the vector we should insert into. 9551 if (OtherElementsInOrder) { 9552 // If 2nd operand is undefined, we assume no shifts and no swapping. 9553 if (V2.isUndef()) { 9554 ShiftElts = 0; 9555 Swap = false; 9556 } else { 9557 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9558 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9559 : BigEndianShifts[CurrentElement & 0xF]; 9560 Swap = CurrentElement < BytesInVector; 9561 } 9562 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9563 FoundCandidate = true; 9564 break; 9565 } 9566 } 9567 9568 if (!FoundCandidate) 9569 return SDValue(); 9570 9571 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9572 // optionally with VECSHL if shift is required. 9573 if (Swap) 9574 std::swap(V1, V2); 9575 if (V2.isUndef()) 9576 V2 = V1; 9577 if (ShiftElts) { 9578 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9579 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9580 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9581 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9582 } 9583 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9584 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9585 } 9586 9587 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9588 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9589 /// SDValue. 9590 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9591 SelectionDAG &DAG) const { 9592 const unsigned NumHalfWords = 8; 9593 const unsigned BytesInVector = NumHalfWords * 2; 9594 // Check that the shuffle is on half-words. 9595 if (!isNByteElemShuffleMask(N, 2, 1)) 9596 return SDValue(); 9597 9598 bool IsLE = Subtarget.isLittleEndian(); 9599 SDLoc dl(N); 9600 SDValue V1 = N->getOperand(0); 9601 SDValue V2 = N->getOperand(1); 9602 unsigned ShiftElts = 0, InsertAtByte = 0; 9603 bool Swap = false; 9604 9605 // Shifts required to get the half-word we want at element 3. 9606 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9607 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9608 9609 uint32_t Mask = 0; 9610 uint32_t OriginalOrderLow = 0x1234567; 9611 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9612 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9613 // 32-bit space, only need 4-bit nibbles per element. 9614 for (unsigned i = 0; i < NumHalfWords; ++i) { 9615 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9616 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9617 } 9618 9619 // For each mask element, find out if we're just inserting something 9620 // from V2 into V1 or vice versa. Possible permutations inserting an element 9621 // from V2 into V1: 9622 // X, 1, 2, 3, 4, 5, 6, 7 9623 // 0, X, 2, 3, 4, 5, 6, 7 9624 // 0, 1, X, 3, 4, 5, 6, 7 9625 // 0, 1, 2, X, 4, 5, 6, 7 9626 // 0, 1, 2, 3, X, 5, 6, 7 9627 // 0, 1, 2, 3, 4, X, 6, 7 9628 // 0, 1, 2, 3, 4, 5, X, 7 9629 // 0, 1, 2, 3, 4, 5, 6, X 9630 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9631 9632 bool FoundCandidate = false; 9633 // Go through the mask of half-words to find an element that's being moved 9634 // from one vector to the other. 9635 for (unsigned i = 0; i < NumHalfWords; ++i) { 9636 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9637 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9638 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9639 uint32_t TargetOrder = 0x0; 9640 9641 // If both vector operands for the shuffle are the same vector, the mask 9642 // will contain only elements from the first one and the second one will be 9643 // undef. 9644 if (V2.isUndef()) { 9645 ShiftElts = 0; 9646 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9647 TargetOrder = OriginalOrderLow; 9648 Swap = false; 9649 // Skip if not the correct element or mask of other elements don't equal 9650 // to our expected order. 9651 if (MaskOneElt == VINSERTHSrcElem && 9652 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9653 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9654 FoundCandidate = true; 9655 break; 9656 } 9657 } else { // If both operands are defined. 9658 // Target order is [8,15] if the current mask is between [0,7]. 9659 TargetOrder = 9660 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9661 // Skip if mask of other elements don't equal our expected order. 9662 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9663 // We only need the last 3 bits for the number of shifts. 9664 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9665 : BigEndianShifts[MaskOneElt & 0x7]; 9666 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9667 Swap = MaskOneElt < NumHalfWords; 9668 FoundCandidate = true; 9669 break; 9670 } 9671 } 9672 } 9673 9674 if (!FoundCandidate) 9675 return SDValue(); 9676 9677 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9678 // optionally with VECSHL if shift is required. 9679 if (Swap) 9680 std::swap(V1, V2); 9681 if (V2.isUndef()) 9682 V2 = V1; 9683 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9684 if (ShiftElts) { 9685 // Double ShiftElts because we're left shifting on v16i8 type. 9686 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9687 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9688 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9689 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9690 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9691 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9692 } 9693 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9694 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9695 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9696 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9697 } 9698 9699 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9700 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9701 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9702 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9703 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9704 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9705 assert(Op.getValueType() == MVT::v1i128 && 9706 "Only set v1i128 as custom, other type shouldn't reach here!"); 9707 SDLoc dl(Op); 9708 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9709 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9710 unsigned SHLAmt = N1.getConstantOperandVal(0); 9711 if (SHLAmt % 8 == 0) { 9712 SmallVector<int, 16> Mask(16, 0); 9713 std::iota(Mask.begin(), Mask.end(), 0); 9714 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9715 if (SDValue Shuffle = 9716 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9717 DAG.getUNDEF(MVT::v16i8), Mask)) 9718 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9719 } 9720 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9721 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9722 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9723 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9724 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9725 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9726 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9727 } 9728 9729 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9730 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9731 /// return the code it can be lowered into. Worst case, it can always be 9732 /// lowered into a vperm. 9733 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9734 SelectionDAG &DAG) const { 9735 SDLoc dl(Op); 9736 SDValue V1 = Op.getOperand(0); 9737 SDValue V2 = Op.getOperand(1); 9738 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9739 9740 // Any nodes that were combined in the target-independent combiner prior 9741 // to vector legalization will not be sent to the target combine. Try to 9742 // combine it here. 9743 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9744 DAG.ReplaceAllUsesOfValueWith(Op, NewShuffle); 9745 Op = NewShuffle; 9746 SVOp = cast<ShuffleVectorSDNode>(Op); 9747 } 9748 EVT VT = Op.getValueType(); 9749 bool isLittleEndian = Subtarget.isLittleEndian(); 9750 9751 unsigned ShiftElts, InsertAtByte; 9752 bool Swap = false; 9753 9754 // If this is a load-and-splat, we can do that with a single instruction 9755 // in some cases. However if the load has multiple uses, we don't want to 9756 // combine it because that will just produce multiple loads. 9757 const SDValue *InputLoad = getNormalLoadInput(V1); 9758 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9759 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9760 InputLoad->hasOneUse()) { 9761 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9762 int SplatIdx = 9763 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9764 9765 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9766 // For 4-byte load-and-splat, we need Power9. 9767 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9768 uint64_t Offset = 0; 9769 if (IsFourByte) 9770 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9771 else 9772 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9773 9774 // If we are loading a partial vector, it does not make sense to adjust 9775 // the base pointer. This happens with (splat (s_to_v_permuted (ld))). 9776 if (LD->getMemoryVT().getSizeInBits() == (IsFourByte ? 32 : 64)) 9777 Offset = 0; 9778 SDValue BasePtr = LD->getBasePtr(); 9779 if (Offset != 0) 9780 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9781 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9782 SDValue Ops[] = { 9783 LD->getChain(), // Chain 9784 BasePtr, // BasePtr 9785 DAG.getValueType(Op.getValueType()) // VT 9786 }; 9787 SDVTList VTL = 9788 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9789 SDValue LdSplt = 9790 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9791 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9792 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9793 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9794 return LdSplt; 9795 } 9796 } 9797 if (Subtarget.hasP9Vector() && 9798 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9799 isLittleEndian)) { 9800 if (Swap) 9801 std::swap(V1, V2); 9802 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9803 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9804 if (ShiftElts) { 9805 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9806 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9807 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9808 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9809 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9810 } 9811 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9812 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9813 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9814 } 9815 9816 if (Subtarget.hasP9Altivec()) { 9817 SDValue NewISDNode; 9818 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9819 return NewISDNode; 9820 9821 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9822 return NewISDNode; 9823 } 9824 9825 if (Subtarget.hasVSX() && 9826 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9827 if (Swap) 9828 std::swap(V1, V2); 9829 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9830 SDValue Conv2 = 9831 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9832 9833 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9834 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9835 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9836 } 9837 9838 if (Subtarget.hasVSX() && 9839 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9840 if (Swap) 9841 std::swap(V1, V2); 9842 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9843 SDValue Conv2 = 9844 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9845 9846 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9847 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9848 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9849 } 9850 9851 if (Subtarget.hasP9Vector()) { 9852 if (PPC::isXXBRHShuffleMask(SVOp)) { 9853 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9854 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9855 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9856 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9857 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9858 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9859 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9860 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9861 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9862 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9863 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9864 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9865 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9866 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9867 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9868 } 9869 } 9870 9871 if (Subtarget.hasVSX()) { 9872 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9873 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9874 9875 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9876 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9877 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9878 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9879 } 9880 9881 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9882 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9883 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9884 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9885 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9886 } 9887 } 9888 9889 if (Subtarget.hasQPX()) { 9890 if (VT.getVectorNumElements() != 4) 9891 return SDValue(); 9892 9893 if (V2.isUndef()) V2 = V1; 9894 9895 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9896 if (AlignIdx != -1) { 9897 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9898 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9899 } else if (SVOp->isSplat()) { 9900 int SplatIdx = SVOp->getSplatIndex(); 9901 if (SplatIdx >= 4) { 9902 std::swap(V1, V2); 9903 SplatIdx -= 4; 9904 } 9905 9906 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9907 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9908 } 9909 9910 // Lower this into a qvgpci/qvfperm pair. 9911 9912 // Compute the qvgpci literal 9913 unsigned idx = 0; 9914 for (unsigned i = 0; i < 4; ++i) { 9915 int m = SVOp->getMaskElt(i); 9916 unsigned mm = m >= 0 ? (unsigned) m : i; 9917 idx |= mm << (3-i)*3; 9918 } 9919 9920 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9921 DAG.getConstant(idx, dl, MVT::i32)); 9922 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9923 } 9924 9925 // Cases that are handled by instructions that take permute immediates 9926 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9927 // selected by the instruction selector. 9928 if (V2.isUndef()) { 9929 if (PPC::isSplatShuffleMask(SVOp, 1) || 9930 PPC::isSplatShuffleMask(SVOp, 2) || 9931 PPC::isSplatShuffleMask(SVOp, 4) || 9932 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9933 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9934 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9935 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9936 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9937 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9938 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9939 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9940 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9941 (Subtarget.hasP8Altivec() && ( 9942 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9943 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9944 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9945 return Op; 9946 } 9947 } 9948 9949 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9950 // and produce a fixed permutation. If any of these match, do not lower to 9951 // VPERM. 9952 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9953 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9954 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9955 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9956 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9957 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9958 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9959 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9960 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9961 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9962 (Subtarget.hasP8Altivec() && ( 9963 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9964 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9965 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9966 return Op; 9967 9968 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9969 // perfect shuffle table to emit an optimal matching sequence. 9970 ArrayRef<int> PermMask = SVOp->getMask(); 9971 9972 unsigned PFIndexes[4]; 9973 bool isFourElementShuffle = true; 9974 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9975 unsigned EltNo = 8; // Start out undef. 9976 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9977 if (PermMask[i*4+j] < 0) 9978 continue; // Undef, ignore it. 9979 9980 unsigned ByteSource = PermMask[i*4+j]; 9981 if ((ByteSource & 3) != j) { 9982 isFourElementShuffle = false; 9983 break; 9984 } 9985 9986 if (EltNo == 8) { 9987 EltNo = ByteSource/4; 9988 } else if (EltNo != ByteSource/4) { 9989 isFourElementShuffle = false; 9990 break; 9991 } 9992 } 9993 PFIndexes[i] = EltNo; 9994 } 9995 9996 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9997 // perfect shuffle vector to determine if it is cost effective to do this as 9998 // discrete instructions, or whether we should use a vperm. 9999 // For now, we skip this for little endian until such time as we have a 10000 // little-endian perfect shuffle table. 10001 if (isFourElementShuffle && !isLittleEndian) { 10002 // Compute the index in the perfect shuffle table. 10003 unsigned PFTableIndex = 10004 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10005 10006 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10007 unsigned Cost = (PFEntry >> 30); 10008 10009 // Determining when to avoid vperm is tricky. Many things affect the cost 10010 // of vperm, particularly how many times the perm mask needs to be computed. 10011 // For example, if the perm mask can be hoisted out of a loop or is already 10012 // used (perhaps because there are multiple permutes with the same shuffle 10013 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10014 // the loop requires an extra register. 10015 // 10016 // As a compromise, we only emit discrete instructions if the shuffle can be 10017 // generated in 3 or fewer operations. When we have loop information 10018 // available, if this block is within a loop, we should avoid using vperm 10019 // for 3-operation perms and use a constant pool load instead. 10020 if (Cost < 3) 10021 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10022 } 10023 10024 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10025 // vector that will get spilled to the constant pool. 10026 if (V2.isUndef()) V2 = V1; 10027 10028 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10029 // that it is in input element units, not in bytes. Convert now. 10030 10031 // For little endian, the order of the input vectors is reversed, and 10032 // the permutation mask is complemented with respect to 31. This is 10033 // necessary to produce proper semantics with the big-endian-biased vperm 10034 // instruction. 10035 EVT EltVT = V1.getValueType().getVectorElementType(); 10036 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10037 10038 SmallVector<SDValue, 16> ResultMask; 10039 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10040 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10041 10042 for (unsigned j = 0; j != BytesPerElement; ++j) 10043 if (isLittleEndian) 10044 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10045 dl, MVT::i32)); 10046 else 10047 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10048 MVT::i32)); 10049 } 10050 10051 ShufflesHandledWithVPERM++; 10052 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10053 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10054 LLVM_DEBUG(SVOp->dump()); 10055 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10056 LLVM_DEBUG(VPermMask.dump()); 10057 10058 if (isLittleEndian) 10059 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10060 V2, V1, VPermMask); 10061 else 10062 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10063 V1, V2, VPermMask); 10064 } 10065 10066 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10067 /// vector comparison. If it is, return true and fill in Opc/isDot with 10068 /// information about the intrinsic. 10069 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10070 bool &isDot, const PPCSubtarget &Subtarget) { 10071 unsigned IntrinsicID = 10072 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10073 CompareOpc = -1; 10074 isDot = false; 10075 switch (IntrinsicID) { 10076 default: 10077 return false; 10078 // Comparison predicates. 10079 case Intrinsic::ppc_altivec_vcmpbfp_p: 10080 CompareOpc = 966; 10081 isDot = true; 10082 break; 10083 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10084 CompareOpc = 198; 10085 isDot = true; 10086 break; 10087 case Intrinsic::ppc_altivec_vcmpequb_p: 10088 CompareOpc = 6; 10089 isDot = true; 10090 break; 10091 case Intrinsic::ppc_altivec_vcmpequh_p: 10092 CompareOpc = 70; 10093 isDot = true; 10094 break; 10095 case Intrinsic::ppc_altivec_vcmpequw_p: 10096 CompareOpc = 134; 10097 isDot = true; 10098 break; 10099 case Intrinsic::ppc_altivec_vcmpequd_p: 10100 if (Subtarget.hasP8Altivec()) { 10101 CompareOpc = 199; 10102 isDot = true; 10103 } else 10104 return false; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpneb_p: 10107 case Intrinsic::ppc_altivec_vcmpneh_p: 10108 case Intrinsic::ppc_altivec_vcmpnew_p: 10109 case Intrinsic::ppc_altivec_vcmpnezb_p: 10110 case Intrinsic::ppc_altivec_vcmpnezh_p: 10111 case Intrinsic::ppc_altivec_vcmpnezw_p: 10112 if (Subtarget.hasP9Altivec()) { 10113 switch (IntrinsicID) { 10114 default: 10115 llvm_unreachable("Unknown comparison intrinsic."); 10116 case Intrinsic::ppc_altivec_vcmpneb_p: 10117 CompareOpc = 7; 10118 break; 10119 case Intrinsic::ppc_altivec_vcmpneh_p: 10120 CompareOpc = 71; 10121 break; 10122 case Intrinsic::ppc_altivec_vcmpnew_p: 10123 CompareOpc = 135; 10124 break; 10125 case Intrinsic::ppc_altivec_vcmpnezb_p: 10126 CompareOpc = 263; 10127 break; 10128 case Intrinsic::ppc_altivec_vcmpnezh_p: 10129 CompareOpc = 327; 10130 break; 10131 case Intrinsic::ppc_altivec_vcmpnezw_p: 10132 CompareOpc = 391; 10133 break; 10134 } 10135 isDot = true; 10136 } else 10137 return false; 10138 break; 10139 case Intrinsic::ppc_altivec_vcmpgefp_p: 10140 CompareOpc = 454; 10141 isDot = true; 10142 break; 10143 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10144 CompareOpc = 710; 10145 isDot = true; 10146 break; 10147 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10148 CompareOpc = 774; 10149 isDot = true; 10150 break; 10151 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10152 CompareOpc = 838; 10153 isDot = true; 10154 break; 10155 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10156 CompareOpc = 902; 10157 isDot = true; 10158 break; 10159 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10160 if (Subtarget.hasP8Altivec()) { 10161 CompareOpc = 967; 10162 isDot = true; 10163 } else 10164 return false; 10165 break; 10166 case Intrinsic::ppc_altivec_vcmpgtub_p: 10167 CompareOpc = 518; 10168 isDot = true; 10169 break; 10170 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10171 CompareOpc = 582; 10172 isDot = true; 10173 break; 10174 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10175 CompareOpc = 646; 10176 isDot = true; 10177 break; 10178 case Intrinsic::ppc_altivec_vcmpgtud_p: 10179 if (Subtarget.hasP8Altivec()) { 10180 CompareOpc = 711; 10181 isDot = true; 10182 } else 10183 return false; 10184 break; 10185 10186 // VSX predicate comparisons use the same infrastructure 10187 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10188 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10189 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10190 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10191 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10192 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10193 if (Subtarget.hasVSX()) { 10194 switch (IntrinsicID) { 10195 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10196 CompareOpc = 99; 10197 break; 10198 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10199 CompareOpc = 115; 10200 break; 10201 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10202 CompareOpc = 107; 10203 break; 10204 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10205 CompareOpc = 67; 10206 break; 10207 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10208 CompareOpc = 83; 10209 break; 10210 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10211 CompareOpc = 75; 10212 break; 10213 } 10214 isDot = true; 10215 } else 10216 return false; 10217 break; 10218 10219 // Normal Comparisons. 10220 case Intrinsic::ppc_altivec_vcmpbfp: 10221 CompareOpc = 966; 10222 break; 10223 case Intrinsic::ppc_altivec_vcmpeqfp: 10224 CompareOpc = 198; 10225 break; 10226 case Intrinsic::ppc_altivec_vcmpequb: 10227 CompareOpc = 6; 10228 break; 10229 case Intrinsic::ppc_altivec_vcmpequh: 10230 CompareOpc = 70; 10231 break; 10232 case Intrinsic::ppc_altivec_vcmpequw: 10233 CompareOpc = 134; 10234 break; 10235 case Intrinsic::ppc_altivec_vcmpequd: 10236 if (Subtarget.hasP8Altivec()) 10237 CompareOpc = 199; 10238 else 10239 return false; 10240 break; 10241 case Intrinsic::ppc_altivec_vcmpneb: 10242 case Intrinsic::ppc_altivec_vcmpneh: 10243 case Intrinsic::ppc_altivec_vcmpnew: 10244 case Intrinsic::ppc_altivec_vcmpnezb: 10245 case Intrinsic::ppc_altivec_vcmpnezh: 10246 case Intrinsic::ppc_altivec_vcmpnezw: 10247 if (Subtarget.hasP9Altivec()) 10248 switch (IntrinsicID) { 10249 default: 10250 llvm_unreachable("Unknown comparison intrinsic."); 10251 case Intrinsic::ppc_altivec_vcmpneb: 10252 CompareOpc = 7; 10253 break; 10254 case Intrinsic::ppc_altivec_vcmpneh: 10255 CompareOpc = 71; 10256 break; 10257 case Intrinsic::ppc_altivec_vcmpnew: 10258 CompareOpc = 135; 10259 break; 10260 case Intrinsic::ppc_altivec_vcmpnezb: 10261 CompareOpc = 263; 10262 break; 10263 case Intrinsic::ppc_altivec_vcmpnezh: 10264 CompareOpc = 327; 10265 break; 10266 case Intrinsic::ppc_altivec_vcmpnezw: 10267 CompareOpc = 391; 10268 break; 10269 } 10270 else 10271 return false; 10272 break; 10273 case Intrinsic::ppc_altivec_vcmpgefp: 10274 CompareOpc = 454; 10275 break; 10276 case Intrinsic::ppc_altivec_vcmpgtfp: 10277 CompareOpc = 710; 10278 break; 10279 case Intrinsic::ppc_altivec_vcmpgtsb: 10280 CompareOpc = 774; 10281 break; 10282 case Intrinsic::ppc_altivec_vcmpgtsh: 10283 CompareOpc = 838; 10284 break; 10285 case Intrinsic::ppc_altivec_vcmpgtsw: 10286 CompareOpc = 902; 10287 break; 10288 case Intrinsic::ppc_altivec_vcmpgtsd: 10289 if (Subtarget.hasP8Altivec()) 10290 CompareOpc = 967; 10291 else 10292 return false; 10293 break; 10294 case Intrinsic::ppc_altivec_vcmpgtub: 10295 CompareOpc = 518; 10296 break; 10297 case Intrinsic::ppc_altivec_vcmpgtuh: 10298 CompareOpc = 582; 10299 break; 10300 case Intrinsic::ppc_altivec_vcmpgtuw: 10301 CompareOpc = 646; 10302 break; 10303 case Intrinsic::ppc_altivec_vcmpgtud: 10304 if (Subtarget.hasP8Altivec()) 10305 CompareOpc = 711; 10306 else 10307 return false; 10308 break; 10309 } 10310 return true; 10311 } 10312 10313 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10314 /// lower, do it, otherwise return null. 10315 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10316 SelectionDAG &DAG) const { 10317 unsigned IntrinsicID = 10318 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10319 10320 SDLoc dl(Op); 10321 10322 if (IntrinsicID == Intrinsic::thread_pointer) { 10323 // Reads the thread pointer register, used for __builtin_thread_pointer. 10324 if (Subtarget.isPPC64()) 10325 return DAG.getRegister(PPC::X13, MVT::i64); 10326 return DAG.getRegister(PPC::R2, MVT::i32); 10327 } 10328 10329 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10330 // opcode number of the comparison. 10331 int CompareOpc; 10332 bool isDot; 10333 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10334 return SDValue(); // Don't custom lower most intrinsics. 10335 10336 // If this is a non-dot comparison, make the VCMP node and we are done. 10337 if (!isDot) { 10338 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10339 Op.getOperand(1), Op.getOperand(2), 10340 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10341 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10342 } 10343 10344 // Create the PPCISD altivec 'dot' comparison node. 10345 SDValue Ops[] = { 10346 Op.getOperand(2), // LHS 10347 Op.getOperand(3), // RHS 10348 DAG.getConstant(CompareOpc, dl, MVT::i32) 10349 }; 10350 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10351 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10352 10353 // Now that we have the comparison, emit a copy from the CR to a GPR. 10354 // This is flagged to the above dot comparison. 10355 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10356 DAG.getRegister(PPC::CR6, MVT::i32), 10357 CompNode.getValue(1)); 10358 10359 // Unpack the result based on how the target uses it. 10360 unsigned BitNo; // Bit # of CR6. 10361 bool InvertBit; // Invert result? 10362 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10363 default: // Can't happen, don't crash on invalid number though. 10364 case 0: // Return the value of the EQ bit of CR6. 10365 BitNo = 0; InvertBit = false; 10366 break; 10367 case 1: // Return the inverted value of the EQ bit of CR6. 10368 BitNo = 0; InvertBit = true; 10369 break; 10370 case 2: // Return the value of the LT bit of CR6. 10371 BitNo = 2; InvertBit = false; 10372 break; 10373 case 3: // Return the inverted value of the LT bit of CR6. 10374 BitNo = 2; InvertBit = true; 10375 break; 10376 } 10377 10378 // Shift the bit into the low position. 10379 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10380 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10381 // Isolate the bit. 10382 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10383 DAG.getConstant(1, dl, MVT::i32)); 10384 10385 // If we are supposed to, toggle the bit. 10386 if (InvertBit) 10387 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10388 DAG.getConstant(1, dl, MVT::i32)); 10389 return Flags; 10390 } 10391 10392 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10393 SelectionDAG &DAG) const { 10394 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10395 // the beginning of the argument list. 10396 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10397 SDLoc DL(Op); 10398 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10399 case Intrinsic::ppc_cfence: { 10400 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10401 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10402 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10403 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10404 Op.getOperand(ArgStart + 1)), 10405 Op.getOperand(0)), 10406 0); 10407 } 10408 default: 10409 break; 10410 } 10411 return SDValue(); 10412 } 10413 10414 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10415 // Check for a DIV with the same operands as this REM. 10416 for (auto UI : Op.getOperand(1)->uses()) { 10417 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10418 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10419 if (UI->getOperand(0) == Op.getOperand(0) && 10420 UI->getOperand(1) == Op.getOperand(1)) 10421 return SDValue(); 10422 } 10423 return Op; 10424 } 10425 10426 // Lower scalar BSWAP64 to xxbrd. 10427 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10428 SDLoc dl(Op); 10429 // MTVSRDD 10430 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10431 Op.getOperand(0)); 10432 // XXBRD 10433 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10434 // MFVSRD 10435 int VectorIndex = 0; 10436 if (Subtarget.isLittleEndian()) 10437 VectorIndex = 1; 10438 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10439 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10440 return Op; 10441 } 10442 10443 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10444 // compared to a value that is atomically loaded (atomic loads zero-extend). 10445 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10446 SelectionDAG &DAG) const { 10447 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10448 "Expecting an atomic compare-and-swap here."); 10449 SDLoc dl(Op); 10450 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10451 EVT MemVT = AtomicNode->getMemoryVT(); 10452 if (MemVT.getSizeInBits() >= 32) 10453 return Op; 10454 10455 SDValue CmpOp = Op.getOperand(2); 10456 // If this is already correctly zero-extended, leave it alone. 10457 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10458 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10459 return Op; 10460 10461 // Clear the high bits of the compare operand. 10462 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10463 SDValue NewCmpOp = 10464 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10465 DAG.getConstant(MaskVal, dl, MVT::i32)); 10466 10467 // Replace the existing compare operand with the properly zero-extended one. 10468 SmallVector<SDValue, 4> Ops; 10469 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10470 Ops.push_back(AtomicNode->getOperand(i)); 10471 Ops[2] = NewCmpOp; 10472 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10473 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10474 auto NodeTy = 10475 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10476 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10477 } 10478 10479 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10480 SelectionDAG &DAG) const { 10481 SDLoc dl(Op); 10482 // Create a stack slot that is 16-byte aligned. 10483 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10484 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10485 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10486 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10487 10488 // Store the input value into Value#0 of the stack slot. 10489 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10490 MachinePointerInfo()); 10491 // Load it out. 10492 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10493 } 10494 10495 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10496 SelectionDAG &DAG) const { 10497 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10498 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10499 10500 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10501 // We have legal lowering for constant indices but not for variable ones. 10502 if (!C) 10503 return SDValue(); 10504 10505 EVT VT = Op.getValueType(); 10506 SDLoc dl(Op); 10507 SDValue V1 = Op.getOperand(0); 10508 SDValue V2 = Op.getOperand(1); 10509 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10510 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10511 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10512 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10513 unsigned InsertAtElement = C->getZExtValue(); 10514 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10515 if (Subtarget.isLittleEndian()) { 10516 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10517 } 10518 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10519 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10520 } 10521 return Op; 10522 } 10523 10524 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10525 SelectionDAG &DAG) const { 10526 SDLoc dl(Op); 10527 SDNode *N = Op.getNode(); 10528 10529 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10530 "Unknown extract_vector_elt type"); 10531 10532 SDValue Value = N->getOperand(0); 10533 10534 // The first part of this is like the store lowering except that we don't 10535 // need to track the chain. 10536 10537 // The values are now known to be -1 (false) or 1 (true). To convert this 10538 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10539 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10540 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10541 10542 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10543 // understand how to form the extending load. 10544 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10545 10546 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10547 10548 // Now convert to an integer and store. 10549 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10550 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10551 Value); 10552 10553 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10554 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10555 MachinePointerInfo PtrInfo = 10556 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10557 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10558 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10559 10560 SDValue StoreChain = DAG.getEntryNode(); 10561 SDValue Ops[] = {StoreChain, 10562 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10563 Value, FIdx}; 10564 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10565 10566 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10567 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10568 10569 // Extract the value requested. 10570 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10571 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10572 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10573 10574 SDValue IntVal = 10575 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10576 10577 if (!Subtarget.useCRBits()) 10578 return IntVal; 10579 10580 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10581 } 10582 10583 /// Lowering for QPX v4i1 loads 10584 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10585 SelectionDAG &DAG) const { 10586 SDLoc dl(Op); 10587 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10588 SDValue LoadChain = LN->getChain(); 10589 SDValue BasePtr = LN->getBasePtr(); 10590 10591 if (Op.getValueType() == MVT::v4f64 || 10592 Op.getValueType() == MVT::v4f32) { 10593 EVT MemVT = LN->getMemoryVT(); 10594 unsigned Alignment = LN->getAlignment(); 10595 10596 // If this load is properly aligned, then it is legal. 10597 if (Alignment >= MemVT.getStoreSize()) 10598 return Op; 10599 10600 EVT ScalarVT = Op.getValueType().getScalarType(), 10601 ScalarMemVT = MemVT.getScalarType(); 10602 unsigned Stride = ScalarMemVT.getStoreSize(); 10603 10604 SDValue Vals[4], LoadChains[4]; 10605 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10606 SDValue Load; 10607 if (ScalarVT != ScalarMemVT) 10608 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10609 BasePtr, 10610 LN->getPointerInfo().getWithOffset(Idx * Stride), 10611 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10612 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10613 else 10614 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10615 LN->getPointerInfo().getWithOffset(Idx * Stride), 10616 MinAlign(Alignment, Idx * Stride), 10617 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10618 10619 if (Idx == 0 && LN->isIndexed()) { 10620 assert(LN->getAddressingMode() == ISD::PRE_INC && 10621 "Unknown addressing mode on vector load"); 10622 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10623 LN->getAddressingMode()); 10624 } 10625 10626 Vals[Idx] = Load; 10627 LoadChains[Idx] = Load.getValue(1); 10628 10629 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10630 DAG.getConstant(Stride, dl, 10631 BasePtr.getValueType())); 10632 } 10633 10634 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10635 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10636 10637 if (LN->isIndexed()) { 10638 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10639 return DAG.getMergeValues(RetOps, dl); 10640 } 10641 10642 SDValue RetOps[] = { Value, TF }; 10643 return DAG.getMergeValues(RetOps, dl); 10644 } 10645 10646 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10647 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10648 10649 // To lower v4i1 from a byte array, we load the byte elements of the 10650 // vector and then reuse the BUILD_VECTOR logic. 10651 10652 SDValue VectElmts[4], VectElmtChains[4]; 10653 for (unsigned i = 0; i < 4; ++i) { 10654 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10655 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10656 10657 VectElmts[i] = DAG.getExtLoad( 10658 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10659 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10660 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10661 VectElmtChains[i] = VectElmts[i].getValue(1); 10662 } 10663 10664 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10665 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10666 10667 SDValue RVals[] = { Value, LoadChain }; 10668 return DAG.getMergeValues(RVals, dl); 10669 } 10670 10671 /// Lowering for QPX v4i1 stores 10672 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10673 SelectionDAG &DAG) const { 10674 SDLoc dl(Op); 10675 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10676 SDValue StoreChain = SN->getChain(); 10677 SDValue BasePtr = SN->getBasePtr(); 10678 SDValue Value = SN->getValue(); 10679 10680 if (Value.getValueType() == MVT::v4f64 || 10681 Value.getValueType() == MVT::v4f32) { 10682 EVT MemVT = SN->getMemoryVT(); 10683 unsigned Alignment = SN->getAlignment(); 10684 10685 // If this store is properly aligned, then it is legal. 10686 if (Alignment >= MemVT.getStoreSize()) 10687 return Op; 10688 10689 EVT ScalarVT = Value.getValueType().getScalarType(), 10690 ScalarMemVT = MemVT.getScalarType(); 10691 unsigned Stride = ScalarMemVT.getStoreSize(); 10692 10693 SDValue Stores[4]; 10694 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10695 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10696 DAG.getVectorIdxConstant(Idx, dl)); 10697 SDValue Store; 10698 if (ScalarVT != ScalarMemVT) 10699 Store = 10700 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10701 SN->getPointerInfo().getWithOffset(Idx * Stride), 10702 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10703 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10704 else 10705 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10706 SN->getPointerInfo().getWithOffset(Idx * Stride), 10707 MinAlign(Alignment, Idx * Stride), 10708 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10709 10710 if (Idx == 0 && SN->isIndexed()) { 10711 assert(SN->getAddressingMode() == ISD::PRE_INC && 10712 "Unknown addressing mode on vector store"); 10713 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10714 SN->getAddressingMode()); 10715 } 10716 10717 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10718 DAG.getConstant(Stride, dl, 10719 BasePtr.getValueType())); 10720 Stores[Idx] = Store; 10721 } 10722 10723 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10724 10725 if (SN->isIndexed()) { 10726 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10727 return DAG.getMergeValues(RetOps, dl); 10728 } 10729 10730 return TF; 10731 } 10732 10733 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10734 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10735 10736 // The values are now known to be -1 (false) or 1 (true). To convert this 10737 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10738 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10739 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10740 10741 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10742 // understand how to form the extending load. 10743 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10744 10745 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10746 10747 // Now convert to an integer and store. 10748 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10749 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10750 Value); 10751 10752 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10753 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10754 MachinePointerInfo PtrInfo = 10755 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10756 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10757 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10758 10759 SDValue Ops[] = {StoreChain, 10760 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10761 Value, FIdx}; 10762 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10763 10764 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10765 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10766 10767 // Move data into the byte array. 10768 SDValue Loads[4], LoadChains[4]; 10769 for (unsigned i = 0; i < 4; ++i) { 10770 unsigned Offset = 4*i; 10771 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10772 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10773 10774 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10775 PtrInfo.getWithOffset(Offset)); 10776 LoadChains[i] = Loads[i].getValue(1); 10777 } 10778 10779 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10780 10781 SDValue Stores[4]; 10782 for (unsigned i = 0; i < 4; ++i) { 10783 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10784 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10785 10786 Stores[i] = DAG.getTruncStore( 10787 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10788 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10789 SN->getAAInfo()); 10790 } 10791 10792 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10793 10794 return StoreChain; 10795 } 10796 10797 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10798 SDLoc dl(Op); 10799 if (Op.getValueType() == MVT::v4i32) { 10800 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10801 10802 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10803 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10804 10805 SDValue RHSSwap = // = vrlw RHS, 16 10806 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10807 10808 // Shrinkify inputs to v8i16. 10809 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10810 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10811 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10812 10813 // Low parts multiplied together, generating 32-bit results (we ignore the 10814 // top parts). 10815 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10816 LHS, RHS, DAG, dl, MVT::v4i32); 10817 10818 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10819 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10820 // Shift the high parts up 16 bits. 10821 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10822 Neg16, DAG, dl); 10823 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10824 } else if (Op.getValueType() == MVT::v16i8) { 10825 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10826 bool isLittleEndian = Subtarget.isLittleEndian(); 10827 10828 // Multiply the even 8-bit parts, producing 16-bit sums. 10829 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10830 LHS, RHS, DAG, dl, MVT::v8i16); 10831 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10832 10833 // Multiply the odd 8-bit parts, producing 16-bit sums. 10834 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10835 LHS, RHS, DAG, dl, MVT::v8i16); 10836 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10837 10838 // Merge the results together. Because vmuleub and vmuloub are 10839 // instructions with a big-endian bias, we must reverse the 10840 // element numbering and reverse the meaning of "odd" and "even" 10841 // when generating little endian code. 10842 int Ops[16]; 10843 for (unsigned i = 0; i != 8; ++i) { 10844 if (isLittleEndian) { 10845 Ops[i*2 ] = 2*i; 10846 Ops[i*2+1] = 2*i+16; 10847 } else { 10848 Ops[i*2 ] = 2*i+1; 10849 Ops[i*2+1] = 2*i+1+16; 10850 } 10851 } 10852 if (isLittleEndian) 10853 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10854 else 10855 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10856 } else { 10857 llvm_unreachable("Unknown mul to lower!"); 10858 } 10859 } 10860 10861 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10862 10863 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10864 10865 EVT VT = Op.getValueType(); 10866 assert(VT.isVector() && 10867 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10868 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10869 VT == MVT::v16i8) && 10870 "Unexpected vector element type!"); 10871 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10872 "Current subtarget doesn't support smax v2i64!"); 10873 10874 // For vector abs, it can be lowered to: 10875 // abs x 10876 // ==> 10877 // y = -x 10878 // smax(x, y) 10879 10880 SDLoc dl(Op); 10881 SDValue X = Op.getOperand(0); 10882 SDValue Zero = DAG.getConstant(0, dl, VT); 10883 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10884 10885 // SMAX patch https://reviews.llvm.org/D47332 10886 // hasn't landed yet, so use intrinsic first here. 10887 // TODO: Should use SMAX directly once SMAX patch landed 10888 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10889 if (VT == MVT::v2i64) 10890 BifID = Intrinsic::ppc_altivec_vmaxsd; 10891 else if (VT == MVT::v8i16) 10892 BifID = Intrinsic::ppc_altivec_vmaxsh; 10893 else if (VT == MVT::v16i8) 10894 BifID = Intrinsic::ppc_altivec_vmaxsb; 10895 10896 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10897 } 10898 10899 // Custom lowering for fpext vf32 to v2f64 10900 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10901 10902 assert(Op.getOpcode() == ISD::FP_EXTEND && 10903 "Should only be called for ISD::FP_EXTEND"); 10904 10905 // FIXME: handle extends from half precision float vectors on P9. 10906 // We only want to custom lower an extend from v2f32 to v2f64. 10907 if (Op.getValueType() != MVT::v2f64 || 10908 Op.getOperand(0).getValueType() != MVT::v2f32) 10909 return SDValue(); 10910 10911 SDLoc dl(Op); 10912 SDValue Op0 = Op.getOperand(0); 10913 10914 switch (Op0.getOpcode()) { 10915 default: 10916 return SDValue(); 10917 case ISD::EXTRACT_SUBVECTOR: { 10918 assert(Op0.getNumOperands() == 2 && 10919 isa<ConstantSDNode>(Op0->getOperand(1)) && 10920 "Node should have 2 operands with second one being a constant!"); 10921 10922 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10923 return SDValue(); 10924 10925 // Custom lower is only done for high or low doubleword. 10926 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10927 if (Idx % 2 != 0) 10928 return SDValue(); 10929 10930 // Since input is v4f32, at this point Idx is either 0 or 2. 10931 // Shift to get the doubleword position we want. 10932 int DWord = Idx >> 1; 10933 10934 // High and low word positions are different on little endian. 10935 if (Subtarget.isLittleEndian()) 10936 DWord ^= 0x1; 10937 10938 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10939 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10940 } 10941 case ISD::FADD: 10942 case ISD::FMUL: 10943 case ISD::FSUB: { 10944 SDValue NewLoad[2]; 10945 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10946 // Ensure both input are loads. 10947 SDValue LdOp = Op0.getOperand(i); 10948 if (LdOp.getOpcode() != ISD::LOAD) 10949 return SDValue(); 10950 // Generate new load node. 10951 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10952 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10953 NewLoad[i] = DAG.getMemIntrinsicNode( 10954 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10955 LD->getMemoryVT(), LD->getMemOperand()); 10956 } 10957 SDValue NewOp = 10958 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10959 NewLoad[1], Op0.getNode()->getFlags()); 10960 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10961 DAG.getConstant(0, dl, MVT::i32)); 10962 } 10963 case ISD::LOAD: { 10964 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10965 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10966 SDValue NewLd = DAG.getMemIntrinsicNode( 10967 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10968 LD->getMemoryVT(), LD->getMemOperand()); 10969 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10970 DAG.getConstant(0, dl, MVT::i32)); 10971 } 10972 } 10973 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10974 } 10975 10976 /// LowerOperation - Provide custom lowering hooks for some operations. 10977 /// 10978 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10979 switch (Op.getOpcode()) { 10980 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10981 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10982 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10983 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10984 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10985 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10986 case ISD::SETCC: return LowerSETCC(Op, DAG); 10987 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10988 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10989 10990 // Variable argument lowering. 10991 case ISD::VASTART: return LowerVASTART(Op, DAG); 10992 case ISD::VAARG: return LowerVAARG(Op, DAG); 10993 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10994 10995 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10996 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10997 case ISD::GET_DYNAMIC_AREA_OFFSET: 10998 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10999 11000 // Exception handling lowering. 11001 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11002 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11003 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11004 11005 case ISD::LOAD: return LowerLOAD(Op, DAG); 11006 case ISD::STORE: return LowerSTORE(Op, DAG); 11007 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11008 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11009 case ISD::FP_TO_UINT: 11010 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11011 case ISD::UINT_TO_FP: 11012 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11013 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11014 11015 // Lower 64-bit shifts. 11016 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11017 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11018 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11019 11020 // Vector-related lowering. 11021 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11022 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11023 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11024 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11025 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 11026 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11027 case ISD::MUL: return LowerMUL(Op, DAG); 11028 case ISD::ABS: return LowerABS(Op, DAG); 11029 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11030 case ISD::ROTL: return LowerROTL(Op, DAG); 11031 11032 // For counter-based loop handling. 11033 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11034 11035 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11036 11037 // Frame & Return address. 11038 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11039 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11040 11041 case ISD::INTRINSIC_VOID: 11042 return LowerINTRINSIC_VOID(Op, DAG); 11043 case ISD::SREM: 11044 case ISD::UREM: 11045 return LowerREM(Op, DAG); 11046 case ISD::BSWAP: 11047 return LowerBSWAP(Op, DAG); 11048 case ISD::ATOMIC_CMP_SWAP: 11049 return LowerATOMIC_CMP_SWAP(Op, DAG); 11050 } 11051 } 11052 11053 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11054 SmallVectorImpl<SDValue>&Results, 11055 SelectionDAG &DAG) const { 11056 SDLoc dl(N); 11057 switch (N->getOpcode()) { 11058 default: 11059 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11060 case ISD::READCYCLECOUNTER: { 11061 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11062 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11063 11064 Results.push_back( 11065 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11066 Results.push_back(RTB.getValue(2)); 11067 break; 11068 } 11069 case ISD::INTRINSIC_W_CHAIN: { 11070 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11071 Intrinsic::loop_decrement) 11072 break; 11073 11074 assert(N->getValueType(0) == MVT::i1 && 11075 "Unexpected result type for CTR decrement intrinsic"); 11076 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11077 N->getValueType(0)); 11078 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11079 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11080 N->getOperand(1)); 11081 11082 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11083 Results.push_back(NewInt.getValue(1)); 11084 break; 11085 } 11086 case ISD::VAARG: { 11087 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11088 return; 11089 11090 EVT VT = N->getValueType(0); 11091 11092 if (VT == MVT::i64) { 11093 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11094 11095 Results.push_back(NewNode); 11096 Results.push_back(NewNode.getValue(1)); 11097 } 11098 return; 11099 } 11100 case ISD::FP_TO_SINT: 11101 case ISD::FP_TO_UINT: 11102 // LowerFP_TO_INT() can only handle f32 and f64. 11103 if (N->getOperand(0).getValueType() == MVT::ppcf128) 11104 return; 11105 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11106 return; 11107 case ISD::TRUNCATE: { 11108 EVT TrgVT = N->getValueType(0); 11109 EVT OpVT = N->getOperand(0).getValueType(); 11110 if (TrgVT.isVector() && 11111 isOperationCustom(N->getOpcode(), TrgVT) && 11112 OpVT.getSizeInBits() <= 128 && 11113 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 11114 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 11115 return; 11116 } 11117 case ISD::BITCAST: 11118 // Don't handle bitcast here. 11119 return; 11120 case ISD::FP_EXTEND: 11121 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11122 if (Lowered) 11123 Results.push_back(Lowered); 11124 return; 11125 } 11126 } 11127 11128 //===----------------------------------------------------------------------===// 11129 // Other Lowering Code 11130 //===----------------------------------------------------------------------===// 11131 11132 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11133 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11134 Function *Func = Intrinsic::getDeclaration(M, Id); 11135 return Builder.CreateCall(Func, {}); 11136 } 11137 11138 // The mappings for emitLeading/TrailingFence is taken from 11139 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11140 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11141 Instruction *Inst, 11142 AtomicOrdering Ord) const { 11143 if (Ord == AtomicOrdering::SequentiallyConsistent) 11144 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11145 if (isReleaseOrStronger(Ord)) 11146 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11147 return nullptr; 11148 } 11149 11150 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11151 Instruction *Inst, 11152 AtomicOrdering Ord) const { 11153 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11154 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11155 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11156 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11157 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11158 return Builder.CreateCall( 11159 Intrinsic::getDeclaration( 11160 Builder.GetInsertBlock()->getParent()->getParent(), 11161 Intrinsic::ppc_cfence, {Inst->getType()}), 11162 {Inst}); 11163 // FIXME: Can use isync for rmw operation. 11164 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11165 } 11166 return nullptr; 11167 } 11168 11169 MachineBasicBlock * 11170 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11171 unsigned AtomicSize, 11172 unsigned BinOpcode, 11173 unsigned CmpOpcode, 11174 unsigned CmpPred) const { 11175 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11176 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11177 11178 auto LoadMnemonic = PPC::LDARX; 11179 auto StoreMnemonic = PPC::STDCX; 11180 switch (AtomicSize) { 11181 default: 11182 llvm_unreachable("Unexpected size of atomic entity"); 11183 case 1: 11184 LoadMnemonic = PPC::LBARX; 11185 StoreMnemonic = PPC::STBCX; 11186 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11187 break; 11188 case 2: 11189 LoadMnemonic = PPC::LHARX; 11190 StoreMnemonic = PPC::STHCX; 11191 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11192 break; 11193 case 4: 11194 LoadMnemonic = PPC::LWARX; 11195 StoreMnemonic = PPC::STWCX; 11196 break; 11197 case 8: 11198 LoadMnemonic = PPC::LDARX; 11199 StoreMnemonic = PPC::STDCX; 11200 break; 11201 } 11202 11203 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11204 MachineFunction *F = BB->getParent(); 11205 MachineFunction::iterator It = ++BB->getIterator(); 11206 11207 Register dest = MI.getOperand(0).getReg(); 11208 Register ptrA = MI.getOperand(1).getReg(); 11209 Register ptrB = MI.getOperand(2).getReg(); 11210 Register incr = MI.getOperand(3).getReg(); 11211 DebugLoc dl = MI.getDebugLoc(); 11212 11213 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11214 MachineBasicBlock *loop2MBB = 11215 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11216 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11217 F->insert(It, loopMBB); 11218 if (CmpOpcode) 11219 F->insert(It, loop2MBB); 11220 F->insert(It, exitMBB); 11221 exitMBB->splice(exitMBB->begin(), BB, 11222 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11223 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11224 11225 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11226 Register TmpReg = (!BinOpcode) ? incr : 11227 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11228 : &PPC::GPRCRegClass); 11229 11230 // thisMBB: 11231 // ... 11232 // fallthrough --> loopMBB 11233 BB->addSuccessor(loopMBB); 11234 11235 // loopMBB: 11236 // l[wd]arx dest, ptr 11237 // add r0, dest, incr 11238 // st[wd]cx. r0, ptr 11239 // bne- loopMBB 11240 // fallthrough --> exitMBB 11241 11242 // For max/min... 11243 // loopMBB: 11244 // l[wd]arx dest, ptr 11245 // cmpl?[wd] incr, dest 11246 // bgt exitMBB 11247 // loop2MBB: 11248 // st[wd]cx. dest, ptr 11249 // bne- loopMBB 11250 // fallthrough --> exitMBB 11251 11252 BB = loopMBB; 11253 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11254 .addReg(ptrA).addReg(ptrB); 11255 if (BinOpcode) 11256 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11257 if (CmpOpcode) { 11258 // Signed comparisons of byte or halfword values must be sign-extended. 11259 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11260 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11261 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11262 ExtReg).addReg(dest); 11263 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11264 .addReg(incr).addReg(ExtReg); 11265 } else 11266 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11267 .addReg(incr).addReg(dest); 11268 11269 BuildMI(BB, dl, TII->get(PPC::BCC)) 11270 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11271 BB->addSuccessor(loop2MBB); 11272 BB->addSuccessor(exitMBB); 11273 BB = loop2MBB; 11274 } 11275 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11276 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11277 BuildMI(BB, dl, TII->get(PPC::BCC)) 11278 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11279 BB->addSuccessor(loopMBB); 11280 BB->addSuccessor(exitMBB); 11281 11282 // exitMBB: 11283 // ... 11284 BB = exitMBB; 11285 return BB; 11286 } 11287 11288 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11289 MachineInstr &MI, MachineBasicBlock *BB, 11290 bool is8bit, // operation 11291 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11292 // If we support part-word atomic mnemonics, just use them 11293 if (Subtarget.hasPartwordAtomics()) 11294 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11295 CmpPred); 11296 11297 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11298 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11299 // In 64 bit mode we have to use 64 bits for addresses, even though the 11300 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11301 // registers without caring whether they're 32 or 64, but here we're 11302 // doing actual arithmetic on the addresses. 11303 bool is64bit = Subtarget.isPPC64(); 11304 bool isLittleEndian = Subtarget.isLittleEndian(); 11305 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11306 11307 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11308 MachineFunction *F = BB->getParent(); 11309 MachineFunction::iterator It = ++BB->getIterator(); 11310 11311 Register dest = MI.getOperand(0).getReg(); 11312 Register ptrA = MI.getOperand(1).getReg(); 11313 Register ptrB = MI.getOperand(2).getReg(); 11314 Register incr = MI.getOperand(3).getReg(); 11315 DebugLoc dl = MI.getDebugLoc(); 11316 11317 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11318 MachineBasicBlock *loop2MBB = 11319 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11320 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11321 F->insert(It, loopMBB); 11322 if (CmpOpcode) 11323 F->insert(It, loop2MBB); 11324 F->insert(It, exitMBB); 11325 exitMBB->splice(exitMBB->begin(), BB, 11326 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11327 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11328 11329 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11330 const TargetRegisterClass *RC = 11331 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11332 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11333 11334 Register PtrReg = RegInfo.createVirtualRegister(RC); 11335 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11336 Register ShiftReg = 11337 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11338 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11339 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11340 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11341 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11342 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11343 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11344 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11345 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11346 Register Ptr1Reg; 11347 Register TmpReg = 11348 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11349 11350 // thisMBB: 11351 // ... 11352 // fallthrough --> loopMBB 11353 BB->addSuccessor(loopMBB); 11354 11355 // The 4-byte load must be aligned, while a char or short may be 11356 // anywhere in the word. Hence all this nasty bookkeeping code. 11357 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11358 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11359 // xori shift, shift1, 24 [16] 11360 // rlwinm ptr, ptr1, 0, 0, 29 11361 // slw incr2, incr, shift 11362 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11363 // slw mask, mask2, shift 11364 // loopMBB: 11365 // lwarx tmpDest, ptr 11366 // add tmp, tmpDest, incr2 11367 // andc tmp2, tmpDest, mask 11368 // and tmp3, tmp, mask 11369 // or tmp4, tmp3, tmp2 11370 // stwcx. tmp4, ptr 11371 // bne- loopMBB 11372 // fallthrough --> exitMBB 11373 // srw dest, tmpDest, shift 11374 if (ptrA != ZeroReg) { 11375 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11376 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11377 .addReg(ptrA) 11378 .addReg(ptrB); 11379 } else { 11380 Ptr1Reg = ptrB; 11381 } 11382 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11383 // mode. 11384 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11385 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11386 .addImm(3) 11387 .addImm(27) 11388 .addImm(is8bit ? 28 : 27); 11389 if (!isLittleEndian) 11390 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11391 .addReg(Shift1Reg) 11392 .addImm(is8bit ? 24 : 16); 11393 if (is64bit) 11394 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11395 .addReg(Ptr1Reg) 11396 .addImm(0) 11397 .addImm(61); 11398 else 11399 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11400 .addReg(Ptr1Reg) 11401 .addImm(0) 11402 .addImm(0) 11403 .addImm(29); 11404 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11405 if (is8bit) 11406 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11407 else { 11408 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11409 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11410 .addReg(Mask3Reg) 11411 .addImm(65535); 11412 } 11413 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11414 .addReg(Mask2Reg) 11415 .addReg(ShiftReg); 11416 11417 BB = loopMBB; 11418 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11419 .addReg(ZeroReg) 11420 .addReg(PtrReg); 11421 if (BinOpcode) 11422 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11423 .addReg(Incr2Reg) 11424 .addReg(TmpDestReg); 11425 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11426 .addReg(TmpDestReg) 11427 .addReg(MaskReg); 11428 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11429 if (CmpOpcode) { 11430 // For unsigned comparisons, we can directly compare the shifted values. 11431 // For signed comparisons we shift and sign extend. 11432 Register SReg = RegInfo.createVirtualRegister(GPRC); 11433 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11434 .addReg(TmpDestReg) 11435 .addReg(MaskReg); 11436 unsigned ValueReg = SReg; 11437 unsigned CmpReg = Incr2Reg; 11438 if (CmpOpcode == PPC::CMPW) { 11439 ValueReg = RegInfo.createVirtualRegister(GPRC); 11440 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11441 .addReg(SReg) 11442 .addReg(ShiftReg); 11443 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11444 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11445 .addReg(ValueReg); 11446 ValueReg = ValueSReg; 11447 CmpReg = incr; 11448 } 11449 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11450 .addReg(CmpReg) 11451 .addReg(ValueReg); 11452 BuildMI(BB, dl, TII->get(PPC::BCC)) 11453 .addImm(CmpPred) 11454 .addReg(PPC::CR0) 11455 .addMBB(exitMBB); 11456 BB->addSuccessor(loop2MBB); 11457 BB->addSuccessor(exitMBB); 11458 BB = loop2MBB; 11459 } 11460 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11461 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11462 .addReg(Tmp4Reg) 11463 .addReg(ZeroReg) 11464 .addReg(PtrReg); 11465 BuildMI(BB, dl, TII->get(PPC::BCC)) 11466 .addImm(PPC::PRED_NE) 11467 .addReg(PPC::CR0) 11468 .addMBB(loopMBB); 11469 BB->addSuccessor(loopMBB); 11470 BB->addSuccessor(exitMBB); 11471 11472 // exitMBB: 11473 // ... 11474 BB = exitMBB; 11475 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11476 .addReg(TmpDestReg) 11477 .addReg(ShiftReg); 11478 return BB; 11479 } 11480 11481 llvm::MachineBasicBlock * 11482 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11483 MachineBasicBlock *MBB) const { 11484 DebugLoc DL = MI.getDebugLoc(); 11485 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11486 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11487 11488 MachineFunction *MF = MBB->getParent(); 11489 MachineRegisterInfo &MRI = MF->getRegInfo(); 11490 11491 const BasicBlock *BB = MBB->getBasicBlock(); 11492 MachineFunction::iterator I = ++MBB->getIterator(); 11493 11494 Register DstReg = MI.getOperand(0).getReg(); 11495 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11496 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11497 Register mainDstReg = MRI.createVirtualRegister(RC); 11498 Register restoreDstReg = MRI.createVirtualRegister(RC); 11499 11500 MVT PVT = getPointerTy(MF->getDataLayout()); 11501 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11502 "Invalid Pointer Size!"); 11503 // For v = setjmp(buf), we generate 11504 // 11505 // thisMBB: 11506 // SjLjSetup mainMBB 11507 // bl mainMBB 11508 // v_restore = 1 11509 // b sinkMBB 11510 // 11511 // mainMBB: 11512 // buf[LabelOffset] = LR 11513 // v_main = 0 11514 // 11515 // sinkMBB: 11516 // v = phi(main, restore) 11517 // 11518 11519 MachineBasicBlock *thisMBB = MBB; 11520 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11521 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11522 MF->insert(I, mainMBB); 11523 MF->insert(I, sinkMBB); 11524 11525 MachineInstrBuilder MIB; 11526 11527 // Transfer the remainder of BB and its successor edges to sinkMBB. 11528 sinkMBB->splice(sinkMBB->begin(), MBB, 11529 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11530 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11531 11532 // Note that the structure of the jmp_buf used here is not compatible 11533 // with that used by libc, and is not designed to be. Specifically, it 11534 // stores only those 'reserved' registers that LLVM does not otherwise 11535 // understand how to spill. Also, by convention, by the time this 11536 // intrinsic is called, Clang has already stored the frame address in the 11537 // first slot of the buffer and stack address in the third. Following the 11538 // X86 target code, we'll store the jump address in the second slot. We also 11539 // need to save the TOC pointer (R2) to handle jumps between shared 11540 // libraries, and that will be stored in the fourth slot. The thread 11541 // identifier (R13) is not affected. 11542 11543 // thisMBB: 11544 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11545 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11546 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11547 11548 // Prepare IP either in reg. 11549 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11550 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11551 Register BufReg = MI.getOperand(1).getReg(); 11552 11553 if (Subtarget.is64BitELFABI()) { 11554 setUsesTOCBasePtr(*MBB->getParent()); 11555 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11556 .addReg(PPC::X2) 11557 .addImm(TOCOffset) 11558 .addReg(BufReg) 11559 .cloneMemRefs(MI); 11560 } 11561 11562 // Naked functions never have a base pointer, and so we use r1. For all 11563 // other functions, this decision must be delayed until during PEI. 11564 unsigned BaseReg; 11565 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11566 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11567 else 11568 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11569 11570 MIB = BuildMI(*thisMBB, MI, DL, 11571 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11572 .addReg(BaseReg) 11573 .addImm(BPOffset) 11574 .addReg(BufReg) 11575 .cloneMemRefs(MI); 11576 11577 // Setup 11578 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11579 MIB.addRegMask(TRI->getNoPreservedMask()); 11580 11581 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11582 11583 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11584 .addMBB(mainMBB); 11585 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11586 11587 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11588 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11589 11590 // mainMBB: 11591 // mainDstReg = 0 11592 MIB = 11593 BuildMI(mainMBB, DL, 11594 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11595 11596 // Store IP 11597 if (Subtarget.isPPC64()) { 11598 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11599 .addReg(LabelReg) 11600 .addImm(LabelOffset) 11601 .addReg(BufReg); 11602 } else { 11603 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11604 .addReg(LabelReg) 11605 .addImm(LabelOffset) 11606 .addReg(BufReg); 11607 } 11608 MIB.cloneMemRefs(MI); 11609 11610 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11611 mainMBB->addSuccessor(sinkMBB); 11612 11613 // sinkMBB: 11614 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11615 TII->get(PPC::PHI), DstReg) 11616 .addReg(mainDstReg).addMBB(mainMBB) 11617 .addReg(restoreDstReg).addMBB(thisMBB); 11618 11619 MI.eraseFromParent(); 11620 return sinkMBB; 11621 } 11622 11623 MachineBasicBlock * 11624 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11625 MachineBasicBlock *MBB) const { 11626 DebugLoc DL = MI.getDebugLoc(); 11627 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11628 11629 MachineFunction *MF = MBB->getParent(); 11630 MachineRegisterInfo &MRI = MF->getRegInfo(); 11631 11632 MVT PVT = getPointerTy(MF->getDataLayout()); 11633 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11634 "Invalid Pointer Size!"); 11635 11636 const TargetRegisterClass *RC = 11637 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11638 Register Tmp = MRI.createVirtualRegister(RC); 11639 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11640 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11641 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11642 unsigned BP = 11643 (PVT == MVT::i64) 11644 ? PPC::X30 11645 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11646 : PPC::R30); 11647 11648 MachineInstrBuilder MIB; 11649 11650 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11651 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11652 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11653 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11654 11655 Register BufReg = MI.getOperand(0).getReg(); 11656 11657 // Reload FP (the jumped-to function may not have had a 11658 // frame pointer, and if so, then its r31 will be restored 11659 // as necessary). 11660 if (PVT == MVT::i64) { 11661 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11662 .addImm(0) 11663 .addReg(BufReg); 11664 } else { 11665 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11666 .addImm(0) 11667 .addReg(BufReg); 11668 } 11669 MIB.cloneMemRefs(MI); 11670 11671 // Reload IP 11672 if (PVT == MVT::i64) { 11673 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11674 .addImm(LabelOffset) 11675 .addReg(BufReg); 11676 } else { 11677 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11678 .addImm(LabelOffset) 11679 .addReg(BufReg); 11680 } 11681 MIB.cloneMemRefs(MI); 11682 11683 // Reload SP 11684 if (PVT == MVT::i64) { 11685 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11686 .addImm(SPOffset) 11687 .addReg(BufReg); 11688 } else { 11689 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11690 .addImm(SPOffset) 11691 .addReg(BufReg); 11692 } 11693 MIB.cloneMemRefs(MI); 11694 11695 // Reload BP 11696 if (PVT == MVT::i64) { 11697 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11698 .addImm(BPOffset) 11699 .addReg(BufReg); 11700 } else { 11701 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11702 .addImm(BPOffset) 11703 .addReg(BufReg); 11704 } 11705 MIB.cloneMemRefs(MI); 11706 11707 // Reload TOC 11708 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11709 setUsesTOCBasePtr(*MBB->getParent()); 11710 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11711 .addImm(TOCOffset) 11712 .addReg(BufReg) 11713 .cloneMemRefs(MI); 11714 } 11715 11716 // Jump 11717 BuildMI(*MBB, MI, DL, 11718 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11719 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11720 11721 MI.eraseFromParent(); 11722 return MBB; 11723 } 11724 11725 MachineBasicBlock * 11726 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11727 MachineBasicBlock *BB) const { 11728 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11729 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11730 if (Subtarget.is64BitELFABI() && 11731 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11732 !Subtarget.isUsingPCRelativeCalls()) { 11733 // Call lowering should have added an r2 operand to indicate a dependence 11734 // on the TOC base pointer value. It can't however, because there is no 11735 // way to mark the dependence as implicit there, and so the stackmap code 11736 // will confuse it with a regular operand. Instead, add the dependence 11737 // here. 11738 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11739 } 11740 11741 return emitPatchPoint(MI, BB); 11742 } 11743 11744 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11745 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11746 return emitEHSjLjSetJmp(MI, BB); 11747 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11748 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11749 return emitEHSjLjLongJmp(MI, BB); 11750 } 11751 11752 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11753 11754 // To "insert" these instructions we actually have to insert their 11755 // control-flow patterns. 11756 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11757 MachineFunction::iterator It = ++BB->getIterator(); 11758 11759 MachineFunction *F = BB->getParent(); 11760 11761 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11762 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11763 MI.getOpcode() == PPC::SELECT_I8) { 11764 SmallVector<MachineOperand, 2> Cond; 11765 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11766 MI.getOpcode() == PPC::SELECT_CC_I8) 11767 Cond.push_back(MI.getOperand(4)); 11768 else 11769 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11770 Cond.push_back(MI.getOperand(1)); 11771 11772 DebugLoc dl = MI.getDebugLoc(); 11773 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11774 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11775 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11776 MI.getOpcode() == PPC::SELECT_CC_F8 || 11777 MI.getOpcode() == PPC::SELECT_CC_F16 || 11778 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11779 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11780 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11781 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11782 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11783 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11784 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11785 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11786 MI.getOpcode() == PPC::SELECT_CC_SPE || 11787 MI.getOpcode() == PPC::SELECT_F4 || 11788 MI.getOpcode() == PPC::SELECT_F8 || 11789 MI.getOpcode() == PPC::SELECT_F16 || 11790 MI.getOpcode() == PPC::SELECT_QFRC || 11791 MI.getOpcode() == PPC::SELECT_QSRC || 11792 MI.getOpcode() == PPC::SELECT_QBRC || 11793 MI.getOpcode() == PPC::SELECT_SPE || 11794 MI.getOpcode() == PPC::SELECT_SPE4 || 11795 MI.getOpcode() == PPC::SELECT_VRRC || 11796 MI.getOpcode() == PPC::SELECT_VSFRC || 11797 MI.getOpcode() == PPC::SELECT_VSSRC || 11798 MI.getOpcode() == PPC::SELECT_VSRC) { 11799 // The incoming instruction knows the destination vreg to set, the 11800 // condition code register to branch on, the true/false values to 11801 // select between, and a branch opcode to use. 11802 11803 // thisMBB: 11804 // ... 11805 // TrueVal = ... 11806 // cmpTY ccX, r1, r2 11807 // bCC copy1MBB 11808 // fallthrough --> copy0MBB 11809 MachineBasicBlock *thisMBB = BB; 11810 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11811 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11812 DebugLoc dl = MI.getDebugLoc(); 11813 F->insert(It, copy0MBB); 11814 F->insert(It, sinkMBB); 11815 11816 // Transfer the remainder of BB and its successor edges to sinkMBB. 11817 sinkMBB->splice(sinkMBB->begin(), BB, 11818 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11819 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11820 11821 // Next, add the true and fallthrough blocks as its successors. 11822 BB->addSuccessor(copy0MBB); 11823 BB->addSuccessor(sinkMBB); 11824 11825 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11826 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11827 MI.getOpcode() == PPC::SELECT_F16 || 11828 MI.getOpcode() == PPC::SELECT_SPE4 || 11829 MI.getOpcode() == PPC::SELECT_SPE || 11830 MI.getOpcode() == PPC::SELECT_QFRC || 11831 MI.getOpcode() == PPC::SELECT_QSRC || 11832 MI.getOpcode() == PPC::SELECT_QBRC || 11833 MI.getOpcode() == PPC::SELECT_VRRC || 11834 MI.getOpcode() == PPC::SELECT_VSFRC || 11835 MI.getOpcode() == PPC::SELECT_VSSRC || 11836 MI.getOpcode() == PPC::SELECT_VSRC) { 11837 BuildMI(BB, dl, TII->get(PPC::BC)) 11838 .addReg(MI.getOperand(1).getReg()) 11839 .addMBB(sinkMBB); 11840 } else { 11841 unsigned SelectPred = MI.getOperand(4).getImm(); 11842 BuildMI(BB, dl, TII->get(PPC::BCC)) 11843 .addImm(SelectPred) 11844 .addReg(MI.getOperand(1).getReg()) 11845 .addMBB(sinkMBB); 11846 } 11847 11848 // copy0MBB: 11849 // %FalseValue = ... 11850 // # fallthrough to sinkMBB 11851 BB = copy0MBB; 11852 11853 // Update machine-CFG edges 11854 BB->addSuccessor(sinkMBB); 11855 11856 // sinkMBB: 11857 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11858 // ... 11859 BB = sinkMBB; 11860 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11861 .addReg(MI.getOperand(3).getReg()) 11862 .addMBB(copy0MBB) 11863 .addReg(MI.getOperand(2).getReg()) 11864 .addMBB(thisMBB); 11865 } else if (MI.getOpcode() == PPC::ReadTB) { 11866 // To read the 64-bit time-base register on a 32-bit target, we read the 11867 // two halves. Should the counter have wrapped while it was being read, we 11868 // need to try again. 11869 // ... 11870 // readLoop: 11871 // mfspr Rx,TBU # load from TBU 11872 // mfspr Ry,TB # load from TB 11873 // mfspr Rz,TBU # load from TBU 11874 // cmpw crX,Rx,Rz # check if 'old'='new' 11875 // bne readLoop # branch if they're not equal 11876 // ... 11877 11878 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11879 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11880 DebugLoc dl = MI.getDebugLoc(); 11881 F->insert(It, readMBB); 11882 F->insert(It, sinkMBB); 11883 11884 // Transfer the remainder of BB and its successor edges to sinkMBB. 11885 sinkMBB->splice(sinkMBB->begin(), BB, 11886 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11887 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11888 11889 BB->addSuccessor(readMBB); 11890 BB = readMBB; 11891 11892 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11893 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11894 Register LoReg = MI.getOperand(0).getReg(); 11895 Register HiReg = MI.getOperand(1).getReg(); 11896 11897 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11898 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11899 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11900 11901 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11902 11903 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11904 .addReg(HiReg) 11905 .addReg(ReadAgainReg); 11906 BuildMI(BB, dl, TII->get(PPC::BCC)) 11907 .addImm(PPC::PRED_NE) 11908 .addReg(CmpReg) 11909 .addMBB(readMBB); 11910 11911 BB->addSuccessor(readMBB); 11912 BB->addSuccessor(sinkMBB); 11913 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11914 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11915 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11916 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11917 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11918 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11919 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11920 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11921 11922 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11923 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11924 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11925 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11926 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11927 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11928 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11929 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11930 11931 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11932 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11933 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11934 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11935 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11936 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11937 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11938 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11939 11940 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11941 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11942 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11943 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11944 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11945 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11946 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11947 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11948 11949 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11950 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11951 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11952 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11953 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11954 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11955 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11956 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11957 11958 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11959 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11960 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11961 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11962 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11963 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11964 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11965 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11966 11967 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11968 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11969 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11970 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11971 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11972 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11973 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11974 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11975 11976 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11977 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11978 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11979 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11980 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11981 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11982 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11983 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11984 11985 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11986 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11987 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11988 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11989 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11990 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11991 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11992 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11993 11994 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11995 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11996 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11997 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11998 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11999 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12000 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12001 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12002 12003 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12004 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12005 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12006 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12007 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12008 BB = EmitAtomicBinary(MI, BB, 4, 0); 12009 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12010 BB = EmitAtomicBinary(MI, BB, 8, 0); 12011 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12012 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12013 (Subtarget.hasPartwordAtomics() && 12014 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12015 (Subtarget.hasPartwordAtomics() && 12016 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12017 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12018 12019 auto LoadMnemonic = PPC::LDARX; 12020 auto StoreMnemonic = PPC::STDCX; 12021 switch (MI.getOpcode()) { 12022 default: 12023 llvm_unreachable("Compare and swap of unknown size"); 12024 case PPC::ATOMIC_CMP_SWAP_I8: 12025 LoadMnemonic = PPC::LBARX; 12026 StoreMnemonic = PPC::STBCX; 12027 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12028 break; 12029 case PPC::ATOMIC_CMP_SWAP_I16: 12030 LoadMnemonic = PPC::LHARX; 12031 StoreMnemonic = PPC::STHCX; 12032 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12033 break; 12034 case PPC::ATOMIC_CMP_SWAP_I32: 12035 LoadMnemonic = PPC::LWARX; 12036 StoreMnemonic = PPC::STWCX; 12037 break; 12038 case PPC::ATOMIC_CMP_SWAP_I64: 12039 LoadMnemonic = PPC::LDARX; 12040 StoreMnemonic = PPC::STDCX; 12041 break; 12042 } 12043 Register dest = MI.getOperand(0).getReg(); 12044 Register ptrA = MI.getOperand(1).getReg(); 12045 Register ptrB = MI.getOperand(2).getReg(); 12046 Register oldval = MI.getOperand(3).getReg(); 12047 Register newval = MI.getOperand(4).getReg(); 12048 DebugLoc dl = MI.getDebugLoc(); 12049 12050 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12051 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12052 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12053 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12054 F->insert(It, loop1MBB); 12055 F->insert(It, loop2MBB); 12056 F->insert(It, midMBB); 12057 F->insert(It, exitMBB); 12058 exitMBB->splice(exitMBB->begin(), BB, 12059 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12060 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12061 12062 // thisMBB: 12063 // ... 12064 // fallthrough --> loopMBB 12065 BB->addSuccessor(loop1MBB); 12066 12067 // loop1MBB: 12068 // l[bhwd]arx dest, ptr 12069 // cmp[wd] dest, oldval 12070 // bne- midMBB 12071 // loop2MBB: 12072 // st[bhwd]cx. newval, ptr 12073 // bne- loopMBB 12074 // b exitBB 12075 // midMBB: 12076 // st[bhwd]cx. dest, ptr 12077 // exitBB: 12078 BB = loop1MBB; 12079 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12080 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12081 .addReg(oldval) 12082 .addReg(dest); 12083 BuildMI(BB, dl, TII->get(PPC::BCC)) 12084 .addImm(PPC::PRED_NE) 12085 .addReg(PPC::CR0) 12086 .addMBB(midMBB); 12087 BB->addSuccessor(loop2MBB); 12088 BB->addSuccessor(midMBB); 12089 12090 BB = loop2MBB; 12091 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12092 .addReg(newval) 12093 .addReg(ptrA) 12094 .addReg(ptrB); 12095 BuildMI(BB, dl, TII->get(PPC::BCC)) 12096 .addImm(PPC::PRED_NE) 12097 .addReg(PPC::CR0) 12098 .addMBB(loop1MBB); 12099 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12100 BB->addSuccessor(loop1MBB); 12101 BB->addSuccessor(exitMBB); 12102 12103 BB = midMBB; 12104 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12105 .addReg(dest) 12106 .addReg(ptrA) 12107 .addReg(ptrB); 12108 BB->addSuccessor(exitMBB); 12109 12110 // exitMBB: 12111 // ... 12112 BB = exitMBB; 12113 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12114 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12115 // We must use 64-bit registers for addresses when targeting 64-bit, 12116 // since we're actually doing arithmetic on them. Other registers 12117 // can be 32-bit. 12118 bool is64bit = Subtarget.isPPC64(); 12119 bool isLittleEndian = Subtarget.isLittleEndian(); 12120 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12121 12122 Register dest = MI.getOperand(0).getReg(); 12123 Register ptrA = MI.getOperand(1).getReg(); 12124 Register ptrB = MI.getOperand(2).getReg(); 12125 Register oldval = MI.getOperand(3).getReg(); 12126 Register newval = MI.getOperand(4).getReg(); 12127 DebugLoc dl = MI.getDebugLoc(); 12128 12129 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12130 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12131 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12132 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12133 F->insert(It, loop1MBB); 12134 F->insert(It, loop2MBB); 12135 F->insert(It, midMBB); 12136 F->insert(It, exitMBB); 12137 exitMBB->splice(exitMBB->begin(), BB, 12138 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12139 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12140 12141 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12142 const TargetRegisterClass *RC = 12143 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12144 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12145 12146 Register PtrReg = RegInfo.createVirtualRegister(RC); 12147 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12148 Register ShiftReg = 12149 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12150 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12151 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12152 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12153 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12154 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12155 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12156 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12157 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12158 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12159 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12160 Register Ptr1Reg; 12161 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12162 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12163 // thisMBB: 12164 // ... 12165 // fallthrough --> loopMBB 12166 BB->addSuccessor(loop1MBB); 12167 12168 // The 4-byte load must be aligned, while a char or short may be 12169 // anywhere in the word. Hence all this nasty bookkeeping code. 12170 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12171 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12172 // xori shift, shift1, 24 [16] 12173 // rlwinm ptr, ptr1, 0, 0, 29 12174 // slw newval2, newval, shift 12175 // slw oldval2, oldval,shift 12176 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12177 // slw mask, mask2, shift 12178 // and newval3, newval2, mask 12179 // and oldval3, oldval2, mask 12180 // loop1MBB: 12181 // lwarx tmpDest, ptr 12182 // and tmp, tmpDest, mask 12183 // cmpw tmp, oldval3 12184 // bne- midMBB 12185 // loop2MBB: 12186 // andc tmp2, tmpDest, mask 12187 // or tmp4, tmp2, newval3 12188 // stwcx. tmp4, ptr 12189 // bne- loop1MBB 12190 // b exitBB 12191 // midMBB: 12192 // stwcx. tmpDest, ptr 12193 // exitBB: 12194 // srw dest, tmpDest, shift 12195 if (ptrA != ZeroReg) { 12196 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12197 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12198 .addReg(ptrA) 12199 .addReg(ptrB); 12200 } else { 12201 Ptr1Reg = ptrB; 12202 } 12203 12204 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12205 // mode. 12206 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12207 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12208 .addImm(3) 12209 .addImm(27) 12210 .addImm(is8bit ? 28 : 27); 12211 if (!isLittleEndian) 12212 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12213 .addReg(Shift1Reg) 12214 .addImm(is8bit ? 24 : 16); 12215 if (is64bit) 12216 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12217 .addReg(Ptr1Reg) 12218 .addImm(0) 12219 .addImm(61); 12220 else 12221 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12222 .addReg(Ptr1Reg) 12223 .addImm(0) 12224 .addImm(0) 12225 .addImm(29); 12226 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12227 .addReg(newval) 12228 .addReg(ShiftReg); 12229 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12230 .addReg(oldval) 12231 .addReg(ShiftReg); 12232 if (is8bit) 12233 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12234 else { 12235 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12236 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12237 .addReg(Mask3Reg) 12238 .addImm(65535); 12239 } 12240 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12241 .addReg(Mask2Reg) 12242 .addReg(ShiftReg); 12243 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12244 .addReg(NewVal2Reg) 12245 .addReg(MaskReg); 12246 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12247 .addReg(OldVal2Reg) 12248 .addReg(MaskReg); 12249 12250 BB = loop1MBB; 12251 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12252 .addReg(ZeroReg) 12253 .addReg(PtrReg); 12254 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12255 .addReg(TmpDestReg) 12256 .addReg(MaskReg); 12257 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12258 .addReg(TmpReg) 12259 .addReg(OldVal3Reg); 12260 BuildMI(BB, dl, TII->get(PPC::BCC)) 12261 .addImm(PPC::PRED_NE) 12262 .addReg(PPC::CR0) 12263 .addMBB(midMBB); 12264 BB->addSuccessor(loop2MBB); 12265 BB->addSuccessor(midMBB); 12266 12267 BB = loop2MBB; 12268 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12269 .addReg(TmpDestReg) 12270 .addReg(MaskReg); 12271 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12272 .addReg(Tmp2Reg) 12273 .addReg(NewVal3Reg); 12274 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12275 .addReg(Tmp4Reg) 12276 .addReg(ZeroReg) 12277 .addReg(PtrReg); 12278 BuildMI(BB, dl, TII->get(PPC::BCC)) 12279 .addImm(PPC::PRED_NE) 12280 .addReg(PPC::CR0) 12281 .addMBB(loop1MBB); 12282 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12283 BB->addSuccessor(loop1MBB); 12284 BB->addSuccessor(exitMBB); 12285 12286 BB = midMBB; 12287 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12288 .addReg(TmpDestReg) 12289 .addReg(ZeroReg) 12290 .addReg(PtrReg); 12291 BB->addSuccessor(exitMBB); 12292 12293 // exitMBB: 12294 // ... 12295 BB = exitMBB; 12296 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12297 .addReg(TmpReg) 12298 .addReg(ShiftReg); 12299 } else if (MI.getOpcode() == PPC::FADDrtz) { 12300 // This pseudo performs an FADD with rounding mode temporarily forced 12301 // to round-to-zero. We emit this via custom inserter since the FPSCR 12302 // is not modeled at the SelectionDAG level. 12303 Register Dest = MI.getOperand(0).getReg(); 12304 Register Src1 = MI.getOperand(1).getReg(); 12305 Register Src2 = MI.getOperand(2).getReg(); 12306 DebugLoc dl = MI.getDebugLoc(); 12307 12308 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12309 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12310 12311 // Save FPSCR value. 12312 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12313 12314 // Set rounding mode to round-to-zero. 12315 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12316 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12317 12318 // Perform addition. 12319 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12320 12321 // Restore FPSCR value. 12322 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12323 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12324 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12325 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12326 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12327 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12328 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12329 ? PPC::ANDI8_rec 12330 : PPC::ANDI_rec; 12331 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12332 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12333 12334 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12335 Register Dest = RegInfo.createVirtualRegister( 12336 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12337 12338 DebugLoc Dl = MI.getDebugLoc(); 12339 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12340 .addReg(MI.getOperand(1).getReg()) 12341 .addImm(1); 12342 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12343 MI.getOperand(0).getReg()) 12344 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12345 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12346 DebugLoc Dl = MI.getDebugLoc(); 12347 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12348 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12349 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12350 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12351 MI.getOperand(0).getReg()) 12352 .addReg(CRReg); 12353 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12354 DebugLoc Dl = MI.getDebugLoc(); 12355 unsigned Imm = MI.getOperand(1).getImm(); 12356 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12357 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12358 MI.getOperand(0).getReg()) 12359 .addReg(PPC::CR0EQ); 12360 } else if (MI.getOpcode() == PPC::SETRNDi) { 12361 DebugLoc dl = MI.getDebugLoc(); 12362 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12363 12364 // Save FPSCR value. 12365 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12366 12367 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12368 // the following settings: 12369 // 00 Round to nearest 12370 // 01 Round to 0 12371 // 10 Round to +inf 12372 // 11 Round to -inf 12373 12374 // When the operand is immediate, using the two least significant bits of 12375 // the immediate to set the bits 62:63 of FPSCR. 12376 unsigned Mode = MI.getOperand(1).getImm(); 12377 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12378 .addImm(31); 12379 12380 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12381 .addImm(30); 12382 } else if (MI.getOpcode() == PPC::SETRND) { 12383 DebugLoc dl = MI.getDebugLoc(); 12384 12385 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12386 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12387 // If the target doesn't have DirectMove, we should use stack to do the 12388 // conversion, because the target doesn't have the instructions like mtvsrd 12389 // or mfvsrd to do this conversion directly. 12390 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12391 if (Subtarget.hasDirectMove()) { 12392 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12393 .addReg(SrcReg); 12394 } else { 12395 // Use stack to do the register copy. 12396 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12397 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12398 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12399 if (RC == &PPC::F8RCRegClass) { 12400 // Copy register from F8RCRegClass to G8RCRegclass. 12401 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12402 "Unsupported RegClass."); 12403 12404 StoreOp = PPC::STFD; 12405 LoadOp = PPC::LD; 12406 } else { 12407 // Copy register from G8RCRegClass to F8RCRegclass. 12408 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12409 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12410 "Unsupported RegClass."); 12411 } 12412 12413 MachineFrameInfo &MFI = F->getFrameInfo(); 12414 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12415 12416 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12417 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12418 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12419 MFI.getObjectAlign(FrameIdx)); 12420 12421 // Store the SrcReg into the stack. 12422 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12423 .addReg(SrcReg) 12424 .addImm(0) 12425 .addFrameIndex(FrameIdx) 12426 .addMemOperand(MMOStore); 12427 12428 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12429 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12430 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12431 MFI.getObjectAlign(FrameIdx)); 12432 12433 // Load from the stack where SrcReg is stored, and save to DestReg, 12434 // so we have done the RegClass conversion from RegClass::SrcReg to 12435 // RegClass::DestReg. 12436 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12437 .addImm(0) 12438 .addFrameIndex(FrameIdx) 12439 .addMemOperand(MMOLoad); 12440 } 12441 }; 12442 12443 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12444 12445 // Save FPSCR value. 12446 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12447 12448 // When the operand is gprc register, use two least significant bits of the 12449 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12450 // 12451 // copy OldFPSCRTmpReg, OldFPSCRReg 12452 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12453 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12454 // copy NewFPSCRReg, NewFPSCRTmpReg 12455 // mtfsf 255, NewFPSCRReg 12456 MachineOperand SrcOp = MI.getOperand(1); 12457 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12458 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12459 12460 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12461 12462 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12463 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12464 12465 // The first operand of INSERT_SUBREG should be a register which has 12466 // subregisters, we only care about its RegClass, so we should use an 12467 // IMPLICIT_DEF register. 12468 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12469 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12470 .addReg(ImDefReg) 12471 .add(SrcOp) 12472 .addImm(1); 12473 12474 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12475 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12476 .addReg(OldFPSCRTmpReg) 12477 .addReg(ExtSrcReg) 12478 .addImm(0) 12479 .addImm(62); 12480 12481 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12482 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12483 12484 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12485 // bits of FPSCR. 12486 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12487 .addImm(255) 12488 .addReg(NewFPSCRReg) 12489 .addImm(0) 12490 .addImm(0); 12491 } else { 12492 llvm_unreachable("Unexpected instr type to insert"); 12493 } 12494 12495 MI.eraseFromParent(); // The pseudo instruction is gone now. 12496 return BB; 12497 } 12498 12499 //===----------------------------------------------------------------------===// 12500 // Target Optimization Hooks 12501 //===----------------------------------------------------------------------===// 12502 12503 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12504 // For the estimates, convergence is quadratic, so we essentially double the 12505 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12506 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12507 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12508 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12509 if (VT.getScalarType() == MVT::f64) 12510 RefinementSteps++; 12511 return RefinementSteps; 12512 } 12513 12514 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12515 int Enabled, int &RefinementSteps, 12516 bool &UseOneConstNR, 12517 bool Reciprocal) const { 12518 EVT VT = Operand.getValueType(); 12519 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12520 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12521 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12522 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12523 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12524 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12525 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12526 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12527 12528 // The Newton-Raphson computation with a single constant does not provide 12529 // enough accuracy on some CPUs. 12530 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12531 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12532 } 12533 return SDValue(); 12534 } 12535 12536 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12537 int Enabled, 12538 int &RefinementSteps) const { 12539 EVT VT = Operand.getValueType(); 12540 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12541 (VT == MVT::f64 && Subtarget.hasFRE()) || 12542 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12543 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12544 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12545 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12546 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12547 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12548 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12549 } 12550 return SDValue(); 12551 } 12552 12553 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12554 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12555 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12556 // enabled for division), this functionality is redundant with the default 12557 // combiner logic (once the division -> reciprocal/multiply transformation 12558 // has taken place). As a result, this matters more for older cores than for 12559 // newer ones. 12560 12561 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12562 // reciprocal if there are two or more FDIVs (for embedded cores with only 12563 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12564 switch (Subtarget.getCPUDirective()) { 12565 default: 12566 return 3; 12567 case PPC::DIR_440: 12568 case PPC::DIR_A2: 12569 case PPC::DIR_E500: 12570 case PPC::DIR_E500mc: 12571 case PPC::DIR_E5500: 12572 return 2; 12573 } 12574 } 12575 12576 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12577 // collapsed, and so we need to look through chains of them. 12578 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12579 int64_t& Offset, SelectionDAG &DAG) { 12580 if (DAG.isBaseWithConstantOffset(Loc)) { 12581 Base = Loc.getOperand(0); 12582 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12583 12584 // The base might itself be a base plus an offset, and if so, accumulate 12585 // that as well. 12586 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12587 } 12588 } 12589 12590 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12591 unsigned Bytes, int Dist, 12592 SelectionDAG &DAG) { 12593 if (VT.getSizeInBits() / 8 != Bytes) 12594 return false; 12595 12596 SDValue BaseLoc = Base->getBasePtr(); 12597 if (Loc.getOpcode() == ISD::FrameIndex) { 12598 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12599 return false; 12600 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12601 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12602 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12603 int FS = MFI.getObjectSize(FI); 12604 int BFS = MFI.getObjectSize(BFI); 12605 if (FS != BFS || FS != (int)Bytes) return false; 12606 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12607 } 12608 12609 SDValue Base1 = Loc, Base2 = BaseLoc; 12610 int64_t Offset1 = 0, Offset2 = 0; 12611 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12612 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12613 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12614 return true; 12615 12616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12617 const GlobalValue *GV1 = nullptr; 12618 const GlobalValue *GV2 = nullptr; 12619 Offset1 = 0; 12620 Offset2 = 0; 12621 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12622 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12623 if (isGA1 && isGA2 && GV1 == GV2) 12624 return Offset1 == (Offset2 + Dist*Bytes); 12625 return false; 12626 } 12627 12628 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12629 // not enforce equality of the chain operands. 12630 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12631 unsigned Bytes, int Dist, 12632 SelectionDAG &DAG) { 12633 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12634 EVT VT = LS->getMemoryVT(); 12635 SDValue Loc = LS->getBasePtr(); 12636 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12637 } 12638 12639 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12640 EVT VT; 12641 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12642 default: return false; 12643 case Intrinsic::ppc_qpx_qvlfd: 12644 case Intrinsic::ppc_qpx_qvlfda: 12645 VT = MVT::v4f64; 12646 break; 12647 case Intrinsic::ppc_qpx_qvlfs: 12648 case Intrinsic::ppc_qpx_qvlfsa: 12649 VT = MVT::v4f32; 12650 break; 12651 case Intrinsic::ppc_qpx_qvlfcd: 12652 case Intrinsic::ppc_qpx_qvlfcda: 12653 VT = MVT::v2f64; 12654 break; 12655 case Intrinsic::ppc_qpx_qvlfcs: 12656 case Intrinsic::ppc_qpx_qvlfcsa: 12657 VT = MVT::v2f32; 12658 break; 12659 case Intrinsic::ppc_qpx_qvlfiwa: 12660 case Intrinsic::ppc_qpx_qvlfiwz: 12661 case Intrinsic::ppc_altivec_lvx: 12662 case Intrinsic::ppc_altivec_lvxl: 12663 case Intrinsic::ppc_vsx_lxvw4x: 12664 case Intrinsic::ppc_vsx_lxvw4x_be: 12665 VT = MVT::v4i32; 12666 break; 12667 case Intrinsic::ppc_vsx_lxvd2x: 12668 case Intrinsic::ppc_vsx_lxvd2x_be: 12669 VT = MVT::v2f64; 12670 break; 12671 case Intrinsic::ppc_altivec_lvebx: 12672 VT = MVT::i8; 12673 break; 12674 case Intrinsic::ppc_altivec_lvehx: 12675 VT = MVT::i16; 12676 break; 12677 case Intrinsic::ppc_altivec_lvewx: 12678 VT = MVT::i32; 12679 break; 12680 } 12681 12682 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12683 } 12684 12685 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12686 EVT VT; 12687 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12688 default: return false; 12689 case Intrinsic::ppc_qpx_qvstfd: 12690 case Intrinsic::ppc_qpx_qvstfda: 12691 VT = MVT::v4f64; 12692 break; 12693 case Intrinsic::ppc_qpx_qvstfs: 12694 case Intrinsic::ppc_qpx_qvstfsa: 12695 VT = MVT::v4f32; 12696 break; 12697 case Intrinsic::ppc_qpx_qvstfcd: 12698 case Intrinsic::ppc_qpx_qvstfcda: 12699 VT = MVT::v2f64; 12700 break; 12701 case Intrinsic::ppc_qpx_qvstfcs: 12702 case Intrinsic::ppc_qpx_qvstfcsa: 12703 VT = MVT::v2f32; 12704 break; 12705 case Intrinsic::ppc_qpx_qvstfiw: 12706 case Intrinsic::ppc_qpx_qvstfiwa: 12707 case Intrinsic::ppc_altivec_stvx: 12708 case Intrinsic::ppc_altivec_stvxl: 12709 case Intrinsic::ppc_vsx_stxvw4x: 12710 VT = MVT::v4i32; 12711 break; 12712 case Intrinsic::ppc_vsx_stxvd2x: 12713 VT = MVT::v2f64; 12714 break; 12715 case Intrinsic::ppc_vsx_stxvw4x_be: 12716 VT = MVT::v4i32; 12717 break; 12718 case Intrinsic::ppc_vsx_stxvd2x_be: 12719 VT = MVT::v2f64; 12720 break; 12721 case Intrinsic::ppc_altivec_stvebx: 12722 VT = MVT::i8; 12723 break; 12724 case Intrinsic::ppc_altivec_stvehx: 12725 VT = MVT::i16; 12726 break; 12727 case Intrinsic::ppc_altivec_stvewx: 12728 VT = MVT::i32; 12729 break; 12730 } 12731 12732 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12733 } 12734 12735 return false; 12736 } 12737 12738 // Return true is there is a nearyby consecutive load to the one provided 12739 // (regardless of alignment). We search up and down the chain, looking though 12740 // token factors and other loads (but nothing else). As a result, a true result 12741 // indicates that it is safe to create a new consecutive load adjacent to the 12742 // load provided. 12743 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12744 SDValue Chain = LD->getChain(); 12745 EVT VT = LD->getMemoryVT(); 12746 12747 SmallSet<SDNode *, 16> LoadRoots; 12748 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12749 SmallSet<SDNode *, 16> Visited; 12750 12751 // First, search up the chain, branching to follow all token-factor operands. 12752 // If we find a consecutive load, then we're done, otherwise, record all 12753 // nodes just above the top-level loads and token factors. 12754 while (!Queue.empty()) { 12755 SDNode *ChainNext = Queue.pop_back_val(); 12756 if (!Visited.insert(ChainNext).second) 12757 continue; 12758 12759 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12760 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12761 return true; 12762 12763 if (!Visited.count(ChainLD->getChain().getNode())) 12764 Queue.push_back(ChainLD->getChain().getNode()); 12765 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12766 for (const SDUse &O : ChainNext->ops()) 12767 if (!Visited.count(O.getNode())) 12768 Queue.push_back(O.getNode()); 12769 } else 12770 LoadRoots.insert(ChainNext); 12771 } 12772 12773 // Second, search down the chain, starting from the top-level nodes recorded 12774 // in the first phase. These top-level nodes are the nodes just above all 12775 // loads and token factors. Starting with their uses, recursively look though 12776 // all loads (just the chain uses) and token factors to find a consecutive 12777 // load. 12778 Visited.clear(); 12779 Queue.clear(); 12780 12781 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12782 IE = LoadRoots.end(); I != IE; ++I) { 12783 Queue.push_back(*I); 12784 12785 while (!Queue.empty()) { 12786 SDNode *LoadRoot = Queue.pop_back_val(); 12787 if (!Visited.insert(LoadRoot).second) 12788 continue; 12789 12790 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12791 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12792 return true; 12793 12794 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12795 UE = LoadRoot->use_end(); UI != UE; ++UI) 12796 if (((isa<MemSDNode>(*UI) && 12797 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12798 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12799 Queue.push_back(*UI); 12800 } 12801 } 12802 12803 return false; 12804 } 12805 12806 /// This function is called when we have proved that a SETCC node can be replaced 12807 /// by subtraction (and other supporting instructions) so that the result of 12808 /// comparison is kept in a GPR instead of CR. This function is purely for 12809 /// codegen purposes and has some flags to guide the codegen process. 12810 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12811 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12812 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12813 12814 // Zero extend the operands to the largest legal integer. Originally, they 12815 // must be of a strictly smaller size. 12816 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12817 DAG.getConstant(Size, DL, MVT::i32)); 12818 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12819 DAG.getConstant(Size, DL, MVT::i32)); 12820 12821 // Swap if needed. Depends on the condition code. 12822 if (Swap) 12823 std::swap(Op0, Op1); 12824 12825 // Subtract extended integers. 12826 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12827 12828 // Move the sign bit to the least significant position and zero out the rest. 12829 // Now the least significant bit carries the result of original comparison. 12830 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12831 DAG.getConstant(Size - 1, DL, MVT::i32)); 12832 auto Final = Shifted; 12833 12834 // Complement the result if needed. Based on the condition code. 12835 if (Complement) 12836 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12837 DAG.getConstant(1, DL, MVT::i64)); 12838 12839 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12840 } 12841 12842 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12843 DAGCombinerInfo &DCI) const { 12844 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12845 12846 SelectionDAG &DAG = DCI.DAG; 12847 SDLoc DL(N); 12848 12849 // Size of integers being compared has a critical role in the following 12850 // analysis, so we prefer to do this when all types are legal. 12851 if (!DCI.isAfterLegalizeDAG()) 12852 return SDValue(); 12853 12854 // If all users of SETCC extend its value to a legal integer type 12855 // then we replace SETCC with a subtraction 12856 for (SDNode::use_iterator UI = N->use_begin(), 12857 UE = N->use_end(); UI != UE; ++UI) { 12858 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12859 return SDValue(); 12860 } 12861 12862 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12863 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12864 12865 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12866 12867 if (OpSize < Size) { 12868 switch (CC) { 12869 default: break; 12870 case ISD::SETULT: 12871 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12872 case ISD::SETULE: 12873 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12874 case ISD::SETUGT: 12875 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12876 case ISD::SETUGE: 12877 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12878 } 12879 } 12880 12881 return SDValue(); 12882 } 12883 12884 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12885 DAGCombinerInfo &DCI) const { 12886 SelectionDAG &DAG = DCI.DAG; 12887 SDLoc dl(N); 12888 12889 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12890 // If we're tracking CR bits, we need to be careful that we don't have: 12891 // trunc(binary-ops(zext(x), zext(y))) 12892 // or 12893 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12894 // such that we're unnecessarily moving things into GPRs when it would be 12895 // better to keep them in CR bits. 12896 12897 // Note that trunc here can be an actual i1 trunc, or can be the effective 12898 // truncation that comes from a setcc or select_cc. 12899 if (N->getOpcode() == ISD::TRUNCATE && 12900 N->getValueType(0) != MVT::i1) 12901 return SDValue(); 12902 12903 if (N->getOperand(0).getValueType() != MVT::i32 && 12904 N->getOperand(0).getValueType() != MVT::i64) 12905 return SDValue(); 12906 12907 if (N->getOpcode() == ISD::SETCC || 12908 N->getOpcode() == ISD::SELECT_CC) { 12909 // If we're looking at a comparison, then we need to make sure that the 12910 // high bits (all except for the first) don't matter the result. 12911 ISD::CondCode CC = 12912 cast<CondCodeSDNode>(N->getOperand( 12913 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12914 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12915 12916 if (ISD::isSignedIntSetCC(CC)) { 12917 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12918 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12919 return SDValue(); 12920 } else if (ISD::isUnsignedIntSetCC(CC)) { 12921 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12922 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12923 !DAG.MaskedValueIsZero(N->getOperand(1), 12924 APInt::getHighBitsSet(OpBits, OpBits-1))) 12925 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12926 : SDValue()); 12927 } else { 12928 // This is neither a signed nor an unsigned comparison, just make sure 12929 // that the high bits are equal. 12930 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12931 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12932 12933 // We don't really care about what is known about the first bit (if 12934 // anything), so clear it in all masks prior to comparing them. 12935 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12936 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12937 12938 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12939 return SDValue(); 12940 } 12941 } 12942 12943 // We now know that the higher-order bits are irrelevant, we just need to 12944 // make sure that all of the intermediate operations are bit operations, and 12945 // all inputs are extensions. 12946 if (N->getOperand(0).getOpcode() != ISD::AND && 12947 N->getOperand(0).getOpcode() != ISD::OR && 12948 N->getOperand(0).getOpcode() != ISD::XOR && 12949 N->getOperand(0).getOpcode() != ISD::SELECT && 12950 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12951 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12952 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12953 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12954 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12955 return SDValue(); 12956 12957 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12958 N->getOperand(1).getOpcode() != ISD::AND && 12959 N->getOperand(1).getOpcode() != ISD::OR && 12960 N->getOperand(1).getOpcode() != ISD::XOR && 12961 N->getOperand(1).getOpcode() != ISD::SELECT && 12962 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12963 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12964 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12965 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12966 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12967 return SDValue(); 12968 12969 SmallVector<SDValue, 4> Inputs; 12970 SmallVector<SDValue, 8> BinOps, PromOps; 12971 SmallPtrSet<SDNode *, 16> Visited; 12972 12973 for (unsigned i = 0; i < 2; ++i) { 12974 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12975 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12976 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12977 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12978 isa<ConstantSDNode>(N->getOperand(i))) 12979 Inputs.push_back(N->getOperand(i)); 12980 else 12981 BinOps.push_back(N->getOperand(i)); 12982 12983 if (N->getOpcode() == ISD::TRUNCATE) 12984 break; 12985 } 12986 12987 // Visit all inputs, collect all binary operations (and, or, xor and 12988 // select) that are all fed by extensions. 12989 while (!BinOps.empty()) { 12990 SDValue BinOp = BinOps.back(); 12991 BinOps.pop_back(); 12992 12993 if (!Visited.insert(BinOp.getNode()).second) 12994 continue; 12995 12996 PromOps.push_back(BinOp); 12997 12998 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12999 // The condition of the select is not promoted. 13000 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13001 continue; 13002 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13003 continue; 13004 13005 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13006 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13007 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13008 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13009 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13010 Inputs.push_back(BinOp.getOperand(i)); 13011 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13012 BinOp.getOperand(i).getOpcode() == ISD::OR || 13013 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13014 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13015 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13016 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13017 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13018 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13019 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13020 BinOps.push_back(BinOp.getOperand(i)); 13021 } else { 13022 // We have an input that is not an extension or another binary 13023 // operation; we'll abort this transformation. 13024 return SDValue(); 13025 } 13026 } 13027 } 13028 13029 // Make sure that this is a self-contained cluster of operations (which 13030 // is not quite the same thing as saying that everything has only one 13031 // use). 13032 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13033 if (isa<ConstantSDNode>(Inputs[i])) 13034 continue; 13035 13036 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13037 UE = Inputs[i].getNode()->use_end(); 13038 UI != UE; ++UI) { 13039 SDNode *User = *UI; 13040 if (User != N && !Visited.count(User)) 13041 return SDValue(); 13042 13043 // Make sure that we're not going to promote the non-output-value 13044 // operand(s) or SELECT or SELECT_CC. 13045 // FIXME: Although we could sometimes handle this, and it does occur in 13046 // practice that one of the condition inputs to the select is also one of 13047 // the outputs, we currently can't deal with this. 13048 if (User->getOpcode() == ISD::SELECT) { 13049 if (User->getOperand(0) == Inputs[i]) 13050 return SDValue(); 13051 } else if (User->getOpcode() == ISD::SELECT_CC) { 13052 if (User->getOperand(0) == Inputs[i] || 13053 User->getOperand(1) == Inputs[i]) 13054 return SDValue(); 13055 } 13056 } 13057 } 13058 13059 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13060 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13061 UE = PromOps[i].getNode()->use_end(); 13062 UI != UE; ++UI) { 13063 SDNode *User = *UI; 13064 if (User != N && !Visited.count(User)) 13065 return SDValue(); 13066 13067 // Make sure that we're not going to promote the non-output-value 13068 // operand(s) or SELECT or SELECT_CC. 13069 // FIXME: Although we could sometimes handle this, and it does occur in 13070 // practice that one of the condition inputs to the select is also one of 13071 // the outputs, we currently can't deal with this. 13072 if (User->getOpcode() == ISD::SELECT) { 13073 if (User->getOperand(0) == PromOps[i]) 13074 return SDValue(); 13075 } else if (User->getOpcode() == ISD::SELECT_CC) { 13076 if (User->getOperand(0) == PromOps[i] || 13077 User->getOperand(1) == PromOps[i]) 13078 return SDValue(); 13079 } 13080 } 13081 } 13082 13083 // Replace all inputs with the extension operand. 13084 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13085 // Constants may have users outside the cluster of to-be-promoted nodes, 13086 // and so we need to replace those as we do the promotions. 13087 if (isa<ConstantSDNode>(Inputs[i])) 13088 continue; 13089 else 13090 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13091 } 13092 13093 std::list<HandleSDNode> PromOpHandles; 13094 for (auto &PromOp : PromOps) 13095 PromOpHandles.emplace_back(PromOp); 13096 13097 // Replace all operations (these are all the same, but have a different 13098 // (i1) return type). DAG.getNode will validate that the types of 13099 // a binary operator match, so go through the list in reverse so that 13100 // we've likely promoted both operands first. Any intermediate truncations or 13101 // extensions disappear. 13102 while (!PromOpHandles.empty()) { 13103 SDValue PromOp = PromOpHandles.back().getValue(); 13104 PromOpHandles.pop_back(); 13105 13106 if (PromOp.getOpcode() == ISD::TRUNCATE || 13107 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13108 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13109 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13110 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13111 PromOp.getOperand(0).getValueType() != MVT::i1) { 13112 // The operand is not yet ready (see comment below). 13113 PromOpHandles.emplace_front(PromOp); 13114 continue; 13115 } 13116 13117 SDValue RepValue = PromOp.getOperand(0); 13118 if (isa<ConstantSDNode>(RepValue)) 13119 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13120 13121 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13122 continue; 13123 } 13124 13125 unsigned C; 13126 switch (PromOp.getOpcode()) { 13127 default: C = 0; break; 13128 case ISD::SELECT: C = 1; break; 13129 case ISD::SELECT_CC: C = 2; break; 13130 } 13131 13132 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13133 PromOp.getOperand(C).getValueType() != MVT::i1) || 13134 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13135 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13136 // The to-be-promoted operands of this node have not yet been 13137 // promoted (this should be rare because we're going through the 13138 // list backward, but if one of the operands has several users in 13139 // this cluster of to-be-promoted nodes, it is possible). 13140 PromOpHandles.emplace_front(PromOp); 13141 continue; 13142 } 13143 13144 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13145 PromOp.getNode()->op_end()); 13146 13147 // If there are any constant inputs, make sure they're replaced now. 13148 for (unsigned i = 0; i < 2; ++i) 13149 if (isa<ConstantSDNode>(Ops[C+i])) 13150 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13151 13152 DAG.ReplaceAllUsesOfValueWith(PromOp, 13153 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13154 } 13155 13156 // Now we're left with the initial truncation itself. 13157 if (N->getOpcode() == ISD::TRUNCATE) 13158 return N->getOperand(0); 13159 13160 // Otherwise, this is a comparison. The operands to be compared have just 13161 // changed type (to i1), but everything else is the same. 13162 return SDValue(N, 0); 13163 } 13164 13165 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13166 DAGCombinerInfo &DCI) const { 13167 SelectionDAG &DAG = DCI.DAG; 13168 SDLoc dl(N); 13169 13170 // If we're tracking CR bits, we need to be careful that we don't have: 13171 // zext(binary-ops(trunc(x), trunc(y))) 13172 // or 13173 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13174 // such that we're unnecessarily moving things into CR bits that can more 13175 // efficiently stay in GPRs. Note that if we're not certain that the high 13176 // bits are set as required by the final extension, we still may need to do 13177 // some masking to get the proper behavior. 13178 13179 // This same functionality is important on PPC64 when dealing with 13180 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13181 // the return values of functions. Because it is so similar, it is handled 13182 // here as well. 13183 13184 if (N->getValueType(0) != MVT::i32 && 13185 N->getValueType(0) != MVT::i64) 13186 return SDValue(); 13187 13188 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13189 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13190 return SDValue(); 13191 13192 if (N->getOperand(0).getOpcode() != ISD::AND && 13193 N->getOperand(0).getOpcode() != ISD::OR && 13194 N->getOperand(0).getOpcode() != ISD::XOR && 13195 N->getOperand(0).getOpcode() != ISD::SELECT && 13196 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13197 return SDValue(); 13198 13199 SmallVector<SDValue, 4> Inputs; 13200 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13201 SmallPtrSet<SDNode *, 16> Visited; 13202 13203 // Visit all inputs, collect all binary operations (and, or, xor and 13204 // select) that are all fed by truncations. 13205 while (!BinOps.empty()) { 13206 SDValue BinOp = BinOps.back(); 13207 BinOps.pop_back(); 13208 13209 if (!Visited.insert(BinOp.getNode()).second) 13210 continue; 13211 13212 PromOps.push_back(BinOp); 13213 13214 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13215 // The condition of the select is not promoted. 13216 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13217 continue; 13218 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13219 continue; 13220 13221 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13222 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13223 Inputs.push_back(BinOp.getOperand(i)); 13224 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13225 BinOp.getOperand(i).getOpcode() == ISD::OR || 13226 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13227 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13228 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13229 BinOps.push_back(BinOp.getOperand(i)); 13230 } else { 13231 // We have an input that is not a truncation or another binary 13232 // operation; we'll abort this transformation. 13233 return SDValue(); 13234 } 13235 } 13236 } 13237 13238 // The operands of a select that must be truncated when the select is 13239 // promoted because the operand is actually part of the to-be-promoted set. 13240 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13241 13242 // Make sure that this is a self-contained cluster of operations (which 13243 // is not quite the same thing as saying that everything has only one 13244 // use). 13245 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13246 if (isa<ConstantSDNode>(Inputs[i])) 13247 continue; 13248 13249 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13250 UE = Inputs[i].getNode()->use_end(); 13251 UI != UE; ++UI) { 13252 SDNode *User = *UI; 13253 if (User != N && !Visited.count(User)) 13254 return SDValue(); 13255 13256 // If we're going to promote the non-output-value operand(s) or SELECT or 13257 // SELECT_CC, record them for truncation. 13258 if (User->getOpcode() == ISD::SELECT) { 13259 if (User->getOperand(0) == Inputs[i]) 13260 SelectTruncOp[0].insert(std::make_pair(User, 13261 User->getOperand(0).getValueType())); 13262 } else if (User->getOpcode() == ISD::SELECT_CC) { 13263 if (User->getOperand(0) == Inputs[i]) 13264 SelectTruncOp[0].insert(std::make_pair(User, 13265 User->getOperand(0).getValueType())); 13266 if (User->getOperand(1) == Inputs[i]) 13267 SelectTruncOp[1].insert(std::make_pair(User, 13268 User->getOperand(1).getValueType())); 13269 } 13270 } 13271 } 13272 13273 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13274 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13275 UE = PromOps[i].getNode()->use_end(); 13276 UI != UE; ++UI) { 13277 SDNode *User = *UI; 13278 if (User != N && !Visited.count(User)) 13279 return SDValue(); 13280 13281 // If we're going to promote the non-output-value operand(s) or SELECT or 13282 // SELECT_CC, record them for truncation. 13283 if (User->getOpcode() == ISD::SELECT) { 13284 if (User->getOperand(0) == PromOps[i]) 13285 SelectTruncOp[0].insert(std::make_pair(User, 13286 User->getOperand(0).getValueType())); 13287 } else if (User->getOpcode() == ISD::SELECT_CC) { 13288 if (User->getOperand(0) == PromOps[i]) 13289 SelectTruncOp[0].insert(std::make_pair(User, 13290 User->getOperand(0).getValueType())); 13291 if (User->getOperand(1) == PromOps[i]) 13292 SelectTruncOp[1].insert(std::make_pair(User, 13293 User->getOperand(1).getValueType())); 13294 } 13295 } 13296 } 13297 13298 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13299 bool ReallyNeedsExt = false; 13300 if (N->getOpcode() != ISD::ANY_EXTEND) { 13301 // If all of the inputs are not already sign/zero extended, then 13302 // we'll still need to do that at the end. 13303 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13304 if (isa<ConstantSDNode>(Inputs[i])) 13305 continue; 13306 13307 unsigned OpBits = 13308 Inputs[i].getOperand(0).getValueSizeInBits(); 13309 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13310 13311 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13312 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13313 APInt::getHighBitsSet(OpBits, 13314 OpBits-PromBits))) || 13315 (N->getOpcode() == ISD::SIGN_EXTEND && 13316 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13317 (OpBits-(PromBits-1)))) { 13318 ReallyNeedsExt = true; 13319 break; 13320 } 13321 } 13322 } 13323 13324 // Replace all inputs, either with the truncation operand, or a 13325 // truncation or extension to the final output type. 13326 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13327 // Constant inputs need to be replaced with the to-be-promoted nodes that 13328 // use them because they might have users outside of the cluster of 13329 // promoted nodes. 13330 if (isa<ConstantSDNode>(Inputs[i])) 13331 continue; 13332 13333 SDValue InSrc = Inputs[i].getOperand(0); 13334 if (Inputs[i].getValueType() == N->getValueType(0)) 13335 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13336 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13337 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13338 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13339 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13340 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13341 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13342 else 13343 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13344 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13345 } 13346 13347 std::list<HandleSDNode> PromOpHandles; 13348 for (auto &PromOp : PromOps) 13349 PromOpHandles.emplace_back(PromOp); 13350 13351 // Replace all operations (these are all the same, but have a different 13352 // (promoted) return type). DAG.getNode will validate that the types of 13353 // a binary operator match, so go through the list in reverse so that 13354 // we've likely promoted both operands first. 13355 while (!PromOpHandles.empty()) { 13356 SDValue PromOp = PromOpHandles.back().getValue(); 13357 PromOpHandles.pop_back(); 13358 13359 unsigned C; 13360 switch (PromOp.getOpcode()) { 13361 default: C = 0; break; 13362 case ISD::SELECT: C = 1; break; 13363 case ISD::SELECT_CC: C = 2; break; 13364 } 13365 13366 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13367 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13368 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13369 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13370 // The to-be-promoted operands of this node have not yet been 13371 // promoted (this should be rare because we're going through the 13372 // list backward, but if one of the operands has several users in 13373 // this cluster of to-be-promoted nodes, it is possible). 13374 PromOpHandles.emplace_front(PromOp); 13375 continue; 13376 } 13377 13378 // For SELECT and SELECT_CC nodes, we do a similar check for any 13379 // to-be-promoted comparison inputs. 13380 if (PromOp.getOpcode() == ISD::SELECT || 13381 PromOp.getOpcode() == ISD::SELECT_CC) { 13382 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13383 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13384 (SelectTruncOp[1].count(PromOp.getNode()) && 13385 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13386 PromOpHandles.emplace_front(PromOp); 13387 continue; 13388 } 13389 } 13390 13391 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13392 PromOp.getNode()->op_end()); 13393 13394 // If this node has constant inputs, then they'll need to be promoted here. 13395 for (unsigned i = 0; i < 2; ++i) { 13396 if (!isa<ConstantSDNode>(Ops[C+i])) 13397 continue; 13398 if (Ops[C+i].getValueType() == N->getValueType(0)) 13399 continue; 13400 13401 if (N->getOpcode() == ISD::SIGN_EXTEND) 13402 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13403 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13404 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13405 else 13406 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13407 } 13408 13409 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13410 // truncate them again to the original value type. 13411 if (PromOp.getOpcode() == ISD::SELECT || 13412 PromOp.getOpcode() == ISD::SELECT_CC) { 13413 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13414 if (SI0 != SelectTruncOp[0].end()) 13415 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13416 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13417 if (SI1 != SelectTruncOp[1].end()) 13418 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13419 } 13420 13421 DAG.ReplaceAllUsesOfValueWith(PromOp, 13422 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13423 } 13424 13425 // Now we're left with the initial extension itself. 13426 if (!ReallyNeedsExt) 13427 return N->getOperand(0); 13428 13429 // To zero extend, just mask off everything except for the first bit (in the 13430 // i1 case). 13431 if (N->getOpcode() == ISD::ZERO_EXTEND) 13432 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13433 DAG.getConstant(APInt::getLowBitsSet( 13434 N->getValueSizeInBits(0), PromBits), 13435 dl, N->getValueType(0))); 13436 13437 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13438 "Invalid extension type"); 13439 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13440 SDValue ShiftCst = 13441 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13442 return DAG.getNode( 13443 ISD::SRA, dl, N->getValueType(0), 13444 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13445 ShiftCst); 13446 } 13447 13448 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13449 DAGCombinerInfo &DCI) const { 13450 assert(N->getOpcode() == ISD::SETCC && 13451 "Should be called with a SETCC node"); 13452 13453 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13454 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13455 SDValue LHS = N->getOperand(0); 13456 SDValue RHS = N->getOperand(1); 13457 13458 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13459 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13460 LHS.hasOneUse()) 13461 std::swap(LHS, RHS); 13462 13463 // x == 0-y --> x+y == 0 13464 // x != 0-y --> x+y != 0 13465 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13466 RHS.hasOneUse()) { 13467 SDLoc DL(N); 13468 SelectionDAG &DAG = DCI.DAG; 13469 EVT VT = N->getValueType(0); 13470 EVT OpVT = LHS.getValueType(); 13471 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13472 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13473 } 13474 } 13475 13476 return DAGCombineTruncBoolExt(N, DCI); 13477 } 13478 13479 // Is this an extending load from an f32 to an f64? 13480 static bool isFPExtLoad(SDValue Op) { 13481 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13482 return LD->getExtensionType() == ISD::EXTLOAD && 13483 Op.getValueType() == MVT::f64; 13484 return false; 13485 } 13486 13487 /// Reduces the number of fp-to-int conversion when building a vector. 13488 /// 13489 /// If this vector is built out of floating to integer conversions, 13490 /// transform it to a vector built out of floating point values followed by a 13491 /// single floating to integer conversion of the vector. 13492 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13493 /// becomes (fptosi (build_vector ($A, $B, ...))) 13494 SDValue PPCTargetLowering:: 13495 combineElementTruncationToVectorTruncation(SDNode *N, 13496 DAGCombinerInfo &DCI) const { 13497 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13498 "Should be called with a BUILD_VECTOR node"); 13499 13500 SelectionDAG &DAG = DCI.DAG; 13501 SDLoc dl(N); 13502 13503 SDValue FirstInput = N->getOperand(0); 13504 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13505 "The input operand must be an fp-to-int conversion."); 13506 13507 // This combine happens after legalization so the fp_to_[su]i nodes are 13508 // already converted to PPCSISD nodes. 13509 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13510 if (FirstConversion == PPCISD::FCTIDZ || 13511 FirstConversion == PPCISD::FCTIDUZ || 13512 FirstConversion == PPCISD::FCTIWZ || 13513 FirstConversion == PPCISD::FCTIWUZ) { 13514 bool IsSplat = true; 13515 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13516 FirstConversion == PPCISD::FCTIWUZ; 13517 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13518 SmallVector<SDValue, 4> Ops; 13519 EVT TargetVT = N->getValueType(0); 13520 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13521 SDValue NextOp = N->getOperand(i); 13522 if (NextOp.getOpcode() != PPCISD::MFVSR) 13523 return SDValue(); 13524 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13525 if (NextConversion != FirstConversion) 13526 return SDValue(); 13527 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13528 // This is not valid if the input was originally double precision. It is 13529 // also not profitable to do unless this is an extending load in which 13530 // case doing this combine will allow us to combine consecutive loads. 13531 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13532 return SDValue(); 13533 if (N->getOperand(i) != FirstInput) 13534 IsSplat = false; 13535 } 13536 13537 // If this is a splat, we leave it as-is since there will be only a single 13538 // fp-to-int conversion followed by a splat of the integer. This is better 13539 // for 32-bit and smaller ints and neutral for 64-bit ints. 13540 if (IsSplat) 13541 return SDValue(); 13542 13543 // Now that we know we have the right type of node, get its operands 13544 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13545 SDValue In = N->getOperand(i).getOperand(0); 13546 if (Is32Bit) { 13547 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13548 // here, we know that all inputs are extending loads so this is safe). 13549 if (In.isUndef()) 13550 Ops.push_back(DAG.getUNDEF(SrcVT)); 13551 else { 13552 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13553 MVT::f32, In.getOperand(0), 13554 DAG.getIntPtrConstant(1, dl)); 13555 Ops.push_back(Trunc); 13556 } 13557 } else 13558 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13559 } 13560 13561 unsigned Opcode; 13562 if (FirstConversion == PPCISD::FCTIDZ || 13563 FirstConversion == PPCISD::FCTIWZ) 13564 Opcode = ISD::FP_TO_SINT; 13565 else 13566 Opcode = ISD::FP_TO_UINT; 13567 13568 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13569 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13570 return DAG.getNode(Opcode, dl, TargetVT, BV); 13571 } 13572 return SDValue(); 13573 } 13574 13575 /// Reduce the number of loads when building a vector. 13576 /// 13577 /// Building a vector out of multiple loads can be converted to a load 13578 /// of the vector type if the loads are consecutive. If the loads are 13579 /// consecutive but in descending order, a shuffle is added at the end 13580 /// to reorder the vector. 13581 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13582 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13583 "Should be called with a BUILD_VECTOR node"); 13584 13585 SDLoc dl(N); 13586 13587 // Return early for non byte-sized type, as they can't be consecutive. 13588 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13589 return SDValue(); 13590 13591 bool InputsAreConsecutiveLoads = true; 13592 bool InputsAreReverseConsecutive = true; 13593 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13594 SDValue FirstInput = N->getOperand(0); 13595 bool IsRoundOfExtLoad = false; 13596 13597 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13598 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13599 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13600 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13601 } 13602 // Not a build vector of (possibly fp_rounded) loads. 13603 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13604 N->getNumOperands() == 1) 13605 return SDValue(); 13606 13607 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13608 // If any inputs are fp_round(extload), they all must be. 13609 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13610 return SDValue(); 13611 13612 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13613 N->getOperand(i); 13614 if (NextInput.getOpcode() != ISD::LOAD) 13615 return SDValue(); 13616 13617 SDValue PreviousInput = 13618 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13619 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13620 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13621 13622 // If any inputs are fp_round(extload), they all must be. 13623 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13624 return SDValue(); 13625 13626 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13627 InputsAreConsecutiveLoads = false; 13628 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13629 InputsAreReverseConsecutive = false; 13630 13631 // Exit early if the loads are neither consecutive nor reverse consecutive. 13632 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13633 return SDValue(); 13634 } 13635 13636 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13637 "The loads cannot be both consecutive and reverse consecutive."); 13638 13639 SDValue FirstLoadOp = 13640 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13641 SDValue LastLoadOp = 13642 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13643 N->getOperand(N->getNumOperands()-1); 13644 13645 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13646 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13647 if (InputsAreConsecutiveLoads) { 13648 assert(LD1 && "Input needs to be a LoadSDNode."); 13649 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13650 LD1->getBasePtr(), LD1->getPointerInfo(), 13651 LD1->getAlignment()); 13652 } 13653 if (InputsAreReverseConsecutive) { 13654 assert(LDL && "Input needs to be a LoadSDNode."); 13655 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13656 LDL->getBasePtr(), LDL->getPointerInfo(), 13657 LDL->getAlignment()); 13658 SmallVector<int, 16> Ops; 13659 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13660 Ops.push_back(i); 13661 13662 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13663 DAG.getUNDEF(N->getValueType(0)), Ops); 13664 } 13665 return SDValue(); 13666 } 13667 13668 // This function adds the required vector_shuffle needed to get 13669 // the elements of the vector extract in the correct position 13670 // as specified by the CorrectElems encoding. 13671 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13672 SDValue Input, uint64_t Elems, 13673 uint64_t CorrectElems) { 13674 SDLoc dl(N); 13675 13676 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13677 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13678 13679 // Knowing the element indices being extracted from the original 13680 // vector and the order in which they're being inserted, just put 13681 // them at element indices required for the instruction. 13682 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13683 if (DAG.getDataLayout().isLittleEndian()) 13684 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13685 else 13686 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13687 CorrectElems = CorrectElems >> 8; 13688 Elems = Elems >> 8; 13689 } 13690 13691 SDValue Shuffle = 13692 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13693 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13694 13695 EVT VT = N->getValueType(0); 13696 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13697 13698 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13699 Input.getValueType().getVectorElementType(), 13700 VT.getVectorNumElements()); 13701 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13702 DAG.getValueType(ExtVT)); 13703 } 13704 13705 // Look for build vector patterns where input operands come from sign 13706 // extended vector_extract elements of specific indices. If the correct indices 13707 // aren't used, add a vector shuffle to fix up the indices and create 13708 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13709 // during instruction selection. 13710 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13711 // This array encodes the indices that the vector sign extend instructions 13712 // extract from when extending from one type to another for both BE and LE. 13713 // The right nibble of each byte corresponds to the LE incides. 13714 // and the left nibble of each byte corresponds to the BE incides. 13715 // For example: 0x3074B8FC byte->word 13716 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13717 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13718 // For example: 0x000070F8 byte->double word 13719 // For LE: the allowed indices are: 0x0,0x8 13720 // For BE: the allowed indices are: 0x7,0xF 13721 uint64_t TargetElems[] = { 13722 0x3074B8FC, // b->w 13723 0x000070F8, // b->d 13724 0x10325476, // h->w 13725 0x00003074, // h->d 13726 0x00001032, // w->d 13727 }; 13728 13729 uint64_t Elems = 0; 13730 int Index; 13731 SDValue Input; 13732 13733 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13734 if (!Op) 13735 return false; 13736 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13737 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13738 return false; 13739 13740 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13741 // of the right width. 13742 SDValue Extract = Op.getOperand(0); 13743 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13744 Extract = Extract.getOperand(0); 13745 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13746 return false; 13747 13748 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13749 if (!ExtOp) 13750 return false; 13751 13752 Index = ExtOp->getZExtValue(); 13753 if (Input && Input != Extract.getOperand(0)) 13754 return false; 13755 13756 if (!Input) 13757 Input = Extract.getOperand(0); 13758 13759 Elems = Elems << 8; 13760 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13761 Elems |= Index; 13762 13763 return true; 13764 }; 13765 13766 // If the build vector operands aren't sign extended vector extracts, 13767 // of the same input vector, then return. 13768 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13769 if (!isSExtOfVecExtract(N->getOperand(i))) { 13770 return SDValue(); 13771 } 13772 } 13773 13774 // If the vector extract indicies are not correct, add the appropriate 13775 // vector_shuffle. 13776 int TgtElemArrayIdx; 13777 int InputSize = Input.getValueType().getScalarSizeInBits(); 13778 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13779 if (InputSize + OutputSize == 40) 13780 TgtElemArrayIdx = 0; 13781 else if (InputSize + OutputSize == 72) 13782 TgtElemArrayIdx = 1; 13783 else if (InputSize + OutputSize == 48) 13784 TgtElemArrayIdx = 2; 13785 else if (InputSize + OutputSize == 80) 13786 TgtElemArrayIdx = 3; 13787 else if (InputSize + OutputSize == 96) 13788 TgtElemArrayIdx = 4; 13789 else 13790 return SDValue(); 13791 13792 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13793 CorrectElems = DAG.getDataLayout().isLittleEndian() 13794 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13795 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13796 if (Elems != CorrectElems) { 13797 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13798 } 13799 13800 // Regular lowering will catch cases where a shuffle is not needed. 13801 return SDValue(); 13802 } 13803 13804 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13805 DAGCombinerInfo &DCI) const { 13806 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13807 "Should be called with a BUILD_VECTOR node"); 13808 13809 SelectionDAG &DAG = DCI.DAG; 13810 SDLoc dl(N); 13811 13812 if (!Subtarget.hasVSX()) 13813 return SDValue(); 13814 13815 // The target independent DAG combiner will leave a build_vector of 13816 // float-to-int conversions intact. We can generate MUCH better code for 13817 // a float-to-int conversion of a vector of floats. 13818 SDValue FirstInput = N->getOperand(0); 13819 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13820 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13821 if (Reduced) 13822 return Reduced; 13823 } 13824 13825 // If we're building a vector out of consecutive loads, just load that 13826 // vector type. 13827 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13828 if (Reduced) 13829 return Reduced; 13830 13831 // If we're building a vector out of extended elements from another vector 13832 // we have P9 vector integer extend instructions. The code assumes legal 13833 // input types (i.e. it can't handle things like v4i16) so do not run before 13834 // legalization. 13835 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13836 Reduced = combineBVOfVecSExt(N, DAG); 13837 if (Reduced) 13838 return Reduced; 13839 } 13840 13841 13842 if (N->getValueType(0) != MVT::v2f64) 13843 return SDValue(); 13844 13845 // Looking for: 13846 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13847 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13848 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13849 return SDValue(); 13850 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13851 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13852 return SDValue(); 13853 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13854 return SDValue(); 13855 13856 SDValue Ext1 = FirstInput.getOperand(0); 13857 SDValue Ext2 = N->getOperand(1).getOperand(0); 13858 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13859 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13860 return SDValue(); 13861 13862 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13863 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13864 if (!Ext1Op || !Ext2Op) 13865 return SDValue(); 13866 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13867 Ext1.getOperand(0) != Ext2.getOperand(0)) 13868 return SDValue(); 13869 13870 int FirstElem = Ext1Op->getZExtValue(); 13871 int SecondElem = Ext2Op->getZExtValue(); 13872 int SubvecIdx; 13873 if (FirstElem == 0 && SecondElem == 1) 13874 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13875 else if (FirstElem == 2 && SecondElem == 3) 13876 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13877 else 13878 return SDValue(); 13879 13880 SDValue SrcVec = Ext1.getOperand(0); 13881 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13882 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13883 return DAG.getNode(NodeType, dl, MVT::v2f64, 13884 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13885 } 13886 13887 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13888 DAGCombinerInfo &DCI) const { 13889 assert((N->getOpcode() == ISD::SINT_TO_FP || 13890 N->getOpcode() == ISD::UINT_TO_FP) && 13891 "Need an int -> FP conversion node here"); 13892 13893 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13894 return SDValue(); 13895 13896 SelectionDAG &DAG = DCI.DAG; 13897 SDLoc dl(N); 13898 SDValue Op(N, 0); 13899 13900 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13901 // from the hardware. 13902 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13903 return SDValue(); 13904 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13905 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13906 return SDValue(); 13907 13908 SDValue FirstOperand(Op.getOperand(0)); 13909 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13910 (FirstOperand.getValueType() == MVT::i8 || 13911 FirstOperand.getValueType() == MVT::i16); 13912 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13913 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13914 bool DstDouble = Op.getValueType() == MVT::f64; 13915 unsigned ConvOp = Signed ? 13916 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13917 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13918 SDValue WidthConst = 13919 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13920 dl, false); 13921 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13922 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13923 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13924 DAG.getVTList(MVT::f64, MVT::Other), 13925 Ops, MVT::i8, LDN->getMemOperand()); 13926 13927 // For signed conversion, we need to sign-extend the value in the VSR 13928 if (Signed) { 13929 SDValue ExtOps[] = { Ld, WidthConst }; 13930 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13931 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13932 } else 13933 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13934 } 13935 13936 13937 // For i32 intermediate values, unfortunately, the conversion functions 13938 // leave the upper 32 bits of the value are undefined. Within the set of 13939 // scalar instructions, we have no method for zero- or sign-extending the 13940 // value. Thus, we cannot handle i32 intermediate values here. 13941 if (Op.getOperand(0).getValueType() == MVT::i32) 13942 return SDValue(); 13943 13944 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13945 "UINT_TO_FP is supported only with FPCVT"); 13946 13947 // If we have FCFIDS, then use it when converting to single-precision. 13948 // Otherwise, convert to double-precision and then round. 13949 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13950 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13951 : PPCISD::FCFIDS) 13952 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13953 : PPCISD::FCFID); 13954 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13955 ? MVT::f32 13956 : MVT::f64; 13957 13958 // If we're converting from a float, to an int, and back to a float again, 13959 // then we don't need the store/load pair at all. 13960 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13961 Subtarget.hasFPCVT()) || 13962 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13963 SDValue Src = Op.getOperand(0).getOperand(0); 13964 if (Src.getValueType() == MVT::f32) { 13965 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13966 DCI.AddToWorklist(Src.getNode()); 13967 } else if (Src.getValueType() != MVT::f64) { 13968 // Make sure that we don't pick up a ppc_fp128 source value. 13969 return SDValue(); 13970 } 13971 13972 unsigned FCTOp = 13973 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13974 PPCISD::FCTIDUZ; 13975 13976 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13977 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13978 13979 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13980 FP = DAG.getNode(ISD::FP_ROUND, dl, 13981 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13982 DCI.AddToWorklist(FP.getNode()); 13983 } 13984 13985 return FP; 13986 } 13987 13988 return SDValue(); 13989 } 13990 13991 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13992 // builtins) into loads with swaps. 13993 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13994 DAGCombinerInfo &DCI) const { 13995 SelectionDAG &DAG = DCI.DAG; 13996 SDLoc dl(N); 13997 SDValue Chain; 13998 SDValue Base; 13999 MachineMemOperand *MMO; 14000 14001 switch (N->getOpcode()) { 14002 default: 14003 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14004 case ISD::LOAD: { 14005 LoadSDNode *LD = cast<LoadSDNode>(N); 14006 Chain = LD->getChain(); 14007 Base = LD->getBasePtr(); 14008 MMO = LD->getMemOperand(); 14009 // If the MMO suggests this isn't a load of a full vector, leave 14010 // things alone. For a built-in, we have to make the change for 14011 // correctness, so if there is a size problem that will be a bug. 14012 if (MMO->getSize() < 16) 14013 return SDValue(); 14014 break; 14015 } 14016 case ISD::INTRINSIC_W_CHAIN: { 14017 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14018 Chain = Intrin->getChain(); 14019 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14020 // us what we want. Get operand 2 instead. 14021 Base = Intrin->getOperand(2); 14022 MMO = Intrin->getMemOperand(); 14023 break; 14024 } 14025 } 14026 14027 MVT VecTy = N->getValueType(0).getSimpleVT(); 14028 14029 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14030 // aligned and the type is a vector with elements up to 4 bytes 14031 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14032 VecTy.getScalarSizeInBits() <= 32) { 14033 return SDValue(); 14034 } 14035 14036 SDValue LoadOps[] = { Chain, Base }; 14037 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14038 DAG.getVTList(MVT::v2f64, MVT::Other), 14039 LoadOps, MVT::v2f64, MMO); 14040 14041 DCI.AddToWorklist(Load.getNode()); 14042 Chain = Load.getValue(1); 14043 SDValue Swap = DAG.getNode( 14044 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14045 DCI.AddToWorklist(Swap.getNode()); 14046 14047 // Add a bitcast if the resulting load type doesn't match v2f64. 14048 if (VecTy != MVT::v2f64) { 14049 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14050 DCI.AddToWorklist(N.getNode()); 14051 // Package {bitcast value, swap's chain} to match Load's shape. 14052 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14053 N, Swap.getValue(1)); 14054 } 14055 14056 return Swap; 14057 } 14058 14059 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14060 // builtins) into stores with swaps. 14061 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14062 DAGCombinerInfo &DCI) const { 14063 SelectionDAG &DAG = DCI.DAG; 14064 SDLoc dl(N); 14065 SDValue Chain; 14066 SDValue Base; 14067 unsigned SrcOpnd; 14068 MachineMemOperand *MMO; 14069 14070 switch (N->getOpcode()) { 14071 default: 14072 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14073 case ISD::STORE: { 14074 StoreSDNode *ST = cast<StoreSDNode>(N); 14075 Chain = ST->getChain(); 14076 Base = ST->getBasePtr(); 14077 MMO = ST->getMemOperand(); 14078 SrcOpnd = 1; 14079 // If the MMO suggests this isn't a store of a full vector, leave 14080 // things alone. For a built-in, we have to make the change for 14081 // correctness, so if there is a size problem that will be a bug. 14082 if (MMO->getSize() < 16) 14083 return SDValue(); 14084 break; 14085 } 14086 case ISD::INTRINSIC_VOID: { 14087 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14088 Chain = Intrin->getChain(); 14089 // Intrin->getBasePtr() oddly does not get what we want. 14090 Base = Intrin->getOperand(3); 14091 MMO = Intrin->getMemOperand(); 14092 SrcOpnd = 2; 14093 break; 14094 } 14095 } 14096 14097 SDValue Src = N->getOperand(SrcOpnd); 14098 MVT VecTy = Src.getValueType().getSimpleVT(); 14099 14100 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14101 // aligned and the type is a vector with elements up to 4 bytes 14102 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14103 VecTy.getScalarSizeInBits() <= 32) { 14104 return SDValue(); 14105 } 14106 14107 // All stores are done as v2f64 and possible bit cast. 14108 if (VecTy != MVT::v2f64) { 14109 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14110 DCI.AddToWorklist(Src.getNode()); 14111 } 14112 14113 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14114 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14115 DCI.AddToWorklist(Swap.getNode()); 14116 Chain = Swap.getValue(1); 14117 SDValue StoreOps[] = { Chain, Swap, Base }; 14118 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14119 DAG.getVTList(MVT::Other), 14120 StoreOps, VecTy, MMO); 14121 DCI.AddToWorklist(Store.getNode()); 14122 return Store; 14123 } 14124 14125 // Handle DAG combine for STORE (FP_TO_INT F). 14126 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14127 DAGCombinerInfo &DCI) const { 14128 14129 SelectionDAG &DAG = DCI.DAG; 14130 SDLoc dl(N); 14131 unsigned Opcode = N->getOperand(1).getOpcode(); 14132 14133 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14134 && "Not a FP_TO_INT Instruction!"); 14135 14136 SDValue Val = N->getOperand(1).getOperand(0); 14137 EVT Op1VT = N->getOperand(1).getValueType(); 14138 EVT ResVT = Val.getValueType(); 14139 14140 // Floating point types smaller than 32 bits are not legal on Power. 14141 if (ResVT.getScalarSizeInBits() < 32) 14142 return SDValue(); 14143 14144 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14145 bool ValidTypeForStoreFltAsInt = 14146 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14147 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14148 14149 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14150 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14151 return SDValue(); 14152 14153 // Extend f32 values to f64 14154 if (ResVT.getScalarSizeInBits() == 32) { 14155 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14156 DCI.AddToWorklist(Val.getNode()); 14157 } 14158 14159 // Set signed or unsigned conversion opcode. 14160 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14161 PPCISD::FP_TO_SINT_IN_VSR : 14162 PPCISD::FP_TO_UINT_IN_VSR; 14163 14164 Val = DAG.getNode(ConvOpcode, 14165 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14166 DCI.AddToWorklist(Val.getNode()); 14167 14168 // Set number of bytes being converted. 14169 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14170 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14171 DAG.getIntPtrConstant(ByteSize, dl, false), 14172 DAG.getValueType(Op1VT) }; 14173 14174 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14175 DAG.getVTList(MVT::Other), Ops, 14176 cast<StoreSDNode>(N)->getMemoryVT(), 14177 cast<StoreSDNode>(N)->getMemOperand()); 14178 14179 DCI.AddToWorklist(Val.getNode()); 14180 return Val; 14181 } 14182 14183 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14184 // Check that the source of the element keeps flipping 14185 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14186 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14187 for (int i = 1, e = Mask.size(); i < e; i++) { 14188 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14189 return false; 14190 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14191 return false; 14192 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14193 } 14194 return true; 14195 } 14196 14197 static bool isSplatBV(SDValue Op) { 14198 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14199 return false; 14200 SDValue FirstOp; 14201 14202 // Find first non-undef input. 14203 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14204 FirstOp = Op.getOperand(i); 14205 if (!FirstOp.isUndef()) 14206 break; 14207 } 14208 14209 // All inputs are undef or the same as the first non-undef input. 14210 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14211 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14212 return false; 14213 return true; 14214 } 14215 14216 static SDValue isScalarToVec(SDValue Op) { 14217 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14218 return Op; 14219 if (Op.getOpcode() != ISD::BITCAST) 14220 return SDValue(); 14221 Op = Op.getOperand(0); 14222 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14223 return Op; 14224 return SDValue(); 14225 } 14226 14227 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14228 int LHSMaxIdx, int RHSMinIdx, 14229 int RHSMaxIdx, int HalfVec) { 14230 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14231 int Idx = ShuffV[i]; 14232 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14233 ShuffV[i] += HalfVec; 14234 } 14235 return; 14236 } 14237 14238 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14239 // the original is: 14240 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14241 // In such a case, just change the shuffle mask to extract the element 14242 // from the permuted index. 14243 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14244 SDLoc dl(OrigSToV); 14245 EVT VT = OrigSToV.getValueType(); 14246 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14247 "Expecting a SCALAR_TO_VECTOR here"); 14248 SDValue Input = OrigSToV.getOperand(0); 14249 14250 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14251 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14252 SDValue OrigVector = Input.getOperand(0); 14253 14254 // Can't handle non-const element indices or different vector types 14255 // for the input to the extract and the output of the scalar_to_vector. 14256 if (Idx && VT == OrigVector.getValueType()) { 14257 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14258 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14259 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14260 } 14261 } 14262 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14263 OrigSToV.getOperand(0)); 14264 } 14265 14266 // On little endian subtargets, combine shuffles such as: 14267 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14268 // into: 14269 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14270 // because the latter can be matched to a single instruction merge. 14271 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14272 // to put the value into element zero. Adjust the shuffle mask so that the 14273 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14274 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14275 SelectionDAG &DAG) const { 14276 SDValue LHS = SVN->getOperand(0); 14277 SDValue RHS = SVN->getOperand(1); 14278 auto Mask = SVN->getMask(); 14279 int NumElts = LHS.getValueType().getVectorNumElements(); 14280 SDValue Res(SVN, 0); 14281 SDLoc dl(SVN); 14282 14283 // None of these combines are useful on big endian systems since the ISA 14284 // already has a big endian bias. 14285 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14286 return Res; 14287 14288 // If this is not a shuffle of a shuffle and the first element comes from 14289 // the second vector, canonicalize to the commuted form. This will make it 14290 // more likely to match one of the single instruction patterns. 14291 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14292 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14293 std::swap(LHS, RHS); 14294 Res = DAG.getCommutedVectorShuffle(*SVN); 14295 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14296 } 14297 14298 // Adjust the shuffle mask if either input vector comes from a 14299 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14300 // form (to prevent the need for a swap). 14301 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14302 SDValue SToVLHS = isScalarToVec(LHS); 14303 SDValue SToVRHS = isScalarToVec(RHS); 14304 if (SToVLHS || SToVRHS) { 14305 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14306 : SToVRHS.getValueType().getVectorNumElements(); 14307 int NumEltsOut = ShuffV.size(); 14308 14309 // Initially assume that neither input is permuted. These will be adjusted 14310 // accordingly if either input is. 14311 int LHSMaxIdx = -1; 14312 int RHSMinIdx = -1; 14313 int RHSMaxIdx = -1; 14314 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14315 14316 // Get the permuted scalar to vector nodes for the source(s) that come from 14317 // ISD::SCALAR_TO_VECTOR. 14318 if (SToVLHS) { 14319 // Set up the values for the shuffle vector fixup. 14320 LHSMaxIdx = NumEltsOut / NumEltsIn; 14321 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14322 if (SToVLHS.getValueType() != LHS.getValueType()) 14323 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14324 LHS = SToVLHS; 14325 } 14326 if (SToVRHS) { 14327 RHSMinIdx = NumEltsOut; 14328 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14329 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14330 if (SToVRHS.getValueType() != RHS.getValueType()) 14331 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14332 RHS = SToVRHS; 14333 } 14334 14335 // Fix up the shuffle mask to reflect where the desired element actually is. 14336 // The minimum and maximum indices that correspond to element zero for both 14337 // the LHS and RHS are computed and will control which shuffle mask entries 14338 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14339 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14340 // HalfVec to refer to the corresponding element in the permuted vector. 14341 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14342 HalfVec); 14343 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14344 14345 // We may have simplified away the shuffle. We won't be able to do anything 14346 // further with it here. 14347 if (!isa<ShuffleVectorSDNode>(Res)) 14348 return Res; 14349 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14350 } 14351 14352 // The common case after we commuted the shuffle is that the RHS is a splat 14353 // and we have elements coming in from the splat at indices that are not 14354 // conducive to using a merge. 14355 // Example: 14356 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14357 if (!isSplatBV(RHS)) 14358 return Res; 14359 14360 // We are looking for a mask such that all even elements are from 14361 // one vector and all odd elements from the other. 14362 if (!isAlternatingShuffMask(Mask, NumElts)) 14363 return Res; 14364 14365 // Adjust the mask so we are pulling in the same index from the splat 14366 // as the index from the interesting vector in consecutive elements. 14367 // Example (even elements from first vector): 14368 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14369 if (Mask[0] < NumElts) 14370 for (int i = 1, e = Mask.size(); i < e; i += 2) 14371 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14372 // Example (odd elements from first vector): 14373 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14374 else 14375 for (int i = 0, e = Mask.size(); i < e; i += 2) 14376 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14377 14378 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14379 return Res; 14380 } 14381 14382 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14383 LSBaseSDNode *LSBase, 14384 DAGCombinerInfo &DCI) const { 14385 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14386 "Not a reverse memop pattern!"); 14387 14388 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14389 auto Mask = SVN->getMask(); 14390 int i = 0; 14391 auto I = Mask.rbegin(); 14392 auto E = Mask.rend(); 14393 14394 for (; I != E; ++I) { 14395 if (*I != i) 14396 return false; 14397 i++; 14398 } 14399 return true; 14400 }; 14401 14402 SelectionDAG &DAG = DCI.DAG; 14403 EVT VT = SVN->getValueType(0); 14404 14405 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14406 return SDValue(); 14407 14408 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14409 // See comment in PPCVSXSwapRemoval.cpp. 14410 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14411 if (!Subtarget.hasP9Vector()) 14412 return SDValue(); 14413 14414 if(!IsElementReverse(SVN)) 14415 return SDValue(); 14416 14417 if (LSBase->getOpcode() == ISD::LOAD) { 14418 SDLoc dl(SVN); 14419 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14420 return DAG.getMemIntrinsicNode( 14421 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14422 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14423 } 14424 14425 if (LSBase->getOpcode() == ISD::STORE) { 14426 SDLoc dl(LSBase); 14427 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14428 LSBase->getBasePtr()}; 14429 return DAG.getMemIntrinsicNode( 14430 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14431 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14432 } 14433 14434 llvm_unreachable("Expected a load or store node here"); 14435 } 14436 14437 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14438 DAGCombinerInfo &DCI) const { 14439 SelectionDAG &DAG = DCI.DAG; 14440 SDLoc dl(N); 14441 switch (N->getOpcode()) { 14442 default: break; 14443 case ISD::ADD: 14444 return combineADD(N, DCI); 14445 case ISD::SHL: 14446 return combineSHL(N, DCI); 14447 case ISD::SRA: 14448 return combineSRA(N, DCI); 14449 case ISD::SRL: 14450 return combineSRL(N, DCI); 14451 case ISD::MUL: 14452 return combineMUL(N, DCI); 14453 case ISD::FMA: 14454 case PPCISD::FNMSUB: 14455 return combineFMALike(N, DCI); 14456 case PPCISD::SHL: 14457 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14458 return N->getOperand(0); 14459 break; 14460 case PPCISD::SRL: 14461 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14462 return N->getOperand(0); 14463 break; 14464 case PPCISD::SRA: 14465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14466 if (C->isNullValue() || // 0 >>s V -> 0. 14467 C->isAllOnesValue()) // -1 >>s V -> -1. 14468 return N->getOperand(0); 14469 } 14470 break; 14471 case ISD::SIGN_EXTEND: 14472 case ISD::ZERO_EXTEND: 14473 case ISD::ANY_EXTEND: 14474 return DAGCombineExtBoolTrunc(N, DCI); 14475 case ISD::TRUNCATE: 14476 return combineTRUNCATE(N, DCI); 14477 case ISD::SETCC: 14478 if (SDValue CSCC = combineSetCC(N, DCI)) 14479 return CSCC; 14480 LLVM_FALLTHROUGH; 14481 case ISD::SELECT_CC: 14482 return DAGCombineTruncBoolExt(N, DCI); 14483 case ISD::SINT_TO_FP: 14484 case ISD::UINT_TO_FP: 14485 return combineFPToIntToFP(N, DCI); 14486 case ISD::VECTOR_SHUFFLE: 14487 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14488 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14489 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14490 } 14491 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14492 case ISD::STORE: { 14493 14494 EVT Op1VT = N->getOperand(1).getValueType(); 14495 unsigned Opcode = N->getOperand(1).getOpcode(); 14496 14497 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14498 SDValue Val= combineStoreFPToInt(N, DCI); 14499 if (Val) 14500 return Val; 14501 } 14502 14503 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14504 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14505 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14506 if (Val) 14507 return Val; 14508 } 14509 14510 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14511 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14512 N->getOperand(1).getNode()->hasOneUse() && 14513 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14514 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14515 14516 // STBRX can only handle simple types and it makes no sense to store less 14517 // two bytes in byte-reversed order. 14518 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14519 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14520 break; 14521 14522 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14523 // Do an any-extend to 32-bits if this is a half-word input. 14524 if (BSwapOp.getValueType() == MVT::i16) 14525 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14526 14527 // If the type of BSWAP operand is wider than stored memory width 14528 // it need to be shifted to the right side before STBRX. 14529 if (Op1VT.bitsGT(mVT)) { 14530 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14531 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14532 DAG.getConstant(Shift, dl, MVT::i32)); 14533 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14534 if (Op1VT == MVT::i64) 14535 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14536 } 14537 14538 SDValue Ops[] = { 14539 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14540 }; 14541 return 14542 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14543 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14544 cast<StoreSDNode>(N)->getMemOperand()); 14545 } 14546 14547 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14548 // So it can increase the chance of CSE constant construction. 14549 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14550 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14551 // Need to sign-extended to 64-bits to handle negative values. 14552 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14553 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14554 MemVT.getSizeInBits()); 14555 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14556 14557 // DAG.getTruncStore() can't be used here because it doesn't accept 14558 // the general (base + offset) addressing mode. 14559 // So we use UpdateNodeOperands and setTruncatingStore instead. 14560 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14561 N->getOperand(3)); 14562 cast<StoreSDNode>(N)->setTruncatingStore(true); 14563 return SDValue(N, 0); 14564 } 14565 14566 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14567 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14568 if (Op1VT.isSimple()) { 14569 MVT StoreVT = Op1VT.getSimpleVT(); 14570 if (Subtarget.needsSwapsForVSXMemOps() && 14571 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14572 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14573 return expandVSXStoreForLE(N, DCI); 14574 } 14575 break; 14576 } 14577 case ISD::LOAD: { 14578 LoadSDNode *LD = cast<LoadSDNode>(N); 14579 EVT VT = LD->getValueType(0); 14580 14581 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14582 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14583 if (VT.isSimple()) { 14584 MVT LoadVT = VT.getSimpleVT(); 14585 if (Subtarget.needsSwapsForVSXMemOps() && 14586 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14587 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14588 return expandVSXLoadForLE(N, DCI); 14589 } 14590 14591 // We sometimes end up with a 64-bit integer load, from which we extract 14592 // two single-precision floating-point numbers. This happens with 14593 // std::complex<float>, and other similar structures, because of the way we 14594 // canonicalize structure copies. However, if we lack direct moves, 14595 // then the final bitcasts from the extracted integer values to the 14596 // floating-point numbers turn into store/load pairs. Even with direct moves, 14597 // just loading the two floating-point numbers is likely better. 14598 auto ReplaceTwoFloatLoad = [&]() { 14599 if (VT != MVT::i64) 14600 return false; 14601 14602 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14603 LD->isVolatile()) 14604 return false; 14605 14606 // We're looking for a sequence like this: 14607 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14608 // t16: i64 = srl t13, Constant:i32<32> 14609 // t17: i32 = truncate t16 14610 // t18: f32 = bitcast t17 14611 // t19: i32 = truncate t13 14612 // t20: f32 = bitcast t19 14613 14614 if (!LD->hasNUsesOfValue(2, 0)) 14615 return false; 14616 14617 auto UI = LD->use_begin(); 14618 while (UI.getUse().getResNo() != 0) ++UI; 14619 SDNode *Trunc = *UI++; 14620 while (UI.getUse().getResNo() != 0) ++UI; 14621 SDNode *RightShift = *UI; 14622 if (Trunc->getOpcode() != ISD::TRUNCATE) 14623 std::swap(Trunc, RightShift); 14624 14625 if (Trunc->getOpcode() != ISD::TRUNCATE || 14626 Trunc->getValueType(0) != MVT::i32 || 14627 !Trunc->hasOneUse()) 14628 return false; 14629 if (RightShift->getOpcode() != ISD::SRL || 14630 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14631 RightShift->getConstantOperandVal(1) != 32 || 14632 !RightShift->hasOneUse()) 14633 return false; 14634 14635 SDNode *Trunc2 = *RightShift->use_begin(); 14636 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14637 Trunc2->getValueType(0) != MVT::i32 || 14638 !Trunc2->hasOneUse()) 14639 return false; 14640 14641 SDNode *Bitcast = *Trunc->use_begin(); 14642 SDNode *Bitcast2 = *Trunc2->use_begin(); 14643 14644 if (Bitcast->getOpcode() != ISD::BITCAST || 14645 Bitcast->getValueType(0) != MVT::f32) 14646 return false; 14647 if (Bitcast2->getOpcode() != ISD::BITCAST || 14648 Bitcast2->getValueType(0) != MVT::f32) 14649 return false; 14650 14651 if (Subtarget.isLittleEndian()) 14652 std::swap(Bitcast, Bitcast2); 14653 14654 // Bitcast has the second float (in memory-layout order) and Bitcast2 14655 // has the first one. 14656 14657 SDValue BasePtr = LD->getBasePtr(); 14658 if (LD->isIndexed()) { 14659 assert(LD->getAddressingMode() == ISD::PRE_INC && 14660 "Non-pre-inc AM on PPC?"); 14661 BasePtr = 14662 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14663 LD->getOffset()); 14664 } 14665 14666 auto MMOFlags = 14667 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14668 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14669 LD->getPointerInfo(), LD->getAlignment(), 14670 MMOFlags, LD->getAAInfo()); 14671 SDValue AddPtr = 14672 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14673 BasePtr, DAG.getIntPtrConstant(4, dl)); 14674 SDValue FloatLoad2 = DAG.getLoad( 14675 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14676 LD->getPointerInfo().getWithOffset(4), 14677 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14678 14679 if (LD->isIndexed()) { 14680 // Note that DAGCombine should re-form any pre-increment load(s) from 14681 // what is produced here if that makes sense. 14682 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14683 } 14684 14685 DCI.CombineTo(Bitcast2, FloatLoad); 14686 DCI.CombineTo(Bitcast, FloatLoad2); 14687 14688 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14689 SDValue(FloatLoad2.getNode(), 1)); 14690 return true; 14691 }; 14692 14693 if (ReplaceTwoFloatLoad()) 14694 return SDValue(N, 0); 14695 14696 EVT MemVT = LD->getMemoryVT(); 14697 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14698 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14699 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14700 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14701 if (LD->isUnindexed() && VT.isVector() && 14702 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14703 // P8 and later hardware should just use LOAD. 14704 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14705 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14706 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14707 LD->getAlignment() >= ScalarABIAlignment)) && 14708 LD->getAlignment() < ABIAlignment) { 14709 // This is a type-legal unaligned Altivec or QPX load. 14710 SDValue Chain = LD->getChain(); 14711 SDValue Ptr = LD->getBasePtr(); 14712 bool isLittleEndian = Subtarget.isLittleEndian(); 14713 14714 // This implements the loading of unaligned vectors as described in 14715 // the venerable Apple Velocity Engine overview. Specifically: 14716 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14717 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14718 // 14719 // The general idea is to expand a sequence of one or more unaligned 14720 // loads into an alignment-based permutation-control instruction (lvsl 14721 // or lvsr), a series of regular vector loads (which always truncate 14722 // their input address to an aligned address), and a series of 14723 // permutations. The results of these permutations are the requested 14724 // loaded values. The trick is that the last "extra" load is not taken 14725 // from the address you might suspect (sizeof(vector) bytes after the 14726 // last requested load), but rather sizeof(vector) - 1 bytes after the 14727 // last requested vector. The point of this is to avoid a page fault if 14728 // the base address happened to be aligned. This works because if the 14729 // base address is aligned, then adding less than a full vector length 14730 // will cause the last vector in the sequence to be (re)loaded. 14731 // Otherwise, the next vector will be fetched as you might suspect was 14732 // necessary. 14733 14734 // We might be able to reuse the permutation generation from 14735 // a different base address offset from this one by an aligned amount. 14736 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14737 // optimization later. 14738 Intrinsic::ID Intr, IntrLD, IntrPerm; 14739 MVT PermCntlTy, PermTy, LDTy; 14740 if (Subtarget.hasAltivec()) { 14741 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14742 Intrinsic::ppc_altivec_lvsl; 14743 IntrLD = Intrinsic::ppc_altivec_lvx; 14744 IntrPerm = Intrinsic::ppc_altivec_vperm; 14745 PermCntlTy = MVT::v16i8; 14746 PermTy = MVT::v4i32; 14747 LDTy = MVT::v4i32; 14748 } else { 14749 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14750 Intrinsic::ppc_qpx_qvlpcls; 14751 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14752 Intrinsic::ppc_qpx_qvlfs; 14753 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14754 PermCntlTy = MVT::v4f64; 14755 PermTy = MVT::v4f64; 14756 LDTy = MemVT.getSimpleVT(); 14757 } 14758 14759 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14760 14761 // Create the new MMO for the new base load. It is like the original MMO, 14762 // but represents an area in memory almost twice the vector size centered 14763 // on the original address. If the address is unaligned, we might start 14764 // reading up to (sizeof(vector)-1) bytes below the address of the 14765 // original unaligned load. 14766 MachineFunction &MF = DAG.getMachineFunction(); 14767 MachineMemOperand *BaseMMO = 14768 MF.getMachineMemOperand(LD->getMemOperand(), 14769 -(long)MemVT.getStoreSize()+1, 14770 2*MemVT.getStoreSize()-1); 14771 14772 // Create the new base load. 14773 SDValue LDXIntID = 14774 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14775 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14776 SDValue BaseLoad = 14777 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14778 DAG.getVTList(PermTy, MVT::Other), 14779 BaseLoadOps, LDTy, BaseMMO); 14780 14781 // Note that the value of IncOffset (which is provided to the next 14782 // load's pointer info offset value, and thus used to calculate the 14783 // alignment), and the value of IncValue (which is actually used to 14784 // increment the pointer value) are different! This is because we 14785 // require the next load to appear to be aligned, even though it 14786 // is actually offset from the base pointer by a lesser amount. 14787 int IncOffset = VT.getSizeInBits() / 8; 14788 int IncValue = IncOffset; 14789 14790 // Walk (both up and down) the chain looking for another load at the real 14791 // (aligned) offset (the alignment of the other load does not matter in 14792 // this case). If found, then do not use the offset reduction trick, as 14793 // that will prevent the loads from being later combined (as they would 14794 // otherwise be duplicates). 14795 if (!findConsecutiveLoad(LD, DAG)) 14796 --IncValue; 14797 14798 SDValue Increment = 14799 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14800 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14801 14802 MachineMemOperand *ExtraMMO = 14803 MF.getMachineMemOperand(LD->getMemOperand(), 14804 1, 2*MemVT.getStoreSize()-1); 14805 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14806 SDValue ExtraLoad = 14807 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14808 DAG.getVTList(PermTy, MVT::Other), 14809 ExtraLoadOps, LDTy, ExtraMMO); 14810 14811 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14812 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14813 14814 // Because vperm has a big-endian bias, we must reverse the order 14815 // of the input vectors and complement the permute control vector 14816 // when generating little endian code. We have already handled the 14817 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14818 // and ExtraLoad here. 14819 SDValue Perm; 14820 if (isLittleEndian) 14821 Perm = BuildIntrinsicOp(IntrPerm, 14822 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14823 else 14824 Perm = BuildIntrinsicOp(IntrPerm, 14825 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14826 14827 if (VT != PermTy) 14828 Perm = Subtarget.hasAltivec() ? 14829 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14830 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14831 DAG.getTargetConstant(1, dl, MVT::i64)); 14832 // second argument is 1 because this rounding 14833 // is always exact. 14834 14835 // The output of the permutation is our loaded result, the TokenFactor is 14836 // our new chain. 14837 DCI.CombineTo(N, Perm, TF); 14838 return SDValue(N, 0); 14839 } 14840 } 14841 break; 14842 case ISD::INTRINSIC_WO_CHAIN: { 14843 bool isLittleEndian = Subtarget.isLittleEndian(); 14844 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14845 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14846 : Intrinsic::ppc_altivec_lvsl); 14847 if ((IID == Intr || 14848 IID == Intrinsic::ppc_qpx_qvlpcld || 14849 IID == Intrinsic::ppc_qpx_qvlpcls) && 14850 N->getOperand(1)->getOpcode() == ISD::ADD) { 14851 SDValue Add = N->getOperand(1); 14852 14853 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14854 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14855 14856 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14857 APInt::getAllOnesValue(Bits /* alignment */) 14858 .zext(Add.getScalarValueSizeInBits()))) { 14859 SDNode *BasePtr = Add->getOperand(0).getNode(); 14860 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14861 UE = BasePtr->use_end(); 14862 UI != UE; ++UI) { 14863 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14864 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14865 // We've found another LVSL/LVSR, and this address is an aligned 14866 // multiple of that one. The results will be the same, so use the 14867 // one we've just found instead. 14868 14869 return SDValue(*UI, 0); 14870 } 14871 } 14872 } 14873 14874 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14875 SDNode *BasePtr = Add->getOperand(0).getNode(); 14876 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14877 UE = BasePtr->use_end(); UI != UE; ++UI) { 14878 if (UI->getOpcode() == ISD::ADD && 14879 isa<ConstantSDNode>(UI->getOperand(1)) && 14880 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14881 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14882 (1ULL << Bits) == 0) { 14883 SDNode *OtherAdd = *UI; 14884 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14885 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14886 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14887 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14888 return SDValue(*VI, 0); 14889 } 14890 } 14891 } 14892 } 14893 } 14894 } 14895 14896 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14897 // Expose the vabsduw/h/b opportunity for down stream 14898 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14899 (IID == Intrinsic::ppc_altivec_vmaxsw || 14900 IID == Intrinsic::ppc_altivec_vmaxsh || 14901 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14902 SDValue V1 = N->getOperand(1); 14903 SDValue V2 = N->getOperand(2); 14904 if ((V1.getSimpleValueType() == MVT::v4i32 || 14905 V1.getSimpleValueType() == MVT::v8i16 || 14906 V1.getSimpleValueType() == MVT::v16i8) && 14907 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14908 // (0-a, a) 14909 if (V1.getOpcode() == ISD::SUB && 14910 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14911 V1.getOperand(1) == V2) { 14912 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14913 } 14914 // (a, 0-a) 14915 if (V2.getOpcode() == ISD::SUB && 14916 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14917 V2.getOperand(1) == V1) { 14918 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14919 } 14920 // (x-y, y-x) 14921 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14922 V1.getOperand(0) == V2.getOperand(1) && 14923 V1.getOperand(1) == V2.getOperand(0)) { 14924 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14925 } 14926 } 14927 } 14928 } 14929 14930 break; 14931 case ISD::INTRINSIC_W_CHAIN: 14932 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14933 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14934 if (Subtarget.needsSwapsForVSXMemOps()) { 14935 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14936 default: 14937 break; 14938 case Intrinsic::ppc_vsx_lxvw4x: 14939 case Intrinsic::ppc_vsx_lxvd2x: 14940 return expandVSXLoadForLE(N, DCI); 14941 } 14942 } 14943 break; 14944 case ISD::INTRINSIC_VOID: 14945 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14946 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14947 if (Subtarget.needsSwapsForVSXMemOps()) { 14948 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14949 default: 14950 break; 14951 case Intrinsic::ppc_vsx_stxvw4x: 14952 case Intrinsic::ppc_vsx_stxvd2x: 14953 return expandVSXStoreForLE(N, DCI); 14954 } 14955 } 14956 break; 14957 case ISD::BSWAP: 14958 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14959 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14960 N->getOperand(0).hasOneUse() && 14961 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14962 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14963 N->getValueType(0) == MVT::i64))) { 14964 SDValue Load = N->getOperand(0); 14965 LoadSDNode *LD = cast<LoadSDNode>(Load); 14966 // Create the byte-swapping load. 14967 SDValue Ops[] = { 14968 LD->getChain(), // Chain 14969 LD->getBasePtr(), // Ptr 14970 DAG.getValueType(N->getValueType(0)) // VT 14971 }; 14972 SDValue BSLoad = 14973 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14974 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14975 MVT::i64 : MVT::i32, MVT::Other), 14976 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14977 14978 // If this is an i16 load, insert the truncate. 14979 SDValue ResVal = BSLoad; 14980 if (N->getValueType(0) == MVT::i16) 14981 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14982 14983 // First, combine the bswap away. This makes the value produced by the 14984 // load dead. 14985 DCI.CombineTo(N, ResVal); 14986 14987 // Next, combine the load away, we give it a bogus result value but a real 14988 // chain result. The result value is dead because the bswap is dead. 14989 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14990 14991 // Return N so it doesn't get rechecked! 14992 return SDValue(N, 0); 14993 } 14994 break; 14995 case PPCISD::VCMP: 14996 // If a VCMPo node already exists with exactly the same operands as this 14997 // node, use its result instead of this node (VCMPo computes both a CR6 and 14998 // a normal output). 14999 // 15000 if (!N->getOperand(0).hasOneUse() && 15001 !N->getOperand(1).hasOneUse() && 15002 !N->getOperand(2).hasOneUse()) { 15003 15004 // Scan all of the users of the LHS, looking for VCMPo's that match. 15005 SDNode *VCMPoNode = nullptr; 15006 15007 SDNode *LHSN = N->getOperand(0).getNode(); 15008 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15009 UI != E; ++UI) 15010 if (UI->getOpcode() == PPCISD::VCMPo && 15011 UI->getOperand(1) == N->getOperand(1) && 15012 UI->getOperand(2) == N->getOperand(2) && 15013 UI->getOperand(0) == N->getOperand(0)) { 15014 VCMPoNode = *UI; 15015 break; 15016 } 15017 15018 // If there is no VCMPo node, or if the flag value has a single use, don't 15019 // transform this. 15020 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 15021 break; 15022 15023 // Look at the (necessarily single) use of the flag value. If it has a 15024 // chain, this transformation is more complex. Note that multiple things 15025 // could use the value result, which we should ignore. 15026 SDNode *FlagUser = nullptr; 15027 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 15028 FlagUser == nullptr; ++UI) { 15029 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 15030 SDNode *User = *UI; 15031 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15032 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 15033 FlagUser = User; 15034 break; 15035 } 15036 } 15037 } 15038 15039 // If the user is a MFOCRF instruction, we know this is safe. 15040 // Otherwise we give up for right now. 15041 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15042 return SDValue(VCMPoNode, 0); 15043 } 15044 break; 15045 case ISD::BRCOND: { 15046 SDValue Cond = N->getOperand(1); 15047 SDValue Target = N->getOperand(2); 15048 15049 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15050 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15051 Intrinsic::loop_decrement) { 15052 15053 // We now need to make the intrinsic dead (it cannot be instruction 15054 // selected). 15055 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15056 assert(Cond.getNode()->hasOneUse() && 15057 "Counter decrement has more than one use"); 15058 15059 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15060 N->getOperand(0), Target); 15061 } 15062 } 15063 break; 15064 case ISD::BR_CC: { 15065 // If this is a branch on an altivec predicate comparison, lower this so 15066 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15067 // lowering is done pre-legalize, because the legalizer lowers the predicate 15068 // compare down to code that is difficult to reassemble. 15069 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15070 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15071 15072 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15073 // value. If so, pass-through the AND to get to the intrinsic. 15074 if (LHS.getOpcode() == ISD::AND && 15075 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15076 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15077 Intrinsic::loop_decrement && 15078 isa<ConstantSDNode>(LHS.getOperand(1)) && 15079 !isNullConstant(LHS.getOperand(1))) 15080 LHS = LHS.getOperand(0); 15081 15082 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15083 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15084 Intrinsic::loop_decrement && 15085 isa<ConstantSDNode>(RHS)) { 15086 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15087 "Counter decrement comparison is not EQ or NE"); 15088 15089 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15090 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15091 (CC == ISD::SETNE && !Val); 15092 15093 // We now need to make the intrinsic dead (it cannot be instruction 15094 // selected). 15095 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15096 assert(LHS.getNode()->hasOneUse() && 15097 "Counter decrement has more than one use"); 15098 15099 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15100 N->getOperand(0), N->getOperand(4)); 15101 } 15102 15103 int CompareOpc; 15104 bool isDot; 15105 15106 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15107 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15108 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15109 assert(isDot && "Can't compare against a vector result!"); 15110 15111 // If this is a comparison against something other than 0/1, then we know 15112 // that the condition is never/always true. 15113 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15114 if (Val != 0 && Val != 1) { 15115 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15116 return N->getOperand(0); 15117 // Always !=, turn it into an unconditional branch. 15118 return DAG.getNode(ISD::BR, dl, MVT::Other, 15119 N->getOperand(0), N->getOperand(4)); 15120 } 15121 15122 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15123 15124 // Create the PPCISD altivec 'dot' comparison node. 15125 SDValue Ops[] = { 15126 LHS.getOperand(2), // LHS of compare 15127 LHS.getOperand(3), // RHS of compare 15128 DAG.getConstant(CompareOpc, dl, MVT::i32) 15129 }; 15130 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15131 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15132 15133 // Unpack the result based on how the target uses it. 15134 PPC::Predicate CompOpc; 15135 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15136 default: // Can't happen, don't crash on invalid number though. 15137 case 0: // Branch on the value of the EQ bit of CR6. 15138 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15139 break; 15140 case 1: // Branch on the inverted value of the EQ bit of CR6. 15141 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15142 break; 15143 case 2: // Branch on the value of the LT bit of CR6. 15144 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15145 break; 15146 case 3: // Branch on the inverted value of the LT bit of CR6. 15147 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15148 break; 15149 } 15150 15151 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15152 DAG.getConstant(CompOpc, dl, MVT::i32), 15153 DAG.getRegister(PPC::CR6, MVT::i32), 15154 N->getOperand(4), CompNode.getValue(1)); 15155 } 15156 break; 15157 } 15158 case ISD::BUILD_VECTOR: 15159 return DAGCombineBuildVector(N, DCI); 15160 case ISD::ABS: 15161 return combineABS(N, DCI); 15162 case ISD::VSELECT: 15163 return combineVSelect(N, DCI); 15164 } 15165 15166 return SDValue(); 15167 } 15168 15169 SDValue 15170 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15171 SelectionDAG &DAG, 15172 SmallVectorImpl<SDNode *> &Created) const { 15173 // fold (sdiv X, pow2) 15174 EVT VT = N->getValueType(0); 15175 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15176 return SDValue(); 15177 if ((VT != MVT::i32 && VT != MVT::i64) || 15178 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15179 return SDValue(); 15180 15181 SDLoc DL(N); 15182 SDValue N0 = N->getOperand(0); 15183 15184 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15185 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15186 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15187 15188 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15189 Created.push_back(Op.getNode()); 15190 15191 if (IsNegPow2) { 15192 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15193 Created.push_back(Op.getNode()); 15194 } 15195 15196 return Op; 15197 } 15198 15199 //===----------------------------------------------------------------------===// 15200 // Inline Assembly Support 15201 //===----------------------------------------------------------------------===// 15202 15203 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15204 KnownBits &Known, 15205 const APInt &DemandedElts, 15206 const SelectionDAG &DAG, 15207 unsigned Depth) const { 15208 Known.resetAll(); 15209 switch (Op.getOpcode()) { 15210 default: break; 15211 case PPCISD::LBRX: { 15212 // lhbrx is known to have the top bits cleared out. 15213 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15214 Known.Zero = 0xFFFF0000; 15215 break; 15216 } 15217 case ISD::INTRINSIC_WO_CHAIN: { 15218 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15219 default: break; 15220 case Intrinsic::ppc_altivec_vcmpbfp_p: 15221 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15222 case Intrinsic::ppc_altivec_vcmpequb_p: 15223 case Intrinsic::ppc_altivec_vcmpequh_p: 15224 case Intrinsic::ppc_altivec_vcmpequw_p: 15225 case Intrinsic::ppc_altivec_vcmpequd_p: 15226 case Intrinsic::ppc_altivec_vcmpgefp_p: 15227 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15228 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15229 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15230 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15231 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15232 case Intrinsic::ppc_altivec_vcmpgtub_p: 15233 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15234 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15235 case Intrinsic::ppc_altivec_vcmpgtud_p: 15236 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15237 break; 15238 } 15239 } 15240 } 15241 } 15242 15243 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15244 switch (Subtarget.getCPUDirective()) { 15245 default: break; 15246 case PPC::DIR_970: 15247 case PPC::DIR_PWR4: 15248 case PPC::DIR_PWR5: 15249 case PPC::DIR_PWR5X: 15250 case PPC::DIR_PWR6: 15251 case PPC::DIR_PWR6X: 15252 case PPC::DIR_PWR7: 15253 case PPC::DIR_PWR8: 15254 case PPC::DIR_PWR9: 15255 case PPC::DIR_PWR10: 15256 case PPC::DIR_PWR_FUTURE: { 15257 if (!ML) 15258 break; 15259 15260 if (!DisableInnermostLoopAlign32) { 15261 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15262 // so that we can decrease cache misses and branch-prediction misses. 15263 // Actual alignment of the loop will depend on the hotness check and other 15264 // logic in alignBlocks. 15265 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15266 return Align(32); 15267 } 15268 15269 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15270 15271 // For small loops (between 5 and 8 instructions), align to a 32-byte 15272 // boundary so that the entire loop fits in one instruction-cache line. 15273 uint64_t LoopSize = 0; 15274 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15275 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15276 LoopSize += TII->getInstSizeInBytes(*J); 15277 if (LoopSize > 32) 15278 break; 15279 } 15280 15281 if (LoopSize > 16 && LoopSize <= 32) 15282 return Align(32); 15283 15284 break; 15285 } 15286 } 15287 15288 return TargetLowering::getPrefLoopAlignment(ML); 15289 } 15290 15291 /// getConstraintType - Given a constraint, return the type of 15292 /// constraint it is for this target. 15293 PPCTargetLowering::ConstraintType 15294 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15295 if (Constraint.size() == 1) { 15296 switch (Constraint[0]) { 15297 default: break; 15298 case 'b': 15299 case 'r': 15300 case 'f': 15301 case 'd': 15302 case 'v': 15303 case 'y': 15304 return C_RegisterClass; 15305 case 'Z': 15306 // FIXME: While Z does indicate a memory constraint, it specifically 15307 // indicates an r+r address (used in conjunction with the 'y' modifier 15308 // in the replacement string). Currently, we're forcing the base 15309 // register to be r0 in the asm printer (which is interpreted as zero) 15310 // and forming the complete address in the second register. This is 15311 // suboptimal. 15312 return C_Memory; 15313 } 15314 } else if (Constraint == "wc") { // individual CR bits. 15315 return C_RegisterClass; 15316 } else if (Constraint == "wa" || Constraint == "wd" || 15317 Constraint == "wf" || Constraint == "ws" || 15318 Constraint == "wi" || Constraint == "ww") { 15319 return C_RegisterClass; // VSX registers. 15320 } 15321 return TargetLowering::getConstraintType(Constraint); 15322 } 15323 15324 /// Examine constraint type and operand type and determine a weight value. 15325 /// This object must already have been set up with the operand type 15326 /// and the current alternative constraint selected. 15327 TargetLowering::ConstraintWeight 15328 PPCTargetLowering::getSingleConstraintMatchWeight( 15329 AsmOperandInfo &info, const char *constraint) const { 15330 ConstraintWeight weight = CW_Invalid; 15331 Value *CallOperandVal = info.CallOperandVal; 15332 // If we don't have a value, we can't do a match, 15333 // but allow it at the lowest weight. 15334 if (!CallOperandVal) 15335 return CW_Default; 15336 Type *type = CallOperandVal->getType(); 15337 15338 // Look at the constraint type. 15339 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15340 return CW_Register; // an individual CR bit. 15341 else if ((StringRef(constraint) == "wa" || 15342 StringRef(constraint) == "wd" || 15343 StringRef(constraint) == "wf") && 15344 type->isVectorTy()) 15345 return CW_Register; 15346 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15347 return CW_Register; // just hold 64-bit integers data. 15348 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15349 return CW_Register; 15350 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15351 return CW_Register; 15352 15353 switch (*constraint) { 15354 default: 15355 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15356 break; 15357 case 'b': 15358 if (type->isIntegerTy()) 15359 weight = CW_Register; 15360 break; 15361 case 'f': 15362 if (type->isFloatTy()) 15363 weight = CW_Register; 15364 break; 15365 case 'd': 15366 if (type->isDoubleTy()) 15367 weight = CW_Register; 15368 break; 15369 case 'v': 15370 if (type->isVectorTy()) 15371 weight = CW_Register; 15372 break; 15373 case 'y': 15374 weight = CW_Register; 15375 break; 15376 case 'Z': 15377 weight = CW_Memory; 15378 break; 15379 } 15380 return weight; 15381 } 15382 15383 std::pair<unsigned, const TargetRegisterClass *> 15384 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15385 StringRef Constraint, 15386 MVT VT) const { 15387 if (Constraint.size() == 1) { 15388 // GCC RS6000 Constraint Letters 15389 switch (Constraint[0]) { 15390 case 'b': // R1-R31 15391 if (VT == MVT::i64 && Subtarget.isPPC64()) 15392 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15393 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15394 case 'r': // R0-R31 15395 if (VT == MVT::i64 && Subtarget.isPPC64()) 15396 return std::make_pair(0U, &PPC::G8RCRegClass); 15397 return std::make_pair(0U, &PPC::GPRCRegClass); 15398 // 'd' and 'f' constraints are both defined to be "the floating point 15399 // registers", where one is for 32-bit and the other for 64-bit. We don't 15400 // really care overly much here so just give them all the same reg classes. 15401 case 'd': 15402 case 'f': 15403 if (Subtarget.hasSPE()) { 15404 if (VT == MVT::f32 || VT == MVT::i32) 15405 return std::make_pair(0U, &PPC::GPRCRegClass); 15406 if (VT == MVT::f64 || VT == MVT::i64) 15407 return std::make_pair(0U, &PPC::SPERCRegClass); 15408 } else { 15409 if (VT == MVT::f32 || VT == MVT::i32) 15410 return std::make_pair(0U, &PPC::F4RCRegClass); 15411 if (VT == MVT::f64 || VT == MVT::i64) 15412 return std::make_pair(0U, &PPC::F8RCRegClass); 15413 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15414 return std::make_pair(0U, &PPC::QFRCRegClass); 15415 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15416 return std::make_pair(0U, &PPC::QSRCRegClass); 15417 } 15418 break; 15419 case 'v': 15420 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15421 return std::make_pair(0U, &PPC::QFRCRegClass); 15422 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15423 return std::make_pair(0U, &PPC::QSRCRegClass); 15424 if (Subtarget.hasAltivec()) 15425 return std::make_pair(0U, &PPC::VRRCRegClass); 15426 break; 15427 case 'y': // crrc 15428 return std::make_pair(0U, &PPC::CRRCRegClass); 15429 } 15430 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15431 // An individual CR bit. 15432 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15433 } else if ((Constraint == "wa" || Constraint == "wd" || 15434 Constraint == "wf" || Constraint == "wi") && 15435 Subtarget.hasVSX()) { 15436 return std::make_pair(0U, &PPC::VSRCRegClass); 15437 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15438 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15439 return std::make_pair(0U, &PPC::VSSRCRegClass); 15440 else 15441 return std::make_pair(0U, &PPC::VSFRCRegClass); 15442 } 15443 15444 // If we name a VSX register, we can't defer to the base class because it 15445 // will not recognize the correct register (their names will be VSL{0-31} 15446 // and V{0-31} so they won't match). So we match them here. 15447 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15448 int VSNum = atoi(Constraint.data() + 3); 15449 assert(VSNum >= 0 && VSNum <= 63 && 15450 "Attempted to access a vsr out of range"); 15451 if (VSNum < 32) 15452 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15453 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15454 } 15455 std::pair<unsigned, const TargetRegisterClass *> R = 15456 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15457 15458 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15459 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15460 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15461 // register. 15462 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15463 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15464 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15465 PPC::GPRCRegClass.contains(R.first)) 15466 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15467 PPC::sub_32, &PPC::G8RCRegClass), 15468 &PPC::G8RCRegClass); 15469 15470 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15471 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15472 R.first = PPC::CR0; 15473 R.second = &PPC::CRRCRegClass; 15474 } 15475 15476 return R; 15477 } 15478 15479 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15480 /// vector. If it is invalid, don't add anything to Ops. 15481 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15482 std::string &Constraint, 15483 std::vector<SDValue>&Ops, 15484 SelectionDAG &DAG) const { 15485 SDValue Result; 15486 15487 // Only support length 1 constraints. 15488 if (Constraint.length() > 1) return; 15489 15490 char Letter = Constraint[0]; 15491 switch (Letter) { 15492 default: break; 15493 case 'I': 15494 case 'J': 15495 case 'K': 15496 case 'L': 15497 case 'M': 15498 case 'N': 15499 case 'O': 15500 case 'P': { 15501 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15502 if (!CST) return; // Must be an immediate to match. 15503 SDLoc dl(Op); 15504 int64_t Value = CST->getSExtValue(); 15505 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15506 // numbers are printed as such. 15507 switch (Letter) { 15508 default: llvm_unreachable("Unknown constraint letter!"); 15509 case 'I': // "I" is a signed 16-bit constant. 15510 if (isInt<16>(Value)) 15511 Result = DAG.getTargetConstant(Value, dl, TCVT); 15512 break; 15513 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15514 if (isShiftedUInt<16, 16>(Value)) 15515 Result = DAG.getTargetConstant(Value, dl, TCVT); 15516 break; 15517 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15518 if (isShiftedInt<16, 16>(Value)) 15519 Result = DAG.getTargetConstant(Value, dl, TCVT); 15520 break; 15521 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15522 if (isUInt<16>(Value)) 15523 Result = DAG.getTargetConstant(Value, dl, TCVT); 15524 break; 15525 case 'M': // "M" is a constant that is greater than 31. 15526 if (Value > 31) 15527 Result = DAG.getTargetConstant(Value, dl, TCVT); 15528 break; 15529 case 'N': // "N" is a positive constant that is an exact power of two. 15530 if (Value > 0 && isPowerOf2_64(Value)) 15531 Result = DAG.getTargetConstant(Value, dl, TCVT); 15532 break; 15533 case 'O': // "O" is the constant zero. 15534 if (Value == 0) 15535 Result = DAG.getTargetConstant(Value, dl, TCVT); 15536 break; 15537 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15538 if (isInt<16>(-Value)) 15539 Result = DAG.getTargetConstant(Value, dl, TCVT); 15540 break; 15541 } 15542 break; 15543 } 15544 } 15545 15546 if (Result.getNode()) { 15547 Ops.push_back(Result); 15548 return; 15549 } 15550 15551 // Handle standard constraint letters. 15552 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15553 } 15554 15555 // isLegalAddressingMode - Return true if the addressing mode represented 15556 // by AM is legal for this target, for a load/store of the specified type. 15557 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15558 const AddrMode &AM, Type *Ty, 15559 unsigned AS, Instruction *I) const { 15560 // PPC does not allow r+i addressing modes for vectors! 15561 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15562 return false; 15563 15564 // PPC allows a sign-extended 16-bit immediate field. 15565 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15566 return false; 15567 15568 // No global is ever allowed as a base. 15569 if (AM.BaseGV) 15570 return false; 15571 15572 // PPC only support r+r, 15573 switch (AM.Scale) { 15574 case 0: // "r+i" or just "i", depending on HasBaseReg. 15575 break; 15576 case 1: 15577 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15578 return false; 15579 // Otherwise we have r+r or r+i. 15580 break; 15581 case 2: 15582 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15583 return false; 15584 // Allow 2*r as r+r. 15585 break; 15586 default: 15587 // No other scales are supported. 15588 return false; 15589 } 15590 15591 return true; 15592 } 15593 15594 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15595 SelectionDAG &DAG) const { 15596 MachineFunction &MF = DAG.getMachineFunction(); 15597 MachineFrameInfo &MFI = MF.getFrameInfo(); 15598 MFI.setReturnAddressIsTaken(true); 15599 15600 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15601 return SDValue(); 15602 15603 SDLoc dl(Op); 15604 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15605 15606 // Make sure the function does not optimize away the store of the RA to 15607 // the stack. 15608 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15609 FuncInfo->setLRStoreRequired(); 15610 bool isPPC64 = Subtarget.isPPC64(); 15611 auto PtrVT = getPointerTy(MF.getDataLayout()); 15612 15613 if (Depth > 0) { 15614 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15615 SDValue Offset = 15616 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15617 isPPC64 ? MVT::i64 : MVT::i32); 15618 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15619 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15620 MachinePointerInfo()); 15621 } 15622 15623 // Just load the return address off the stack. 15624 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15625 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15626 MachinePointerInfo()); 15627 } 15628 15629 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15630 SelectionDAG &DAG) const { 15631 SDLoc dl(Op); 15632 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15633 15634 MachineFunction &MF = DAG.getMachineFunction(); 15635 MachineFrameInfo &MFI = MF.getFrameInfo(); 15636 MFI.setFrameAddressIsTaken(true); 15637 15638 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15639 bool isPPC64 = PtrVT == MVT::i64; 15640 15641 // Naked functions never have a frame pointer, and so we use r1. For all 15642 // other functions, this decision must be delayed until during PEI. 15643 unsigned FrameReg; 15644 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15645 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15646 else 15647 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15648 15649 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15650 PtrVT); 15651 while (Depth--) 15652 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15653 FrameAddr, MachinePointerInfo()); 15654 return FrameAddr; 15655 } 15656 15657 // FIXME? Maybe this could be a TableGen attribute on some registers and 15658 // this table could be generated automatically from RegInfo. 15659 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15660 const MachineFunction &MF) const { 15661 bool isPPC64 = Subtarget.isPPC64(); 15662 15663 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15664 if (!is64Bit && VT != LLT::scalar(32)) 15665 report_fatal_error("Invalid register global variable type"); 15666 15667 Register Reg = StringSwitch<Register>(RegName) 15668 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15669 .Case("r2", isPPC64 ? Register() : PPC::R2) 15670 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15671 .Default(Register()); 15672 15673 if (Reg) 15674 return Reg; 15675 report_fatal_error("Invalid register name global variable"); 15676 } 15677 15678 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15679 // 32-bit SVR4 ABI access everything as got-indirect. 15680 if (Subtarget.is32BitELFABI()) 15681 return true; 15682 15683 // AIX accesses everything indirectly through the TOC, which is similar to 15684 // the GOT. 15685 if (Subtarget.isAIXABI()) 15686 return true; 15687 15688 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15689 // If it is small or large code model, module locals are accessed 15690 // indirectly by loading their address from .toc/.got. 15691 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15692 return true; 15693 15694 // JumpTable and BlockAddress are accessed as got-indirect. 15695 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15696 return true; 15697 15698 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15699 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15700 15701 return false; 15702 } 15703 15704 bool 15705 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15706 // The PowerPC target isn't yet aware of offsets. 15707 return false; 15708 } 15709 15710 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15711 const CallInst &I, 15712 MachineFunction &MF, 15713 unsigned Intrinsic) const { 15714 switch (Intrinsic) { 15715 case Intrinsic::ppc_qpx_qvlfd: 15716 case Intrinsic::ppc_qpx_qvlfs: 15717 case Intrinsic::ppc_qpx_qvlfcd: 15718 case Intrinsic::ppc_qpx_qvlfcs: 15719 case Intrinsic::ppc_qpx_qvlfiwa: 15720 case Intrinsic::ppc_qpx_qvlfiwz: 15721 case Intrinsic::ppc_altivec_lvx: 15722 case Intrinsic::ppc_altivec_lvxl: 15723 case Intrinsic::ppc_altivec_lvebx: 15724 case Intrinsic::ppc_altivec_lvehx: 15725 case Intrinsic::ppc_altivec_lvewx: 15726 case Intrinsic::ppc_vsx_lxvd2x: 15727 case Intrinsic::ppc_vsx_lxvw4x: { 15728 EVT VT; 15729 switch (Intrinsic) { 15730 case Intrinsic::ppc_altivec_lvebx: 15731 VT = MVT::i8; 15732 break; 15733 case Intrinsic::ppc_altivec_lvehx: 15734 VT = MVT::i16; 15735 break; 15736 case Intrinsic::ppc_altivec_lvewx: 15737 VT = MVT::i32; 15738 break; 15739 case Intrinsic::ppc_vsx_lxvd2x: 15740 VT = MVT::v2f64; 15741 break; 15742 case Intrinsic::ppc_qpx_qvlfd: 15743 VT = MVT::v4f64; 15744 break; 15745 case Intrinsic::ppc_qpx_qvlfs: 15746 VT = MVT::v4f32; 15747 break; 15748 case Intrinsic::ppc_qpx_qvlfcd: 15749 VT = MVT::v2f64; 15750 break; 15751 case Intrinsic::ppc_qpx_qvlfcs: 15752 VT = MVT::v2f32; 15753 break; 15754 default: 15755 VT = MVT::v4i32; 15756 break; 15757 } 15758 15759 Info.opc = ISD::INTRINSIC_W_CHAIN; 15760 Info.memVT = VT; 15761 Info.ptrVal = I.getArgOperand(0); 15762 Info.offset = -VT.getStoreSize()+1; 15763 Info.size = 2*VT.getStoreSize()-1; 15764 Info.align = Align(1); 15765 Info.flags = MachineMemOperand::MOLoad; 15766 return true; 15767 } 15768 case Intrinsic::ppc_qpx_qvlfda: 15769 case Intrinsic::ppc_qpx_qvlfsa: 15770 case Intrinsic::ppc_qpx_qvlfcda: 15771 case Intrinsic::ppc_qpx_qvlfcsa: 15772 case Intrinsic::ppc_qpx_qvlfiwaa: 15773 case Intrinsic::ppc_qpx_qvlfiwza: { 15774 EVT VT; 15775 switch (Intrinsic) { 15776 case Intrinsic::ppc_qpx_qvlfda: 15777 VT = MVT::v4f64; 15778 break; 15779 case Intrinsic::ppc_qpx_qvlfsa: 15780 VT = MVT::v4f32; 15781 break; 15782 case Intrinsic::ppc_qpx_qvlfcda: 15783 VT = MVT::v2f64; 15784 break; 15785 case Intrinsic::ppc_qpx_qvlfcsa: 15786 VT = MVT::v2f32; 15787 break; 15788 default: 15789 VT = MVT::v4i32; 15790 break; 15791 } 15792 15793 Info.opc = ISD::INTRINSIC_W_CHAIN; 15794 Info.memVT = VT; 15795 Info.ptrVal = I.getArgOperand(0); 15796 Info.offset = 0; 15797 Info.size = VT.getStoreSize(); 15798 Info.align = Align(1); 15799 Info.flags = MachineMemOperand::MOLoad; 15800 return true; 15801 } 15802 case Intrinsic::ppc_qpx_qvstfd: 15803 case Intrinsic::ppc_qpx_qvstfs: 15804 case Intrinsic::ppc_qpx_qvstfcd: 15805 case Intrinsic::ppc_qpx_qvstfcs: 15806 case Intrinsic::ppc_qpx_qvstfiw: 15807 case Intrinsic::ppc_altivec_stvx: 15808 case Intrinsic::ppc_altivec_stvxl: 15809 case Intrinsic::ppc_altivec_stvebx: 15810 case Intrinsic::ppc_altivec_stvehx: 15811 case Intrinsic::ppc_altivec_stvewx: 15812 case Intrinsic::ppc_vsx_stxvd2x: 15813 case Intrinsic::ppc_vsx_stxvw4x: { 15814 EVT VT; 15815 switch (Intrinsic) { 15816 case Intrinsic::ppc_altivec_stvebx: 15817 VT = MVT::i8; 15818 break; 15819 case Intrinsic::ppc_altivec_stvehx: 15820 VT = MVT::i16; 15821 break; 15822 case Intrinsic::ppc_altivec_stvewx: 15823 VT = MVT::i32; 15824 break; 15825 case Intrinsic::ppc_vsx_stxvd2x: 15826 VT = MVT::v2f64; 15827 break; 15828 case Intrinsic::ppc_qpx_qvstfd: 15829 VT = MVT::v4f64; 15830 break; 15831 case Intrinsic::ppc_qpx_qvstfs: 15832 VT = MVT::v4f32; 15833 break; 15834 case Intrinsic::ppc_qpx_qvstfcd: 15835 VT = MVT::v2f64; 15836 break; 15837 case Intrinsic::ppc_qpx_qvstfcs: 15838 VT = MVT::v2f32; 15839 break; 15840 default: 15841 VT = MVT::v4i32; 15842 break; 15843 } 15844 15845 Info.opc = ISD::INTRINSIC_VOID; 15846 Info.memVT = VT; 15847 Info.ptrVal = I.getArgOperand(1); 15848 Info.offset = -VT.getStoreSize()+1; 15849 Info.size = 2*VT.getStoreSize()-1; 15850 Info.align = Align(1); 15851 Info.flags = MachineMemOperand::MOStore; 15852 return true; 15853 } 15854 case Intrinsic::ppc_qpx_qvstfda: 15855 case Intrinsic::ppc_qpx_qvstfsa: 15856 case Intrinsic::ppc_qpx_qvstfcda: 15857 case Intrinsic::ppc_qpx_qvstfcsa: 15858 case Intrinsic::ppc_qpx_qvstfiwa: { 15859 EVT VT; 15860 switch (Intrinsic) { 15861 case Intrinsic::ppc_qpx_qvstfda: 15862 VT = MVT::v4f64; 15863 break; 15864 case Intrinsic::ppc_qpx_qvstfsa: 15865 VT = MVT::v4f32; 15866 break; 15867 case Intrinsic::ppc_qpx_qvstfcda: 15868 VT = MVT::v2f64; 15869 break; 15870 case Intrinsic::ppc_qpx_qvstfcsa: 15871 VT = MVT::v2f32; 15872 break; 15873 default: 15874 VT = MVT::v4i32; 15875 break; 15876 } 15877 15878 Info.opc = ISD::INTRINSIC_VOID; 15879 Info.memVT = VT; 15880 Info.ptrVal = I.getArgOperand(1); 15881 Info.offset = 0; 15882 Info.size = VT.getStoreSize(); 15883 Info.align = Align(1); 15884 Info.flags = MachineMemOperand::MOStore; 15885 return true; 15886 } 15887 default: 15888 break; 15889 } 15890 15891 return false; 15892 } 15893 15894 /// It returns EVT::Other if the type should be determined using generic 15895 /// target-independent logic. 15896 EVT PPCTargetLowering::getOptimalMemOpType( 15897 const MemOp &Op, const AttributeList &FuncAttributes) const { 15898 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15899 // When expanding a memset, require at least two QPX instructions to cover 15900 // the cost of loading the value to be stored from the constant pool. 15901 if (Subtarget.hasQPX() && Op.size() >= 32 && 15902 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15903 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15904 return MVT::v4f64; 15905 } 15906 15907 // We should use Altivec/VSX loads and stores when available. For unaligned 15908 // addresses, unaligned VSX loads are only fast starting with the P8. 15909 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15910 (Op.isAligned(Align(16)) || 15911 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15912 return MVT::v4i32; 15913 } 15914 15915 if (Subtarget.isPPC64()) { 15916 return MVT::i64; 15917 } 15918 15919 return MVT::i32; 15920 } 15921 15922 /// Returns true if it is beneficial to convert a load of a constant 15923 /// to just the constant itself. 15924 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15925 Type *Ty) const { 15926 assert(Ty->isIntegerTy()); 15927 15928 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15929 return !(BitSize == 0 || BitSize > 64); 15930 } 15931 15932 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15933 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15934 return false; 15935 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15936 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15937 return NumBits1 == 64 && NumBits2 == 32; 15938 } 15939 15940 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15941 if (!VT1.isInteger() || !VT2.isInteger()) 15942 return false; 15943 unsigned NumBits1 = VT1.getSizeInBits(); 15944 unsigned NumBits2 = VT2.getSizeInBits(); 15945 return NumBits1 == 64 && NumBits2 == 32; 15946 } 15947 15948 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15949 // Generally speaking, zexts are not free, but they are free when they can be 15950 // folded with other operations. 15951 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15952 EVT MemVT = LD->getMemoryVT(); 15953 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15954 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15955 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15956 LD->getExtensionType() == ISD::ZEXTLOAD)) 15957 return true; 15958 } 15959 15960 // FIXME: Add other cases... 15961 // - 32-bit shifts with a zext to i64 15962 // - zext after ctlz, bswap, etc. 15963 // - zext after and by a constant mask 15964 15965 return TargetLowering::isZExtFree(Val, VT2); 15966 } 15967 15968 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15969 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15970 "invalid fpext types"); 15971 // Extending to float128 is not free. 15972 if (DestVT == MVT::f128) 15973 return false; 15974 return true; 15975 } 15976 15977 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15978 return isInt<16>(Imm) || isUInt<16>(Imm); 15979 } 15980 15981 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15982 return isInt<16>(Imm) || isUInt<16>(Imm); 15983 } 15984 15985 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15986 unsigned, 15987 unsigned, 15988 MachineMemOperand::Flags, 15989 bool *Fast) const { 15990 if (DisablePPCUnaligned) 15991 return false; 15992 15993 // PowerPC supports unaligned memory access for simple non-vector types. 15994 // Although accessing unaligned addresses is not as efficient as accessing 15995 // aligned addresses, it is generally more efficient than manual expansion, 15996 // and generally only traps for software emulation when crossing page 15997 // boundaries. 15998 15999 if (!VT.isSimple()) 16000 return false; 16001 16002 if (VT.isFloatingPoint() && !VT.isVector() && 16003 !Subtarget.allowsUnalignedFPAccess()) 16004 return false; 16005 16006 if (VT.getSimpleVT().isVector()) { 16007 if (Subtarget.hasVSX()) { 16008 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16009 VT != MVT::v4f32 && VT != MVT::v4i32) 16010 return false; 16011 } else { 16012 return false; 16013 } 16014 } 16015 16016 if (VT == MVT::ppcf128) 16017 return false; 16018 16019 if (Fast) 16020 *Fast = true; 16021 16022 return true; 16023 } 16024 16025 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16026 EVT VT) const { 16027 return isFMAFasterThanFMulAndFAdd( 16028 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16029 } 16030 16031 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16032 Type *Ty) const { 16033 switch (Ty->getScalarType()->getTypeID()) { 16034 case Type::FloatTyID: 16035 case Type::DoubleTyID: 16036 return true; 16037 case Type::FP128TyID: 16038 return EnableQuadPrecision && Subtarget.hasP9Vector(); 16039 default: 16040 return false; 16041 } 16042 } 16043 16044 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 16045 // FIXME: add more patterns which are profitable to hoist. 16046 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16047 if (I->getOpcode() != Instruction::FMul) 16048 return true; 16049 16050 if (!I->hasOneUse()) 16051 return true; 16052 16053 Instruction *User = I->user_back(); 16054 assert(User && "A single use instruction with no uses."); 16055 16056 if (User->getOpcode() != Instruction::FSub && 16057 User->getOpcode() != Instruction::FAdd) 16058 return true; 16059 16060 const TargetOptions &Options = getTargetMachine().Options; 16061 const Function *F = I->getFunction(); 16062 const DataLayout &DL = F->getParent()->getDataLayout(); 16063 Type *Ty = User->getOperand(0)->getType(); 16064 16065 return !( 16066 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16067 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16068 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16069 } 16070 16071 const MCPhysReg * 16072 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16073 // LR is a callee-save register, but we must treat it as clobbered by any call 16074 // site. Hence we include LR in the scratch registers, which are in turn added 16075 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16076 // to CTR, which is used by any indirect call. 16077 static const MCPhysReg ScratchRegs[] = { 16078 PPC::X12, PPC::LR8, PPC::CTR8, 0 16079 }; 16080 16081 return ScratchRegs; 16082 } 16083 16084 Register PPCTargetLowering::getExceptionPointerRegister( 16085 const Constant *PersonalityFn) const { 16086 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16087 } 16088 16089 Register PPCTargetLowering::getExceptionSelectorRegister( 16090 const Constant *PersonalityFn) const { 16091 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16092 } 16093 16094 bool 16095 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16096 EVT VT , unsigned DefinedValues) const { 16097 if (VT == MVT::v2i64) 16098 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16099 16100 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 16101 return true; 16102 16103 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16104 } 16105 16106 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16107 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16108 return TargetLowering::getSchedulingPreference(N); 16109 16110 return Sched::ILP; 16111 } 16112 16113 // Create a fast isel object. 16114 FastISel * 16115 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16116 const TargetLibraryInfo *LibInfo) const { 16117 return PPC::createFastISel(FuncInfo, LibInfo); 16118 } 16119 16120 // 'Inverted' means the FMA opcode after negating one multiplicand. 16121 // For example, (fma -a b c) = (fnmsub a b c) 16122 static unsigned invertFMAOpcode(unsigned Opc) { 16123 switch (Opc) { 16124 default: 16125 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16126 case ISD::FMA: 16127 return PPCISD::FNMSUB; 16128 case PPCISD::FNMSUB: 16129 return ISD::FMA; 16130 } 16131 } 16132 16133 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16134 bool LegalOps, bool OptForSize, 16135 NegatibleCost &Cost, 16136 unsigned Depth) const { 16137 if (Depth > SelectionDAG::MaxRecursionDepth) 16138 return SDValue(); 16139 16140 unsigned Opc = Op.getOpcode(); 16141 EVT VT = Op.getValueType(); 16142 SDNodeFlags Flags = Op.getNode()->getFlags(); 16143 16144 switch (Opc) { 16145 case PPCISD::FNMSUB: 16146 // TODO: QPX subtarget is deprecated. No transformation here. 16147 if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX()) 16148 break; 16149 16150 const TargetOptions &Options = getTargetMachine().Options; 16151 SDValue N0 = Op.getOperand(0); 16152 SDValue N1 = Op.getOperand(1); 16153 SDValue N2 = Op.getOperand(2); 16154 SDLoc Loc(Op); 16155 16156 NegatibleCost N2Cost = NegatibleCost::Expensive; 16157 SDValue NegN2 = 16158 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16159 16160 if (!NegN2) 16161 return SDValue(); 16162 16163 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16164 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16165 // These transformations may change sign of zeroes. For example, 16166 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16167 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16168 // Try and choose the cheaper one to negate. 16169 NegatibleCost N0Cost = NegatibleCost::Expensive; 16170 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16171 N0Cost, Depth + 1); 16172 16173 NegatibleCost N1Cost = NegatibleCost::Expensive; 16174 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16175 N1Cost, Depth + 1); 16176 16177 if (NegN0 && N0Cost <= N1Cost) { 16178 Cost = std::min(N0Cost, N2Cost); 16179 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16180 } else if (NegN1) { 16181 Cost = std::min(N1Cost, N2Cost); 16182 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16183 } 16184 } 16185 16186 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16187 if (isOperationLegal(ISD::FMA, VT)) { 16188 Cost = N2Cost; 16189 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16190 } 16191 16192 break; 16193 } 16194 16195 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16196 Cost, Depth); 16197 } 16198 16199 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16200 bool PPCTargetLowering::useLoadStackGuardNode() const { 16201 if (!Subtarget.isTargetLinux()) 16202 return TargetLowering::useLoadStackGuardNode(); 16203 return true; 16204 } 16205 16206 // Override to disable global variable loading on Linux. 16207 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16208 if (!Subtarget.isTargetLinux()) 16209 return TargetLowering::insertSSPDeclarations(M); 16210 } 16211 16212 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16213 bool ForCodeSize) const { 16214 if (!VT.isSimple() || !Subtarget.hasVSX()) 16215 return false; 16216 16217 switch(VT.getSimpleVT().SimpleTy) { 16218 default: 16219 // For FP types that are currently not supported by PPC backend, return 16220 // false. Examples: f16, f80. 16221 return false; 16222 case MVT::f32: 16223 case MVT::f64: 16224 case MVT::ppcf128: 16225 return Imm.isPosZero(); 16226 } 16227 } 16228 16229 // For vector shift operation op, fold 16230 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16231 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16232 SelectionDAG &DAG) { 16233 SDValue N0 = N->getOperand(0); 16234 SDValue N1 = N->getOperand(1); 16235 EVT VT = N0.getValueType(); 16236 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16237 unsigned Opcode = N->getOpcode(); 16238 unsigned TargetOpcode; 16239 16240 switch (Opcode) { 16241 default: 16242 llvm_unreachable("Unexpected shift operation"); 16243 case ISD::SHL: 16244 TargetOpcode = PPCISD::SHL; 16245 break; 16246 case ISD::SRL: 16247 TargetOpcode = PPCISD::SRL; 16248 break; 16249 case ISD::SRA: 16250 TargetOpcode = PPCISD::SRA; 16251 break; 16252 } 16253 16254 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16255 N1->getOpcode() == ISD::AND) 16256 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16257 if (Mask->getZExtValue() == OpSizeInBits - 1) 16258 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16259 16260 return SDValue(); 16261 } 16262 16263 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16264 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16265 return Value; 16266 16267 SDValue N0 = N->getOperand(0); 16268 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16269 if (!Subtarget.isISA3_0() || 16270 N0.getOpcode() != ISD::SIGN_EXTEND || 16271 N0.getOperand(0).getValueType() != MVT::i32 || 16272 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16273 return SDValue(); 16274 16275 // We can't save an operation here if the value is already extended, and 16276 // the existing shift is easier to combine. 16277 SDValue ExtsSrc = N0.getOperand(0); 16278 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16279 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16280 return SDValue(); 16281 16282 SDLoc DL(N0); 16283 SDValue ShiftBy = SDValue(CN1, 0); 16284 // We want the shift amount to be i32 on the extswli, but the shift could 16285 // have an i64. 16286 if (ShiftBy.getValueType() == MVT::i64) 16287 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16288 16289 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16290 ShiftBy); 16291 } 16292 16293 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16294 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16295 return Value; 16296 16297 return SDValue(); 16298 } 16299 16300 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16301 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16302 return Value; 16303 16304 return SDValue(); 16305 } 16306 16307 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16308 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16309 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16310 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16311 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16312 const PPCSubtarget &Subtarget) { 16313 if (!Subtarget.isPPC64()) 16314 return SDValue(); 16315 16316 SDValue LHS = N->getOperand(0); 16317 SDValue RHS = N->getOperand(1); 16318 16319 auto isZextOfCompareWithConstant = [](SDValue Op) { 16320 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16321 Op.getValueType() != MVT::i64) 16322 return false; 16323 16324 SDValue Cmp = Op.getOperand(0); 16325 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16326 Cmp.getOperand(0).getValueType() != MVT::i64) 16327 return false; 16328 16329 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16330 int64_t NegConstant = 0 - Constant->getSExtValue(); 16331 // Due to the limitations of the addi instruction, 16332 // -C is required to be [-32768, 32767]. 16333 return isInt<16>(NegConstant); 16334 } 16335 16336 return false; 16337 }; 16338 16339 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16340 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16341 16342 // If there is a pattern, canonicalize a zext operand to the RHS. 16343 if (LHSHasPattern && !RHSHasPattern) 16344 std::swap(LHS, RHS); 16345 else if (!LHSHasPattern && !RHSHasPattern) 16346 return SDValue(); 16347 16348 SDLoc DL(N); 16349 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16350 SDValue Cmp = RHS.getOperand(0); 16351 SDValue Z = Cmp.getOperand(0); 16352 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16353 16354 assert(Constant && "Constant Should not be a null pointer."); 16355 int64_t NegConstant = 0 - Constant->getSExtValue(); 16356 16357 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16358 default: break; 16359 case ISD::SETNE: { 16360 // when C == 0 16361 // --> addze X, (addic Z, -1).carry 16362 // / 16363 // add X, (zext(setne Z, C))-- 16364 // \ when -32768 <= -C <= 32767 && C != 0 16365 // --> addze X, (addic (addi Z, -C), -1).carry 16366 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16367 DAG.getConstant(NegConstant, DL, MVT::i64)); 16368 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16369 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16370 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16371 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16372 SDValue(Addc.getNode(), 1)); 16373 } 16374 case ISD::SETEQ: { 16375 // when C == 0 16376 // --> addze X, (subfic Z, 0).carry 16377 // / 16378 // add X, (zext(sete Z, C))-- 16379 // \ when -32768 <= -C <= 32767 && C != 0 16380 // --> addze X, (subfic (addi Z, -C), 0).carry 16381 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16382 DAG.getConstant(NegConstant, DL, MVT::i64)); 16383 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16384 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16385 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16386 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16387 SDValue(Subc.getNode(), 1)); 16388 } 16389 } 16390 16391 return SDValue(); 16392 } 16393 16394 // Transform 16395 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16396 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16397 // In this case both C1 and C2 must be known constants. 16398 // C1+C2 must fit into a 34 bit signed integer. 16399 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16400 const PPCSubtarget &Subtarget) { 16401 if (!Subtarget.isUsingPCRelativeCalls()) 16402 return SDValue(); 16403 16404 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16405 // If we find that node try to cast the Global Address and the Constant. 16406 SDValue LHS = N->getOperand(0); 16407 SDValue RHS = N->getOperand(1); 16408 16409 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16410 std::swap(LHS, RHS); 16411 16412 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16413 return SDValue(); 16414 16415 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16416 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16417 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16418 16419 // Check that both casts succeeded. 16420 if (!GSDN || !ConstNode) 16421 return SDValue(); 16422 16423 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16424 SDLoc DL(GSDN); 16425 16426 // The signed int offset needs to fit in 34 bits. 16427 if (!isInt<34>(NewOffset)) 16428 return SDValue(); 16429 16430 // The new global address is a copy of the old global address except 16431 // that it has the updated Offset. 16432 SDValue GA = 16433 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16434 NewOffset, GSDN->getTargetFlags()); 16435 SDValue MatPCRel = 16436 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16437 return MatPCRel; 16438 } 16439 16440 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16441 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16442 return Value; 16443 16444 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16445 return Value; 16446 16447 return SDValue(); 16448 } 16449 16450 // Detect TRUNCATE operations on bitcasts of float128 values. 16451 // What we are looking for here is the situtation where we extract a subset 16452 // of bits from a 128 bit float. 16453 // This can be of two forms: 16454 // 1) BITCAST of f128 feeding TRUNCATE 16455 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16456 // The reason this is required is because we do not have a legal i128 type 16457 // and so we want to prevent having to store the f128 and then reload part 16458 // of it. 16459 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16460 DAGCombinerInfo &DCI) const { 16461 // If we are using CRBits then try that first. 16462 if (Subtarget.useCRBits()) { 16463 // Check if CRBits did anything and return that if it did. 16464 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16465 return CRTruncValue; 16466 } 16467 16468 SDLoc dl(N); 16469 SDValue Op0 = N->getOperand(0); 16470 16471 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16472 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16473 EVT VT = N->getValueType(0); 16474 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16475 return SDValue(); 16476 SDValue Sub = Op0.getOperand(0); 16477 if (Sub.getOpcode() == ISD::SUB) { 16478 SDValue SubOp0 = Sub.getOperand(0); 16479 SDValue SubOp1 = Sub.getOperand(1); 16480 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16481 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16482 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16483 SubOp1.getOperand(0), 16484 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16485 } 16486 } 16487 } 16488 16489 // Looking for a truncate of i128 to i64. 16490 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16491 return SDValue(); 16492 16493 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16494 16495 // SRL feeding TRUNCATE. 16496 if (Op0.getOpcode() == ISD::SRL) { 16497 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16498 // The right shift has to be by 64 bits. 16499 if (!ConstNode || ConstNode->getZExtValue() != 64) 16500 return SDValue(); 16501 16502 // Switch the element number to extract. 16503 EltToExtract = EltToExtract ? 0 : 1; 16504 // Update Op0 past the SRL. 16505 Op0 = Op0.getOperand(0); 16506 } 16507 16508 // BITCAST feeding a TRUNCATE possibly via SRL. 16509 if (Op0.getOpcode() == ISD::BITCAST && 16510 Op0.getValueType() == MVT::i128 && 16511 Op0.getOperand(0).getValueType() == MVT::f128) { 16512 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16513 return DCI.DAG.getNode( 16514 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16515 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16516 } 16517 return SDValue(); 16518 } 16519 16520 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16521 SelectionDAG &DAG = DCI.DAG; 16522 16523 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16524 if (!ConstOpOrElement) 16525 return SDValue(); 16526 16527 // An imul is usually smaller than the alternative sequence for legal type. 16528 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16529 isOperationLegal(ISD::MUL, N->getValueType(0))) 16530 return SDValue(); 16531 16532 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16533 switch (this->Subtarget.getCPUDirective()) { 16534 default: 16535 // TODO: enhance the condition for subtarget before pwr8 16536 return false; 16537 case PPC::DIR_PWR8: 16538 // type mul add shl 16539 // scalar 4 1 1 16540 // vector 7 2 2 16541 return true; 16542 case PPC::DIR_PWR9: 16543 case PPC::DIR_PWR10: 16544 case PPC::DIR_PWR_FUTURE: 16545 // type mul add shl 16546 // scalar 5 2 2 16547 // vector 7 2 2 16548 16549 // The cycle RATIO of related operations are showed as a table above. 16550 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16551 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16552 // are 4, it is always profitable; but for 3 instrs patterns 16553 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16554 // So we should only do it for vector type. 16555 return IsAddOne && IsNeg ? VT.isVector() : true; 16556 } 16557 }; 16558 16559 EVT VT = N->getValueType(0); 16560 SDLoc DL(N); 16561 16562 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16563 bool IsNeg = MulAmt.isNegative(); 16564 APInt MulAmtAbs = MulAmt.abs(); 16565 16566 if ((MulAmtAbs - 1).isPowerOf2()) { 16567 // (mul x, 2^N + 1) => (add (shl x, N), x) 16568 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16569 16570 if (!IsProfitable(IsNeg, true, VT)) 16571 return SDValue(); 16572 16573 SDValue Op0 = N->getOperand(0); 16574 SDValue Op1 = 16575 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16576 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16577 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16578 16579 if (!IsNeg) 16580 return Res; 16581 16582 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16583 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16584 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16585 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16586 16587 if (!IsProfitable(IsNeg, false, VT)) 16588 return SDValue(); 16589 16590 SDValue Op0 = N->getOperand(0); 16591 SDValue Op1 = 16592 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16593 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16594 16595 if (!IsNeg) 16596 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16597 else 16598 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16599 16600 } else { 16601 return SDValue(); 16602 } 16603 } 16604 16605 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16606 // in combiner since we need to check SD flags and other subtarget features. 16607 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16608 DAGCombinerInfo &DCI) const { 16609 SDValue N0 = N->getOperand(0); 16610 SDValue N1 = N->getOperand(1); 16611 SDValue N2 = N->getOperand(2); 16612 SDNodeFlags Flags = N->getFlags(); 16613 EVT VT = N->getValueType(0); 16614 SelectionDAG &DAG = DCI.DAG; 16615 const TargetOptions &Options = getTargetMachine().Options; 16616 unsigned Opc = N->getOpcode(); 16617 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16618 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16619 SDLoc Loc(N); 16620 16621 // TODO: QPX subtarget is deprecated. No transformation here. 16622 if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT)) 16623 return SDValue(); 16624 16625 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16626 // since (fnmsub a b c)=-0 while c-ab=+0. 16627 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16628 return SDValue(); 16629 16630 // (fma (fneg a) b c) => (fnmsub a b c) 16631 // (fnmsub (fneg a) b c) => (fma a b c) 16632 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16633 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16634 16635 // (fma a (fneg b) c) => (fnmsub a b c) 16636 // (fnmsub a (fneg b) c) => (fma a b c) 16637 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16638 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16639 16640 return SDValue(); 16641 } 16642 16643 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16644 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16645 if (!Subtarget.is64BitELFABI()) 16646 return false; 16647 16648 // If not a tail call then no need to proceed. 16649 if (!CI->isTailCall()) 16650 return false; 16651 16652 // If sibling calls have been disabled and tail-calls aren't guaranteed 16653 // there is no reason to duplicate. 16654 auto &TM = getTargetMachine(); 16655 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16656 return false; 16657 16658 // Can't tail call a function called indirectly, or if it has variadic args. 16659 const Function *Callee = CI->getCalledFunction(); 16660 if (!Callee || Callee->isVarArg()) 16661 return false; 16662 16663 // Make sure the callee and caller calling conventions are eligible for tco. 16664 const Function *Caller = CI->getParent()->getParent(); 16665 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16666 CI->getCallingConv())) 16667 return false; 16668 16669 // If the function is local then we have a good chance at tail-calling it 16670 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16671 } 16672 16673 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16674 if (!Subtarget.hasVSX()) 16675 return false; 16676 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16677 return true; 16678 return VT == MVT::f32 || VT == MVT::f64 || 16679 VT == MVT::v4f32 || VT == MVT::v2f64; 16680 } 16681 16682 bool PPCTargetLowering:: 16683 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16684 const Value *Mask = AndI.getOperand(1); 16685 // If the mask is suitable for andi. or andis. we should sink the and. 16686 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16687 // Can't handle constants wider than 64-bits. 16688 if (CI->getBitWidth() > 64) 16689 return false; 16690 int64_t ConstVal = CI->getZExtValue(); 16691 return isUInt<16>(ConstVal) || 16692 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16693 } 16694 16695 // For non-constant masks, we can always use the record-form and. 16696 return true; 16697 } 16698 16699 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16700 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16701 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16702 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16703 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16704 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16705 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16706 assert(Subtarget.hasP9Altivec() && 16707 "Only combine this when P9 altivec supported!"); 16708 EVT VT = N->getValueType(0); 16709 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16710 return SDValue(); 16711 16712 SelectionDAG &DAG = DCI.DAG; 16713 SDLoc dl(N); 16714 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16715 // Even for signed integers, if it's known to be positive (as signed 16716 // integer) due to zero-extended inputs. 16717 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16718 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16719 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16720 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16721 (SubOpcd1 == ISD::ZERO_EXTEND || 16722 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16723 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16724 N->getOperand(0)->getOperand(0), 16725 N->getOperand(0)->getOperand(1), 16726 DAG.getTargetConstant(0, dl, MVT::i32)); 16727 } 16728 16729 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16730 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16731 N->getOperand(0).hasOneUse()) { 16732 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16733 N->getOperand(0)->getOperand(0), 16734 N->getOperand(0)->getOperand(1), 16735 DAG.getTargetConstant(1, dl, MVT::i32)); 16736 } 16737 } 16738 16739 return SDValue(); 16740 } 16741 16742 // For type v4i32/v8ii16/v16i8, transform 16743 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16744 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16745 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16746 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16747 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16748 DAGCombinerInfo &DCI) const { 16749 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16750 assert(Subtarget.hasP9Altivec() && 16751 "Only combine this when P9 altivec supported!"); 16752 16753 SelectionDAG &DAG = DCI.DAG; 16754 SDLoc dl(N); 16755 SDValue Cond = N->getOperand(0); 16756 SDValue TrueOpnd = N->getOperand(1); 16757 SDValue FalseOpnd = N->getOperand(2); 16758 EVT VT = N->getOperand(1).getValueType(); 16759 16760 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16761 FalseOpnd.getOpcode() != ISD::SUB) 16762 return SDValue(); 16763 16764 // ABSD only available for type v4i32/v8i16/v16i8 16765 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16766 return SDValue(); 16767 16768 // At least to save one more dependent computation 16769 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16770 return SDValue(); 16771 16772 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16773 16774 // Can only handle unsigned comparison here 16775 switch (CC) { 16776 default: 16777 return SDValue(); 16778 case ISD::SETUGT: 16779 case ISD::SETUGE: 16780 break; 16781 case ISD::SETULT: 16782 case ISD::SETULE: 16783 std::swap(TrueOpnd, FalseOpnd); 16784 break; 16785 } 16786 16787 SDValue CmpOpnd1 = Cond.getOperand(0); 16788 SDValue CmpOpnd2 = Cond.getOperand(1); 16789 16790 // SETCC CmpOpnd1 CmpOpnd2 cond 16791 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16792 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16793 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16794 TrueOpnd.getOperand(1) == CmpOpnd2 && 16795 FalseOpnd.getOperand(0) == CmpOpnd2 && 16796 FalseOpnd.getOperand(1) == CmpOpnd1) { 16797 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16798 CmpOpnd1, CmpOpnd2, 16799 DAG.getTargetConstant(0, dl, MVT::i32)); 16800 } 16801 16802 return SDValue(); 16803 } 16804