1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 STATISTIC(NumTailCalls, "Number of tail calls"); 125 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 126 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 127 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 128 129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 130 131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 132 133 // FIXME: Remove this once the bug has been fixed! 134 extern cl::opt<bool> ANDIGlueBug; 135 136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 137 const PPCSubtarget &STI) 138 : TargetLowering(TM), Subtarget(STI) { 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 if (Subtarget.isISA3_0()) { 170 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 171 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 172 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 174 } else { 175 // No extending loads from f16 or HW conversions back and forth. 176 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 177 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 178 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 179 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 180 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 181 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 182 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 183 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 184 } 185 186 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 187 188 // PowerPC has pre-inc load and store's. 189 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 194 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 199 if (!Subtarget.hasSPE()) { 200 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 204 } 205 206 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 207 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 208 for (MVT VT : ScalarIntVTs) { 209 setOperationAction(ISD::ADDC, VT, Legal); 210 setOperationAction(ISD::ADDE, VT, Legal); 211 setOperationAction(ISD::SUBC, VT, Legal); 212 setOperationAction(ISD::SUBE, VT, Legal); 213 } 214 215 if (Subtarget.useCRBits()) { 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 217 218 if (isPPC64 || Subtarget.hasFPCVT()) { 219 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 220 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 221 isPPC64 ? MVT::i64 : MVT::i32); 222 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 223 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 224 isPPC64 ? MVT::i64 : MVT::i32); 225 } else { 226 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 228 } 229 230 // PowerPC does not support direct load/store of condition registers. 231 setOperationAction(ISD::LOAD, MVT::i1, Custom); 232 setOperationAction(ISD::STORE, MVT::i1, Custom); 233 234 // FIXME: Remove this once the ANDI glue bug is fixed: 235 if (ANDIGlueBug) 236 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 237 238 for (MVT VT : MVT::integer_valuetypes()) { 239 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 241 setTruncStoreAction(VT, MVT::i1, Expand); 242 } 243 244 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 245 } 246 247 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 248 // PPC (the libcall is not available). 249 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 250 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 251 252 // We do not currently implement these libm ops for PowerPC. 253 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 254 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 259 260 // PowerPC has no SREM/UREM instructions unless we are on P9 261 // On P9 we may use a hardware instruction to compute the remainder. 262 // When the result of both the remainder and the division is required it is 263 // more efficient to compute the remainder from the result of the division 264 // rather than use the remainder instruction. The instructions are legalized 265 // directly because the DivRemPairsPass performs the transformation at the IR 266 // level. 267 if (Subtarget.isISA3_0()) { 268 setOperationAction(ISD::SREM, MVT::i32, Legal); 269 setOperationAction(ISD::UREM, MVT::i32, Legal); 270 setOperationAction(ISD::SREM, MVT::i64, Legal); 271 setOperationAction(ISD::UREM, MVT::i64, Legal); 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::STRICT_FP_TO_SINT, MVT::i32, Legal); 428 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 429 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 430 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 431 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 432 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 433 } else { 434 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 435 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 436 437 // PowerPC does not have [U|S]INT_TO_FP 438 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 439 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 440 } 441 442 if (Subtarget.hasDirectMove() && isPPC64) { 443 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 444 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 445 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 446 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 447 if (TM.Options.UnsafeFPMath) { 448 setOperationAction(ISD::LRINT, MVT::f64, Legal); 449 setOperationAction(ISD::LRINT, MVT::f32, Legal); 450 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 451 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 452 setOperationAction(ISD::LROUND, MVT::f64, Legal); 453 setOperationAction(ISD::LROUND, MVT::f32, Legal); 454 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 455 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 456 } 457 } else { 458 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 459 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 460 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 461 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 462 } 463 464 // We cannot sextinreg(i1). Expand to shifts. 465 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 466 467 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 468 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 469 // support continuation, user-level threading, and etc.. As a result, no 470 // other SjLj exception interfaces are implemented and please don't build 471 // your own exception handling based on them. 472 // LLVM/Clang supports zero-cost DWARF exception handling. 473 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 474 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 475 476 // We want to legalize GlobalAddress and ConstantPool nodes into the 477 // appropriate instructions to materialize the address. 478 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 479 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 480 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 481 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 482 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 483 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 484 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 485 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 486 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 487 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 488 489 // TRAP is legal. 490 setOperationAction(ISD::TRAP, MVT::Other, Legal); 491 492 // TRAMPOLINE is custom lowered. 493 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 494 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 495 496 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 497 setOperationAction(ISD::VASTART , MVT::Other, Custom); 498 499 if (Subtarget.is64BitELFABI()) { 500 // VAARG always uses double-word chunks, so promote anything smaller. 501 setOperationAction(ISD::VAARG, MVT::i1, Promote); 502 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 503 setOperationAction(ISD::VAARG, MVT::i8, Promote); 504 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 505 setOperationAction(ISD::VAARG, MVT::i16, Promote); 506 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 507 setOperationAction(ISD::VAARG, MVT::i32, Promote); 508 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 509 setOperationAction(ISD::VAARG, MVT::Other, Expand); 510 } else if (Subtarget.is32BitELFABI()) { 511 // VAARG is custom lowered with the 32-bit SVR4 ABI. 512 setOperationAction(ISD::VAARG, MVT::Other, Custom); 513 setOperationAction(ISD::VAARG, MVT::i64, Custom); 514 } else 515 setOperationAction(ISD::VAARG, MVT::Other, Expand); 516 517 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 518 if (Subtarget.is32BitELFABI()) 519 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 520 else 521 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 522 523 // Use the default implementation. 524 setOperationAction(ISD::VAEND , MVT::Other, Expand); 525 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 526 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 527 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 528 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 529 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 530 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 531 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 532 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 533 534 // We want to custom lower some of our intrinsics. 535 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 536 537 // To handle counter-based loop conditions. 538 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 539 540 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 541 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 542 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 543 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 544 545 // Comparisons that require checking two conditions. 546 if (Subtarget.hasSPE()) { 547 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 548 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 549 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 550 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 551 } 552 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 553 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 554 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 555 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 556 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 557 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 558 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 559 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 560 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 561 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 562 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 563 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 564 565 if (Subtarget.has64BitSupport()) { 566 // They also have instructions for converting between i64 and fp. 567 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 568 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 569 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 570 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 571 // This is just the low 32 bits of a (signed) fp->i64 conversion. 572 // We cannot do this with Promote because i64 is not a legal type. 573 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 574 575 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 576 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 577 } else { 578 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 579 if (Subtarget.hasSPE()) { 580 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 582 } else 583 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 584 } 585 586 // With the instructions enabled under FPCVT, we can do everything. 587 if (Subtarget.hasFPCVT()) { 588 if (Subtarget.has64BitSupport()) { 589 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 590 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 591 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 592 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 593 } 594 595 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 596 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 597 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 599 } 600 601 if (Subtarget.use64BitRegs()) { 602 // 64-bit PowerPC implementations can support i64 types directly 603 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 604 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 605 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 606 // 64-bit PowerPC wants to expand i128 shifts itself. 607 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 608 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 609 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 610 } else { 611 // 32-bit PowerPC wants to expand i64 shifts itself. 612 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 613 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 614 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 615 } 616 617 if (Subtarget.hasVSX()) { 618 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 619 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 620 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 621 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 622 } 623 624 if (Subtarget.hasAltivec()) { 625 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 626 setOperationAction(ISD::SADDSAT, VT, Legal); 627 setOperationAction(ISD::SSUBSAT, VT, Legal); 628 setOperationAction(ISD::UADDSAT, VT, Legal); 629 setOperationAction(ISD::USUBSAT, VT, Legal); 630 } 631 // First set operation action for all vector types to expand. Then we 632 // will selectively turn on ones that can be effectively codegen'd. 633 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 634 // add/sub are legal for all supported vector VT's. 635 setOperationAction(ISD::ADD, VT, Legal); 636 setOperationAction(ISD::SUB, VT, Legal); 637 638 // For v2i64, these are only valid with P8Vector. This is corrected after 639 // the loop. 640 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 641 setOperationAction(ISD::SMAX, VT, Legal); 642 setOperationAction(ISD::SMIN, VT, Legal); 643 setOperationAction(ISD::UMAX, VT, Legal); 644 setOperationAction(ISD::UMIN, VT, Legal); 645 } 646 else { 647 setOperationAction(ISD::SMAX, VT, Expand); 648 setOperationAction(ISD::SMIN, VT, Expand); 649 setOperationAction(ISD::UMAX, VT, Expand); 650 setOperationAction(ISD::UMIN, VT, Expand); 651 } 652 653 if (Subtarget.hasVSX()) { 654 setOperationAction(ISD::FMAXNUM, VT, Legal); 655 setOperationAction(ISD::FMINNUM, VT, Legal); 656 } 657 658 // Vector instructions introduced in P8 659 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 660 setOperationAction(ISD::CTPOP, VT, Legal); 661 setOperationAction(ISD::CTLZ, VT, Legal); 662 } 663 else { 664 setOperationAction(ISD::CTPOP, VT, Expand); 665 setOperationAction(ISD::CTLZ, VT, Expand); 666 } 667 668 // Vector instructions introduced in P9 669 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 670 setOperationAction(ISD::CTTZ, VT, Legal); 671 else 672 setOperationAction(ISD::CTTZ, VT, Expand); 673 674 // We promote all shuffles to v16i8. 675 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 676 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 677 678 // We promote all non-typed operations to v4i32. 679 setOperationAction(ISD::AND , VT, Promote); 680 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 681 setOperationAction(ISD::OR , VT, Promote); 682 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 683 setOperationAction(ISD::XOR , VT, Promote); 684 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 685 setOperationAction(ISD::LOAD , VT, Promote); 686 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 687 setOperationAction(ISD::SELECT, VT, Promote); 688 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 689 setOperationAction(ISD::VSELECT, VT, Legal); 690 setOperationAction(ISD::SELECT_CC, VT, Promote); 691 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 692 setOperationAction(ISD::STORE, VT, Promote); 693 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 694 695 // No other operations are legal. 696 setOperationAction(ISD::MUL , VT, Expand); 697 setOperationAction(ISD::SDIV, VT, Expand); 698 setOperationAction(ISD::SREM, VT, Expand); 699 setOperationAction(ISD::UDIV, VT, Expand); 700 setOperationAction(ISD::UREM, VT, Expand); 701 setOperationAction(ISD::FDIV, VT, Expand); 702 setOperationAction(ISD::FREM, VT, Expand); 703 setOperationAction(ISD::FNEG, VT, Expand); 704 setOperationAction(ISD::FSQRT, VT, Expand); 705 setOperationAction(ISD::FLOG, VT, Expand); 706 setOperationAction(ISD::FLOG10, VT, Expand); 707 setOperationAction(ISD::FLOG2, VT, Expand); 708 setOperationAction(ISD::FEXP, VT, Expand); 709 setOperationAction(ISD::FEXP2, VT, Expand); 710 setOperationAction(ISD::FSIN, VT, Expand); 711 setOperationAction(ISD::FCOS, VT, Expand); 712 setOperationAction(ISD::FABS, VT, Expand); 713 setOperationAction(ISD::FFLOOR, VT, Expand); 714 setOperationAction(ISD::FCEIL, VT, Expand); 715 setOperationAction(ISD::FTRUNC, VT, Expand); 716 setOperationAction(ISD::FRINT, VT, Expand); 717 setOperationAction(ISD::FNEARBYINT, VT, Expand); 718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 719 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 720 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 721 setOperationAction(ISD::MULHU, VT, Expand); 722 setOperationAction(ISD::MULHS, VT, Expand); 723 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 724 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 725 setOperationAction(ISD::UDIVREM, VT, Expand); 726 setOperationAction(ISD::SDIVREM, VT, Expand); 727 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 728 setOperationAction(ISD::FPOW, VT, Expand); 729 setOperationAction(ISD::BSWAP, VT, Expand); 730 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 731 setOperationAction(ISD::ROTL, VT, Expand); 732 setOperationAction(ISD::ROTR, VT, Expand); 733 734 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 735 setTruncStoreAction(VT, InnerVT, Expand); 736 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 737 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 738 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 739 } 740 } 741 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 742 if (!Subtarget.hasP8Vector()) { 743 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 744 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 745 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 746 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 747 } 748 749 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 750 setOperationAction(ISD::ABS, VT, Custom); 751 752 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 753 // with merges, splats, etc. 754 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 755 756 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 757 // are cheap, so handle them before they get expanded to scalar. 758 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 759 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 760 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 761 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 762 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 763 764 setOperationAction(ISD::AND , MVT::v4i32, Legal); 765 setOperationAction(ISD::OR , MVT::v4i32, Legal); 766 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 767 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 768 setOperationAction(ISD::SELECT, MVT::v4i32, 769 Subtarget.useCRBits() ? Legal : Expand); 770 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 771 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 772 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 773 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 774 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 775 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 776 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 777 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 778 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 779 780 // Without hasP8Altivec set, v2i64 SMAX isn't available. 781 // But ABS custom lowering requires SMAX support. 782 if (!Subtarget.hasP8Altivec()) 783 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 784 785 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 786 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 787 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 788 if (Subtarget.hasAltivec()) 789 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 790 setOperationAction(ISD::ROTL, VT, Legal); 791 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 792 if (Subtarget.hasP8Altivec()) 793 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 794 795 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 796 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 797 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 798 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 799 800 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 801 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 802 803 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 804 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 805 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 806 } 807 808 if (Subtarget.hasP8Altivec()) 809 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 810 else 811 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 812 813 if (Subtarget.isISA3_1()) { 814 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 815 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 816 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 817 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 818 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 819 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 820 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 821 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 822 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 823 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 824 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 825 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 826 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 827 } 828 829 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 830 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 831 832 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 833 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 834 835 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 836 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 837 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 838 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 839 840 // Altivec does not contain unordered floating-point compare instructions 841 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 842 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 843 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 844 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 845 846 if (Subtarget.hasVSX()) { 847 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 848 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 849 if (Subtarget.hasP8Vector()) { 850 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 851 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 852 } 853 if (Subtarget.hasDirectMove() && isPPC64) { 854 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 855 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 856 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 857 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 858 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 859 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 860 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 862 } 863 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 864 865 // The nearbyint variants are not allowed to raise the inexact exception 866 // so we can only code-gen them with unsafe math. 867 if (TM.Options.UnsafeFPMath) { 868 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 869 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 870 } 871 872 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 873 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 874 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 875 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 876 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 877 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 878 setOperationAction(ISD::FROUND, MVT::f64, Legal); 879 setOperationAction(ISD::FRINT, MVT::f64, Legal); 880 881 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 882 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 883 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 884 setOperationAction(ISD::FROUND, MVT::f32, Legal); 885 setOperationAction(ISD::FRINT, MVT::f32, Legal); 886 887 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 888 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 889 890 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 891 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 892 893 // Share the Altivec comparison restrictions. 894 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 895 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 896 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 897 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 898 899 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 900 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 901 902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 903 904 if (Subtarget.hasP8Vector()) 905 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 906 907 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 908 909 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 910 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 911 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 912 913 if (Subtarget.hasP8Altivec()) { 914 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 915 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 916 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 917 918 // 128 bit shifts can be accomplished via 3 instructions for SHL and 919 // SRL, but not for SRA because of the instructions available: 920 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 921 // doing 922 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 923 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 924 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 925 926 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 927 } 928 else { 929 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 930 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 931 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 932 933 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 934 935 // VSX v2i64 only supports non-arithmetic operations. 936 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 937 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 938 } 939 940 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 941 942 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 943 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 944 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 945 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 946 947 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 948 949 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 950 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 951 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 952 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 953 954 // Custom handling for partial vectors of integers converted to 955 // floating point. We already have optimal handling for v2i32 through 956 // the DAG combine, so those aren't necessary. 957 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 958 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 959 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 960 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 961 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 962 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 963 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 964 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 965 966 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 967 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 968 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 969 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 970 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 971 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 972 973 if (Subtarget.hasDirectMove()) 974 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 975 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 976 977 // Handle constrained floating-point operations of vector. 978 // The predictor is `hasVSX` because altivec instruction has 979 // no exception but VSX vector instruction has. 980 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 981 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 982 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 983 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 984 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 985 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 986 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 987 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 988 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 989 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 990 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 991 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 992 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 993 994 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 995 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 996 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 997 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 998 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 999 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1000 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1001 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1002 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 1003 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1004 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1005 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1006 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1007 1008 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1009 } 1010 1011 if (Subtarget.hasP8Altivec()) { 1012 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1013 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1014 } 1015 1016 if (Subtarget.hasP9Vector()) { 1017 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1019 1020 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1021 // SRL, but not for SRA because of the instructions available: 1022 // VS{RL} and VS{RL}O. 1023 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1024 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1025 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1026 1027 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1028 setOperationAction(ISD::FADD, MVT::f128, Legal); 1029 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1030 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1031 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1032 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1033 // No extending loads to f128 on PPC. 1034 for (MVT FPT : MVT::fp_valuetypes()) 1035 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1036 setOperationAction(ISD::FMA, MVT::f128, Legal); 1037 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1038 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1039 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1040 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1041 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1042 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1043 1044 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1045 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1046 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1047 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1048 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1049 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1050 1051 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1052 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1053 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1054 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1055 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1056 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1057 // No implementation for these ops for PowerPC. 1058 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1059 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1060 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1061 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1062 setOperationAction(ISD::FREM, MVT::f128, Expand); 1063 1064 // Handle constrained floating-point operations of fp128 1065 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1066 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1067 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1068 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1069 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1070 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1071 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1072 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1073 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1074 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1075 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1076 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1077 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1078 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1079 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1080 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1081 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1082 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1083 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1084 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1085 } 1086 1087 if (Subtarget.hasP9Altivec()) { 1088 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1089 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1090 1091 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1092 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1093 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1094 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1095 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1096 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1097 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1098 } 1099 } 1100 1101 if (Subtarget.has64BitSupport()) 1102 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1103 1104 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1105 1106 if (!isPPC64) { 1107 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1108 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1109 } 1110 1111 setBooleanContents(ZeroOrOneBooleanContent); 1112 1113 if (Subtarget.hasAltivec()) { 1114 // Altivec instructions set fields to all zeros or all ones. 1115 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1116 } 1117 1118 if (!isPPC64) { 1119 // These libcalls are not available in 32-bit. 1120 setLibcallName(RTLIB::SHL_I128, nullptr); 1121 setLibcallName(RTLIB::SRL_I128, nullptr); 1122 setLibcallName(RTLIB::SRA_I128, nullptr); 1123 } 1124 1125 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1126 1127 // We have target-specific dag combine patterns for the following nodes: 1128 setTargetDAGCombine(ISD::ADD); 1129 setTargetDAGCombine(ISD::SHL); 1130 setTargetDAGCombine(ISD::SRA); 1131 setTargetDAGCombine(ISD::SRL); 1132 setTargetDAGCombine(ISD::MUL); 1133 setTargetDAGCombine(ISD::FMA); 1134 setTargetDAGCombine(ISD::SINT_TO_FP); 1135 setTargetDAGCombine(ISD::BUILD_VECTOR); 1136 if (Subtarget.hasFPCVT()) 1137 setTargetDAGCombine(ISD::UINT_TO_FP); 1138 setTargetDAGCombine(ISD::LOAD); 1139 setTargetDAGCombine(ISD::STORE); 1140 setTargetDAGCombine(ISD::BR_CC); 1141 if (Subtarget.useCRBits()) 1142 setTargetDAGCombine(ISD::BRCOND); 1143 setTargetDAGCombine(ISD::BSWAP); 1144 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1145 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1146 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1147 1148 setTargetDAGCombine(ISD::SIGN_EXTEND); 1149 setTargetDAGCombine(ISD::ZERO_EXTEND); 1150 setTargetDAGCombine(ISD::ANY_EXTEND); 1151 1152 setTargetDAGCombine(ISD::TRUNCATE); 1153 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1154 1155 1156 if (Subtarget.useCRBits()) { 1157 setTargetDAGCombine(ISD::TRUNCATE); 1158 setTargetDAGCombine(ISD::SETCC); 1159 setTargetDAGCombine(ISD::SELECT_CC); 1160 } 1161 1162 // Use reciprocal estimates. 1163 if (TM.Options.UnsafeFPMath) { 1164 setTargetDAGCombine(ISD::FDIV); 1165 setTargetDAGCombine(ISD::FSQRT); 1166 } 1167 1168 if (Subtarget.hasP9Altivec()) { 1169 setTargetDAGCombine(ISD::ABS); 1170 setTargetDAGCombine(ISD::VSELECT); 1171 } 1172 1173 setLibcallName(RTLIB::LOG_F128, "logf128"); 1174 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1175 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1176 setLibcallName(RTLIB::EXP_F128, "expf128"); 1177 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1178 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1179 setLibcallName(RTLIB::COS_F128, "cosf128"); 1180 setLibcallName(RTLIB::POW_F128, "powf128"); 1181 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1182 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1183 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1184 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1185 1186 // With 32 condition bits, we don't need to sink (and duplicate) compares 1187 // aggressively in CodeGenPrep. 1188 if (Subtarget.useCRBits()) { 1189 setHasMultipleConditionRegisters(); 1190 setJumpIsExpensive(); 1191 } 1192 1193 setMinFunctionAlignment(Align(4)); 1194 1195 switch (Subtarget.getCPUDirective()) { 1196 default: break; 1197 case PPC::DIR_970: 1198 case PPC::DIR_A2: 1199 case PPC::DIR_E500: 1200 case PPC::DIR_E500mc: 1201 case PPC::DIR_E5500: 1202 case PPC::DIR_PWR4: 1203 case PPC::DIR_PWR5: 1204 case PPC::DIR_PWR5X: 1205 case PPC::DIR_PWR6: 1206 case PPC::DIR_PWR6X: 1207 case PPC::DIR_PWR7: 1208 case PPC::DIR_PWR8: 1209 case PPC::DIR_PWR9: 1210 case PPC::DIR_PWR10: 1211 case PPC::DIR_PWR_FUTURE: 1212 setPrefLoopAlignment(Align(16)); 1213 setPrefFunctionAlignment(Align(16)); 1214 break; 1215 } 1216 1217 if (Subtarget.enableMachineScheduler()) 1218 setSchedulingPreference(Sched::Source); 1219 else 1220 setSchedulingPreference(Sched::Hybrid); 1221 1222 computeRegisterProperties(STI.getRegisterInfo()); 1223 1224 // The Freescale cores do better with aggressive inlining of memcpy and 1225 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1226 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1227 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1228 MaxStoresPerMemset = 32; 1229 MaxStoresPerMemsetOptSize = 16; 1230 MaxStoresPerMemcpy = 32; 1231 MaxStoresPerMemcpyOptSize = 8; 1232 MaxStoresPerMemmove = 32; 1233 MaxStoresPerMemmoveOptSize = 8; 1234 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1235 // The A2 also benefits from (very) aggressive inlining of memcpy and 1236 // friends. The overhead of a the function call, even when warm, can be 1237 // over one hundred cycles. 1238 MaxStoresPerMemset = 128; 1239 MaxStoresPerMemcpy = 128; 1240 MaxStoresPerMemmove = 128; 1241 MaxLoadsPerMemcmp = 128; 1242 } else { 1243 MaxLoadsPerMemcmp = 8; 1244 MaxLoadsPerMemcmpOptSize = 4; 1245 } 1246 1247 // Let the subtarget (CPU) decide if a predictable select is more expensive 1248 // than the corresponding branch. This information is used in CGP to decide 1249 // when to convert selects into branches. 1250 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1251 } 1252 1253 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1254 /// the desired ByVal argument alignment. 1255 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1256 if (MaxAlign == MaxMaxAlign) 1257 return; 1258 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1259 if (MaxMaxAlign >= 32 && 1260 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1261 MaxAlign = Align(32); 1262 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1263 MaxAlign < 16) 1264 MaxAlign = Align(16); 1265 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1266 Align EltAlign; 1267 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1268 if (EltAlign > MaxAlign) 1269 MaxAlign = EltAlign; 1270 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1271 for (auto *EltTy : STy->elements()) { 1272 Align EltAlign; 1273 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1274 if (EltAlign > MaxAlign) 1275 MaxAlign = EltAlign; 1276 if (MaxAlign == MaxMaxAlign) 1277 break; 1278 } 1279 } 1280 } 1281 1282 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1283 /// function arguments in the caller parameter area. 1284 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1285 const DataLayout &DL) const { 1286 // 16byte and wider vectors are passed on 16byte boundary. 1287 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1288 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1289 if (Subtarget.hasAltivec()) 1290 getMaxByValAlign(Ty, Alignment, Align(16)); 1291 return Alignment.value(); 1292 } 1293 1294 bool PPCTargetLowering::useSoftFloat() const { 1295 return Subtarget.useSoftFloat(); 1296 } 1297 1298 bool PPCTargetLowering::hasSPE() const { 1299 return Subtarget.hasSPE(); 1300 } 1301 1302 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1303 return VT.isScalarInteger(); 1304 } 1305 1306 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1307 /// type is cheaper than a multiply followed by a shift. 1308 /// This is true for words and doublewords on 64-bit PowerPC. 1309 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1310 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1311 isOperationLegal(ISD::MULHU, Type))) 1312 return true; 1313 return TargetLowering::isMulhCheaperThanMulShift(Type); 1314 } 1315 1316 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1317 switch ((PPCISD::NodeType)Opcode) { 1318 case PPCISD::FIRST_NUMBER: break; 1319 case PPCISD::FSEL: return "PPCISD::FSEL"; 1320 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1321 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1322 case PPCISD::FCFID: return "PPCISD::FCFID"; 1323 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1324 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1325 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1326 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1327 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1328 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1329 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1330 case PPCISD::FP_TO_UINT_IN_VSR: 1331 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1332 case PPCISD::FP_TO_SINT_IN_VSR: 1333 return "PPCISD::FP_TO_SINT_IN_VSR"; 1334 case PPCISD::FRE: return "PPCISD::FRE"; 1335 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1336 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1337 case PPCISD::VPERM: return "PPCISD::VPERM"; 1338 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1339 case PPCISD::XXSPLTI_SP_TO_DP: 1340 return "PPCISD::XXSPLTI_SP_TO_DP"; 1341 case PPCISD::XXSPLTI32DX: 1342 return "PPCISD::XXSPLTI32DX"; 1343 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1344 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1345 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1346 case PPCISD::CMPB: return "PPCISD::CMPB"; 1347 case PPCISD::Hi: return "PPCISD::Hi"; 1348 case PPCISD::Lo: return "PPCISD::Lo"; 1349 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1350 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1351 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1352 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1353 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1354 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1355 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1356 case PPCISD::SRL: return "PPCISD::SRL"; 1357 case PPCISD::SRA: return "PPCISD::SRA"; 1358 case PPCISD::SHL: return "PPCISD::SHL"; 1359 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1360 case PPCISD::CALL: return "PPCISD::CALL"; 1361 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1362 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1363 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1364 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1365 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1366 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1367 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1368 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1369 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1370 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1371 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1372 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1373 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1374 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1375 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1376 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1377 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1378 case PPCISD::ANDI_rec_1_EQ_BIT: 1379 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1380 case PPCISD::ANDI_rec_1_GT_BIT: 1381 return "PPCISD::ANDI_rec_1_GT_BIT"; 1382 case PPCISD::VCMP: return "PPCISD::VCMP"; 1383 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1384 case PPCISD::LBRX: return "PPCISD::LBRX"; 1385 case PPCISD::STBRX: return "PPCISD::STBRX"; 1386 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1387 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1388 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1389 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1390 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1391 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1392 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1393 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1394 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1395 case PPCISD::ST_VSR_SCAL_INT: 1396 return "PPCISD::ST_VSR_SCAL_INT"; 1397 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1398 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1399 case PPCISD::BDZ: return "PPCISD::BDZ"; 1400 case PPCISD::MFFS: return "PPCISD::MFFS"; 1401 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1402 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1403 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1404 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1405 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1406 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1407 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1408 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1409 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1410 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1411 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1412 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1413 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1414 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1415 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1416 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1417 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1418 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1419 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1420 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1421 case PPCISD::SC: return "PPCISD::SC"; 1422 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1423 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1424 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1425 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1426 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1427 case PPCISD::VABSD: return "PPCISD::VABSD"; 1428 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1429 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1430 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1431 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1432 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1433 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1434 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1435 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1436 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1437 } 1438 return nullptr; 1439 } 1440 1441 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1442 EVT VT) const { 1443 if (!VT.isVector()) 1444 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1445 1446 return VT.changeVectorElementTypeToInteger(); 1447 } 1448 1449 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1450 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1451 return true; 1452 } 1453 1454 //===----------------------------------------------------------------------===// 1455 // Node matching predicates, for use by the tblgen matching code. 1456 //===----------------------------------------------------------------------===// 1457 1458 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1459 static bool isFloatingPointZero(SDValue Op) { 1460 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1461 return CFP->getValueAPF().isZero(); 1462 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1463 // Maybe this has already been legalized into the constant pool? 1464 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1465 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1466 return CFP->getValueAPF().isZero(); 1467 } 1468 return false; 1469 } 1470 1471 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1472 /// true if Op is undef or if it matches the specified value. 1473 static bool isConstantOrUndef(int Op, int Val) { 1474 return Op < 0 || Op == Val; 1475 } 1476 1477 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1478 /// VPKUHUM instruction. 1479 /// The ShuffleKind distinguishes between big-endian operations with 1480 /// two different inputs (0), either-endian operations with two identical 1481 /// inputs (1), and little-endian operations with two different inputs (2). 1482 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1483 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1484 SelectionDAG &DAG) { 1485 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1486 if (ShuffleKind == 0) { 1487 if (IsLE) 1488 return false; 1489 for (unsigned i = 0; i != 16; ++i) 1490 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1491 return false; 1492 } else if (ShuffleKind == 2) { 1493 if (!IsLE) 1494 return false; 1495 for (unsigned i = 0; i != 16; ++i) 1496 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1497 return false; 1498 } else if (ShuffleKind == 1) { 1499 unsigned j = IsLE ? 0 : 1; 1500 for (unsigned i = 0; i != 8; ++i) 1501 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1502 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1503 return false; 1504 } 1505 return true; 1506 } 1507 1508 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1509 /// VPKUWUM instruction. 1510 /// The ShuffleKind distinguishes between big-endian operations with 1511 /// two different inputs (0), either-endian operations with two identical 1512 /// inputs (1), and little-endian operations with two different inputs (2). 1513 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1514 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1515 SelectionDAG &DAG) { 1516 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1517 if (ShuffleKind == 0) { 1518 if (IsLE) 1519 return false; 1520 for (unsigned i = 0; i != 16; i += 2) 1521 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1522 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1523 return false; 1524 } else if (ShuffleKind == 2) { 1525 if (!IsLE) 1526 return false; 1527 for (unsigned i = 0; i != 16; i += 2) 1528 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1529 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1530 return false; 1531 } else if (ShuffleKind == 1) { 1532 unsigned j = IsLE ? 0 : 2; 1533 for (unsigned i = 0; i != 8; i += 2) 1534 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1535 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1536 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1537 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1538 return false; 1539 } 1540 return true; 1541 } 1542 1543 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1544 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1545 /// current subtarget. 1546 /// 1547 /// The ShuffleKind distinguishes between big-endian operations with 1548 /// two different inputs (0), either-endian operations with two identical 1549 /// inputs (1), and little-endian operations with two different inputs (2). 1550 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1551 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1552 SelectionDAG &DAG) { 1553 const PPCSubtarget& Subtarget = 1554 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1555 if (!Subtarget.hasP8Vector()) 1556 return false; 1557 1558 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1559 if (ShuffleKind == 0) { 1560 if (IsLE) 1561 return false; 1562 for (unsigned i = 0; i != 16; i += 4) 1563 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1564 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1565 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1566 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1567 return false; 1568 } else if (ShuffleKind == 2) { 1569 if (!IsLE) 1570 return false; 1571 for (unsigned i = 0; i != 16; i += 4) 1572 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1573 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1574 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1575 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1576 return false; 1577 } else if (ShuffleKind == 1) { 1578 unsigned j = IsLE ? 0 : 4; 1579 for (unsigned i = 0; i != 8; i += 4) 1580 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1581 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1582 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1583 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1584 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1585 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1586 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1587 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1588 return false; 1589 } 1590 return true; 1591 } 1592 1593 /// isVMerge - Common function, used to match vmrg* shuffles. 1594 /// 1595 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1596 unsigned LHSStart, unsigned RHSStart) { 1597 if (N->getValueType(0) != MVT::v16i8) 1598 return false; 1599 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1600 "Unsupported merge size!"); 1601 1602 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1603 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1604 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1605 LHSStart+j+i*UnitSize) || 1606 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1607 RHSStart+j+i*UnitSize)) 1608 return false; 1609 } 1610 return true; 1611 } 1612 1613 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1614 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1615 /// The ShuffleKind distinguishes between big-endian merges with two 1616 /// different inputs (0), either-endian merges with two identical inputs (1), 1617 /// and little-endian merges with two different inputs (2). For the latter, 1618 /// the input operands are swapped (see PPCInstrAltivec.td). 1619 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1620 unsigned ShuffleKind, SelectionDAG &DAG) { 1621 if (DAG.getDataLayout().isLittleEndian()) { 1622 if (ShuffleKind == 1) // unary 1623 return isVMerge(N, UnitSize, 0, 0); 1624 else if (ShuffleKind == 2) // swapped 1625 return isVMerge(N, UnitSize, 0, 16); 1626 else 1627 return false; 1628 } else { 1629 if (ShuffleKind == 1) // unary 1630 return isVMerge(N, UnitSize, 8, 8); 1631 else if (ShuffleKind == 0) // normal 1632 return isVMerge(N, UnitSize, 8, 24); 1633 else 1634 return false; 1635 } 1636 } 1637 1638 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1639 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1640 /// The ShuffleKind distinguishes between big-endian merges with two 1641 /// different inputs (0), either-endian merges with two identical inputs (1), 1642 /// and little-endian merges with two different inputs (2). For the latter, 1643 /// the input operands are swapped (see PPCInstrAltivec.td). 1644 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1645 unsigned ShuffleKind, SelectionDAG &DAG) { 1646 if (DAG.getDataLayout().isLittleEndian()) { 1647 if (ShuffleKind == 1) // unary 1648 return isVMerge(N, UnitSize, 8, 8); 1649 else if (ShuffleKind == 2) // swapped 1650 return isVMerge(N, UnitSize, 8, 24); 1651 else 1652 return false; 1653 } else { 1654 if (ShuffleKind == 1) // unary 1655 return isVMerge(N, UnitSize, 0, 0); 1656 else if (ShuffleKind == 0) // normal 1657 return isVMerge(N, UnitSize, 0, 16); 1658 else 1659 return false; 1660 } 1661 } 1662 1663 /** 1664 * Common function used to match vmrgew and vmrgow shuffles 1665 * 1666 * The indexOffset determines whether to look for even or odd words in 1667 * the shuffle mask. This is based on the of the endianness of the target 1668 * machine. 1669 * - Little Endian: 1670 * - Use offset of 0 to check for odd elements 1671 * - Use offset of 4 to check for even elements 1672 * - Big Endian: 1673 * - Use offset of 0 to check for even elements 1674 * - Use offset of 4 to check for odd elements 1675 * A detailed description of the vector element ordering for little endian and 1676 * big endian can be found at 1677 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1678 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1679 * compiler differences mean to you 1680 * 1681 * The mask to the shuffle vector instruction specifies the indices of the 1682 * elements from the two input vectors to place in the result. The elements are 1683 * numbered in array-access order, starting with the first vector. These vectors 1684 * are always of type v16i8, thus each vector will contain 16 elements of size 1685 * 8. More info on the shuffle vector can be found in the 1686 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1687 * Language Reference. 1688 * 1689 * The RHSStartValue indicates whether the same input vectors are used (unary) 1690 * or two different input vectors are used, based on the following: 1691 * - If the instruction uses the same vector for both inputs, the range of the 1692 * indices will be 0 to 15. In this case, the RHSStart value passed should 1693 * be 0. 1694 * - If the instruction has two different vectors then the range of the 1695 * indices will be 0 to 31. In this case, the RHSStart value passed should 1696 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1697 * to 31 specify elements in the second vector). 1698 * 1699 * \param[in] N The shuffle vector SD Node to analyze 1700 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1701 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1702 * vector to the shuffle_vector instruction 1703 * \return true iff this shuffle vector represents an even or odd word merge 1704 */ 1705 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1706 unsigned RHSStartValue) { 1707 if (N->getValueType(0) != MVT::v16i8) 1708 return false; 1709 1710 for (unsigned i = 0; i < 2; ++i) 1711 for (unsigned j = 0; j < 4; ++j) 1712 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1713 i*RHSStartValue+j+IndexOffset) || 1714 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1715 i*RHSStartValue+j+IndexOffset+8)) 1716 return false; 1717 return true; 1718 } 1719 1720 /** 1721 * Determine if the specified shuffle mask is suitable for the vmrgew or 1722 * vmrgow instructions. 1723 * 1724 * \param[in] N The shuffle vector SD Node to analyze 1725 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1726 * \param[in] ShuffleKind Identify the type of merge: 1727 * - 0 = big-endian merge with two different inputs; 1728 * - 1 = either-endian merge with two identical inputs; 1729 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1730 * little-endian merges). 1731 * \param[in] DAG The current SelectionDAG 1732 * \return true iff this shuffle mask 1733 */ 1734 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1735 unsigned ShuffleKind, SelectionDAG &DAG) { 1736 if (DAG.getDataLayout().isLittleEndian()) { 1737 unsigned indexOffset = CheckEven ? 4 : 0; 1738 if (ShuffleKind == 1) // Unary 1739 return isVMerge(N, indexOffset, 0); 1740 else if (ShuffleKind == 2) // swapped 1741 return isVMerge(N, indexOffset, 16); 1742 else 1743 return false; 1744 } 1745 else { 1746 unsigned indexOffset = CheckEven ? 0 : 4; 1747 if (ShuffleKind == 1) // Unary 1748 return isVMerge(N, indexOffset, 0); 1749 else if (ShuffleKind == 0) // Normal 1750 return isVMerge(N, indexOffset, 16); 1751 else 1752 return false; 1753 } 1754 return false; 1755 } 1756 1757 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1758 /// amount, otherwise return -1. 1759 /// The ShuffleKind distinguishes between big-endian operations with two 1760 /// different inputs (0), either-endian operations with two identical inputs 1761 /// (1), and little-endian operations with two different inputs (2). For the 1762 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1763 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1764 SelectionDAG &DAG) { 1765 if (N->getValueType(0) != MVT::v16i8) 1766 return -1; 1767 1768 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1769 1770 // Find the first non-undef value in the shuffle mask. 1771 unsigned i; 1772 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1773 /*search*/; 1774 1775 if (i == 16) return -1; // all undef. 1776 1777 // Otherwise, check to see if the rest of the elements are consecutively 1778 // numbered from this value. 1779 unsigned ShiftAmt = SVOp->getMaskElt(i); 1780 if (ShiftAmt < i) return -1; 1781 1782 ShiftAmt -= i; 1783 bool isLE = DAG.getDataLayout().isLittleEndian(); 1784 1785 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1786 // Check the rest of the elements to see if they are consecutive. 1787 for (++i; i != 16; ++i) 1788 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1789 return -1; 1790 } else if (ShuffleKind == 1) { 1791 // Check the rest of the elements to see if they are consecutive. 1792 for (++i; i != 16; ++i) 1793 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1794 return -1; 1795 } else 1796 return -1; 1797 1798 if (isLE) 1799 ShiftAmt = 16 - ShiftAmt; 1800 1801 return ShiftAmt; 1802 } 1803 1804 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1805 /// specifies a splat of a single element that is suitable for input to 1806 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1807 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1808 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1809 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1810 1811 // The consecutive indices need to specify an element, not part of two 1812 // different elements. So abandon ship early if this isn't the case. 1813 if (N->getMaskElt(0) % EltSize != 0) 1814 return false; 1815 1816 // This is a splat operation if each element of the permute is the same, and 1817 // if the value doesn't reference the second vector. 1818 unsigned ElementBase = N->getMaskElt(0); 1819 1820 // FIXME: Handle UNDEF elements too! 1821 if (ElementBase >= 16) 1822 return false; 1823 1824 // Check that the indices are consecutive, in the case of a multi-byte element 1825 // splatted with a v16i8 mask. 1826 for (unsigned i = 1; i != EltSize; ++i) 1827 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1828 return false; 1829 1830 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1831 if (N->getMaskElt(i) < 0) continue; 1832 for (unsigned j = 0; j != EltSize; ++j) 1833 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1834 return false; 1835 } 1836 return true; 1837 } 1838 1839 /// Check that the mask is shuffling N byte elements. Within each N byte 1840 /// element of the mask, the indices could be either in increasing or 1841 /// decreasing order as long as they are consecutive. 1842 /// \param[in] N the shuffle vector SD Node to analyze 1843 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1844 /// Word/DoubleWord/QuadWord). 1845 /// \param[in] StepLen the delta indices number among the N byte element, if 1846 /// the mask is in increasing/decreasing order then it is 1/-1. 1847 /// \return true iff the mask is shuffling N byte elements. 1848 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1849 int StepLen) { 1850 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1851 "Unexpected element width."); 1852 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1853 1854 unsigned NumOfElem = 16 / Width; 1855 unsigned MaskVal[16]; // Width is never greater than 16 1856 for (unsigned i = 0; i < NumOfElem; ++i) { 1857 MaskVal[0] = N->getMaskElt(i * Width); 1858 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1859 return false; 1860 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1861 return false; 1862 } 1863 1864 for (unsigned int j = 1; j < Width; ++j) { 1865 MaskVal[j] = N->getMaskElt(i * Width + j); 1866 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1867 return false; 1868 } 1869 } 1870 } 1871 1872 return true; 1873 } 1874 1875 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1876 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1877 if (!isNByteElemShuffleMask(N, 4, 1)) 1878 return false; 1879 1880 // Now we look at mask elements 0,4,8,12 1881 unsigned M0 = N->getMaskElt(0) / 4; 1882 unsigned M1 = N->getMaskElt(4) / 4; 1883 unsigned M2 = N->getMaskElt(8) / 4; 1884 unsigned M3 = N->getMaskElt(12) / 4; 1885 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1886 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1887 1888 // Below, let H and L be arbitrary elements of the shuffle mask 1889 // where H is in the range [4,7] and L is in the range [0,3]. 1890 // H, 1, 2, 3 or L, 5, 6, 7 1891 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1892 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1893 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1894 InsertAtByte = IsLE ? 12 : 0; 1895 Swap = M0 < 4; 1896 return true; 1897 } 1898 // 0, H, 2, 3 or 4, L, 6, 7 1899 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1900 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1901 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1902 InsertAtByte = IsLE ? 8 : 4; 1903 Swap = M1 < 4; 1904 return true; 1905 } 1906 // 0, 1, H, 3 or 4, 5, L, 7 1907 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1908 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1909 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1910 InsertAtByte = IsLE ? 4 : 8; 1911 Swap = M2 < 4; 1912 return true; 1913 } 1914 // 0, 1, 2, H or 4, 5, 6, L 1915 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1916 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1917 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1918 InsertAtByte = IsLE ? 0 : 12; 1919 Swap = M3 < 4; 1920 return true; 1921 } 1922 1923 // If both vector operands for the shuffle are the same vector, the mask will 1924 // contain only elements from the first one and the second one will be undef. 1925 if (N->getOperand(1).isUndef()) { 1926 ShiftElts = 0; 1927 Swap = true; 1928 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1929 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1930 InsertAtByte = IsLE ? 12 : 0; 1931 return true; 1932 } 1933 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1934 InsertAtByte = IsLE ? 8 : 4; 1935 return true; 1936 } 1937 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1938 InsertAtByte = IsLE ? 4 : 8; 1939 return true; 1940 } 1941 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1942 InsertAtByte = IsLE ? 0 : 12; 1943 return true; 1944 } 1945 } 1946 1947 return false; 1948 } 1949 1950 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1951 bool &Swap, bool IsLE) { 1952 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1953 // Ensure each byte index of the word is consecutive. 1954 if (!isNByteElemShuffleMask(N, 4, 1)) 1955 return false; 1956 1957 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1958 unsigned M0 = N->getMaskElt(0) / 4; 1959 unsigned M1 = N->getMaskElt(4) / 4; 1960 unsigned M2 = N->getMaskElt(8) / 4; 1961 unsigned M3 = N->getMaskElt(12) / 4; 1962 1963 // If both vector operands for the shuffle are the same vector, the mask will 1964 // contain only elements from the first one and the second one will be undef. 1965 if (N->getOperand(1).isUndef()) { 1966 assert(M0 < 4 && "Indexing into an undef vector?"); 1967 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1968 return false; 1969 1970 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1971 Swap = false; 1972 return true; 1973 } 1974 1975 // Ensure each word index of the ShuffleVector Mask is consecutive. 1976 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1977 return false; 1978 1979 if (IsLE) { 1980 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1981 // Input vectors don't need to be swapped if the leading element 1982 // of the result is one of the 3 left elements of the second vector 1983 // (or if there is no shift to be done at all). 1984 Swap = false; 1985 ShiftElts = (8 - M0) % 8; 1986 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1987 // Input vectors need to be swapped if the leading element 1988 // of the result is one of the 3 left elements of the first vector 1989 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1990 Swap = true; 1991 ShiftElts = (4 - M0) % 4; 1992 } 1993 1994 return true; 1995 } else { // BE 1996 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1997 // Input vectors don't need to be swapped if the leading element 1998 // of the result is one of the 4 elements of the first vector. 1999 Swap = false; 2000 ShiftElts = M0; 2001 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2002 // Input vectors need to be swapped if the leading element 2003 // of the result is one of the 4 elements of the right vector. 2004 Swap = true; 2005 ShiftElts = M0 - 4; 2006 } 2007 2008 return true; 2009 } 2010 } 2011 2012 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2013 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2014 2015 if (!isNByteElemShuffleMask(N, Width, -1)) 2016 return false; 2017 2018 for (int i = 0; i < 16; i += Width) 2019 if (N->getMaskElt(i) != i + Width - 1) 2020 return false; 2021 2022 return true; 2023 } 2024 2025 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2026 return isXXBRShuffleMaskHelper(N, 2); 2027 } 2028 2029 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2030 return isXXBRShuffleMaskHelper(N, 4); 2031 } 2032 2033 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2034 return isXXBRShuffleMaskHelper(N, 8); 2035 } 2036 2037 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2038 return isXXBRShuffleMaskHelper(N, 16); 2039 } 2040 2041 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2042 /// if the inputs to the instruction should be swapped and set \p DM to the 2043 /// value for the immediate. 2044 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2045 /// AND element 0 of the result comes from the first input (LE) or second input 2046 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2047 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2048 /// mask. 2049 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2050 bool &Swap, bool IsLE) { 2051 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2052 2053 // Ensure each byte index of the double word is consecutive. 2054 if (!isNByteElemShuffleMask(N, 8, 1)) 2055 return false; 2056 2057 unsigned M0 = N->getMaskElt(0) / 8; 2058 unsigned M1 = N->getMaskElt(8) / 8; 2059 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2060 2061 // If both vector operands for the shuffle are the same vector, the mask will 2062 // contain only elements from the first one and the second one will be undef. 2063 if (N->getOperand(1).isUndef()) { 2064 if ((M0 | M1) < 2) { 2065 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2066 Swap = false; 2067 return true; 2068 } else 2069 return false; 2070 } 2071 2072 if (IsLE) { 2073 if (M0 > 1 && M1 < 2) { 2074 Swap = false; 2075 } else if (M0 < 2 && M1 > 1) { 2076 M0 = (M0 + 2) % 4; 2077 M1 = (M1 + 2) % 4; 2078 Swap = true; 2079 } else 2080 return false; 2081 2082 // Note: if control flow comes here that means Swap is already set above 2083 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2084 return true; 2085 } else { // BE 2086 if (M0 < 2 && M1 > 1) { 2087 Swap = false; 2088 } else if (M0 > 1 && M1 < 2) { 2089 M0 = (M0 + 2) % 4; 2090 M1 = (M1 + 2) % 4; 2091 Swap = true; 2092 } else 2093 return false; 2094 2095 // Note: if control flow comes here that means Swap is already set above 2096 DM = (M0 << 1) + (M1 & 1); 2097 return true; 2098 } 2099 } 2100 2101 2102 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2103 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2104 /// elements are counted from the left of the vector register). 2105 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2106 SelectionDAG &DAG) { 2107 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2108 assert(isSplatShuffleMask(SVOp, EltSize)); 2109 if (DAG.getDataLayout().isLittleEndian()) 2110 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2111 else 2112 return SVOp->getMaskElt(0) / EltSize; 2113 } 2114 2115 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2116 /// by using a vspltis[bhw] instruction of the specified element size, return 2117 /// the constant being splatted. The ByteSize field indicates the number of 2118 /// bytes of each element [124] -> [bhw]. 2119 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2120 SDValue OpVal(nullptr, 0); 2121 2122 // If ByteSize of the splat is bigger than the element size of the 2123 // build_vector, then we have a case where we are checking for a splat where 2124 // multiple elements of the buildvector are folded together into a single 2125 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2126 unsigned EltSize = 16/N->getNumOperands(); 2127 if (EltSize < ByteSize) { 2128 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2129 SDValue UniquedVals[4]; 2130 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2131 2132 // See if all of the elements in the buildvector agree across. 2133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2134 if (N->getOperand(i).isUndef()) continue; 2135 // If the element isn't a constant, bail fully out. 2136 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2137 2138 if (!UniquedVals[i&(Multiple-1)].getNode()) 2139 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2140 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2141 return SDValue(); // no match. 2142 } 2143 2144 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2145 // either constant or undef values that are identical for each chunk. See 2146 // if these chunks can form into a larger vspltis*. 2147 2148 // Check to see if all of the leading entries are either 0 or -1. If 2149 // neither, then this won't fit into the immediate field. 2150 bool LeadingZero = true; 2151 bool LeadingOnes = true; 2152 for (unsigned i = 0; i != Multiple-1; ++i) { 2153 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2154 2155 LeadingZero &= isNullConstant(UniquedVals[i]); 2156 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2157 } 2158 // Finally, check the least significant entry. 2159 if (LeadingZero) { 2160 if (!UniquedVals[Multiple-1].getNode()) 2161 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2162 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2163 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2164 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2165 } 2166 if (LeadingOnes) { 2167 if (!UniquedVals[Multiple-1].getNode()) 2168 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2169 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2170 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2171 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2172 } 2173 2174 return SDValue(); 2175 } 2176 2177 // Check to see if this buildvec has a single non-undef value in its elements. 2178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2179 if (N->getOperand(i).isUndef()) continue; 2180 if (!OpVal.getNode()) 2181 OpVal = N->getOperand(i); 2182 else if (OpVal != N->getOperand(i)) 2183 return SDValue(); 2184 } 2185 2186 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2187 2188 unsigned ValSizeInBytes = EltSize; 2189 uint64_t Value = 0; 2190 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2191 Value = CN->getZExtValue(); 2192 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2193 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2194 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2195 } 2196 2197 // If the splat value is larger than the element value, then we can never do 2198 // this splat. The only case that we could fit the replicated bits into our 2199 // immediate field for would be zero, and we prefer to use vxor for it. 2200 if (ValSizeInBytes < ByteSize) return SDValue(); 2201 2202 // If the element value is larger than the splat value, check if it consists 2203 // of a repeated bit pattern of size ByteSize. 2204 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2205 return SDValue(); 2206 2207 // Properly sign extend the value. 2208 int MaskVal = SignExtend32(Value, ByteSize * 8); 2209 2210 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2211 if (MaskVal == 0) return SDValue(); 2212 2213 // Finally, if this value fits in a 5 bit sext field, return it 2214 if (SignExtend32<5>(MaskVal) == MaskVal) 2215 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2216 return SDValue(); 2217 } 2218 2219 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2220 /// amount, otherwise return -1. 2221 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2222 EVT VT = N->getValueType(0); 2223 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2224 return -1; 2225 2226 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2227 2228 // Find the first non-undef value in the shuffle mask. 2229 unsigned i; 2230 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2231 /*search*/; 2232 2233 if (i == 4) return -1; // all undef. 2234 2235 // Otherwise, check to see if the rest of the elements are consecutively 2236 // numbered from this value. 2237 unsigned ShiftAmt = SVOp->getMaskElt(i); 2238 if (ShiftAmt < i) return -1; 2239 ShiftAmt -= i; 2240 2241 // Check the rest of the elements to see if they are consecutive. 2242 for (++i; i != 4; ++i) 2243 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2244 return -1; 2245 2246 return ShiftAmt; 2247 } 2248 2249 //===----------------------------------------------------------------------===// 2250 // Addressing Mode Selection 2251 //===----------------------------------------------------------------------===// 2252 2253 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2254 /// or 64-bit immediate, and if the value can be accurately represented as a 2255 /// sign extension from a 16-bit value. If so, this returns true and the 2256 /// immediate. 2257 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2258 if (!isa<ConstantSDNode>(N)) 2259 return false; 2260 2261 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2262 if (N->getValueType(0) == MVT::i32) 2263 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2264 else 2265 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2266 } 2267 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2268 return isIntS16Immediate(Op.getNode(), Imm); 2269 } 2270 2271 2272 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2273 /// be represented as an indexed [r+r] operation. 2274 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2275 SDValue &Index, 2276 SelectionDAG &DAG) const { 2277 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2278 UI != E; ++UI) { 2279 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2280 if (Memop->getMemoryVT() == MVT::f64) { 2281 Base = N.getOperand(0); 2282 Index = N.getOperand(1); 2283 return true; 2284 } 2285 } 2286 } 2287 return false; 2288 } 2289 2290 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2291 /// can be represented as an indexed [r+r] operation. Returns false if it 2292 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2293 /// non-zero and N can be represented by a base register plus a signed 16-bit 2294 /// displacement, make a more precise judgement by checking (displacement % \p 2295 /// EncodingAlignment). 2296 bool PPCTargetLowering::SelectAddressRegReg( 2297 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2298 MaybeAlign EncodingAlignment) const { 2299 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2300 // a [pc+imm]. 2301 if (SelectAddressPCRel(N, Base)) 2302 return false; 2303 2304 int16_t Imm = 0; 2305 if (N.getOpcode() == ISD::ADD) { 2306 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2307 // SPE load/store can only handle 8-bit offsets. 2308 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2309 return true; 2310 if (isIntS16Immediate(N.getOperand(1), Imm) && 2311 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2312 return false; // r+i 2313 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2314 return false; // r+i 2315 2316 Base = N.getOperand(0); 2317 Index = N.getOperand(1); 2318 return true; 2319 } else if (N.getOpcode() == ISD::OR) { 2320 if (isIntS16Immediate(N.getOperand(1), Imm) && 2321 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2322 return false; // r+i can fold it if we can. 2323 2324 // If this is an or of disjoint bitfields, we can codegen this as an add 2325 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2326 // disjoint. 2327 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2328 2329 if (LHSKnown.Zero.getBoolValue()) { 2330 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2331 // If all of the bits are known zero on the LHS or RHS, the add won't 2332 // carry. 2333 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2334 Base = N.getOperand(0); 2335 Index = N.getOperand(1); 2336 return true; 2337 } 2338 } 2339 } 2340 2341 return false; 2342 } 2343 2344 // If we happen to be doing an i64 load or store into a stack slot that has 2345 // less than a 4-byte alignment, then the frame-index elimination may need to 2346 // use an indexed load or store instruction (because the offset may not be a 2347 // multiple of 4). The extra register needed to hold the offset comes from the 2348 // register scavenger, and it is possible that the scavenger will need to use 2349 // an emergency spill slot. As a result, we need to make sure that a spill slot 2350 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2351 // stack slot. 2352 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2353 // FIXME: This does not handle the LWA case. 2354 if (VT != MVT::i64) 2355 return; 2356 2357 // NOTE: We'll exclude negative FIs here, which come from argument 2358 // lowering, because there are no known test cases triggering this problem 2359 // using packed structures (or similar). We can remove this exclusion if 2360 // we find such a test case. The reason why this is so test-case driven is 2361 // because this entire 'fixup' is only to prevent crashes (from the 2362 // register scavenger) on not-really-valid inputs. For example, if we have: 2363 // %a = alloca i1 2364 // %b = bitcast i1* %a to i64* 2365 // store i64* a, i64 b 2366 // then the store should really be marked as 'align 1', but is not. If it 2367 // were marked as 'align 1' then the indexed form would have been 2368 // instruction-selected initially, and the problem this 'fixup' is preventing 2369 // won't happen regardless. 2370 if (FrameIdx < 0) 2371 return; 2372 2373 MachineFunction &MF = DAG.getMachineFunction(); 2374 MachineFrameInfo &MFI = MF.getFrameInfo(); 2375 2376 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2377 return; 2378 2379 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2380 FuncInfo->setHasNonRISpills(); 2381 } 2382 2383 /// Returns true if the address N can be represented by a base register plus 2384 /// a signed 16-bit displacement [r+imm], and if it is not better 2385 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2386 /// displacements that are multiples of that value. 2387 bool PPCTargetLowering::SelectAddressRegImm( 2388 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2389 MaybeAlign EncodingAlignment) const { 2390 // FIXME dl should come from parent load or store, not from address 2391 SDLoc dl(N); 2392 2393 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2394 // a [pc+imm]. 2395 if (SelectAddressPCRel(N, Base)) 2396 return false; 2397 2398 // If this can be more profitably realized as r+r, fail. 2399 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2400 return false; 2401 2402 if (N.getOpcode() == ISD::ADD) { 2403 int16_t imm = 0; 2404 if (isIntS16Immediate(N.getOperand(1), imm) && 2405 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2406 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2407 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2408 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2409 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2410 } else { 2411 Base = N.getOperand(0); 2412 } 2413 return true; // [r+i] 2414 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2415 // Match LOAD (ADD (X, Lo(G))). 2416 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2417 && "Cannot handle constant offsets yet!"); 2418 Disp = N.getOperand(1).getOperand(0); // The global address. 2419 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2420 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2421 Disp.getOpcode() == ISD::TargetConstantPool || 2422 Disp.getOpcode() == ISD::TargetJumpTable); 2423 Base = N.getOperand(0); 2424 return true; // [&g+r] 2425 } 2426 } else if (N.getOpcode() == ISD::OR) { 2427 int16_t imm = 0; 2428 if (isIntS16Immediate(N.getOperand(1), imm) && 2429 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2430 // If this is an or of disjoint bitfields, we can codegen this as an add 2431 // (for better address arithmetic) if the LHS and RHS of the OR are 2432 // provably disjoint. 2433 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2434 2435 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2436 // If all of the bits are known zero on the LHS or RHS, the add won't 2437 // carry. 2438 if (FrameIndexSDNode *FI = 2439 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2440 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2441 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2442 } else { 2443 Base = N.getOperand(0); 2444 } 2445 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2446 return true; 2447 } 2448 } 2449 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2450 // Loading from a constant address. 2451 2452 // If this address fits entirely in a 16-bit sext immediate field, codegen 2453 // this as "d, 0" 2454 int16_t Imm; 2455 if (isIntS16Immediate(CN, Imm) && 2456 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2457 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2458 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2459 CN->getValueType(0)); 2460 return true; 2461 } 2462 2463 // Handle 32-bit sext immediates with LIS + addr mode. 2464 if ((CN->getValueType(0) == MVT::i32 || 2465 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2466 (!EncodingAlignment || 2467 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2468 int Addr = (int)CN->getZExtValue(); 2469 2470 // Otherwise, break this down into an LIS + disp. 2471 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2472 2473 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2474 MVT::i32); 2475 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2476 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2477 return true; 2478 } 2479 } 2480 2481 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2482 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2483 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2484 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2485 } else 2486 Base = N; 2487 return true; // [r+0] 2488 } 2489 2490 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2491 /// represented as an indexed [r+r] operation. 2492 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2493 SDValue &Index, 2494 SelectionDAG &DAG) const { 2495 // Check to see if we can easily represent this as an [r+r] address. This 2496 // will fail if it thinks that the address is more profitably represented as 2497 // reg+imm, e.g. where imm = 0. 2498 if (SelectAddressRegReg(N, Base, Index, DAG)) 2499 return true; 2500 2501 // If the address is the result of an add, we will utilize the fact that the 2502 // address calculation includes an implicit add. However, we can reduce 2503 // register pressure if we do not materialize a constant just for use as the 2504 // index register. We only get rid of the add if it is not an add of a 2505 // value and a 16-bit signed constant and both have a single use. 2506 int16_t imm = 0; 2507 if (N.getOpcode() == ISD::ADD && 2508 (!isIntS16Immediate(N.getOperand(1), imm) || 2509 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2510 Base = N.getOperand(0); 2511 Index = N.getOperand(1); 2512 return true; 2513 } 2514 2515 // Otherwise, do it the hard way, using R0 as the base register. 2516 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2517 N.getValueType()); 2518 Index = N; 2519 return true; 2520 } 2521 2522 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2523 Ty *PCRelCand = dyn_cast<Ty>(N); 2524 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2525 } 2526 2527 /// Returns true if this address is a PC Relative address. 2528 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2529 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2530 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2531 // This is a materialize PC Relative node. Always select this as PC Relative. 2532 Base = N; 2533 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2534 return true; 2535 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2536 isValidPCRelNode<GlobalAddressSDNode>(N) || 2537 isValidPCRelNode<JumpTableSDNode>(N) || 2538 isValidPCRelNode<BlockAddressSDNode>(N)) 2539 return true; 2540 return false; 2541 } 2542 2543 /// Returns true if we should use a direct load into vector instruction 2544 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2545 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2546 2547 // If there are any other uses other than scalar to vector, then we should 2548 // keep it as a scalar load -> direct move pattern to prevent multiple 2549 // loads. 2550 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2551 if (!LD) 2552 return false; 2553 2554 EVT MemVT = LD->getMemoryVT(); 2555 if (!MemVT.isSimple()) 2556 return false; 2557 switch(MemVT.getSimpleVT().SimpleTy) { 2558 case MVT::i64: 2559 break; 2560 case MVT::i32: 2561 if (!ST.hasP8Vector()) 2562 return false; 2563 break; 2564 case MVT::i16: 2565 case MVT::i8: 2566 if (!ST.hasP9Vector()) 2567 return false; 2568 break; 2569 default: 2570 return false; 2571 } 2572 2573 SDValue LoadedVal(N, 0); 2574 if (!LoadedVal.hasOneUse()) 2575 return false; 2576 2577 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2578 UI != UE; ++UI) 2579 if (UI.getUse().get().getResNo() == 0 && 2580 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2581 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2582 return false; 2583 2584 return true; 2585 } 2586 2587 /// getPreIndexedAddressParts - returns true by value, base pointer and 2588 /// offset pointer and addressing mode by reference if the node's address 2589 /// can be legally represented as pre-indexed load / store address. 2590 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2591 SDValue &Offset, 2592 ISD::MemIndexedMode &AM, 2593 SelectionDAG &DAG) const { 2594 if (DisablePPCPreinc) return false; 2595 2596 bool isLoad = true; 2597 SDValue Ptr; 2598 EVT VT; 2599 unsigned Alignment; 2600 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2601 Ptr = LD->getBasePtr(); 2602 VT = LD->getMemoryVT(); 2603 Alignment = LD->getAlignment(); 2604 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2605 Ptr = ST->getBasePtr(); 2606 VT = ST->getMemoryVT(); 2607 Alignment = ST->getAlignment(); 2608 isLoad = false; 2609 } else 2610 return false; 2611 2612 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2613 // instructions because we can fold these into a more efficient instruction 2614 // instead, (such as LXSD). 2615 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2616 return false; 2617 } 2618 2619 // PowerPC doesn't have preinc load/store instructions for vectors 2620 if (VT.isVector()) 2621 return false; 2622 2623 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2624 // Common code will reject creating a pre-inc form if the base pointer 2625 // is a frame index, or if N is a store and the base pointer is either 2626 // the same as or a predecessor of the value being stored. Check for 2627 // those situations here, and try with swapped Base/Offset instead. 2628 bool Swap = false; 2629 2630 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2631 Swap = true; 2632 else if (!isLoad) { 2633 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2634 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2635 Swap = true; 2636 } 2637 2638 if (Swap) 2639 std::swap(Base, Offset); 2640 2641 AM = ISD::PRE_INC; 2642 return true; 2643 } 2644 2645 // LDU/STU can only handle immediates that are a multiple of 4. 2646 if (VT != MVT::i64) { 2647 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2648 return false; 2649 } else { 2650 // LDU/STU need an address with at least 4-byte alignment. 2651 if (Alignment < 4) 2652 return false; 2653 2654 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2655 return false; 2656 } 2657 2658 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2659 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2660 // sext i32 to i64 when addr mode is r+i. 2661 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2662 LD->getExtensionType() == ISD::SEXTLOAD && 2663 isa<ConstantSDNode>(Offset)) 2664 return false; 2665 } 2666 2667 AM = ISD::PRE_INC; 2668 return true; 2669 } 2670 2671 //===----------------------------------------------------------------------===// 2672 // LowerOperation implementation 2673 //===----------------------------------------------------------------------===// 2674 2675 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2676 /// and LoOpFlags to the target MO flags. 2677 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2678 unsigned &HiOpFlags, unsigned &LoOpFlags, 2679 const GlobalValue *GV = nullptr) { 2680 HiOpFlags = PPCII::MO_HA; 2681 LoOpFlags = PPCII::MO_LO; 2682 2683 // Don't use the pic base if not in PIC relocation model. 2684 if (IsPIC) { 2685 HiOpFlags |= PPCII::MO_PIC_FLAG; 2686 LoOpFlags |= PPCII::MO_PIC_FLAG; 2687 } 2688 } 2689 2690 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2691 SelectionDAG &DAG) { 2692 SDLoc DL(HiPart); 2693 EVT PtrVT = HiPart.getValueType(); 2694 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2695 2696 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2697 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2698 2699 // With PIC, the first instruction is actually "GR+hi(&G)". 2700 if (isPIC) 2701 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2702 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2703 2704 // Generate non-pic code that has direct accesses to the constant pool. 2705 // The address of the global is just (hi(&g)+lo(&g)). 2706 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2707 } 2708 2709 static void setUsesTOCBasePtr(MachineFunction &MF) { 2710 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2711 FuncInfo->setUsesTOCBasePtr(); 2712 } 2713 2714 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2715 setUsesTOCBasePtr(DAG.getMachineFunction()); 2716 } 2717 2718 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2719 SDValue GA) const { 2720 const bool Is64Bit = Subtarget.isPPC64(); 2721 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2722 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2723 : Subtarget.isAIXABI() 2724 ? DAG.getRegister(PPC::R2, VT) 2725 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2726 SDValue Ops[] = { GA, Reg }; 2727 return DAG.getMemIntrinsicNode( 2728 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2729 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2730 MachineMemOperand::MOLoad); 2731 } 2732 2733 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2734 SelectionDAG &DAG) const { 2735 EVT PtrVT = Op.getValueType(); 2736 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2737 const Constant *C = CP->getConstVal(); 2738 2739 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2740 // The actual address of the GlobalValue is stored in the TOC. 2741 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2742 if (Subtarget.isUsingPCRelativeCalls()) { 2743 SDLoc DL(CP); 2744 EVT Ty = getPointerTy(DAG.getDataLayout()); 2745 SDValue ConstPool = DAG.getTargetConstantPool( 2746 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2747 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2748 } 2749 setUsesTOCBasePtr(DAG); 2750 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2751 return getTOCEntry(DAG, SDLoc(CP), GA); 2752 } 2753 2754 unsigned MOHiFlag, MOLoFlag; 2755 bool IsPIC = isPositionIndependent(); 2756 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2757 2758 if (IsPIC && Subtarget.isSVR4ABI()) { 2759 SDValue GA = 2760 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2761 return getTOCEntry(DAG, SDLoc(CP), GA); 2762 } 2763 2764 SDValue CPIHi = 2765 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2766 SDValue CPILo = 2767 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2768 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2769 } 2770 2771 // For 64-bit PowerPC, prefer the more compact relative encodings. 2772 // This trades 32 bits per jump table entry for one or two instructions 2773 // on the jump site. 2774 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2775 if (isJumpTableRelative()) 2776 return MachineJumpTableInfo::EK_LabelDifference32; 2777 2778 return TargetLowering::getJumpTableEncoding(); 2779 } 2780 2781 bool PPCTargetLowering::isJumpTableRelative() const { 2782 if (UseAbsoluteJumpTables) 2783 return false; 2784 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2785 return true; 2786 return TargetLowering::isJumpTableRelative(); 2787 } 2788 2789 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2790 SelectionDAG &DAG) const { 2791 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2792 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2793 2794 switch (getTargetMachine().getCodeModel()) { 2795 case CodeModel::Small: 2796 case CodeModel::Medium: 2797 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2798 default: 2799 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2800 getPointerTy(DAG.getDataLayout())); 2801 } 2802 } 2803 2804 const MCExpr * 2805 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2806 unsigned JTI, 2807 MCContext &Ctx) const { 2808 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2809 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2810 2811 switch (getTargetMachine().getCodeModel()) { 2812 case CodeModel::Small: 2813 case CodeModel::Medium: 2814 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2815 default: 2816 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2817 } 2818 } 2819 2820 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2821 EVT PtrVT = Op.getValueType(); 2822 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2823 2824 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2825 if (Subtarget.isUsingPCRelativeCalls()) { 2826 SDLoc DL(JT); 2827 EVT Ty = getPointerTy(DAG.getDataLayout()); 2828 SDValue GA = 2829 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2830 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2831 return MatAddr; 2832 } 2833 2834 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2835 // The actual address of the GlobalValue is stored in the TOC. 2836 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2837 setUsesTOCBasePtr(DAG); 2838 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2839 return getTOCEntry(DAG, SDLoc(JT), GA); 2840 } 2841 2842 unsigned MOHiFlag, MOLoFlag; 2843 bool IsPIC = isPositionIndependent(); 2844 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2845 2846 if (IsPIC && Subtarget.isSVR4ABI()) { 2847 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2848 PPCII::MO_PIC_FLAG); 2849 return getTOCEntry(DAG, SDLoc(GA), GA); 2850 } 2851 2852 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2853 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2854 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2855 } 2856 2857 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2858 SelectionDAG &DAG) const { 2859 EVT PtrVT = Op.getValueType(); 2860 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2861 const BlockAddress *BA = BASDN->getBlockAddress(); 2862 2863 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2864 if (Subtarget.isUsingPCRelativeCalls()) { 2865 SDLoc DL(BASDN); 2866 EVT Ty = getPointerTy(DAG.getDataLayout()); 2867 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2868 PPCII::MO_PCREL_FLAG); 2869 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2870 return MatAddr; 2871 } 2872 2873 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2874 // The actual BlockAddress is stored in the TOC. 2875 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2876 setUsesTOCBasePtr(DAG); 2877 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2878 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2879 } 2880 2881 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2882 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2883 return getTOCEntry( 2884 DAG, SDLoc(BASDN), 2885 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2886 2887 unsigned MOHiFlag, MOLoFlag; 2888 bool IsPIC = isPositionIndependent(); 2889 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2890 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2891 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2892 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2893 } 2894 2895 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2896 SelectionDAG &DAG) const { 2897 // FIXME: TLS addresses currently use medium model code sequences, 2898 // which is the most useful form. Eventually support for small and 2899 // large models could be added if users need it, at the cost of 2900 // additional complexity. 2901 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2902 if (DAG.getTarget().useEmulatedTLS()) 2903 return LowerToTLSEmulatedModel(GA, DAG); 2904 2905 SDLoc dl(GA); 2906 const GlobalValue *GV = GA->getGlobal(); 2907 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2908 bool is64bit = Subtarget.isPPC64(); 2909 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2910 PICLevel::Level picLevel = M->getPICLevel(); 2911 2912 const TargetMachine &TM = getTargetMachine(); 2913 TLSModel::Model Model = TM.getTLSModel(GV); 2914 2915 if (Model == TLSModel::LocalExec) { 2916 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2917 PPCII::MO_TPREL_HA); 2918 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2919 PPCII::MO_TPREL_LO); 2920 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2921 : DAG.getRegister(PPC::R2, MVT::i32); 2922 2923 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2924 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2925 } 2926 2927 if (Model == TLSModel::InitialExec) { 2928 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2929 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2930 PPCII::MO_TLS); 2931 SDValue GOTPtr; 2932 if (is64bit) { 2933 setUsesTOCBasePtr(DAG); 2934 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2935 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2936 PtrVT, GOTReg, TGA); 2937 } else { 2938 if (!TM.isPositionIndependent()) 2939 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2940 else if (picLevel == PICLevel::SmallPIC) 2941 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2942 else 2943 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2944 } 2945 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2946 PtrVT, TGA, GOTPtr); 2947 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2948 } 2949 2950 if (Model == TLSModel::GeneralDynamic) { 2951 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2952 SDValue GOTPtr; 2953 if (is64bit) { 2954 setUsesTOCBasePtr(DAG); 2955 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2956 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2957 GOTReg, TGA); 2958 } else { 2959 if (picLevel == PICLevel::SmallPIC) 2960 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2961 else 2962 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2963 } 2964 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2965 GOTPtr, TGA, TGA); 2966 } 2967 2968 if (Model == TLSModel::LocalDynamic) { 2969 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2970 SDValue GOTPtr; 2971 if (is64bit) { 2972 setUsesTOCBasePtr(DAG); 2973 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2974 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2975 GOTReg, TGA); 2976 } else { 2977 if (picLevel == PICLevel::SmallPIC) 2978 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2979 else 2980 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2981 } 2982 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2983 PtrVT, GOTPtr, TGA, TGA); 2984 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2985 PtrVT, TLSAddr, TGA); 2986 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2987 } 2988 2989 llvm_unreachable("Unknown TLS model!"); 2990 } 2991 2992 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2993 SelectionDAG &DAG) const { 2994 EVT PtrVT = Op.getValueType(); 2995 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2996 SDLoc DL(GSDN); 2997 const GlobalValue *GV = GSDN->getGlobal(); 2998 2999 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3000 // The actual address of the GlobalValue is stored in the TOC. 3001 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3002 if (Subtarget.isUsingPCRelativeCalls()) { 3003 EVT Ty = getPointerTy(DAG.getDataLayout()); 3004 if (isAccessedAsGotIndirect(Op)) { 3005 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3006 PPCII::MO_PCREL_FLAG | 3007 PPCII::MO_GOT_FLAG); 3008 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3009 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3010 MachinePointerInfo()); 3011 return Load; 3012 } else { 3013 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3014 PPCII::MO_PCREL_FLAG); 3015 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3016 } 3017 } 3018 setUsesTOCBasePtr(DAG); 3019 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3020 return getTOCEntry(DAG, DL, GA); 3021 } 3022 3023 unsigned MOHiFlag, MOLoFlag; 3024 bool IsPIC = isPositionIndependent(); 3025 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3026 3027 if (IsPIC && Subtarget.isSVR4ABI()) { 3028 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3029 GSDN->getOffset(), 3030 PPCII::MO_PIC_FLAG); 3031 return getTOCEntry(DAG, DL, GA); 3032 } 3033 3034 SDValue GAHi = 3035 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3036 SDValue GALo = 3037 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3038 3039 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3040 } 3041 3042 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3043 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3044 SDLoc dl(Op); 3045 3046 if (Op.getValueType() == MVT::v2i64) { 3047 // When the operands themselves are v2i64 values, we need to do something 3048 // special because VSX has no underlying comparison operations for these. 3049 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3050 // Equality can be handled by casting to the legal type for Altivec 3051 // comparisons, everything else needs to be expanded. 3052 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3053 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3054 DAG.getSetCC(dl, MVT::v4i32, 3055 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3056 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3057 CC)); 3058 } 3059 3060 return SDValue(); 3061 } 3062 3063 // We handle most of these in the usual way. 3064 return Op; 3065 } 3066 3067 // If we're comparing for equality to zero, expose the fact that this is 3068 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3069 // fold the new nodes. 3070 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3071 return V; 3072 3073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3074 // Leave comparisons against 0 and -1 alone for now, since they're usually 3075 // optimized. FIXME: revisit this when we can custom lower all setcc 3076 // optimizations. 3077 if (C->isAllOnesValue() || C->isNullValue()) 3078 return SDValue(); 3079 } 3080 3081 // If we have an integer seteq/setne, turn it into a compare against zero 3082 // by xor'ing the rhs with the lhs, which is faster than setting a 3083 // condition register, reading it back out, and masking the correct bit. The 3084 // normal approach here uses sub to do this instead of xor. Using xor exposes 3085 // the result to other bit-twiddling opportunities. 3086 EVT LHSVT = Op.getOperand(0).getValueType(); 3087 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3088 EVT VT = Op.getValueType(); 3089 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3090 Op.getOperand(1)); 3091 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3092 } 3093 return SDValue(); 3094 } 3095 3096 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3097 SDNode *Node = Op.getNode(); 3098 EVT VT = Node->getValueType(0); 3099 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3100 SDValue InChain = Node->getOperand(0); 3101 SDValue VAListPtr = Node->getOperand(1); 3102 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3103 SDLoc dl(Node); 3104 3105 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3106 3107 // gpr_index 3108 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3109 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3110 InChain = GprIndex.getValue(1); 3111 3112 if (VT == MVT::i64) { 3113 // Check if GprIndex is even 3114 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3115 DAG.getConstant(1, dl, MVT::i32)); 3116 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3117 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3118 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3119 DAG.getConstant(1, dl, MVT::i32)); 3120 // Align GprIndex to be even if it isn't 3121 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3122 GprIndex); 3123 } 3124 3125 // fpr index is 1 byte after gpr 3126 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3127 DAG.getConstant(1, dl, MVT::i32)); 3128 3129 // fpr 3130 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3131 FprPtr, MachinePointerInfo(SV), MVT::i8); 3132 InChain = FprIndex.getValue(1); 3133 3134 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3135 DAG.getConstant(8, dl, MVT::i32)); 3136 3137 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3138 DAG.getConstant(4, dl, MVT::i32)); 3139 3140 // areas 3141 SDValue OverflowArea = 3142 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3143 InChain = OverflowArea.getValue(1); 3144 3145 SDValue RegSaveArea = 3146 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3147 InChain = RegSaveArea.getValue(1); 3148 3149 // select overflow_area if index > 8 3150 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3151 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3152 3153 // adjustment constant gpr_index * 4/8 3154 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3155 VT.isInteger() ? GprIndex : FprIndex, 3156 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3157 MVT::i32)); 3158 3159 // OurReg = RegSaveArea + RegConstant 3160 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3161 RegConstant); 3162 3163 // Floating types are 32 bytes into RegSaveArea 3164 if (VT.isFloatingPoint()) 3165 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3166 DAG.getConstant(32, dl, MVT::i32)); 3167 3168 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3169 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3170 VT.isInteger() ? GprIndex : FprIndex, 3171 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3172 MVT::i32)); 3173 3174 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3175 VT.isInteger() ? VAListPtr : FprPtr, 3176 MachinePointerInfo(SV), MVT::i8); 3177 3178 // determine if we should load from reg_save_area or overflow_area 3179 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3180 3181 // increase overflow_area by 4/8 if gpr/fpr > 8 3182 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3183 DAG.getConstant(VT.isInteger() ? 4 : 8, 3184 dl, MVT::i32)); 3185 3186 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3187 OverflowAreaPlusN); 3188 3189 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3190 MachinePointerInfo(), MVT::i32); 3191 3192 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3193 } 3194 3195 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3196 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3197 3198 // We have to copy the entire va_list struct: 3199 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3200 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3201 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3202 false, true, false, MachinePointerInfo(), 3203 MachinePointerInfo()); 3204 } 3205 3206 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3207 SelectionDAG &DAG) const { 3208 if (Subtarget.isAIXABI()) 3209 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3210 3211 return Op.getOperand(0); 3212 } 3213 3214 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3215 SelectionDAG &DAG) const { 3216 if (Subtarget.isAIXABI()) 3217 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3218 3219 SDValue Chain = Op.getOperand(0); 3220 SDValue Trmp = Op.getOperand(1); // trampoline 3221 SDValue FPtr = Op.getOperand(2); // nested function 3222 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3223 SDLoc dl(Op); 3224 3225 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3226 bool isPPC64 = (PtrVT == MVT::i64); 3227 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3228 3229 TargetLowering::ArgListTy Args; 3230 TargetLowering::ArgListEntry Entry; 3231 3232 Entry.Ty = IntPtrTy; 3233 Entry.Node = Trmp; Args.push_back(Entry); 3234 3235 // TrampSize == (isPPC64 ? 48 : 40); 3236 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3237 isPPC64 ? MVT::i64 : MVT::i32); 3238 Args.push_back(Entry); 3239 3240 Entry.Node = FPtr; Args.push_back(Entry); 3241 Entry.Node = Nest; Args.push_back(Entry); 3242 3243 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3244 TargetLowering::CallLoweringInfo CLI(DAG); 3245 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3246 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3247 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3248 3249 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3250 return CallResult.second; 3251 } 3252 3253 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3254 MachineFunction &MF = DAG.getMachineFunction(); 3255 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3256 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3257 3258 SDLoc dl(Op); 3259 3260 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3261 // vastart just stores the address of the VarArgsFrameIndex slot into the 3262 // memory location argument. 3263 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3264 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3265 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3266 MachinePointerInfo(SV)); 3267 } 3268 3269 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3270 // We suppose the given va_list is already allocated. 3271 // 3272 // typedef struct { 3273 // char gpr; /* index into the array of 8 GPRs 3274 // * stored in the register save area 3275 // * gpr=0 corresponds to r3, 3276 // * gpr=1 to r4, etc. 3277 // */ 3278 // char fpr; /* index into the array of 8 FPRs 3279 // * stored in the register save area 3280 // * fpr=0 corresponds to f1, 3281 // * fpr=1 to f2, etc. 3282 // */ 3283 // char *overflow_arg_area; 3284 // /* location on stack that holds 3285 // * the next overflow argument 3286 // */ 3287 // char *reg_save_area; 3288 // /* where r3:r10 and f1:f8 (if saved) 3289 // * are stored 3290 // */ 3291 // } va_list[1]; 3292 3293 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3294 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3295 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3296 PtrVT); 3297 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3298 PtrVT); 3299 3300 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3301 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3302 3303 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3304 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3305 3306 uint64_t FPROffset = 1; 3307 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3308 3309 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3310 3311 // Store first byte : number of int regs 3312 SDValue firstStore = 3313 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3314 MachinePointerInfo(SV), MVT::i8); 3315 uint64_t nextOffset = FPROffset; 3316 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3317 ConstFPROffset); 3318 3319 // Store second byte : number of float regs 3320 SDValue secondStore = 3321 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3322 MachinePointerInfo(SV, nextOffset), MVT::i8); 3323 nextOffset += StackOffset; 3324 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3325 3326 // Store second word : arguments given on stack 3327 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3328 MachinePointerInfo(SV, nextOffset)); 3329 nextOffset += FrameOffset; 3330 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3331 3332 // Store third word : arguments given in registers 3333 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3334 MachinePointerInfo(SV, nextOffset)); 3335 } 3336 3337 /// FPR - The set of FP registers that should be allocated for arguments 3338 /// on Darwin and AIX. 3339 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3340 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3341 PPC::F11, PPC::F12, PPC::F13}; 3342 3343 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3344 /// the stack. 3345 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3346 unsigned PtrByteSize) { 3347 unsigned ArgSize = ArgVT.getStoreSize(); 3348 if (Flags.isByVal()) 3349 ArgSize = Flags.getByValSize(); 3350 3351 // Round up to multiples of the pointer size, except for array members, 3352 // which are always packed. 3353 if (!Flags.isInConsecutiveRegs()) 3354 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3355 3356 return ArgSize; 3357 } 3358 3359 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3360 /// on the stack. 3361 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3362 ISD::ArgFlagsTy Flags, 3363 unsigned PtrByteSize) { 3364 Align Alignment(PtrByteSize); 3365 3366 // Altivec parameters are padded to a 16 byte boundary. 3367 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3368 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3369 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3370 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3371 Alignment = Align(16); 3372 3373 // ByVal parameters are aligned as requested. 3374 if (Flags.isByVal()) { 3375 auto BVAlign = Flags.getNonZeroByValAlign(); 3376 if (BVAlign > PtrByteSize) { 3377 if (BVAlign.value() % PtrByteSize != 0) 3378 llvm_unreachable( 3379 "ByVal alignment is not a multiple of the pointer size"); 3380 3381 Alignment = BVAlign; 3382 } 3383 } 3384 3385 // Array members are always packed to their original alignment. 3386 if (Flags.isInConsecutiveRegs()) { 3387 // If the array member was split into multiple registers, the first 3388 // needs to be aligned to the size of the full type. (Except for 3389 // ppcf128, which is only aligned as its f64 components.) 3390 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3391 Alignment = Align(OrigVT.getStoreSize()); 3392 else 3393 Alignment = Align(ArgVT.getStoreSize()); 3394 } 3395 3396 return Alignment; 3397 } 3398 3399 /// CalculateStackSlotUsed - Return whether this argument will use its 3400 /// stack slot (instead of being passed in registers). ArgOffset, 3401 /// AvailableFPRs, and AvailableVRs must hold the current argument 3402 /// position, and will be updated to account for this argument. 3403 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3404 unsigned PtrByteSize, unsigned LinkageSize, 3405 unsigned ParamAreaSize, unsigned &ArgOffset, 3406 unsigned &AvailableFPRs, 3407 unsigned &AvailableVRs) { 3408 bool UseMemory = false; 3409 3410 // Respect alignment of argument on the stack. 3411 Align Alignment = 3412 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3413 ArgOffset = alignTo(ArgOffset, Alignment); 3414 // If there's no space left in the argument save area, we must 3415 // use memory (this check also catches zero-sized arguments). 3416 if (ArgOffset >= LinkageSize + ParamAreaSize) 3417 UseMemory = true; 3418 3419 // Allocate argument on the stack. 3420 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3421 if (Flags.isInConsecutiveRegsLast()) 3422 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3423 // If we overran the argument save area, we must use memory 3424 // (this check catches arguments passed partially in memory) 3425 if (ArgOffset > LinkageSize + ParamAreaSize) 3426 UseMemory = true; 3427 3428 // However, if the argument is actually passed in an FPR or a VR, 3429 // we don't use memory after all. 3430 if (!Flags.isByVal()) { 3431 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3432 if (AvailableFPRs > 0) { 3433 --AvailableFPRs; 3434 return false; 3435 } 3436 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3437 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3438 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3439 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3440 if (AvailableVRs > 0) { 3441 --AvailableVRs; 3442 return false; 3443 } 3444 } 3445 3446 return UseMemory; 3447 } 3448 3449 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3450 /// ensure minimum alignment required for target. 3451 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3452 unsigned NumBytes) { 3453 return alignTo(NumBytes, Lowering->getStackAlign()); 3454 } 3455 3456 SDValue PPCTargetLowering::LowerFormalArguments( 3457 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3458 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3459 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3460 if (Subtarget.isAIXABI()) 3461 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3462 InVals); 3463 if (Subtarget.is64BitELFABI()) 3464 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3465 InVals); 3466 if (Subtarget.is32BitELFABI()) 3467 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3468 InVals); 3469 3470 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3471 InVals); 3472 } 3473 3474 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3475 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3476 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3477 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3478 3479 // 32-bit SVR4 ABI Stack Frame Layout: 3480 // +-----------------------------------+ 3481 // +--> | Back chain | 3482 // | +-----------------------------------+ 3483 // | | Floating-point register save area | 3484 // | +-----------------------------------+ 3485 // | | General register save area | 3486 // | +-----------------------------------+ 3487 // | | CR save word | 3488 // | +-----------------------------------+ 3489 // | | VRSAVE save word | 3490 // | +-----------------------------------+ 3491 // | | Alignment padding | 3492 // | +-----------------------------------+ 3493 // | | Vector register save area | 3494 // | +-----------------------------------+ 3495 // | | Local variable space | 3496 // | +-----------------------------------+ 3497 // | | Parameter list area | 3498 // | +-----------------------------------+ 3499 // | | LR save word | 3500 // | +-----------------------------------+ 3501 // SP--> +--- | Back chain | 3502 // +-----------------------------------+ 3503 // 3504 // Specifications: 3505 // System V Application Binary Interface PowerPC Processor Supplement 3506 // AltiVec Technology Programming Interface Manual 3507 3508 MachineFunction &MF = DAG.getMachineFunction(); 3509 MachineFrameInfo &MFI = MF.getFrameInfo(); 3510 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3511 3512 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3513 // Potential tail calls could cause overwriting of argument stack slots. 3514 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3515 (CallConv == CallingConv::Fast)); 3516 const Align PtrAlign(4); 3517 3518 // Assign locations to all of the incoming arguments. 3519 SmallVector<CCValAssign, 16> ArgLocs; 3520 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3521 *DAG.getContext()); 3522 3523 // Reserve space for the linkage area on the stack. 3524 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3525 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3526 if (useSoftFloat()) 3527 CCInfo.PreAnalyzeFormalArguments(Ins); 3528 3529 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3530 CCInfo.clearWasPPCF128(); 3531 3532 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3533 CCValAssign &VA = ArgLocs[i]; 3534 3535 // Arguments stored in registers. 3536 if (VA.isRegLoc()) { 3537 const TargetRegisterClass *RC; 3538 EVT ValVT = VA.getValVT(); 3539 3540 switch (ValVT.getSimpleVT().SimpleTy) { 3541 default: 3542 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3543 case MVT::i1: 3544 case MVT::i32: 3545 RC = &PPC::GPRCRegClass; 3546 break; 3547 case MVT::f32: 3548 if (Subtarget.hasP8Vector()) 3549 RC = &PPC::VSSRCRegClass; 3550 else if (Subtarget.hasSPE()) 3551 RC = &PPC::GPRCRegClass; 3552 else 3553 RC = &PPC::F4RCRegClass; 3554 break; 3555 case MVT::f64: 3556 if (Subtarget.hasVSX()) 3557 RC = &PPC::VSFRCRegClass; 3558 else if (Subtarget.hasSPE()) 3559 // SPE passes doubles in GPR pairs. 3560 RC = &PPC::GPRCRegClass; 3561 else 3562 RC = &PPC::F8RCRegClass; 3563 break; 3564 case MVT::v16i8: 3565 case MVT::v8i16: 3566 case MVT::v4i32: 3567 RC = &PPC::VRRCRegClass; 3568 break; 3569 case MVT::v4f32: 3570 RC = &PPC::VRRCRegClass; 3571 break; 3572 case MVT::v2f64: 3573 case MVT::v2i64: 3574 RC = &PPC::VRRCRegClass; 3575 break; 3576 } 3577 3578 SDValue ArgValue; 3579 // Transform the arguments stored in physical registers into 3580 // virtual ones. 3581 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3582 assert(i + 1 < e && "No second half of double precision argument"); 3583 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3584 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3585 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3586 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3587 if (!Subtarget.isLittleEndian()) 3588 std::swap (ArgValueLo, ArgValueHi); 3589 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3590 ArgValueHi); 3591 } else { 3592 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3593 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3594 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3595 if (ValVT == MVT::i1) 3596 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3597 } 3598 3599 InVals.push_back(ArgValue); 3600 } else { 3601 // Argument stored in memory. 3602 assert(VA.isMemLoc()); 3603 3604 // Get the extended size of the argument type in stack 3605 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3606 // Get the actual size of the argument type 3607 unsigned ObjSize = VA.getValVT().getStoreSize(); 3608 unsigned ArgOffset = VA.getLocMemOffset(); 3609 // Stack objects in PPC32 are right justified. 3610 ArgOffset += ArgSize - ObjSize; 3611 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3612 3613 // Create load nodes to retrieve arguments from the stack. 3614 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3615 InVals.push_back( 3616 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3617 } 3618 } 3619 3620 // Assign locations to all of the incoming aggregate by value arguments. 3621 // Aggregates passed by value are stored in the local variable space of the 3622 // caller's stack frame, right above the parameter list area. 3623 SmallVector<CCValAssign, 16> ByValArgLocs; 3624 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3625 ByValArgLocs, *DAG.getContext()); 3626 3627 // Reserve stack space for the allocations in CCInfo. 3628 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3629 3630 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3631 3632 // Area that is at least reserved in the caller of this function. 3633 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3634 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3635 3636 // Set the size that is at least reserved in caller of this function. Tail 3637 // call optimized function's reserved stack space needs to be aligned so that 3638 // taking the difference between two stack areas will result in an aligned 3639 // stack. 3640 MinReservedArea = 3641 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3642 FuncInfo->setMinReservedArea(MinReservedArea); 3643 3644 SmallVector<SDValue, 8> MemOps; 3645 3646 // If the function takes variable number of arguments, make a frame index for 3647 // the start of the first vararg value... for expansion of llvm.va_start. 3648 if (isVarArg) { 3649 static const MCPhysReg GPArgRegs[] = { 3650 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3651 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3652 }; 3653 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3654 3655 static const MCPhysReg FPArgRegs[] = { 3656 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3657 PPC::F8 3658 }; 3659 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3660 3661 if (useSoftFloat() || hasSPE()) 3662 NumFPArgRegs = 0; 3663 3664 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3665 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3666 3667 // Make room for NumGPArgRegs and NumFPArgRegs. 3668 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3669 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3670 3671 FuncInfo->setVarArgsStackOffset( 3672 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3673 CCInfo.getNextStackOffset(), true)); 3674 3675 FuncInfo->setVarArgsFrameIndex( 3676 MFI.CreateStackObject(Depth, Align(8), false)); 3677 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3678 3679 // The fixed integer arguments of a variadic function are stored to the 3680 // VarArgsFrameIndex on the stack so that they may be loaded by 3681 // dereferencing the result of va_next. 3682 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3683 // Get an existing live-in vreg, or add a new one. 3684 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3685 if (!VReg) 3686 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3687 3688 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3689 SDValue Store = 3690 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3691 MemOps.push_back(Store); 3692 // Increment the address by four for the next argument to store 3693 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3694 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3695 } 3696 3697 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3698 // is set. 3699 // The double arguments are stored to the VarArgsFrameIndex 3700 // on the stack. 3701 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3702 // Get an existing live-in vreg, or add a new one. 3703 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3704 if (!VReg) 3705 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3706 3707 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3708 SDValue Store = 3709 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3710 MemOps.push_back(Store); 3711 // Increment the address by eight for the next argument to store 3712 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3713 PtrVT); 3714 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3715 } 3716 } 3717 3718 if (!MemOps.empty()) 3719 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3720 3721 return Chain; 3722 } 3723 3724 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3725 // value to MVT::i64 and then truncate to the correct register size. 3726 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3727 EVT ObjectVT, SelectionDAG &DAG, 3728 SDValue ArgVal, 3729 const SDLoc &dl) const { 3730 if (Flags.isSExt()) 3731 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3732 DAG.getValueType(ObjectVT)); 3733 else if (Flags.isZExt()) 3734 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3735 DAG.getValueType(ObjectVT)); 3736 3737 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3738 } 3739 3740 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3741 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3742 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3743 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3744 // TODO: add description of PPC stack frame format, or at least some docs. 3745 // 3746 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3747 bool isLittleEndian = Subtarget.isLittleEndian(); 3748 MachineFunction &MF = DAG.getMachineFunction(); 3749 MachineFrameInfo &MFI = MF.getFrameInfo(); 3750 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3751 3752 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3753 "fastcc not supported on varargs functions"); 3754 3755 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3756 // Potential tail calls could cause overwriting of argument stack slots. 3757 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3758 (CallConv == CallingConv::Fast)); 3759 unsigned PtrByteSize = 8; 3760 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3761 3762 static const MCPhysReg GPR[] = { 3763 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3764 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3765 }; 3766 static const MCPhysReg VR[] = { 3767 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3768 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3769 }; 3770 3771 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3772 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3773 const unsigned Num_VR_Regs = array_lengthof(VR); 3774 3775 // Do a first pass over the arguments to determine whether the ABI 3776 // guarantees that our caller has allocated the parameter save area 3777 // on its stack frame. In the ELFv1 ABI, this is always the case; 3778 // in the ELFv2 ABI, it is true if this is a vararg function or if 3779 // any parameter is located in a stack slot. 3780 3781 bool HasParameterArea = !isELFv2ABI || isVarArg; 3782 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3783 unsigned NumBytes = LinkageSize; 3784 unsigned AvailableFPRs = Num_FPR_Regs; 3785 unsigned AvailableVRs = Num_VR_Regs; 3786 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3787 if (Ins[i].Flags.isNest()) 3788 continue; 3789 3790 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3791 PtrByteSize, LinkageSize, ParamAreaSize, 3792 NumBytes, AvailableFPRs, AvailableVRs)) 3793 HasParameterArea = true; 3794 } 3795 3796 // Add DAG nodes to load the arguments or copy them out of registers. On 3797 // entry to a function on PPC, the arguments start after the linkage area, 3798 // although the first ones are often in registers. 3799 3800 unsigned ArgOffset = LinkageSize; 3801 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3802 SmallVector<SDValue, 8> MemOps; 3803 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3804 unsigned CurArgIdx = 0; 3805 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3806 SDValue ArgVal; 3807 bool needsLoad = false; 3808 EVT ObjectVT = Ins[ArgNo].VT; 3809 EVT OrigVT = Ins[ArgNo].ArgVT; 3810 unsigned ObjSize = ObjectVT.getStoreSize(); 3811 unsigned ArgSize = ObjSize; 3812 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3813 if (Ins[ArgNo].isOrigArg()) { 3814 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3815 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3816 } 3817 // We re-align the argument offset for each argument, except when using the 3818 // fast calling convention, when we need to make sure we do that only when 3819 // we'll actually use a stack slot. 3820 unsigned CurArgOffset; 3821 Align Alignment; 3822 auto ComputeArgOffset = [&]() { 3823 /* Respect alignment of argument on the stack. */ 3824 Alignment = 3825 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3826 ArgOffset = alignTo(ArgOffset, Alignment); 3827 CurArgOffset = ArgOffset; 3828 }; 3829 3830 if (CallConv != CallingConv::Fast) { 3831 ComputeArgOffset(); 3832 3833 /* Compute GPR index associated with argument offset. */ 3834 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3835 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3836 } 3837 3838 // FIXME the codegen can be much improved in some cases. 3839 // We do not have to keep everything in memory. 3840 if (Flags.isByVal()) { 3841 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3842 3843 if (CallConv == CallingConv::Fast) 3844 ComputeArgOffset(); 3845 3846 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3847 ObjSize = Flags.getByValSize(); 3848 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3849 // Empty aggregate parameters do not take up registers. Examples: 3850 // struct { } a; 3851 // union { } b; 3852 // int c[0]; 3853 // etc. However, we have to provide a place-holder in InVals, so 3854 // pretend we have an 8-byte item at the current address for that 3855 // purpose. 3856 if (!ObjSize) { 3857 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3858 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3859 InVals.push_back(FIN); 3860 continue; 3861 } 3862 3863 // Create a stack object covering all stack doublewords occupied 3864 // by the argument. If the argument is (fully or partially) on 3865 // the stack, or if the argument is fully in registers but the 3866 // caller has allocated the parameter save anyway, we can refer 3867 // directly to the caller's stack frame. Otherwise, create a 3868 // local copy in our own frame. 3869 int FI; 3870 if (HasParameterArea || 3871 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3872 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3873 else 3874 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3875 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3876 3877 // Handle aggregates smaller than 8 bytes. 3878 if (ObjSize < PtrByteSize) { 3879 // The value of the object is its address, which differs from the 3880 // address of the enclosing doubleword on big-endian systems. 3881 SDValue Arg = FIN; 3882 if (!isLittleEndian) { 3883 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3884 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3885 } 3886 InVals.push_back(Arg); 3887 3888 if (GPR_idx != Num_GPR_Regs) { 3889 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3890 FuncInfo->addLiveInAttr(VReg, Flags); 3891 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3892 SDValue Store; 3893 3894 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3895 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3896 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3897 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3898 MachinePointerInfo(&*FuncArg), ObjType); 3899 } else { 3900 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3901 // store the whole register as-is to the parameter save area 3902 // slot. 3903 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3904 MachinePointerInfo(&*FuncArg)); 3905 } 3906 3907 MemOps.push_back(Store); 3908 } 3909 // Whether we copied from a register or not, advance the offset 3910 // into the parameter save area by a full doubleword. 3911 ArgOffset += PtrByteSize; 3912 continue; 3913 } 3914 3915 // The value of the object is its address, which is the address of 3916 // its first stack doubleword. 3917 InVals.push_back(FIN); 3918 3919 // Store whatever pieces of the object are in registers to memory. 3920 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3921 if (GPR_idx == Num_GPR_Regs) 3922 break; 3923 3924 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3925 FuncInfo->addLiveInAttr(VReg, Flags); 3926 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3927 SDValue Addr = FIN; 3928 if (j) { 3929 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3930 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3931 } 3932 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3933 MachinePointerInfo(&*FuncArg, j)); 3934 MemOps.push_back(Store); 3935 ++GPR_idx; 3936 } 3937 ArgOffset += ArgSize; 3938 continue; 3939 } 3940 3941 switch (ObjectVT.getSimpleVT().SimpleTy) { 3942 default: llvm_unreachable("Unhandled argument type!"); 3943 case MVT::i1: 3944 case MVT::i32: 3945 case MVT::i64: 3946 if (Flags.isNest()) { 3947 // The 'nest' parameter, if any, is passed in R11. 3948 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3949 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3950 3951 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3952 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3953 3954 break; 3955 } 3956 3957 // These can be scalar arguments or elements of an integer array type 3958 // passed directly. Clang may use those instead of "byval" aggregate 3959 // types to avoid forcing arguments to memory unnecessarily. 3960 if (GPR_idx != Num_GPR_Regs) { 3961 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3962 FuncInfo->addLiveInAttr(VReg, Flags); 3963 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3964 3965 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3966 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3967 // value to MVT::i64 and then truncate to the correct register size. 3968 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3969 } else { 3970 if (CallConv == CallingConv::Fast) 3971 ComputeArgOffset(); 3972 3973 needsLoad = true; 3974 ArgSize = PtrByteSize; 3975 } 3976 if (CallConv != CallingConv::Fast || needsLoad) 3977 ArgOffset += 8; 3978 break; 3979 3980 case MVT::f32: 3981 case MVT::f64: 3982 // These can be scalar arguments or elements of a float array type 3983 // passed directly. The latter are used to implement ELFv2 homogenous 3984 // float aggregates. 3985 if (FPR_idx != Num_FPR_Regs) { 3986 unsigned VReg; 3987 3988 if (ObjectVT == MVT::f32) 3989 VReg = MF.addLiveIn(FPR[FPR_idx], 3990 Subtarget.hasP8Vector() 3991 ? &PPC::VSSRCRegClass 3992 : &PPC::F4RCRegClass); 3993 else 3994 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3995 ? &PPC::VSFRCRegClass 3996 : &PPC::F8RCRegClass); 3997 3998 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3999 ++FPR_idx; 4000 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4001 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4002 // once we support fp <-> gpr moves. 4003 4004 // This can only ever happen in the presence of f32 array types, 4005 // since otherwise we never run out of FPRs before running out 4006 // of GPRs. 4007 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4008 FuncInfo->addLiveInAttr(VReg, Flags); 4009 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4010 4011 if (ObjectVT == MVT::f32) { 4012 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4013 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4014 DAG.getConstant(32, dl, MVT::i32)); 4015 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4016 } 4017 4018 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4019 } else { 4020 if (CallConv == CallingConv::Fast) 4021 ComputeArgOffset(); 4022 4023 needsLoad = true; 4024 } 4025 4026 // When passing an array of floats, the array occupies consecutive 4027 // space in the argument area; only round up to the next doubleword 4028 // at the end of the array. Otherwise, each float takes 8 bytes. 4029 if (CallConv != CallingConv::Fast || needsLoad) { 4030 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4031 ArgOffset += ArgSize; 4032 if (Flags.isInConsecutiveRegsLast()) 4033 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4034 } 4035 break; 4036 case MVT::v4f32: 4037 case MVT::v4i32: 4038 case MVT::v8i16: 4039 case MVT::v16i8: 4040 case MVT::v2f64: 4041 case MVT::v2i64: 4042 case MVT::v1i128: 4043 case MVT::f128: 4044 // These can be scalar arguments or elements of a vector array type 4045 // passed directly. The latter are used to implement ELFv2 homogenous 4046 // vector aggregates. 4047 if (VR_idx != Num_VR_Regs) { 4048 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4049 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4050 ++VR_idx; 4051 } else { 4052 if (CallConv == CallingConv::Fast) 4053 ComputeArgOffset(); 4054 needsLoad = true; 4055 } 4056 if (CallConv != CallingConv::Fast || needsLoad) 4057 ArgOffset += 16; 4058 break; 4059 } 4060 4061 // We need to load the argument to a virtual register if we determined 4062 // above that we ran out of physical registers of the appropriate type. 4063 if (needsLoad) { 4064 if (ObjSize < ArgSize && !isLittleEndian) 4065 CurArgOffset += ArgSize - ObjSize; 4066 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4067 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4068 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4069 } 4070 4071 InVals.push_back(ArgVal); 4072 } 4073 4074 // Area that is at least reserved in the caller of this function. 4075 unsigned MinReservedArea; 4076 if (HasParameterArea) 4077 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4078 else 4079 MinReservedArea = LinkageSize; 4080 4081 // Set the size that is at least reserved in caller of this function. Tail 4082 // call optimized functions' reserved stack space needs to be aligned so that 4083 // taking the difference between two stack areas will result in an aligned 4084 // stack. 4085 MinReservedArea = 4086 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4087 FuncInfo->setMinReservedArea(MinReservedArea); 4088 4089 // If the function takes variable number of arguments, make a frame index for 4090 // the start of the first vararg value... for expansion of llvm.va_start. 4091 // On ELFv2ABI spec, it writes: 4092 // C programs that are intended to be *portable* across different compilers 4093 // and architectures must use the header file <stdarg.h> to deal with variable 4094 // argument lists. 4095 if (isVarArg && MFI.hasVAStart()) { 4096 int Depth = ArgOffset; 4097 4098 FuncInfo->setVarArgsFrameIndex( 4099 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4100 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4101 4102 // If this function is vararg, store any remaining integer argument regs 4103 // to their spots on the stack so that they may be loaded by dereferencing 4104 // the result of va_next. 4105 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4106 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4107 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4108 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4109 SDValue Store = 4110 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4111 MemOps.push_back(Store); 4112 // Increment the address by four for the next argument to store 4113 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4114 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4115 } 4116 } 4117 4118 if (!MemOps.empty()) 4119 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4120 4121 return Chain; 4122 } 4123 4124 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4125 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4126 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4127 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4128 // TODO: add description of PPC stack frame format, or at least some docs. 4129 // 4130 MachineFunction &MF = DAG.getMachineFunction(); 4131 MachineFrameInfo &MFI = MF.getFrameInfo(); 4132 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4133 4134 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4135 bool isPPC64 = PtrVT == MVT::i64; 4136 // Potential tail calls could cause overwriting of argument stack slots. 4137 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4138 (CallConv == CallingConv::Fast)); 4139 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4140 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4141 unsigned ArgOffset = LinkageSize; 4142 // Area that is at least reserved in caller of this function. 4143 unsigned MinReservedArea = ArgOffset; 4144 4145 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4146 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4147 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4148 }; 4149 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4150 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4151 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4152 }; 4153 static const MCPhysReg VR[] = { 4154 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4155 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4156 }; 4157 4158 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4159 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4160 const unsigned Num_VR_Regs = array_lengthof( VR); 4161 4162 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4163 4164 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4165 4166 // In 32-bit non-varargs functions, the stack space for vectors is after the 4167 // stack space for non-vectors. We do not use this space unless we have 4168 // too many vectors to fit in registers, something that only occurs in 4169 // constructed examples:), but we have to walk the arglist to figure 4170 // that out...for the pathological case, compute VecArgOffset as the 4171 // start of the vector parameter area. Computing VecArgOffset is the 4172 // entire point of the following loop. 4173 unsigned VecArgOffset = ArgOffset; 4174 if (!isVarArg && !isPPC64) { 4175 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4176 ++ArgNo) { 4177 EVT ObjectVT = Ins[ArgNo].VT; 4178 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4179 4180 if (Flags.isByVal()) { 4181 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4182 unsigned ObjSize = Flags.getByValSize(); 4183 unsigned ArgSize = 4184 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4185 VecArgOffset += ArgSize; 4186 continue; 4187 } 4188 4189 switch(ObjectVT.getSimpleVT().SimpleTy) { 4190 default: llvm_unreachable("Unhandled argument type!"); 4191 case MVT::i1: 4192 case MVT::i32: 4193 case MVT::f32: 4194 VecArgOffset += 4; 4195 break; 4196 case MVT::i64: // PPC64 4197 case MVT::f64: 4198 // FIXME: We are guaranteed to be !isPPC64 at this point. 4199 // Does MVT::i64 apply? 4200 VecArgOffset += 8; 4201 break; 4202 case MVT::v4f32: 4203 case MVT::v4i32: 4204 case MVT::v8i16: 4205 case MVT::v16i8: 4206 // Nothing to do, we're only looking at Nonvector args here. 4207 break; 4208 } 4209 } 4210 } 4211 // We've found where the vector parameter area in memory is. Skip the 4212 // first 12 parameters; these don't use that memory. 4213 VecArgOffset = ((VecArgOffset+15)/16)*16; 4214 VecArgOffset += 12*16; 4215 4216 // Add DAG nodes to load the arguments or copy them out of registers. On 4217 // entry to a function on PPC, the arguments start after the linkage area, 4218 // although the first ones are often in registers. 4219 4220 SmallVector<SDValue, 8> MemOps; 4221 unsigned nAltivecParamsAtEnd = 0; 4222 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4223 unsigned CurArgIdx = 0; 4224 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4225 SDValue ArgVal; 4226 bool needsLoad = false; 4227 EVT ObjectVT = Ins[ArgNo].VT; 4228 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4229 unsigned ArgSize = ObjSize; 4230 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4231 if (Ins[ArgNo].isOrigArg()) { 4232 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4233 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4234 } 4235 unsigned CurArgOffset = ArgOffset; 4236 4237 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4238 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4239 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4240 if (isVarArg || isPPC64) { 4241 MinReservedArea = ((MinReservedArea+15)/16)*16; 4242 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4243 Flags, 4244 PtrByteSize); 4245 } else nAltivecParamsAtEnd++; 4246 } else 4247 // Calculate min reserved area. 4248 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4249 Flags, 4250 PtrByteSize); 4251 4252 // FIXME the codegen can be much improved in some cases. 4253 // We do not have to keep everything in memory. 4254 if (Flags.isByVal()) { 4255 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4256 4257 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4258 ObjSize = Flags.getByValSize(); 4259 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4260 // Objects of size 1 and 2 are right justified, everything else is 4261 // left justified. This means the memory address is adjusted forwards. 4262 if (ObjSize==1 || ObjSize==2) { 4263 CurArgOffset = CurArgOffset + (4 - ObjSize); 4264 } 4265 // The value of the object is its address. 4266 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4267 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4268 InVals.push_back(FIN); 4269 if (ObjSize==1 || ObjSize==2) { 4270 if (GPR_idx != Num_GPR_Regs) { 4271 unsigned VReg; 4272 if (isPPC64) 4273 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4274 else 4275 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4276 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4277 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4278 SDValue Store = 4279 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4280 MachinePointerInfo(&*FuncArg), ObjType); 4281 MemOps.push_back(Store); 4282 ++GPR_idx; 4283 } 4284 4285 ArgOffset += PtrByteSize; 4286 4287 continue; 4288 } 4289 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4290 // Store whatever pieces of the object are in registers 4291 // to memory. ArgOffset will be the address of the beginning 4292 // of the object. 4293 if (GPR_idx != Num_GPR_Regs) { 4294 unsigned VReg; 4295 if (isPPC64) 4296 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4297 else 4298 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4299 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4300 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4301 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4302 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4303 MachinePointerInfo(&*FuncArg, j)); 4304 MemOps.push_back(Store); 4305 ++GPR_idx; 4306 ArgOffset += PtrByteSize; 4307 } else { 4308 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4309 break; 4310 } 4311 } 4312 continue; 4313 } 4314 4315 switch (ObjectVT.getSimpleVT().SimpleTy) { 4316 default: llvm_unreachable("Unhandled argument type!"); 4317 case MVT::i1: 4318 case MVT::i32: 4319 if (!isPPC64) { 4320 if (GPR_idx != Num_GPR_Regs) { 4321 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4322 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4323 4324 if (ObjectVT == MVT::i1) 4325 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4326 4327 ++GPR_idx; 4328 } else { 4329 needsLoad = true; 4330 ArgSize = PtrByteSize; 4331 } 4332 // All int arguments reserve stack space in the Darwin ABI. 4333 ArgOffset += PtrByteSize; 4334 break; 4335 } 4336 LLVM_FALLTHROUGH; 4337 case MVT::i64: // PPC64 4338 if (GPR_idx != Num_GPR_Regs) { 4339 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4340 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4341 4342 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4343 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4344 // value to MVT::i64 and then truncate to the correct register size. 4345 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4346 4347 ++GPR_idx; 4348 } else { 4349 needsLoad = true; 4350 ArgSize = PtrByteSize; 4351 } 4352 // All int arguments reserve stack space in the Darwin ABI. 4353 ArgOffset += 8; 4354 break; 4355 4356 case MVT::f32: 4357 case MVT::f64: 4358 // Every 4 bytes of argument space consumes one of the GPRs available for 4359 // argument passing. 4360 if (GPR_idx != Num_GPR_Regs) { 4361 ++GPR_idx; 4362 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4363 ++GPR_idx; 4364 } 4365 if (FPR_idx != Num_FPR_Regs) { 4366 unsigned VReg; 4367 4368 if (ObjectVT == MVT::f32) 4369 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4370 else 4371 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4372 4373 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4374 ++FPR_idx; 4375 } else { 4376 needsLoad = true; 4377 } 4378 4379 // All FP arguments reserve stack space in the Darwin ABI. 4380 ArgOffset += isPPC64 ? 8 : ObjSize; 4381 break; 4382 case MVT::v4f32: 4383 case MVT::v4i32: 4384 case MVT::v8i16: 4385 case MVT::v16i8: 4386 // Note that vector arguments in registers don't reserve stack space, 4387 // except in varargs functions. 4388 if (VR_idx != Num_VR_Regs) { 4389 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4390 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4391 if (isVarArg) { 4392 while ((ArgOffset % 16) != 0) { 4393 ArgOffset += PtrByteSize; 4394 if (GPR_idx != Num_GPR_Regs) 4395 GPR_idx++; 4396 } 4397 ArgOffset += 16; 4398 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4399 } 4400 ++VR_idx; 4401 } else { 4402 if (!isVarArg && !isPPC64) { 4403 // Vectors go after all the nonvectors. 4404 CurArgOffset = VecArgOffset; 4405 VecArgOffset += 16; 4406 } else { 4407 // Vectors are aligned. 4408 ArgOffset = ((ArgOffset+15)/16)*16; 4409 CurArgOffset = ArgOffset; 4410 ArgOffset += 16; 4411 } 4412 needsLoad = true; 4413 } 4414 break; 4415 } 4416 4417 // We need to load the argument to a virtual register if we determined above 4418 // that we ran out of physical registers of the appropriate type. 4419 if (needsLoad) { 4420 int FI = MFI.CreateFixedObject(ObjSize, 4421 CurArgOffset + (ArgSize - ObjSize), 4422 isImmutable); 4423 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4424 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4425 } 4426 4427 InVals.push_back(ArgVal); 4428 } 4429 4430 // Allow for Altivec parameters at the end, if needed. 4431 if (nAltivecParamsAtEnd) { 4432 MinReservedArea = ((MinReservedArea+15)/16)*16; 4433 MinReservedArea += 16*nAltivecParamsAtEnd; 4434 } 4435 4436 // Area that is at least reserved in the caller of this function. 4437 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4438 4439 // Set the size that is at least reserved in caller of this function. Tail 4440 // call optimized functions' reserved stack space needs to be aligned so that 4441 // taking the difference between two stack areas will result in an aligned 4442 // stack. 4443 MinReservedArea = 4444 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4445 FuncInfo->setMinReservedArea(MinReservedArea); 4446 4447 // If the function takes variable number of arguments, make a frame index for 4448 // the start of the first vararg value... for expansion of llvm.va_start. 4449 if (isVarArg) { 4450 int Depth = ArgOffset; 4451 4452 FuncInfo->setVarArgsFrameIndex( 4453 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4454 Depth, true)); 4455 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4456 4457 // If this function is vararg, store any remaining integer argument regs 4458 // to their spots on the stack so that they may be loaded by dereferencing 4459 // the result of va_next. 4460 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4461 unsigned VReg; 4462 4463 if (isPPC64) 4464 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4465 else 4466 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4467 4468 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4469 SDValue Store = 4470 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4471 MemOps.push_back(Store); 4472 // Increment the address by four for the next argument to store 4473 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4474 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4475 } 4476 } 4477 4478 if (!MemOps.empty()) 4479 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4480 4481 return Chain; 4482 } 4483 4484 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4485 /// adjusted to accommodate the arguments for the tailcall. 4486 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4487 unsigned ParamSize) { 4488 4489 if (!isTailCall) return 0; 4490 4491 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4492 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4493 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4494 // Remember only if the new adjustment is bigger. 4495 if (SPDiff < FI->getTailCallSPDelta()) 4496 FI->setTailCallSPDelta(SPDiff); 4497 4498 return SPDiff; 4499 } 4500 4501 static bool isFunctionGlobalAddress(SDValue Callee); 4502 4503 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4504 const TargetMachine &TM) { 4505 // It does not make sense to call callsShareTOCBase() with a caller that 4506 // is PC Relative since PC Relative callers do not have a TOC. 4507 #ifndef NDEBUG 4508 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4509 assert(!STICaller->isUsingPCRelativeCalls() && 4510 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4511 #endif 4512 4513 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4514 // don't have enough information to determine if the caller and callee share 4515 // the same TOC base, so we have to pessimistically assume they don't for 4516 // correctness. 4517 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4518 if (!G) 4519 return false; 4520 4521 const GlobalValue *GV = G->getGlobal(); 4522 4523 // If the callee is preemptable, then the static linker will use a plt-stub 4524 // which saves the toc to the stack, and needs a nop after the call 4525 // instruction to convert to a toc-restore. 4526 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4527 return false; 4528 4529 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4530 // We may need a TOC restore in the situation where the caller requires a 4531 // valid TOC but the callee is PC Relative and does not. 4532 const Function *F = dyn_cast<Function>(GV); 4533 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4534 4535 // If we have an Alias we can try to get the function from there. 4536 if (Alias) { 4537 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4538 F = dyn_cast<Function>(GlobalObj); 4539 } 4540 4541 // If we still have no valid function pointer we do not have enough 4542 // information to determine if the callee uses PC Relative calls so we must 4543 // assume that it does. 4544 if (!F) 4545 return false; 4546 4547 // If the callee uses PC Relative we cannot guarantee that the callee won't 4548 // clobber the TOC of the caller and so we must assume that the two 4549 // functions do not share a TOC base. 4550 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4551 if (STICallee->isUsingPCRelativeCalls()) 4552 return false; 4553 4554 // The medium and large code models are expected to provide a sufficiently 4555 // large TOC to provide all data addressing needs of a module with a 4556 // single TOC. 4557 if (CodeModel::Medium == TM.getCodeModel() || 4558 CodeModel::Large == TM.getCodeModel()) 4559 return true; 4560 4561 // Otherwise we need to ensure callee and caller are in the same section, 4562 // since the linker may allocate multiple TOCs, and we don't know which 4563 // sections will belong to the same TOC base. 4564 if (!GV->isStrongDefinitionForLinker()) 4565 return false; 4566 4567 // Any explicitly-specified sections and section prefixes must also match. 4568 // Also, if we're using -ffunction-sections, then each function is always in 4569 // a different section (the same is true for COMDAT functions). 4570 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4571 GV->getSection() != Caller->getSection()) 4572 return false; 4573 if (const auto *F = dyn_cast<Function>(GV)) { 4574 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4575 return false; 4576 } 4577 4578 return true; 4579 } 4580 4581 static bool 4582 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4583 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4584 assert(Subtarget.is64BitELFABI()); 4585 4586 const unsigned PtrByteSize = 8; 4587 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4588 4589 static const MCPhysReg GPR[] = { 4590 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4591 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4592 }; 4593 static const MCPhysReg VR[] = { 4594 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4595 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4596 }; 4597 4598 const unsigned NumGPRs = array_lengthof(GPR); 4599 const unsigned NumFPRs = 13; 4600 const unsigned NumVRs = array_lengthof(VR); 4601 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4602 4603 unsigned NumBytes = LinkageSize; 4604 unsigned AvailableFPRs = NumFPRs; 4605 unsigned AvailableVRs = NumVRs; 4606 4607 for (const ISD::OutputArg& Param : Outs) { 4608 if (Param.Flags.isNest()) continue; 4609 4610 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4611 LinkageSize, ParamAreaSize, NumBytes, 4612 AvailableFPRs, AvailableVRs)) 4613 return true; 4614 } 4615 return false; 4616 } 4617 4618 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4619 if (CB.arg_size() != CallerFn->arg_size()) 4620 return false; 4621 4622 auto CalleeArgIter = CB.arg_begin(); 4623 auto CalleeArgEnd = CB.arg_end(); 4624 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4625 4626 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4627 const Value* CalleeArg = *CalleeArgIter; 4628 const Value* CallerArg = &(*CallerArgIter); 4629 if (CalleeArg == CallerArg) 4630 continue; 4631 4632 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4633 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4634 // } 4635 // 1st argument of callee is undef and has the same type as caller. 4636 if (CalleeArg->getType() == CallerArg->getType() && 4637 isa<UndefValue>(CalleeArg)) 4638 continue; 4639 4640 return false; 4641 } 4642 4643 return true; 4644 } 4645 4646 // Returns true if TCO is possible between the callers and callees 4647 // calling conventions. 4648 static bool 4649 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4650 CallingConv::ID CalleeCC) { 4651 // Tail calls are possible with fastcc and ccc. 4652 auto isTailCallableCC = [] (CallingConv::ID CC){ 4653 return CC == CallingConv::C || CC == CallingConv::Fast; 4654 }; 4655 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4656 return false; 4657 4658 // We can safely tail call both fastcc and ccc callees from a c calling 4659 // convention caller. If the caller is fastcc, we may have less stack space 4660 // than a non-fastcc caller with the same signature so disable tail-calls in 4661 // that case. 4662 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4663 } 4664 4665 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4666 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4667 const SmallVectorImpl<ISD::OutputArg> &Outs, 4668 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4669 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4670 4671 if (DisableSCO && !TailCallOpt) return false; 4672 4673 // Variadic argument functions are not supported. 4674 if (isVarArg) return false; 4675 4676 auto &Caller = DAG.getMachineFunction().getFunction(); 4677 // Check that the calling conventions are compatible for tco. 4678 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4679 return false; 4680 4681 // Caller contains any byval parameter is not supported. 4682 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4683 return false; 4684 4685 // Callee contains any byval parameter is not supported, too. 4686 // Note: This is a quick work around, because in some cases, e.g. 4687 // caller's stack size > callee's stack size, we are still able to apply 4688 // sibling call optimization. For example, gcc is able to do SCO for caller1 4689 // in the following example, but not for caller2. 4690 // struct test { 4691 // long int a; 4692 // char ary[56]; 4693 // } gTest; 4694 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4695 // b->a = v.a; 4696 // return 0; 4697 // } 4698 // void caller1(struct test a, struct test c, struct test *b) { 4699 // callee(gTest, b); } 4700 // void caller2(struct test *b) { callee(gTest, b); } 4701 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4702 return false; 4703 4704 // If callee and caller use different calling conventions, we cannot pass 4705 // parameters on stack since offsets for the parameter area may be different. 4706 if (Caller.getCallingConv() != CalleeCC && 4707 needStackSlotPassParameters(Subtarget, Outs)) 4708 return false; 4709 4710 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4711 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4712 // callee potentially have different TOC bases then we cannot tail call since 4713 // we need to restore the TOC pointer after the call. 4714 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4715 // We cannot guarantee this for indirect calls or calls to external functions. 4716 // When PC-Relative addressing is used, the concept of the TOC is no longer 4717 // applicable so this check is not required. 4718 // Check first for indirect calls. 4719 if (!Subtarget.isUsingPCRelativeCalls() && 4720 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4721 return false; 4722 4723 // Check if we share the TOC base. 4724 if (!Subtarget.isUsingPCRelativeCalls() && 4725 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4726 return false; 4727 4728 // TCO allows altering callee ABI, so we don't have to check further. 4729 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4730 return true; 4731 4732 if (DisableSCO) return false; 4733 4734 // If callee use the same argument list that caller is using, then we can 4735 // apply SCO on this case. If it is not, then we need to check if callee needs 4736 // stack for passing arguments. 4737 // PC Relative tail calls may not have a CallBase. 4738 // If there is no CallBase we cannot verify if we have the same argument 4739 // list so assume that we don't have the same argument list. 4740 if (CB && !hasSameArgumentList(&Caller, *CB) && 4741 needStackSlotPassParameters(Subtarget, Outs)) 4742 return false; 4743 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4744 return false; 4745 4746 return true; 4747 } 4748 4749 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4750 /// for tail call optimization. Targets which want to do tail call 4751 /// optimization should implement this function. 4752 bool 4753 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4754 CallingConv::ID CalleeCC, 4755 bool isVarArg, 4756 const SmallVectorImpl<ISD::InputArg> &Ins, 4757 SelectionDAG& DAG) const { 4758 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4759 return false; 4760 4761 // Variable argument functions are not supported. 4762 if (isVarArg) 4763 return false; 4764 4765 MachineFunction &MF = DAG.getMachineFunction(); 4766 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4767 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4768 // Functions containing by val parameters are not supported. 4769 for (unsigned i = 0; i != Ins.size(); i++) { 4770 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4771 if (Flags.isByVal()) return false; 4772 } 4773 4774 // Non-PIC/GOT tail calls are supported. 4775 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4776 return true; 4777 4778 // At the moment we can only do local tail calls (in same module, hidden 4779 // or protected) if we are generating PIC. 4780 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4781 return G->getGlobal()->hasHiddenVisibility() 4782 || G->getGlobal()->hasProtectedVisibility(); 4783 } 4784 4785 return false; 4786 } 4787 4788 /// isCallCompatibleAddress - Return the immediate to use if the specified 4789 /// 32-bit value is representable in the immediate field of a BxA instruction. 4790 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4791 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4792 if (!C) return nullptr; 4793 4794 int Addr = C->getZExtValue(); 4795 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4796 SignExtend32<26>(Addr) != Addr) 4797 return nullptr; // Top 6 bits have to be sext of immediate. 4798 4799 return DAG 4800 .getConstant( 4801 (int)C->getZExtValue() >> 2, SDLoc(Op), 4802 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4803 .getNode(); 4804 } 4805 4806 namespace { 4807 4808 struct TailCallArgumentInfo { 4809 SDValue Arg; 4810 SDValue FrameIdxOp; 4811 int FrameIdx = 0; 4812 4813 TailCallArgumentInfo() = default; 4814 }; 4815 4816 } // end anonymous namespace 4817 4818 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4819 static void StoreTailCallArgumentsToStackSlot( 4820 SelectionDAG &DAG, SDValue Chain, 4821 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4822 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4823 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4824 SDValue Arg = TailCallArgs[i].Arg; 4825 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4826 int FI = TailCallArgs[i].FrameIdx; 4827 // Store relative to framepointer. 4828 MemOpChains.push_back(DAG.getStore( 4829 Chain, dl, Arg, FIN, 4830 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4831 } 4832 } 4833 4834 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4835 /// the appropriate stack slot for the tail call optimized function call. 4836 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4837 SDValue OldRetAddr, SDValue OldFP, 4838 int SPDiff, const SDLoc &dl) { 4839 if (SPDiff) { 4840 // Calculate the new stack slot for the return address. 4841 MachineFunction &MF = DAG.getMachineFunction(); 4842 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4843 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4844 bool isPPC64 = Subtarget.isPPC64(); 4845 int SlotSize = isPPC64 ? 8 : 4; 4846 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4847 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4848 NewRetAddrLoc, true); 4849 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4850 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4851 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4852 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4853 } 4854 return Chain; 4855 } 4856 4857 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4858 /// the position of the argument. 4859 static void 4860 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4861 SDValue Arg, int SPDiff, unsigned ArgOffset, 4862 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4863 int Offset = ArgOffset + SPDiff; 4864 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4865 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4866 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4867 SDValue FIN = DAG.getFrameIndex(FI, VT); 4868 TailCallArgumentInfo Info; 4869 Info.Arg = Arg; 4870 Info.FrameIdxOp = FIN; 4871 Info.FrameIdx = FI; 4872 TailCallArguments.push_back(Info); 4873 } 4874 4875 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4876 /// stack slot. Returns the chain as result and the loaded frame pointers in 4877 /// LROpOut/FPOpout. Used when tail calling. 4878 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4879 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4880 SDValue &FPOpOut, const SDLoc &dl) const { 4881 if (SPDiff) { 4882 // Load the LR and FP stack slot for later adjusting. 4883 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4884 LROpOut = getReturnAddrFrameIndex(DAG); 4885 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4886 Chain = SDValue(LROpOut.getNode(), 1); 4887 } 4888 return Chain; 4889 } 4890 4891 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4892 /// by "Src" to address "Dst" of size "Size". Alignment information is 4893 /// specified by the specific parameter attribute. The copy will be passed as 4894 /// a byval function parameter. 4895 /// Sometimes what we are copying is the end of a larger object, the part that 4896 /// does not fit in registers. 4897 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4898 SDValue Chain, ISD::ArgFlagsTy Flags, 4899 SelectionDAG &DAG, const SDLoc &dl) { 4900 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4901 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4902 Flags.getNonZeroByValAlign(), false, false, false, 4903 MachinePointerInfo(), MachinePointerInfo()); 4904 } 4905 4906 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4907 /// tail calls. 4908 static void LowerMemOpCallTo( 4909 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4910 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4911 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4912 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4913 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4914 if (!isTailCall) { 4915 if (isVector) { 4916 SDValue StackPtr; 4917 if (isPPC64) 4918 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4919 else 4920 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4921 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4922 DAG.getConstant(ArgOffset, dl, PtrVT)); 4923 } 4924 MemOpChains.push_back( 4925 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4926 // Calculate and remember argument location. 4927 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4928 TailCallArguments); 4929 } 4930 4931 static void 4932 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4933 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4934 SDValue FPOp, 4935 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4936 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4937 // might overwrite each other in case of tail call optimization. 4938 SmallVector<SDValue, 8> MemOpChains2; 4939 // Do not flag preceding copytoreg stuff together with the following stuff. 4940 InFlag = SDValue(); 4941 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4942 MemOpChains2, dl); 4943 if (!MemOpChains2.empty()) 4944 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4945 4946 // Store the return address to the appropriate stack slot. 4947 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4948 4949 // Emit callseq_end just before tailcall node. 4950 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4951 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4952 InFlag = Chain.getValue(1); 4953 } 4954 4955 // Is this global address that of a function that can be called by name? (as 4956 // opposed to something that must hold a descriptor for an indirect call). 4957 static bool isFunctionGlobalAddress(SDValue Callee) { 4958 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4959 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4960 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4961 return false; 4962 4963 return G->getGlobal()->getValueType()->isFunctionTy(); 4964 } 4965 4966 return false; 4967 } 4968 4969 SDValue PPCTargetLowering::LowerCallResult( 4970 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4971 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4972 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4973 SmallVector<CCValAssign, 16> RVLocs; 4974 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4975 *DAG.getContext()); 4976 4977 CCRetInfo.AnalyzeCallResult( 4978 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4979 ? RetCC_PPC_Cold 4980 : RetCC_PPC); 4981 4982 // Copy all of the result registers out of their specified physreg. 4983 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4984 CCValAssign &VA = RVLocs[i]; 4985 assert(VA.isRegLoc() && "Can only return in registers!"); 4986 4987 SDValue Val; 4988 4989 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4990 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4991 InFlag); 4992 Chain = Lo.getValue(1); 4993 InFlag = Lo.getValue(2); 4994 VA = RVLocs[++i]; // skip ahead to next loc 4995 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4996 InFlag); 4997 Chain = Hi.getValue(1); 4998 InFlag = Hi.getValue(2); 4999 if (!Subtarget.isLittleEndian()) 5000 std::swap (Lo, Hi); 5001 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5002 } else { 5003 Val = DAG.getCopyFromReg(Chain, dl, 5004 VA.getLocReg(), VA.getLocVT(), InFlag); 5005 Chain = Val.getValue(1); 5006 InFlag = Val.getValue(2); 5007 } 5008 5009 switch (VA.getLocInfo()) { 5010 default: llvm_unreachable("Unknown loc info!"); 5011 case CCValAssign::Full: break; 5012 case CCValAssign::AExt: 5013 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5014 break; 5015 case CCValAssign::ZExt: 5016 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5017 DAG.getValueType(VA.getValVT())); 5018 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5019 break; 5020 case CCValAssign::SExt: 5021 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5022 DAG.getValueType(VA.getValVT())); 5023 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5024 break; 5025 } 5026 5027 InVals.push_back(Val); 5028 } 5029 5030 return Chain; 5031 } 5032 5033 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5034 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5035 // PatchPoint calls are not indirect. 5036 if (isPatchPoint) 5037 return false; 5038 5039 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5040 return false; 5041 5042 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5043 // becuase the immediate function pointer points to a descriptor instead of 5044 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5045 // pointer immediate points to the global entry point, while the BLA would 5046 // need to jump to the local entry point (see rL211174). 5047 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5048 isBLACompatibleAddress(Callee, DAG)) 5049 return false; 5050 5051 return true; 5052 } 5053 5054 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5055 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5056 return Subtarget.isAIXABI() || 5057 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5058 } 5059 5060 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5061 const Function &Caller, 5062 const SDValue &Callee, 5063 const PPCSubtarget &Subtarget, 5064 const TargetMachine &TM) { 5065 if (CFlags.IsTailCall) 5066 return PPCISD::TC_RETURN; 5067 5068 // This is a call through a function pointer. 5069 if (CFlags.IsIndirect) { 5070 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5071 // indirect calls. The save of the caller's TOC pointer to the stack will be 5072 // inserted into the DAG as part of call lowering. The restore of the TOC 5073 // pointer is modeled by using a pseudo instruction for the call opcode that 5074 // represents the 2 instruction sequence of an indirect branch and link, 5075 // immediately followed by a load of the TOC pointer from the the stack save 5076 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5077 // as it is not saved or used. 5078 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5079 : PPCISD::BCTRL; 5080 } 5081 5082 if (Subtarget.isUsingPCRelativeCalls()) { 5083 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5084 return PPCISD::CALL_NOTOC; 5085 } 5086 5087 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5088 // immediately following the call instruction if the caller and callee may 5089 // have different TOC bases. At link time if the linker determines the calls 5090 // may not share a TOC base, the call is redirected to a trampoline inserted 5091 // by the linker. The trampoline will (among other things) save the callers 5092 // TOC pointer at an ABI designated offset in the linkage area and the linker 5093 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5094 // into gpr2. 5095 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5096 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5097 : PPCISD::CALL_NOP; 5098 5099 return PPCISD::CALL; 5100 } 5101 5102 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5103 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5104 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5105 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5106 return SDValue(Dest, 0); 5107 5108 // Returns true if the callee is local, and false otherwise. 5109 auto isLocalCallee = [&]() { 5110 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5111 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5112 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5113 5114 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5115 !dyn_cast_or_null<GlobalIFunc>(GV); 5116 }; 5117 5118 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5119 // a static relocation model causes some versions of GNU LD (2.17.50, at 5120 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5121 // built with secure-PLT. 5122 bool UsePlt = 5123 Subtarget.is32BitELFABI() && !isLocalCallee() && 5124 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5125 5126 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5127 const TargetMachine &TM = Subtarget.getTargetMachine(); 5128 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5129 MCSymbolXCOFF *S = 5130 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5131 5132 if (GV->isDeclaration() && !S->hasRepresentedCsectSet()) { 5133 // On AIX, an undefined symbol needs to be associated with a 5134 // MCSectionXCOFF to get the correct storage mapping class. 5135 // In this case, XCOFF::XMC_PR. 5136 const XCOFF::StorageClass SC = 5137 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV); 5138 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5139 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5140 S->getSymbolTableName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5141 SectionKind::getMetadata()); 5142 S->setRepresentedCsect(Sec); 5143 } 5144 5145 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5146 return DAG.getMCSymbol(S, PtrVT); 5147 }; 5148 5149 if (isFunctionGlobalAddress(Callee)) { 5150 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5151 5152 if (Subtarget.isAIXABI()) { 5153 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5154 return getAIXFuncEntryPointSymbolSDNode(GV); 5155 } 5156 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5157 UsePlt ? PPCII::MO_PLT : 0); 5158 } 5159 5160 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5161 const char *SymName = S->getSymbol(); 5162 if (Subtarget.isAIXABI()) { 5163 // If there exists a user-declared function whose name is the same as the 5164 // ExternalSymbol's, then we pick up the user-declared version. 5165 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5166 if (const Function *F = 5167 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5168 return getAIXFuncEntryPointSymbolSDNode(F); 5169 5170 // On AIX, direct function calls reference the symbol for the function's 5171 // entry point, which is named by prepending a "." before the function's 5172 // C-linkage name. 5173 const auto getFunctionEntryPointSymbol = [&](StringRef SymName) { 5174 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5175 return cast<MCSymbolXCOFF>( 5176 Context.getOrCreateSymbol(Twine(".") + Twine(SymName))); 5177 }; 5178 5179 SymName = getFunctionEntryPointSymbol(SymName)->getName().data(); 5180 } 5181 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5182 UsePlt ? PPCII::MO_PLT : 0); 5183 } 5184 5185 // No transformation needed. 5186 assert(Callee.getNode() && "What no callee?"); 5187 return Callee; 5188 } 5189 5190 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5191 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5192 "Expected a CALLSEQ_STARTSDNode."); 5193 5194 // The last operand is the chain, except when the node has glue. If the node 5195 // has glue, then the last operand is the glue, and the chain is the second 5196 // last operand. 5197 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5198 if (LastValue.getValueType() != MVT::Glue) 5199 return LastValue; 5200 5201 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5202 } 5203 5204 // Creates the node that moves a functions address into the count register 5205 // to prepare for an indirect call instruction. 5206 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5207 SDValue &Glue, SDValue &Chain, 5208 const SDLoc &dl) { 5209 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5210 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5211 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5212 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5213 // The glue is the second value produced. 5214 Glue = Chain.getValue(1); 5215 } 5216 5217 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5218 SDValue &Glue, SDValue &Chain, 5219 SDValue CallSeqStart, 5220 const CallBase *CB, const SDLoc &dl, 5221 bool hasNest, 5222 const PPCSubtarget &Subtarget) { 5223 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5224 // entry point, but to the function descriptor (the function entry point 5225 // address is part of the function descriptor though). 5226 // The function descriptor is a three doubleword structure with the 5227 // following fields: function entry point, TOC base address and 5228 // environment pointer. 5229 // Thus for a call through a function pointer, the following actions need 5230 // to be performed: 5231 // 1. Save the TOC of the caller in the TOC save area of its stack 5232 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5233 // 2. Load the address of the function entry point from the function 5234 // descriptor. 5235 // 3. Load the TOC of the callee from the function descriptor into r2. 5236 // 4. Load the environment pointer from the function descriptor into 5237 // r11. 5238 // 5. Branch to the function entry point address. 5239 // 6. On return of the callee, the TOC of the caller needs to be 5240 // restored (this is done in FinishCall()). 5241 // 5242 // The loads are scheduled at the beginning of the call sequence, and the 5243 // register copies are flagged together to ensure that no other 5244 // operations can be scheduled in between. E.g. without flagging the 5245 // copies together, a TOC access in the caller could be scheduled between 5246 // the assignment of the callee TOC and the branch to the callee, which leads 5247 // to incorrect code. 5248 5249 // Start by loading the function address from the descriptor. 5250 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5251 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5252 ? (MachineMemOperand::MODereferenceable | 5253 MachineMemOperand::MOInvariant) 5254 : MachineMemOperand::MONone; 5255 5256 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5257 5258 // Registers used in building the DAG. 5259 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5260 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5261 5262 // Offsets of descriptor members. 5263 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5264 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5265 5266 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5267 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5268 5269 // One load for the functions entry point address. 5270 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5271 Alignment, MMOFlags); 5272 5273 // One for loading the TOC anchor for the module that contains the called 5274 // function. 5275 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5276 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5277 SDValue TOCPtr = 5278 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5279 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5280 5281 // One for loading the environment pointer. 5282 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5283 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5284 SDValue LoadEnvPtr = 5285 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5286 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5287 5288 5289 // Then copy the newly loaded TOC anchor to the TOC pointer. 5290 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5291 Chain = TOCVal.getValue(0); 5292 Glue = TOCVal.getValue(1); 5293 5294 // If the function call has an explicit 'nest' parameter, it takes the 5295 // place of the environment pointer. 5296 assert((!hasNest || !Subtarget.isAIXABI()) && 5297 "Nest parameter is not supported on AIX."); 5298 if (!hasNest) { 5299 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5300 Chain = EnvVal.getValue(0); 5301 Glue = EnvVal.getValue(1); 5302 } 5303 5304 // The rest of the indirect call sequence is the same as the non-descriptor 5305 // DAG. 5306 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5307 } 5308 5309 static void 5310 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5311 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5312 SelectionDAG &DAG, 5313 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5314 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5315 const PPCSubtarget &Subtarget) { 5316 const bool IsPPC64 = Subtarget.isPPC64(); 5317 // MVT for a general purpose register. 5318 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5319 5320 // First operand is always the chain. 5321 Ops.push_back(Chain); 5322 5323 // If it's a direct call pass the callee as the second operand. 5324 if (!CFlags.IsIndirect) 5325 Ops.push_back(Callee); 5326 else { 5327 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5328 5329 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5330 // on the stack (this would have been done in `LowerCall_64SVR4` or 5331 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5332 // represents both the indirect branch and a load that restores the TOC 5333 // pointer from the linkage area. The operand for the TOC restore is an add 5334 // of the TOC save offset to the stack pointer. This must be the second 5335 // operand: after the chain input but before any other variadic arguments. 5336 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5337 // saved or used. 5338 if (isTOCSaveRestoreRequired(Subtarget)) { 5339 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5340 5341 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5342 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5343 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5344 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5345 Ops.push_back(AddTOC); 5346 } 5347 5348 // Add the register used for the environment pointer. 5349 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5350 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5351 RegVT)); 5352 5353 5354 // Add CTR register as callee so a bctr can be emitted later. 5355 if (CFlags.IsTailCall) 5356 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5357 } 5358 5359 // If this is a tail call add stack pointer delta. 5360 if (CFlags.IsTailCall) 5361 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5362 5363 // Add argument registers to the end of the list so that they are known live 5364 // into the call. 5365 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5366 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5367 RegsToPass[i].second.getValueType())); 5368 5369 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5370 // no way to mark dependencies as implicit here. 5371 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5372 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5373 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5374 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5375 5376 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5377 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5378 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5379 5380 // Add a register mask operand representing the call-preserved registers. 5381 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5382 const uint32_t *Mask = 5383 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5384 assert(Mask && "Missing call preserved mask for calling convention"); 5385 Ops.push_back(DAG.getRegisterMask(Mask)); 5386 5387 // If the glue is valid, it is the last operand. 5388 if (Glue.getNode()) 5389 Ops.push_back(Glue); 5390 } 5391 5392 SDValue PPCTargetLowering::FinishCall( 5393 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5394 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5395 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5396 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5397 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5398 5399 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5400 Subtarget.isAIXABI()) 5401 setUsesTOCBasePtr(DAG); 5402 5403 unsigned CallOpc = 5404 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5405 Subtarget, DAG.getTarget()); 5406 5407 if (!CFlags.IsIndirect) 5408 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5409 else if (Subtarget.usesFunctionDescriptors()) 5410 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5411 dl, CFlags.HasNest, Subtarget); 5412 else 5413 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5414 5415 // Build the operand list for the call instruction. 5416 SmallVector<SDValue, 8> Ops; 5417 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5418 SPDiff, Subtarget); 5419 5420 // Emit tail call. 5421 if (CFlags.IsTailCall) { 5422 // Indirect tail call when using PC Relative calls do not have the same 5423 // constraints. 5424 assert(((Callee.getOpcode() == ISD::Register && 5425 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5426 Callee.getOpcode() == ISD::TargetExternalSymbol || 5427 Callee.getOpcode() == ISD::TargetGlobalAddress || 5428 isa<ConstantSDNode>(Callee) || 5429 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5430 "Expecting a global address, external symbol, absolute value, " 5431 "register or an indirect tail call when PC Relative calls are " 5432 "used."); 5433 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5434 assert(CallOpc == PPCISD::TC_RETURN && 5435 "Unexpected call opcode for a tail call."); 5436 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5437 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5438 } 5439 5440 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5441 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5442 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5443 Glue = Chain.getValue(1); 5444 5445 // When performing tail call optimization the callee pops its arguments off 5446 // the stack. Account for this here so these bytes can be pushed back on in 5447 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5448 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5449 getTargetMachine().Options.GuaranteedTailCallOpt) 5450 ? NumBytes 5451 : 0; 5452 5453 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5454 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5455 Glue, dl); 5456 Glue = Chain.getValue(1); 5457 5458 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5459 DAG, InVals); 5460 } 5461 5462 SDValue 5463 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5464 SmallVectorImpl<SDValue> &InVals) const { 5465 SelectionDAG &DAG = CLI.DAG; 5466 SDLoc &dl = CLI.DL; 5467 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5468 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5469 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5470 SDValue Chain = CLI.Chain; 5471 SDValue Callee = CLI.Callee; 5472 bool &isTailCall = CLI.IsTailCall; 5473 CallingConv::ID CallConv = CLI.CallConv; 5474 bool isVarArg = CLI.IsVarArg; 5475 bool isPatchPoint = CLI.IsPatchPoint; 5476 const CallBase *CB = CLI.CB; 5477 5478 if (isTailCall) { 5479 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5480 isTailCall = false; 5481 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5482 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5483 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5484 else 5485 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5486 Ins, DAG); 5487 if (isTailCall) { 5488 ++NumTailCalls; 5489 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5490 ++NumSiblingCalls; 5491 5492 // PC Relative calls no longer guarantee that the callee is a Global 5493 // Address Node. The callee could be an indirect tail call in which 5494 // case the SDValue for the callee could be a load (to load the address 5495 // of a function pointer) or it may be a register copy (to move the 5496 // address of the callee from a function parameter into a virtual 5497 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5498 assert((Subtarget.isUsingPCRelativeCalls() || 5499 isa<GlobalAddressSDNode>(Callee)) && 5500 "Callee should be an llvm::Function object."); 5501 5502 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5503 << "\nTCO callee: "); 5504 LLVM_DEBUG(Callee.dump()); 5505 } 5506 } 5507 5508 if (!isTailCall && CB && CB->isMustTailCall()) 5509 report_fatal_error("failed to perform tail call elimination on a call " 5510 "site marked musttail"); 5511 5512 // When long calls (i.e. indirect calls) are always used, calls are always 5513 // made via function pointer. If we have a function name, first translate it 5514 // into a pointer. 5515 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5516 !isTailCall) 5517 Callee = LowerGlobalAddress(Callee, DAG); 5518 5519 CallFlags CFlags( 5520 CallConv, isTailCall, isVarArg, isPatchPoint, 5521 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5522 // hasNest 5523 Subtarget.is64BitELFABI() && 5524 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5525 CLI.NoMerge); 5526 5527 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5528 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5529 InVals, CB); 5530 5531 if (Subtarget.isSVR4ABI()) 5532 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5533 InVals, CB); 5534 5535 if (Subtarget.isAIXABI()) 5536 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5537 InVals, CB); 5538 5539 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5540 InVals, CB); 5541 } 5542 5543 SDValue PPCTargetLowering::LowerCall_32SVR4( 5544 SDValue Chain, SDValue Callee, CallFlags CFlags, 5545 const SmallVectorImpl<ISD::OutputArg> &Outs, 5546 const SmallVectorImpl<SDValue> &OutVals, 5547 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5548 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5549 const CallBase *CB) const { 5550 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5551 // of the 32-bit SVR4 ABI stack frame layout. 5552 5553 const CallingConv::ID CallConv = CFlags.CallConv; 5554 const bool IsVarArg = CFlags.IsVarArg; 5555 const bool IsTailCall = CFlags.IsTailCall; 5556 5557 assert((CallConv == CallingConv::C || 5558 CallConv == CallingConv::Cold || 5559 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5560 5561 const Align PtrAlign(4); 5562 5563 MachineFunction &MF = DAG.getMachineFunction(); 5564 5565 // Mark this function as potentially containing a function that contains a 5566 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5567 // and restoring the callers stack pointer in this functions epilog. This is 5568 // done because by tail calling the called function might overwrite the value 5569 // in this function's (MF) stack pointer stack slot 0(SP). 5570 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5571 CallConv == CallingConv::Fast) 5572 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5573 5574 // Count how many bytes are to be pushed on the stack, including the linkage 5575 // area, parameter list area and the part of the local variable space which 5576 // contains copies of aggregates which are passed by value. 5577 5578 // Assign locations to all of the outgoing arguments. 5579 SmallVector<CCValAssign, 16> ArgLocs; 5580 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5581 5582 // Reserve space for the linkage area on the stack. 5583 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5584 PtrAlign); 5585 if (useSoftFloat()) 5586 CCInfo.PreAnalyzeCallOperands(Outs); 5587 5588 if (IsVarArg) { 5589 // Handle fixed and variable vector arguments differently. 5590 // Fixed vector arguments go into registers as long as registers are 5591 // available. Variable vector arguments always go into memory. 5592 unsigned NumArgs = Outs.size(); 5593 5594 for (unsigned i = 0; i != NumArgs; ++i) { 5595 MVT ArgVT = Outs[i].VT; 5596 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5597 bool Result; 5598 5599 if (Outs[i].IsFixed) { 5600 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5601 CCInfo); 5602 } else { 5603 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5604 ArgFlags, CCInfo); 5605 } 5606 5607 if (Result) { 5608 #ifndef NDEBUG 5609 errs() << "Call operand #" << i << " has unhandled type " 5610 << EVT(ArgVT).getEVTString() << "\n"; 5611 #endif 5612 llvm_unreachable(nullptr); 5613 } 5614 } 5615 } else { 5616 // All arguments are treated the same. 5617 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5618 } 5619 CCInfo.clearWasPPCF128(); 5620 5621 // Assign locations to all of the outgoing aggregate by value arguments. 5622 SmallVector<CCValAssign, 16> ByValArgLocs; 5623 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5624 5625 // Reserve stack space for the allocations in CCInfo. 5626 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5627 5628 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5629 5630 // Size of the linkage area, parameter list area and the part of the local 5631 // space variable where copies of aggregates which are passed by value are 5632 // stored. 5633 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5634 5635 // Calculate by how many bytes the stack has to be adjusted in case of tail 5636 // call optimization. 5637 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5638 5639 // Adjust the stack pointer for the new arguments... 5640 // These operations are automatically eliminated by the prolog/epilog pass 5641 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5642 SDValue CallSeqStart = Chain; 5643 5644 // Load the return address and frame pointer so it can be moved somewhere else 5645 // later. 5646 SDValue LROp, FPOp; 5647 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5648 5649 // Set up a copy of the stack pointer for use loading and storing any 5650 // arguments that may not fit in the registers available for argument 5651 // passing. 5652 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5653 5654 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5655 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5656 SmallVector<SDValue, 8> MemOpChains; 5657 5658 bool seenFloatArg = false; 5659 // Walk the register/memloc assignments, inserting copies/loads. 5660 // i - Tracks the index into the list of registers allocated for the call 5661 // RealArgIdx - Tracks the index into the list of actual function arguments 5662 // j - Tracks the index into the list of byval arguments 5663 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5664 i != e; 5665 ++i, ++RealArgIdx) { 5666 CCValAssign &VA = ArgLocs[i]; 5667 SDValue Arg = OutVals[RealArgIdx]; 5668 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5669 5670 if (Flags.isByVal()) { 5671 // Argument is an aggregate which is passed by value, thus we need to 5672 // create a copy of it in the local variable space of the current stack 5673 // frame (which is the stack frame of the caller) and pass the address of 5674 // this copy to the callee. 5675 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5676 CCValAssign &ByValVA = ByValArgLocs[j++]; 5677 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5678 5679 // Memory reserved in the local variable space of the callers stack frame. 5680 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5681 5682 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5683 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5684 StackPtr, PtrOff); 5685 5686 // Create a copy of the argument in the local area of the current 5687 // stack frame. 5688 SDValue MemcpyCall = 5689 CreateCopyOfByValArgument(Arg, PtrOff, 5690 CallSeqStart.getNode()->getOperand(0), 5691 Flags, DAG, dl); 5692 5693 // This must go outside the CALLSEQ_START..END. 5694 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5695 SDLoc(MemcpyCall)); 5696 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5697 NewCallSeqStart.getNode()); 5698 Chain = CallSeqStart = NewCallSeqStart; 5699 5700 // Pass the address of the aggregate copy on the stack either in a 5701 // physical register or in the parameter list area of the current stack 5702 // frame to the callee. 5703 Arg = PtrOff; 5704 } 5705 5706 // When useCRBits() is true, there can be i1 arguments. 5707 // It is because getRegisterType(MVT::i1) => MVT::i1, 5708 // and for other integer types getRegisterType() => MVT::i32. 5709 // Extend i1 and ensure callee will get i32. 5710 if (Arg.getValueType() == MVT::i1) 5711 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5712 dl, MVT::i32, Arg); 5713 5714 if (VA.isRegLoc()) { 5715 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5716 // Put argument in a physical register. 5717 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5718 bool IsLE = Subtarget.isLittleEndian(); 5719 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5720 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5721 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5722 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5723 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5724 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5725 SVal.getValue(0))); 5726 } else 5727 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5728 } else { 5729 // Put argument in the parameter list area of the current stack frame. 5730 assert(VA.isMemLoc()); 5731 unsigned LocMemOffset = VA.getLocMemOffset(); 5732 5733 if (!IsTailCall) { 5734 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5735 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5736 StackPtr, PtrOff); 5737 5738 MemOpChains.push_back( 5739 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5740 } else { 5741 // Calculate and remember argument location. 5742 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5743 TailCallArguments); 5744 } 5745 } 5746 } 5747 5748 if (!MemOpChains.empty()) 5749 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5750 5751 // Build a sequence of copy-to-reg nodes chained together with token chain 5752 // and flag operands which copy the outgoing args into the appropriate regs. 5753 SDValue InFlag; 5754 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5755 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5756 RegsToPass[i].second, InFlag); 5757 InFlag = Chain.getValue(1); 5758 } 5759 5760 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5761 // registers. 5762 if (IsVarArg) { 5763 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5764 SDValue Ops[] = { Chain, InFlag }; 5765 5766 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5767 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5768 5769 InFlag = Chain.getValue(1); 5770 } 5771 5772 if (IsTailCall) 5773 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5774 TailCallArguments); 5775 5776 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5777 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5778 } 5779 5780 // Copy an argument into memory, being careful to do this outside the 5781 // call sequence for the call to which the argument belongs. 5782 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5783 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5784 SelectionDAG &DAG, const SDLoc &dl) const { 5785 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5786 CallSeqStart.getNode()->getOperand(0), 5787 Flags, DAG, dl); 5788 // The MEMCPY must go outside the CALLSEQ_START..END. 5789 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5790 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5791 SDLoc(MemcpyCall)); 5792 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5793 NewCallSeqStart.getNode()); 5794 return NewCallSeqStart; 5795 } 5796 5797 SDValue PPCTargetLowering::LowerCall_64SVR4( 5798 SDValue Chain, SDValue Callee, CallFlags CFlags, 5799 const SmallVectorImpl<ISD::OutputArg> &Outs, 5800 const SmallVectorImpl<SDValue> &OutVals, 5801 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5802 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5803 const CallBase *CB) const { 5804 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5805 bool isLittleEndian = Subtarget.isLittleEndian(); 5806 unsigned NumOps = Outs.size(); 5807 bool IsSibCall = false; 5808 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5809 5810 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5811 unsigned PtrByteSize = 8; 5812 5813 MachineFunction &MF = DAG.getMachineFunction(); 5814 5815 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5816 IsSibCall = true; 5817 5818 // Mark this function as potentially containing a function that contains a 5819 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5820 // and restoring the callers stack pointer in this functions epilog. This is 5821 // done because by tail calling the called function might overwrite the value 5822 // in this function's (MF) stack pointer stack slot 0(SP). 5823 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5824 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5825 5826 assert(!(IsFastCall && CFlags.IsVarArg) && 5827 "fastcc not supported on varargs functions"); 5828 5829 // Count how many bytes are to be pushed on the stack, including the linkage 5830 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5831 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5832 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5833 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5834 unsigned NumBytes = LinkageSize; 5835 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5836 5837 static const MCPhysReg GPR[] = { 5838 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5839 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5840 }; 5841 static const MCPhysReg VR[] = { 5842 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5843 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5844 }; 5845 5846 const unsigned NumGPRs = array_lengthof(GPR); 5847 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5848 const unsigned NumVRs = array_lengthof(VR); 5849 5850 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5851 // can be passed to the callee in registers. 5852 // For the fast calling convention, there is another check below. 5853 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5854 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5855 if (!HasParameterArea) { 5856 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5857 unsigned AvailableFPRs = NumFPRs; 5858 unsigned AvailableVRs = NumVRs; 5859 unsigned NumBytesTmp = NumBytes; 5860 for (unsigned i = 0; i != NumOps; ++i) { 5861 if (Outs[i].Flags.isNest()) continue; 5862 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5863 PtrByteSize, LinkageSize, ParamAreaSize, 5864 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5865 HasParameterArea = true; 5866 } 5867 } 5868 5869 // When using the fast calling convention, we don't provide backing for 5870 // arguments that will be in registers. 5871 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5872 5873 // Avoid allocating parameter area for fastcc functions if all the arguments 5874 // can be passed in the registers. 5875 if (IsFastCall) 5876 HasParameterArea = false; 5877 5878 // Add up all the space actually used. 5879 for (unsigned i = 0; i != NumOps; ++i) { 5880 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5881 EVT ArgVT = Outs[i].VT; 5882 EVT OrigVT = Outs[i].ArgVT; 5883 5884 if (Flags.isNest()) 5885 continue; 5886 5887 if (IsFastCall) { 5888 if (Flags.isByVal()) { 5889 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5890 if (NumGPRsUsed > NumGPRs) 5891 HasParameterArea = true; 5892 } else { 5893 switch (ArgVT.getSimpleVT().SimpleTy) { 5894 default: llvm_unreachable("Unexpected ValueType for argument!"); 5895 case MVT::i1: 5896 case MVT::i32: 5897 case MVT::i64: 5898 if (++NumGPRsUsed <= NumGPRs) 5899 continue; 5900 break; 5901 case MVT::v4i32: 5902 case MVT::v8i16: 5903 case MVT::v16i8: 5904 case MVT::v2f64: 5905 case MVT::v2i64: 5906 case MVT::v1i128: 5907 case MVT::f128: 5908 if (++NumVRsUsed <= NumVRs) 5909 continue; 5910 break; 5911 case MVT::v4f32: 5912 if (++NumVRsUsed <= NumVRs) 5913 continue; 5914 break; 5915 case MVT::f32: 5916 case MVT::f64: 5917 if (++NumFPRsUsed <= NumFPRs) 5918 continue; 5919 break; 5920 } 5921 HasParameterArea = true; 5922 } 5923 } 5924 5925 /* Respect alignment of argument on the stack. */ 5926 auto Alignement = 5927 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5928 NumBytes = alignTo(NumBytes, Alignement); 5929 5930 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5931 if (Flags.isInConsecutiveRegsLast()) 5932 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5933 } 5934 5935 unsigned NumBytesActuallyUsed = NumBytes; 5936 5937 // In the old ELFv1 ABI, 5938 // the prolog code of the callee may store up to 8 GPR argument registers to 5939 // the stack, allowing va_start to index over them in memory if its varargs. 5940 // Because we cannot tell if this is needed on the caller side, we have to 5941 // conservatively assume that it is needed. As such, make sure we have at 5942 // least enough stack space for the caller to store the 8 GPRs. 5943 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5944 // really requires memory operands, e.g. a vararg function. 5945 if (HasParameterArea) 5946 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5947 else 5948 NumBytes = LinkageSize; 5949 5950 // Tail call needs the stack to be aligned. 5951 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5952 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5953 5954 int SPDiff = 0; 5955 5956 // Calculate by how many bytes the stack has to be adjusted in case of tail 5957 // call optimization. 5958 if (!IsSibCall) 5959 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5960 5961 // To protect arguments on the stack from being clobbered in a tail call, 5962 // force all the loads to happen before doing any other lowering. 5963 if (CFlags.IsTailCall) 5964 Chain = DAG.getStackArgumentTokenFactor(Chain); 5965 5966 // Adjust the stack pointer for the new arguments... 5967 // These operations are automatically eliminated by the prolog/epilog pass 5968 if (!IsSibCall) 5969 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5970 SDValue CallSeqStart = Chain; 5971 5972 // Load the return address and frame pointer so it can be move somewhere else 5973 // later. 5974 SDValue LROp, FPOp; 5975 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5976 5977 // Set up a copy of the stack pointer for use loading and storing any 5978 // arguments that may not fit in the registers available for argument 5979 // passing. 5980 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5981 5982 // Figure out which arguments are going to go in registers, and which in 5983 // memory. Also, if this is a vararg function, floating point operations 5984 // must be stored to our stack, and loaded into integer regs as well, if 5985 // any integer regs are available for argument passing. 5986 unsigned ArgOffset = LinkageSize; 5987 5988 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5989 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5990 5991 SmallVector<SDValue, 8> MemOpChains; 5992 for (unsigned i = 0; i != NumOps; ++i) { 5993 SDValue Arg = OutVals[i]; 5994 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5995 EVT ArgVT = Outs[i].VT; 5996 EVT OrigVT = Outs[i].ArgVT; 5997 5998 // PtrOff will be used to store the current argument to the stack if a 5999 // register cannot be found for it. 6000 SDValue PtrOff; 6001 6002 // We re-align the argument offset for each argument, except when using the 6003 // fast calling convention, when we need to make sure we do that only when 6004 // we'll actually use a stack slot. 6005 auto ComputePtrOff = [&]() { 6006 /* Respect alignment of argument on the stack. */ 6007 auto Alignment = 6008 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6009 ArgOffset = alignTo(ArgOffset, Alignment); 6010 6011 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6012 6013 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6014 }; 6015 6016 if (!IsFastCall) { 6017 ComputePtrOff(); 6018 6019 /* Compute GPR index associated with argument offset. */ 6020 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6021 GPR_idx = std::min(GPR_idx, NumGPRs); 6022 } 6023 6024 // Promote integers to 64-bit values. 6025 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6026 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6027 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6028 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6029 } 6030 6031 // FIXME memcpy is used way more than necessary. Correctness first. 6032 // Note: "by value" is code for passing a structure by value, not 6033 // basic types. 6034 if (Flags.isByVal()) { 6035 // Note: Size includes alignment padding, so 6036 // struct x { short a; char b; } 6037 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6038 // These are the proper values we need for right-justifying the 6039 // aggregate in a parameter register. 6040 unsigned Size = Flags.getByValSize(); 6041 6042 // An empty aggregate parameter takes up no storage and no 6043 // registers. 6044 if (Size == 0) 6045 continue; 6046 6047 if (IsFastCall) 6048 ComputePtrOff(); 6049 6050 // All aggregates smaller than 8 bytes must be passed right-justified. 6051 if (Size==1 || Size==2 || Size==4) { 6052 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6053 if (GPR_idx != NumGPRs) { 6054 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6055 MachinePointerInfo(), VT); 6056 MemOpChains.push_back(Load.getValue(1)); 6057 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6058 6059 ArgOffset += PtrByteSize; 6060 continue; 6061 } 6062 } 6063 6064 if (GPR_idx == NumGPRs && Size < 8) { 6065 SDValue AddPtr = PtrOff; 6066 if (!isLittleEndian) { 6067 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6068 PtrOff.getValueType()); 6069 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6070 } 6071 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6072 CallSeqStart, 6073 Flags, DAG, dl); 6074 ArgOffset += PtrByteSize; 6075 continue; 6076 } 6077 // Copy entire object into memory. There are cases where gcc-generated 6078 // code assumes it is there, even if it could be put entirely into 6079 // registers. (This is not what the doc says.) 6080 6081 // FIXME: The above statement is likely due to a misunderstanding of the 6082 // documents. All arguments must be copied into the parameter area BY 6083 // THE CALLEE in the event that the callee takes the address of any 6084 // formal argument. That has not yet been implemented. However, it is 6085 // reasonable to use the stack area as a staging area for the register 6086 // load. 6087 6088 // Skip this for small aggregates, as we will use the same slot for a 6089 // right-justified copy, below. 6090 if (Size >= 8) 6091 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6092 CallSeqStart, 6093 Flags, DAG, dl); 6094 6095 // When a register is available, pass a small aggregate right-justified. 6096 if (Size < 8 && GPR_idx != NumGPRs) { 6097 // The easiest way to get this right-justified in a register 6098 // is to copy the structure into the rightmost portion of a 6099 // local variable slot, then load the whole slot into the 6100 // register. 6101 // FIXME: The memcpy seems to produce pretty awful code for 6102 // small aggregates, particularly for packed ones. 6103 // FIXME: It would be preferable to use the slot in the 6104 // parameter save area instead of a new local variable. 6105 SDValue AddPtr = PtrOff; 6106 if (!isLittleEndian) { 6107 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6108 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6109 } 6110 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6111 CallSeqStart, 6112 Flags, DAG, dl); 6113 6114 // Load the slot into the register. 6115 SDValue Load = 6116 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6117 MemOpChains.push_back(Load.getValue(1)); 6118 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6119 6120 // Done with this argument. 6121 ArgOffset += PtrByteSize; 6122 continue; 6123 } 6124 6125 // For aggregates larger than PtrByteSize, copy the pieces of the 6126 // object that fit into registers from the parameter save area. 6127 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6128 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6129 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6130 if (GPR_idx != NumGPRs) { 6131 SDValue Load = 6132 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6133 MemOpChains.push_back(Load.getValue(1)); 6134 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6135 ArgOffset += PtrByteSize; 6136 } else { 6137 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6138 break; 6139 } 6140 } 6141 continue; 6142 } 6143 6144 switch (Arg.getSimpleValueType().SimpleTy) { 6145 default: llvm_unreachable("Unexpected ValueType for argument!"); 6146 case MVT::i1: 6147 case MVT::i32: 6148 case MVT::i64: 6149 if (Flags.isNest()) { 6150 // The 'nest' parameter, if any, is passed in R11. 6151 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6152 break; 6153 } 6154 6155 // These can be scalar arguments or elements of an integer array type 6156 // passed directly. Clang may use those instead of "byval" aggregate 6157 // types to avoid forcing arguments to memory unnecessarily. 6158 if (GPR_idx != NumGPRs) { 6159 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6160 } else { 6161 if (IsFastCall) 6162 ComputePtrOff(); 6163 6164 assert(HasParameterArea && 6165 "Parameter area must exist to pass an argument in memory."); 6166 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6167 true, CFlags.IsTailCall, false, MemOpChains, 6168 TailCallArguments, dl); 6169 if (IsFastCall) 6170 ArgOffset += PtrByteSize; 6171 } 6172 if (!IsFastCall) 6173 ArgOffset += PtrByteSize; 6174 break; 6175 case MVT::f32: 6176 case MVT::f64: { 6177 // These can be scalar arguments or elements of a float array type 6178 // passed directly. The latter are used to implement ELFv2 homogenous 6179 // float aggregates. 6180 6181 // Named arguments go into FPRs first, and once they overflow, the 6182 // remaining arguments go into GPRs and then the parameter save area. 6183 // Unnamed arguments for vararg functions always go to GPRs and 6184 // then the parameter save area. For now, put all arguments to vararg 6185 // routines always in both locations (FPR *and* GPR or stack slot). 6186 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6187 bool NeededLoad = false; 6188 6189 // First load the argument into the next available FPR. 6190 if (FPR_idx != NumFPRs) 6191 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6192 6193 // Next, load the argument into GPR or stack slot if needed. 6194 if (!NeedGPROrStack) 6195 ; 6196 else if (GPR_idx != NumGPRs && !IsFastCall) { 6197 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6198 // once we support fp <-> gpr moves. 6199 6200 // In the non-vararg case, this can only ever happen in the 6201 // presence of f32 array types, since otherwise we never run 6202 // out of FPRs before running out of GPRs. 6203 SDValue ArgVal; 6204 6205 // Double values are always passed in a single GPR. 6206 if (Arg.getValueType() != MVT::f32) { 6207 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6208 6209 // Non-array float values are extended and passed in a GPR. 6210 } else if (!Flags.isInConsecutiveRegs()) { 6211 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6212 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6213 6214 // If we have an array of floats, we collect every odd element 6215 // together with its predecessor into one GPR. 6216 } else if (ArgOffset % PtrByteSize != 0) { 6217 SDValue Lo, Hi; 6218 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6219 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6220 if (!isLittleEndian) 6221 std::swap(Lo, Hi); 6222 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6223 6224 // The final element, if even, goes into the first half of a GPR. 6225 } else if (Flags.isInConsecutiveRegsLast()) { 6226 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6227 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6228 if (!isLittleEndian) 6229 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6230 DAG.getConstant(32, dl, MVT::i32)); 6231 6232 // Non-final even elements are skipped; they will be handled 6233 // together the with subsequent argument on the next go-around. 6234 } else 6235 ArgVal = SDValue(); 6236 6237 if (ArgVal.getNode()) 6238 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6239 } else { 6240 if (IsFastCall) 6241 ComputePtrOff(); 6242 6243 // Single-precision floating-point values are mapped to the 6244 // second (rightmost) word of the stack doubleword. 6245 if (Arg.getValueType() == MVT::f32 && 6246 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6247 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6248 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6249 } 6250 6251 assert(HasParameterArea && 6252 "Parameter area must exist to pass an argument in memory."); 6253 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6254 true, CFlags.IsTailCall, false, MemOpChains, 6255 TailCallArguments, dl); 6256 6257 NeededLoad = true; 6258 } 6259 // When passing an array of floats, the array occupies consecutive 6260 // space in the argument area; only round up to the next doubleword 6261 // at the end of the array. Otherwise, each float takes 8 bytes. 6262 if (!IsFastCall || NeededLoad) { 6263 ArgOffset += (Arg.getValueType() == MVT::f32 && 6264 Flags.isInConsecutiveRegs()) ? 4 : 8; 6265 if (Flags.isInConsecutiveRegsLast()) 6266 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6267 } 6268 break; 6269 } 6270 case MVT::v4f32: 6271 case MVT::v4i32: 6272 case MVT::v8i16: 6273 case MVT::v16i8: 6274 case MVT::v2f64: 6275 case MVT::v2i64: 6276 case MVT::v1i128: 6277 case MVT::f128: 6278 // These can be scalar arguments or elements of a vector array type 6279 // passed directly. The latter are used to implement ELFv2 homogenous 6280 // vector aggregates. 6281 6282 // For a varargs call, named arguments go into VRs or on the stack as 6283 // usual; unnamed arguments always go to the stack or the corresponding 6284 // GPRs when within range. For now, we always put the value in both 6285 // locations (or even all three). 6286 if (CFlags.IsVarArg) { 6287 assert(HasParameterArea && 6288 "Parameter area must exist if we have a varargs call."); 6289 // We could elide this store in the case where the object fits 6290 // entirely in R registers. Maybe later. 6291 SDValue Store = 6292 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6293 MemOpChains.push_back(Store); 6294 if (VR_idx != NumVRs) { 6295 SDValue Load = 6296 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6297 MemOpChains.push_back(Load.getValue(1)); 6298 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6299 } 6300 ArgOffset += 16; 6301 for (unsigned i=0; i<16; i+=PtrByteSize) { 6302 if (GPR_idx == NumGPRs) 6303 break; 6304 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6305 DAG.getConstant(i, dl, PtrVT)); 6306 SDValue Load = 6307 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6308 MemOpChains.push_back(Load.getValue(1)); 6309 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6310 } 6311 break; 6312 } 6313 6314 // Non-varargs Altivec params go into VRs or on the stack. 6315 if (VR_idx != NumVRs) { 6316 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6317 } else { 6318 if (IsFastCall) 6319 ComputePtrOff(); 6320 6321 assert(HasParameterArea && 6322 "Parameter area must exist to pass an argument in memory."); 6323 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6324 true, CFlags.IsTailCall, true, MemOpChains, 6325 TailCallArguments, dl); 6326 if (IsFastCall) 6327 ArgOffset += 16; 6328 } 6329 6330 if (!IsFastCall) 6331 ArgOffset += 16; 6332 break; 6333 } 6334 } 6335 6336 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6337 "mismatch in size of parameter area"); 6338 (void)NumBytesActuallyUsed; 6339 6340 if (!MemOpChains.empty()) 6341 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6342 6343 // Check if this is an indirect call (MTCTR/BCTRL). 6344 // See prepareDescriptorIndirectCall and buildCallOperands for more 6345 // information about calls through function pointers in the 64-bit SVR4 ABI. 6346 if (CFlags.IsIndirect) { 6347 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6348 // caller in the TOC save area. 6349 if (isTOCSaveRestoreRequired(Subtarget)) { 6350 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6351 // Load r2 into a virtual register and store it to the TOC save area. 6352 setUsesTOCBasePtr(DAG); 6353 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6354 // TOC save area offset. 6355 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6356 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6357 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6358 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6359 MachinePointerInfo::getStack( 6360 DAG.getMachineFunction(), TOCSaveOffset)); 6361 } 6362 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6363 // This does not mean the MTCTR instruction must use R12; it's easier 6364 // to model this as an extra parameter, so do that. 6365 if (isELFv2ABI && !CFlags.IsPatchPoint) 6366 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6367 } 6368 6369 // Build a sequence of copy-to-reg nodes chained together with token chain 6370 // and flag operands which copy the outgoing args into the appropriate regs. 6371 SDValue InFlag; 6372 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6373 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6374 RegsToPass[i].second, InFlag); 6375 InFlag = Chain.getValue(1); 6376 } 6377 6378 if (CFlags.IsTailCall && !IsSibCall) 6379 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6380 TailCallArguments); 6381 6382 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6383 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6384 } 6385 6386 SDValue PPCTargetLowering::LowerCall_Darwin( 6387 SDValue Chain, SDValue Callee, CallFlags CFlags, 6388 const SmallVectorImpl<ISD::OutputArg> &Outs, 6389 const SmallVectorImpl<SDValue> &OutVals, 6390 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6391 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6392 const CallBase *CB) const { 6393 unsigned NumOps = Outs.size(); 6394 6395 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6396 bool isPPC64 = PtrVT == MVT::i64; 6397 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6398 6399 MachineFunction &MF = DAG.getMachineFunction(); 6400 6401 // Mark this function as potentially containing a function that contains a 6402 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6403 // and restoring the callers stack pointer in this functions epilog. This is 6404 // done because by tail calling the called function might overwrite the value 6405 // in this function's (MF) stack pointer stack slot 0(SP). 6406 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6407 CFlags.CallConv == CallingConv::Fast) 6408 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6409 6410 // Count how many bytes are to be pushed on the stack, including the linkage 6411 // area, and parameter passing area. We start with 24/48 bytes, which is 6412 // prereserved space for [SP][CR][LR][3 x unused]. 6413 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6414 unsigned NumBytes = LinkageSize; 6415 6416 // Add up all the space actually used. 6417 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6418 // they all go in registers, but we must reserve stack space for them for 6419 // possible use by the caller. In varargs or 64-bit calls, parameters are 6420 // assigned stack space in order, with padding so Altivec parameters are 6421 // 16-byte aligned. 6422 unsigned nAltivecParamsAtEnd = 0; 6423 for (unsigned i = 0; i != NumOps; ++i) { 6424 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6425 EVT ArgVT = Outs[i].VT; 6426 // Varargs Altivec parameters are padded to a 16 byte boundary. 6427 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6428 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6429 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6430 if (!CFlags.IsVarArg && !isPPC64) { 6431 // Non-varargs Altivec parameters go after all the non-Altivec 6432 // parameters; handle those later so we know how much padding we need. 6433 nAltivecParamsAtEnd++; 6434 continue; 6435 } 6436 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6437 NumBytes = ((NumBytes+15)/16)*16; 6438 } 6439 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6440 } 6441 6442 // Allow for Altivec parameters at the end, if needed. 6443 if (nAltivecParamsAtEnd) { 6444 NumBytes = ((NumBytes+15)/16)*16; 6445 NumBytes += 16*nAltivecParamsAtEnd; 6446 } 6447 6448 // The prolog code of the callee may store up to 8 GPR argument registers to 6449 // the stack, allowing va_start to index over them in memory if its varargs. 6450 // Because we cannot tell if this is needed on the caller side, we have to 6451 // conservatively assume that it is needed. As such, make sure we have at 6452 // least enough stack space for the caller to store the 8 GPRs. 6453 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6454 6455 // Tail call needs the stack to be aligned. 6456 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6457 CFlags.CallConv == CallingConv::Fast) 6458 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6459 6460 // Calculate by how many bytes the stack has to be adjusted in case of tail 6461 // call optimization. 6462 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6463 6464 // To protect arguments on the stack from being clobbered in a tail call, 6465 // force all the loads to happen before doing any other lowering. 6466 if (CFlags.IsTailCall) 6467 Chain = DAG.getStackArgumentTokenFactor(Chain); 6468 6469 // Adjust the stack pointer for the new arguments... 6470 // These operations are automatically eliminated by the prolog/epilog pass 6471 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6472 SDValue CallSeqStart = Chain; 6473 6474 // Load the return address and frame pointer so it can be move somewhere else 6475 // later. 6476 SDValue LROp, FPOp; 6477 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6478 6479 // Set up a copy of the stack pointer for use loading and storing any 6480 // arguments that may not fit in the registers available for argument 6481 // passing. 6482 SDValue StackPtr; 6483 if (isPPC64) 6484 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6485 else 6486 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6487 6488 // Figure out which arguments are going to go in registers, and which in 6489 // memory. Also, if this is a vararg function, floating point operations 6490 // must be stored to our stack, and loaded into integer regs as well, if 6491 // any integer regs are available for argument passing. 6492 unsigned ArgOffset = LinkageSize; 6493 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6494 6495 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6496 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6497 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6498 }; 6499 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6500 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6501 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6502 }; 6503 static const MCPhysReg VR[] = { 6504 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6505 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6506 }; 6507 const unsigned NumGPRs = array_lengthof(GPR_32); 6508 const unsigned NumFPRs = 13; 6509 const unsigned NumVRs = array_lengthof(VR); 6510 6511 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6512 6513 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6514 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6515 6516 SmallVector<SDValue, 8> MemOpChains; 6517 for (unsigned i = 0; i != NumOps; ++i) { 6518 SDValue Arg = OutVals[i]; 6519 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6520 6521 // PtrOff will be used to store the current argument to the stack if a 6522 // register cannot be found for it. 6523 SDValue PtrOff; 6524 6525 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6526 6527 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6528 6529 // On PPC64, promote integers to 64-bit values. 6530 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6531 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6532 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6533 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6534 } 6535 6536 // FIXME memcpy is used way more than necessary. Correctness first. 6537 // Note: "by value" is code for passing a structure by value, not 6538 // basic types. 6539 if (Flags.isByVal()) { 6540 unsigned Size = Flags.getByValSize(); 6541 // Very small objects are passed right-justified. Everything else is 6542 // passed left-justified. 6543 if (Size==1 || Size==2) { 6544 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6545 if (GPR_idx != NumGPRs) { 6546 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6547 MachinePointerInfo(), VT); 6548 MemOpChains.push_back(Load.getValue(1)); 6549 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6550 6551 ArgOffset += PtrByteSize; 6552 } else { 6553 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6554 PtrOff.getValueType()); 6555 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6556 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6557 CallSeqStart, 6558 Flags, DAG, dl); 6559 ArgOffset += PtrByteSize; 6560 } 6561 continue; 6562 } 6563 // Copy entire object into memory. There are cases where gcc-generated 6564 // code assumes it is there, even if it could be put entirely into 6565 // registers. (This is not what the doc says.) 6566 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6567 CallSeqStart, 6568 Flags, DAG, dl); 6569 6570 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6571 // copy the pieces of the object that fit into registers from the 6572 // parameter save area. 6573 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6574 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6575 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6576 if (GPR_idx != NumGPRs) { 6577 SDValue Load = 6578 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6579 MemOpChains.push_back(Load.getValue(1)); 6580 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6581 ArgOffset += PtrByteSize; 6582 } else { 6583 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6584 break; 6585 } 6586 } 6587 continue; 6588 } 6589 6590 switch (Arg.getSimpleValueType().SimpleTy) { 6591 default: llvm_unreachable("Unexpected ValueType for argument!"); 6592 case MVT::i1: 6593 case MVT::i32: 6594 case MVT::i64: 6595 if (GPR_idx != NumGPRs) { 6596 if (Arg.getValueType() == MVT::i1) 6597 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6598 6599 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6600 } else { 6601 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6602 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6603 TailCallArguments, dl); 6604 } 6605 ArgOffset += PtrByteSize; 6606 break; 6607 case MVT::f32: 6608 case MVT::f64: 6609 if (FPR_idx != NumFPRs) { 6610 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6611 6612 if (CFlags.IsVarArg) { 6613 SDValue Store = 6614 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6615 MemOpChains.push_back(Store); 6616 6617 // Float varargs are always shadowed in available integer registers 6618 if (GPR_idx != NumGPRs) { 6619 SDValue Load = 6620 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6621 MemOpChains.push_back(Load.getValue(1)); 6622 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6623 } 6624 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6625 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6626 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6627 SDValue Load = 6628 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6629 MemOpChains.push_back(Load.getValue(1)); 6630 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6631 } 6632 } else { 6633 // If we have any FPRs remaining, we may also have GPRs remaining. 6634 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6635 // GPRs. 6636 if (GPR_idx != NumGPRs) 6637 ++GPR_idx; 6638 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6639 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6640 ++GPR_idx; 6641 } 6642 } else 6643 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6644 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6645 TailCallArguments, dl); 6646 if (isPPC64) 6647 ArgOffset += 8; 6648 else 6649 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6650 break; 6651 case MVT::v4f32: 6652 case MVT::v4i32: 6653 case MVT::v8i16: 6654 case MVT::v16i8: 6655 if (CFlags.IsVarArg) { 6656 // These go aligned on the stack, or in the corresponding R registers 6657 // when within range. The Darwin PPC ABI doc claims they also go in 6658 // V registers; in fact gcc does this only for arguments that are 6659 // prototyped, not for those that match the ... We do it for all 6660 // arguments, seems to work. 6661 while (ArgOffset % 16 !=0) { 6662 ArgOffset += PtrByteSize; 6663 if (GPR_idx != NumGPRs) 6664 GPR_idx++; 6665 } 6666 // We could elide this store in the case where the object fits 6667 // entirely in R registers. Maybe later. 6668 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6669 DAG.getConstant(ArgOffset, dl, PtrVT)); 6670 SDValue Store = 6671 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6672 MemOpChains.push_back(Store); 6673 if (VR_idx != NumVRs) { 6674 SDValue Load = 6675 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6676 MemOpChains.push_back(Load.getValue(1)); 6677 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6678 } 6679 ArgOffset += 16; 6680 for (unsigned i=0; i<16; i+=PtrByteSize) { 6681 if (GPR_idx == NumGPRs) 6682 break; 6683 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6684 DAG.getConstant(i, dl, PtrVT)); 6685 SDValue Load = 6686 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6687 MemOpChains.push_back(Load.getValue(1)); 6688 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6689 } 6690 break; 6691 } 6692 6693 // Non-varargs Altivec params generally go in registers, but have 6694 // stack space allocated at the end. 6695 if (VR_idx != NumVRs) { 6696 // Doesn't have GPR space allocated. 6697 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6698 } else if (nAltivecParamsAtEnd==0) { 6699 // We are emitting Altivec params in order. 6700 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6701 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6702 TailCallArguments, dl); 6703 ArgOffset += 16; 6704 } 6705 break; 6706 } 6707 } 6708 // If all Altivec parameters fit in registers, as they usually do, 6709 // they get stack space following the non-Altivec parameters. We 6710 // don't track this here because nobody below needs it. 6711 // If there are more Altivec parameters than fit in registers emit 6712 // the stores here. 6713 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6714 unsigned j = 0; 6715 // Offset is aligned; skip 1st 12 params which go in V registers. 6716 ArgOffset = ((ArgOffset+15)/16)*16; 6717 ArgOffset += 12*16; 6718 for (unsigned i = 0; i != NumOps; ++i) { 6719 SDValue Arg = OutVals[i]; 6720 EVT ArgType = Outs[i].VT; 6721 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6722 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6723 if (++j > NumVRs) { 6724 SDValue PtrOff; 6725 // We are emitting Altivec params in order. 6726 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6727 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6728 TailCallArguments, dl); 6729 ArgOffset += 16; 6730 } 6731 } 6732 } 6733 } 6734 6735 if (!MemOpChains.empty()) 6736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6737 6738 // On Darwin, R12 must contain the address of an indirect callee. This does 6739 // not mean the MTCTR instruction must use R12; it's easier to model this as 6740 // an extra parameter, so do that. 6741 if (CFlags.IsIndirect) { 6742 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6743 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6744 PPC::R12), Callee)); 6745 } 6746 6747 // Build a sequence of copy-to-reg nodes chained together with token chain 6748 // and flag operands which copy the outgoing args into the appropriate regs. 6749 SDValue InFlag; 6750 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6751 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6752 RegsToPass[i].second, InFlag); 6753 InFlag = Chain.getValue(1); 6754 } 6755 6756 if (CFlags.IsTailCall) 6757 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6758 TailCallArguments); 6759 6760 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6761 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6762 } 6763 6764 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6765 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6766 CCState &State) { 6767 6768 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6769 State.getMachineFunction().getSubtarget()); 6770 const bool IsPPC64 = Subtarget.isPPC64(); 6771 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6772 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6773 6774 assert((!ValVT.isInteger() || 6775 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6776 "Integer argument exceeds register size: should have been legalized"); 6777 6778 if (ValVT == MVT::f128) 6779 report_fatal_error("f128 is unimplemented on AIX."); 6780 6781 if (ArgFlags.isNest()) 6782 report_fatal_error("Nest arguments are unimplemented."); 6783 6784 if (ValVT.isVector() || LocVT.isVector()) 6785 report_fatal_error("Vector arguments are unimplemented on AIX."); 6786 6787 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6788 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6789 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6790 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6791 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6792 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6793 6794 if (ArgFlags.isByVal()) { 6795 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6796 report_fatal_error("Pass-by-value arguments with alignment greater than " 6797 "register width are not supported."); 6798 6799 const unsigned ByValSize = ArgFlags.getByValSize(); 6800 6801 // An empty aggregate parameter takes up no storage and no registers, 6802 // but needs a MemLoc for a stack slot for the formal arguments side. 6803 if (ByValSize == 0) { 6804 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6805 State.getNextStackOffset(), RegVT, 6806 LocInfo)); 6807 return false; 6808 } 6809 6810 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6811 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6812 for (const unsigned E = Offset + StackSize; Offset < E; 6813 Offset += PtrAlign.value()) { 6814 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6815 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6816 else { 6817 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6818 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6819 LocInfo)); 6820 break; 6821 } 6822 } 6823 return false; 6824 } 6825 6826 // Arguments always reserve parameter save area. 6827 switch (ValVT.SimpleTy) { 6828 default: 6829 report_fatal_error("Unhandled value type for argument."); 6830 case MVT::i64: 6831 // i64 arguments should have been split to i32 for PPC32. 6832 assert(IsPPC64 && "PPC32 should have split i64 values."); 6833 LLVM_FALLTHROUGH; 6834 case MVT::i1: 6835 case MVT::i32: { 6836 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6837 // AIX integer arguments are always passed in register width. 6838 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6839 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6840 : CCValAssign::LocInfo::ZExt; 6841 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6842 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6843 else 6844 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6845 6846 return false; 6847 } 6848 case MVT::f32: 6849 case MVT::f64: { 6850 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6851 const unsigned StoreSize = LocVT.getStoreSize(); 6852 // Floats are always 4-byte aligned in the PSA on AIX. 6853 // This includes f64 in 64-bit mode for ABI compatibility. 6854 const unsigned Offset = 6855 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6856 unsigned FReg = State.AllocateReg(FPR); 6857 if (FReg) 6858 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6859 6860 // Reserve and initialize GPRs or initialize the PSA as required. 6861 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6862 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6863 assert(FReg && "An FPR should be available when a GPR is reserved."); 6864 if (State.isVarArg()) { 6865 // Successfully reserved GPRs are only initialized for vararg calls. 6866 // Custom handling is required for: 6867 // f64 in PPC32 needs to be split into 2 GPRs. 6868 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6869 State.addLoc( 6870 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6871 } 6872 } else { 6873 // If there are insufficient GPRs, the PSA needs to be initialized. 6874 // Initialization occurs even if an FPR was initialized for 6875 // compatibility with the AIX XL compiler. The full memory for the 6876 // argument will be initialized even if a prior word is saved in GPR. 6877 // A custom memLoc is used when the argument also passes in FPR so 6878 // that the callee handling can skip over it easily. 6879 State.addLoc( 6880 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6881 LocInfo) 6882 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6883 break; 6884 } 6885 } 6886 6887 return false; 6888 } 6889 } 6890 return true; 6891 } 6892 6893 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6894 bool IsPPC64) { 6895 assert((IsPPC64 || SVT != MVT::i64) && 6896 "i64 should have been split for 32-bit codegen."); 6897 6898 switch (SVT) { 6899 default: 6900 report_fatal_error("Unexpected value type for formal argument"); 6901 case MVT::i1: 6902 case MVT::i32: 6903 case MVT::i64: 6904 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6905 case MVT::f32: 6906 return &PPC::F4RCRegClass; 6907 case MVT::f64: 6908 return &PPC::F8RCRegClass; 6909 } 6910 } 6911 6912 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6913 SelectionDAG &DAG, SDValue ArgValue, 6914 MVT LocVT, const SDLoc &dl) { 6915 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6916 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6917 6918 if (Flags.isSExt()) 6919 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6920 DAG.getValueType(ValVT)); 6921 else if (Flags.isZExt()) 6922 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6923 DAG.getValueType(ValVT)); 6924 6925 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6926 } 6927 6928 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6929 const unsigned LASize = FL->getLinkageSize(); 6930 6931 if (PPC::GPRCRegClass.contains(Reg)) { 6932 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6933 "Reg must be a valid argument register!"); 6934 return LASize + 4 * (Reg - PPC::R3); 6935 } 6936 6937 if (PPC::G8RCRegClass.contains(Reg)) { 6938 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6939 "Reg must be a valid argument register!"); 6940 return LASize + 8 * (Reg - PPC::X3); 6941 } 6942 6943 llvm_unreachable("Only general purpose registers expected."); 6944 } 6945 6946 // AIX ABI Stack Frame Layout: 6947 // 6948 // Low Memory +--------------------------------------------+ 6949 // SP +---> | Back chain | ---+ 6950 // | +--------------------------------------------+ | 6951 // | | Saved Condition Register | | 6952 // | +--------------------------------------------+ | 6953 // | | Saved Linkage Register | | 6954 // | +--------------------------------------------+ | Linkage Area 6955 // | | Reserved for compilers | | 6956 // | +--------------------------------------------+ | 6957 // | | Reserved for binders | | 6958 // | +--------------------------------------------+ | 6959 // | | Saved TOC pointer | ---+ 6960 // | +--------------------------------------------+ 6961 // | | Parameter save area | 6962 // | +--------------------------------------------+ 6963 // | | Alloca space | 6964 // | +--------------------------------------------+ 6965 // | | Local variable space | 6966 // | +--------------------------------------------+ 6967 // | | Float/int conversion temporary | 6968 // | +--------------------------------------------+ 6969 // | | Save area for AltiVec registers | 6970 // | +--------------------------------------------+ 6971 // | | AltiVec alignment padding | 6972 // | +--------------------------------------------+ 6973 // | | Save area for VRSAVE register | 6974 // | +--------------------------------------------+ 6975 // | | Save area for General Purpose registers | 6976 // | +--------------------------------------------+ 6977 // | | Save area for Floating Point registers | 6978 // | +--------------------------------------------+ 6979 // +---- | Back chain | 6980 // High Memory +--------------------------------------------+ 6981 // 6982 // Specifications: 6983 // AIX 7.2 Assembler Language Reference 6984 // Subroutine linkage convention 6985 6986 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6987 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6988 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6989 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6990 6991 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6992 CallConv == CallingConv::Fast) && 6993 "Unexpected calling convention!"); 6994 6995 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6996 report_fatal_error("Tail call support is unimplemented on AIX."); 6997 6998 if (useSoftFloat()) 6999 report_fatal_error("Soft float support is unimplemented on AIX."); 7000 7001 const PPCSubtarget &Subtarget = 7002 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7003 7004 const bool IsPPC64 = Subtarget.isPPC64(); 7005 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7006 7007 // Assign locations to all of the incoming arguments. 7008 SmallVector<CCValAssign, 16> ArgLocs; 7009 MachineFunction &MF = DAG.getMachineFunction(); 7010 MachineFrameInfo &MFI = MF.getFrameInfo(); 7011 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7012 7013 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7014 // Reserve space for the linkage area on the stack. 7015 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7016 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7017 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7018 7019 SmallVector<SDValue, 8> MemOps; 7020 7021 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7022 CCValAssign &VA = ArgLocs[I++]; 7023 MVT LocVT = VA.getLocVT(); 7024 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7025 7026 // For compatibility with the AIX XL compiler, the float args in the 7027 // parameter save area are initialized even if the argument is available 7028 // in register. The caller is required to initialize both the register 7029 // and memory, however, the callee can choose to expect it in either. 7030 // The memloc is dismissed here because the argument is retrieved from 7031 // the register. 7032 if (VA.isMemLoc() && VA.needsCustom()) 7033 continue; 7034 7035 if (Flags.isByVal() && VA.isMemLoc()) { 7036 const unsigned Size = 7037 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7038 PtrByteSize); 7039 const int FI = MF.getFrameInfo().CreateFixedObject( 7040 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7041 /* IsAliased */ true); 7042 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7043 InVals.push_back(FIN); 7044 7045 continue; 7046 } 7047 7048 if (Flags.isByVal()) { 7049 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7050 7051 const MCPhysReg ArgReg = VA.getLocReg(); 7052 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7053 7054 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7055 report_fatal_error("Over aligned byvals not supported yet."); 7056 7057 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7058 const int FI = MF.getFrameInfo().CreateFixedObject( 7059 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7060 /* IsAliased */ true); 7061 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7062 InVals.push_back(FIN); 7063 7064 // Add live ins for all the RegLocs for the same ByVal. 7065 const TargetRegisterClass *RegClass = 7066 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7067 7068 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7069 unsigned Offset) { 7070 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7071 // Since the callers side has left justified the aggregate in the 7072 // register, we can simply store the entire register into the stack 7073 // slot. 7074 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7075 // The store to the fixedstack object is needed becuase accessing a 7076 // field of the ByVal will use a gep and load. Ideally we will optimize 7077 // to extracting the value from the register directly, and elide the 7078 // stores when the arguments address is not taken, but that will need to 7079 // be future work. 7080 SDValue Store = 7081 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7082 DAG.getObjectPtrOffset(dl, FIN, Offset), 7083 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7084 7085 MemOps.push_back(Store); 7086 }; 7087 7088 unsigned Offset = 0; 7089 HandleRegLoc(VA.getLocReg(), Offset); 7090 Offset += PtrByteSize; 7091 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7092 Offset += PtrByteSize) { 7093 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7094 "RegLocs should be for ByVal argument."); 7095 7096 const CCValAssign RL = ArgLocs[I++]; 7097 HandleRegLoc(RL.getLocReg(), Offset); 7098 } 7099 7100 if (Offset != StackSize) { 7101 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7102 "Expected MemLoc for remaining bytes."); 7103 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7104 // Consume the MemLoc.The InVal has already been emitted, so nothing 7105 // more needs to be done. 7106 ++I; 7107 } 7108 7109 continue; 7110 } 7111 7112 EVT ValVT = VA.getValVT(); 7113 if (VA.isRegLoc() && !VA.needsCustom()) { 7114 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7115 unsigned VReg = 7116 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7117 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7118 if (ValVT.isScalarInteger() && 7119 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7120 ArgValue = 7121 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7122 } 7123 InVals.push_back(ArgValue); 7124 continue; 7125 } 7126 if (VA.isMemLoc()) { 7127 const unsigned LocSize = LocVT.getStoreSize(); 7128 const unsigned ValSize = ValVT.getStoreSize(); 7129 assert((ValSize <= LocSize) && 7130 "Object size is larger than size of MemLoc"); 7131 int CurArgOffset = VA.getLocMemOffset(); 7132 // Objects are right-justified because AIX is big-endian. 7133 if (LocSize > ValSize) 7134 CurArgOffset += LocSize - ValSize; 7135 // Potential tail calls could cause overwriting of argument stack slots. 7136 const bool IsImmutable = 7137 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7138 (CallConv == CallingConv::Fast)); 7139 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7140 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7141 SDValue ArgValue = 7142 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7143 InVals.push_back(ArgValue); 7144 continue; 7145 } 7146 } 7147 7148 // On AIX a minimum of 8 words is saved to the parameter save area. 7149 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7150 // Area that is at least reserved in the caller of this function. 7151 unsigned CallerReservedArea = 7152 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7153 7154 // Set the size that is at least reserved in caller of this function. Tail 7155 // call optimized function's reserved stack space needs to be aligned so 7156 // that taking the difference between two stack areas will result in an 7157 // aligned stack. 7158 CallerReservedArea = 7159 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7160 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7161 FuncInfo->setMinReservedArea(CallerReservedArea); 7162 7163 if (isVarArg) { 7164 FuncInfo->setVarArgsFrameIndex( 7165 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7166 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7167 7168 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7169 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7170 7171 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7172 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7173 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7174 7175 // The fixed integer arguments of a variadic function are stored to the 7176 // VarArgsFrameIndex on the stack so that they may be loaded by 7177 // dereferencing the result of va_next. 7178 for (unsigned GPRIndex = 7179 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7180 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7181 7182 const unsigned VReg = 7183 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7184 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7185 7186 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7187 SDValue Store = 7188 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7189 MemOps.push_back(Store); 7190 // Increment the address for the next argument to store. 7191 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7192 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7193 } 7194 } 7195 7196 if (!MemOps.empty()) 7197 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7198 7199 return Chain; 7200 } 7201 7202 SDValue PPCTargetLowering::LowerCall_AIX( 7203 SDValue Chain, SDValue Callee, CallFlags CFlags, 7204 const SmallVectorImpl<ISD::OutputArg> &Outs, 7205 const SmallVectorImpl<SDValue> &OutVals, 7206 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7207 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7208 const CallBase *CB) const { 7209 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7210 // AIX ABI stack frame layout. 7211 7212 assert((CFlags.CallConv == CallingConv::C || 7213 CFlags.CallConv == CallingConv::Cold || 7214 CFlags.CallConv == CallingConv::Fast) && 7215 "Unexpected calling convention!"); 7216 7217 if (CFlags.IsPatchPoint) 7218 report_fatal_error("This call type is unimplemented on AIX."); 7219 7220 const PPCSubtarget& Subtarget = 7221 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7222 if (Subtarget.hasAltivec()) 7223 report_fatal_error("Altivec support is unimplemented on AIX."); 7224 7225 MachineFunction &MF = DAG.getMachineFunction(); 7226 SmallVector<CCValAssign, 16> ArgLocs; 7227 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7228 *DAG.getContext()); 7229 7230 // Reserve space for the linkage save area (LSA) on the stack. 7231 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7232 // [SP][CR][LR][2 x reserved][TOC]. 7233 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7234 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7235 const bool IsPPC64 = Subtarget.isPPC64(); 7236 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7237 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7238 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7239 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7240 7241 // The prolog code of the callee may store up to 8 GPR argument registers to 7242 // the stack, allowing va_start to index over them in memory if the callee 7243 // is variadic. 7244 // Because we cannot tell if this is needed on the caller side, we have to 7245 // conservatively assume that it is needed. As such, make sure we have at 7246 // least enough stack space for the caller to store the 8 GPRs. 7247 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7248 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7249 CCInfo.getNextStackOffset()); 7250 7251 // Adjust the stack pointer for the new arguments... 7252 // These operations are automatically eliminated by the prolog/epilog pass. 7253 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7254 SDValue CallSeqStart = Chain; 7255 7256 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7257 SmallVector<SDValue, 8> MemOpChains; 7258 7259 // Set up a copy of the stack pointer for loading and storing any 7260 // arguments that may not fit in the registers available for argument 7261 // passing. 7262 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7263 : DAG.getRegister(PPC::R1, MVT::i32); 7264 7265 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7266 const unsigned ValNo = ArgLocs[I].getValNo(); 7267 SDValue Arg = OutVals[ValNo]; 7268 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7269 7270 if (Flags.isByVal()) { 7271 const unsigned ByValSize = Flags.getByValSize(); 7272 7273 // Nothing to do for zero-sized ByVals on the caller side. 7274 if (!ByValSize) { 7275 ++I; 7276 continue; 7277 } 7278 7279 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7280 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7281 (LoadOffset != 0) 7282 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7283 : Arg, 7284 MachinePointerInfo(), VT); 7285 }; 7286 7287 unsigned LoadOffset = 0; 7288 7289 // Initialize registers, which are fully occupied by the by-val argument. 7290 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7291 SDValue Load = GetLoad(PtrVT, LoadOffset); 7292 MemOpChains.push_back(Load.getValue(1)); 7293 LoadOffset += PtrByteSize; 7294 const CCValAssign &ByValVA = ArgLocs[I++]; 7295 assert(ByValVA.getValNo() == ValNo && 7296 "Unexpected location for pass-by-value argument."); 7297 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7298 } 7299 7300 if (LoadOffset == ByValSize) 7301 continue; 7302 7303 // There must be one more loc to handle the remainder. 7304 assert(ArgLocs[I].getValNo() == ValNo && 7305 "Expected additional location for by-value argument."); 7306 7307 if (ArgLocs[I].isMemLoc()) { 7308 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7309 const CCValAssign &ByValVA = ArgLocs[I++]; 7310 ISD::ArgFlagsTy MemcpyFlags = Flags; 7311 // Only memcpy the bytes that don't pass in register. 7312 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7313 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7314 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7315 : Arg, 7316 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7317 CallSeqStart, MemcpyFlags, DAG, dl); 7318 continue; 7319 } 7320 7321 // Initialize the final register residue. 7322 // Any residue that occupies the final by-val arg register must be 7323 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7324 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7325 // 2 and 1 byte loads. 7326 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7327 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7328 "Unexpected register residue for by-value argument."); 7329 SDValue ResidueVal; 7330 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7331 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7332 const MVT VT = 7333 N == 1 ? MVT::i8 7334 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7335 SDValue Load = GetLoad(VT, LoadOffset); 7336 MemOpChains.push_back(Load.getValue(1)); 7337 LoadOffset += N; 7338 Bytes += N; 7339 7340 // By-val arguments are passed left-justfied in register. 7341 // Every load here needs to be shifted, otherwise a full register load 7342 // should have been used. 7343 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7344 "Unexpected load emitted during handling of pass-by-value " 7345 "argument."); 7346 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7347 EVT ShiftAmountTy = 7348 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7349 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7350 SDValue ShiftedLoad = 7351 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7352 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7353 ShiftedLoad) 7354 : ShiftedLoad; 7355 } 7356 7357 const CCValAssign &ByValVA = ArgLocs[I++]; 7358 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7359 continue; 7360 } 7361 7362 CCValAssign &VA = ArgLocs[I++]; 7363 const MVT LocVT = VA.getLocVT(); 7364 const MVT ValVT = VA.getValVT(); 7365 7366 switch (VA.getLocInfo()) { 7367 default: 7368 report_fatal_error("Unexpected argument extension type."); 7369 case CCValAssign::Full: 7370 break; 7371 case CCValAssign::ZExt: 7372 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7373 break; 7374 case CCValAssign::SExt: 7375 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7376 break; 7377 } 7378 7379 if (VA.isRegLoc() && !VA.needsCustom()) { 7380 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7381 continue; 7382 } 7383 7384 if (VA.isMemLoc()) { 7385 SDValue PtrOff = 7386 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7387 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7388 MemOpChains.push_back( 7389 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7390 7391 continue; 7392 } 7393 7394 // Custom handling is used for GPR initializations for vararg float 7395 // arguments. 7396 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7397 ValVT.isFloatingPoint() && LocVT.isInteger() && 7398 "Unexpected register handling for calling convention."); 7399 7400 SDValue ArgAsInt = 7401 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7402 7403 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7404 // f32 in 32-bit GPR 7405 // f64 in 64-bit GPR 7406 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7407 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7408 // f32 in 64-bit GPR. 7409 RegsToPass.push_back(std::make_pair( 7410 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7411 else { 7412 // f64 in two 32-bit GPRs 7413 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7414 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7415 "Unexpected custom register for argument!"); 7416 CCValAssign &GPR1 = VA; 7417 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7418 DAG.getConstant(32, dl, MVT::i8)); 7419 RegsToPass.push_back(std::make_pair( 7420 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7421 7422 if (I != E) { 7423 // If only 1 GPR was available, there will only be one custom GPR and 7424 // the argument will also pass in memory. 7425 CCValAssign &PeekArg = ArgLocs[I]; 7426 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7427 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7428 CCValAssign &GPR2 = ArgLocs[I++]; 7429 RegsToPass.push_back(std::make_pair( 7430 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7431 } 7432 } 7433 } 7434 } 7435 7436 if (!MemOpChains.empty()) 7437 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7438 7439 // For indirect calls, we need to save the TOC base to the stack for 7440 // restoration after the call. 7441 if (CFlags.IsIndirect) { 7442 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7443 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7444 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7445 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7446 const unsigned TOCSaveOffset = 7447 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7448 7449 setUsesTOCBasePtr(DAG); 7450 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7451 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7452 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7453 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7454 Chain = DAG.getStore( 7455 Val.getValue(1), dl, Val, AddPtr, 7456 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7457 } 7458 7459 // Build a sequence of copy-to-reg nodes chained together with token chain 7460 // and flag operands which copy the outgoing args into the appropriate regs. 7461 SDValue InFlag; 7462 for (auto Reg : RegsToPass) { 7463 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7464 InFlag = Chain.getValue(1); 7465 } 7466 7467 const int SPDiff = 0; 7468 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7469 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7470 } 7471 7472 bool 7473 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7474 MachineFunction &MF, bool isVarArg, 7475 const SmallVectorImpl<ISD::OutputArg> &Outs, 7476 LLVMContext &Context) const { 7477 SmallVector<CCValAssign, 16> RVLocs; 7478 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7479 return CCInfo.CheckReturn( 7480 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7481 ? RetCC_PPC_Cold 7482 : RetCC_PPC); 7483 } 7484 7485 SDValue 7486 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7487 bool isVarArg, 7488 const SmallVectorImpl<ISD::OutputArg> &Outs, 7489 const SmallVectorImpl<SDValue> &OutVals, 7490 const SDLoc &dl, SelectionDAG &DAG) const { 7491 SmallVector<CCValAssign, 16> RVLocs; 7492 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7493 *DAG.getContext()); 7494 CCInfo.AnalyzeReturn(Outs, 7495 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7496 ? RetCC_PPC_Cold 7497 : RetCC_PPC); 7498 7499 SDValue Flag; 7500 SmallVector<SDValue, 4> RetOps(1, Chain); 7501 7502 // Copy the result values into the output registers. 7503 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7504 CCValAssign &VA = RVLocs[i]; 7505 assert(VA.isRegLoc() && "Can only return in registers!"); 7506 7507 SDValue Arg = OutVals[RealResIdx]; 7508 7509 switch (VA.getLocInfo()) { 7510 default: llvm_unreachable("Unknown loc info!"); 7511 case CCValAssign::Full: break; 7512 case CCValAssign::AExt: 7513 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7514 break; 7515 case CCValAssign::ZExt: 7516 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7517 break; 7518 case CCValAssign::SExt: 7519 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7520 break; 7521 } 7522 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7523 bool isLittleEndian = Subtarget.isLittleEndian(); 7524 // Legalize ret f64 -> ret 2 x i32. 7525 SDValue SVal = 7526 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7527 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7528 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7529 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7530 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7531 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7532 Flag = Chain.getValue(1); 7533 VA = RVLocs[++i]; // skip ahead to next loc 7534 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7535 } else 7536 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7537 Flag = Chain.getValue(1); 7538 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7539 } 7540 7541 RetOps[0] = Chain; // Update chain. 7542 7543 // Add the flag if we have it. 7544 if (Flag.getNode()) 7545 RetOps.push_back(Flag); 7546 7547 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7548 } 7549 7550 SDValue 7551 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7552 SelectionDAG &DAG) const { 7553 SDLoc dl(Op); 7554 7555 // Get the correct type for integers. 7556 EVT IntVT = Op.getValueType(); 7557 7558 // Get the inputs. 7559 SDValue Chain = Op.getOperand(0); 7560 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7561 // Build a DYNAREAOFFSET node. 7562 SDValue Ops[2] = {Chain, FPSIdx}; 7563 SDVTList VTs = DAG.getVTList(IntVT); 7564 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7565 } 7566 7567 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7568 SelectionDAG &DAG) const { 7569 // When we pop the dynamic allocation we need to restore the SP link. 7570 SDLoc dl(Op); 7571 7572 // Get the correct type for pointers. 7573 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7574 7575 // Construct the stack pointer operand. 7576 bool isPPC64 = Subtarget.isPPC64(); 7577 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7578 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7579 7580 // Get the operands for the STACKRESTORE. 7581 SDValue Chain = Op.getOperand(0); 7582 SDValue SaveSP = Op.getOperand(1); 7583 7584 // Load the old link SP. 7585 SDValue LoadLinkSP = 7586 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7587 7588 // Restore the stack pointer. 7589 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7590 7591 // Store the old link SP. 7592 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7593 } 7594 7595 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7596 MachineFunction &MF = DAG.getMachineFunction(); 7597 bool isPPC64 = Subtarget.isPPC64(); 7598 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7599 7600 // Get current frame pointer save index. The users of this index will be 7601 // primarily DYNALLOC instructions. 7602 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7603 int RASI = FI->getReturnAddrSaveIndex(); 7604 7605 // If the frame pointer save index hasn't been defined yet. 7606 if (!RASI) { 7607 // Find out what the fix offset of the frame pointer save area. 7608 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7609 // Allocate the frame index for frame pointer save area. 7610 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7611 // Save the result. 7612 FI->setReturnAddrSaveIndex(RASI); 7613 } 7614 return DAG.getFrameIndex(RASI, PtrVT); 7615 } 7616 7617 SDValue 7618 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7619 MachineFunction &MF = DAG.getMachineFunction(); 7620 bool isPPC64 = Subtarget.isPPC64(); 7621 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7622 7623 // Get current frame pointer save index. The users of this index will be 7624 // primarily DYNALLOC instructions. 7625 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7626 int FPSI = FI->getFramePointerSaveIndex(); 7627 7628 // If the frame pointer save index hasn't been defined yet. 7629 if (!FPSI) { 7630 // Find out what the fix offset of the frame pointer save area. 7631 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7632 // Allocate the frame index for frame pointer save area. 7633 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7634 // Save the result. 7635 FI->setFramePointerSaveIndex(FPSI); 7636 } 7637 return DAG.getFrameIndex(FPSI, PtrVT); 7638 } 7639 7640 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7641 SelectionDAG &DAG) const { 7642 MachineFunction &MF = DAG.getMachineFunction(); 7643 // Get the inputs. 7644 SDValue Chain = Op.getOperand(0); 7645 SDValue Size = Op.getOperand(1); 7646 SDLoc dl(Op); 7647 7648 // Get the correct type for pointers. 7649 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7650 // Negate the size. 7651 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7652 DAG.getConstant(0, dl, PtrVT), Size); 7653 // Construct a node for the frame pointer save index. 7654 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7655 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7656 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7657 if (hasInlineStackProbe(MF)) 7658 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7659 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7660 } 7661 7662 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7663 SelectionDAG &DAG) const { 7664 MachineFunction &MF = DAG.getMachineFunction(); 7665 7666 bool isPPC64 = Subtarget.isPPC64(); 7667 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7668 7669 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7670 return DAG.getFrameIndex(FI, PtrVT); 7671 } 7672 7673 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7674 SelectionDAG &DAG) const { 7675 SDLoc DL(Op); 7676 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7677 DAG.getVTList(MVT::i32, MVT::Other), 7678 Op.getOperand(0), Op.getOperand(1)); 7679 } 7680 7681 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7682 SelectionDAG &DAG) const { 7683 SDLoc DL(Op); 7684 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7685 Op.getOperand(0), Op.getOperand(1)); 7686 } 7687 7688 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7689 7690 assert(Op.getValueType() == MVT::i1 && 7691 "Custom lowering only for i1 loads"); 7692 7693 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7694 7695 SDLoc dl(Op); 7696 LoadSDNode *LD = cast<LoadSDNode>(Op); 7697 7698 SDValue Chain = LD->getChain(); 7699 SDValue BasePtr = LD->getBasePtr(); 7700 MachineMemOperand *MMO = LD->getMemOperand(); 7701 7702 SDValue NewLD = 7703 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7704 BasePtr, MVT::i8, MMO); 7705 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7706 7707 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7708 return DAG.getMergeValues(Ops, dl); 7709 } 7710 7711 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7712 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7713 "Custom lowering only for i1 stores"); 7714 7715 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7716 7717 SDLoc dl(Op); 7718 StoreSDNode *ST = cast<StoreSDNode>(Op); 7719 7720 SDValue Chain = ST->getChain(); 7721 SDValue BasePtr = ST->getBasePtr(); 7722 SDValue Value = ST->getValue(); 7723 MachineMemOperand *MMO = ST->getMemOperand(); 7724 7725 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7726 Value); 7727 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7728 } 7729 7730 // FIXME: Remove this once the ANDI glue bug is fixed: 7731 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7732 assert(Op.getValueType() == MVT::i1 && 7733 "Custom lowering only for i1 results"); 7734 7735 SDLoc DL(Op); 7736 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7737 } 7738 7739 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7740 SelectionDAG &DAG) const { 7741 7742 // Implements a vector truncate that fits in a vector register as a shuffle. 7743 // We want to legalize vector truncates down to where the source fits in 7744 // a vector register (and target is therefore smaller than vector register 7745 // size). At that point legalization will try to custom lower the sub-legal 7746 // result and get here - where we can contain the truncate as a single target 7747 // operation. 7748 7749 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7750 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7751 // 7752 // We will implement it for big-endian ordering as this (where x denotes 7753 // undefined): 7754 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7755 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7756 // 7757 // The same operation in little-endian ordering will be: 7758 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7759 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7760 7761 assert(Op.getValueType().isVector() && "Vector type expected."); 7762 7763 SDLoc DL(Op); 7764 SDValue N1 = Op.getOperand(0); 7765 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7766 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7767 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7768 7769 EVT TrgVT = Op.getValueType(); 7770 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7771 EVT EltVT = TrgVT.getVectorElementType(); 7772 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7773 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7774 7775 // First list the elements we want to keep. 7776 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7777 SmallVector<int, 16> ShuffV; 7778 if (Subtarget.isLittleEndian()) 7779 for (unsigned i = 0; i < TrgNumElts; ++i) 7780 ShuffV.push_back(i * SizeMult); 7781 else 7782 for (unsigned i = 1; i <= TrgNumElts; ++i) 7783 ShuffV.push_back(i * SizeMult - 1); 7784 7785 // Populate the remaining elements with undefs. 7786 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7787 // ShuffV.push_back(i + WideNumElts); 7788 ShuffV.push_back(WideNumElts + 1); 7789 7790 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7791 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7792 } 7793 7794 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7795 /// possible. 7796 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7797 // Not FP? Not a fsel. 7798 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7799 !Op.getOperand(2).getValueType().isFloatingPoint()) 7800 return Op; 7801 7802 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7803 7804 EVT ResVT = Op.getValueType(); 7805 EVT CmpVT = Op.getOperand(0).getValueType(); 7806 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7807 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7808 SDLoc dl(Op); 7809 SDNodeFlags Flags = Op.getNode()->getFlags(); 7810 7811 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7812 // presence of infinities. 7813 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7814 switch (CC) { 7815 default: 7816 break; 7817 case ISD::SETOGT: 7818 case ISD::SETGT: 7819 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7820 case ISD::SETOLT: 7821 case ISD::SETLT: 7822 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7823 } 7824 } 7825 7826 // We might be able to do better than this under some circumstances, but in 7827 // general, fsel-based lowering of select is a finite-math-only optimization. 7828 // For more information, see section F.3 of the 2.06 ISA specification. 7829 // With ISA 3.0 7830 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7831 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7832 return Op; 7833 7834 // If the RHS of the comparison is a 0.0, we don't need to do the 7835 // subtraction at all. 7836 SDValue Sel1; 7837 if (isFloatingPointZero(RHS)) 7838 switch (CC) { 7839 default: break; // SETUO etc aren't handled by fsel. 7840 case ISD::SETNE: 7841 std::swap(TV, FV); 7842 LLVM_FALLTHROUGH; 7843 case ISD::SETEQ: 7844 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7845 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7846 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7847 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7848 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7849 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7850 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7851 case ISD::SETULT: 7852 case ISD::SETLT: 7853 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7854 LLVM_FALLTHROUGH; 7855 case ISD::SETOGE: 7856 case ISD::SETGE: 7857 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7858 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7859 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7860 case ISD::SETUGT: 7861 case ISD::SETGT: 7862 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7863 LLVM_FALLTHROUGH; 7864 case ISD::SETOLE: 7865 case ISD::SETLE: 7866 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7867 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7868 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7869 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7870 } 7871 7872 SDValue Cmp; 7873 switch (CC) { 7874 default: break; // SETUO etc aren't handled by fsel. 7875 case ISD::SETNE: 7876 std::swap(TV, FV); 7877 LLVM_FALLTHROUGH; 7878 case ISD::SETEQ: 7879 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7880 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7881 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7882 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7883 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7884 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7885 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7886 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7887 case ISD::SETULT: 7888 case ISD::SETLT: 7889 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7890 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7891 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7892 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7893 case ISD::SETOGE: 7894 case ISD::SETGE: 7895 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7896 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7897 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7898 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7899 case ISD::SETUGT: 7900 case ISD::SETGT: 7901 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7902 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7903 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7904 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7905 case ISD::SETOLE: 7906 case ISD::SETLE: 7907 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7908 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7909 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7910 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7911 } 7912 return Op; 7913 } 7914 7915 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7916 SelectionDAG &DAG, 7917 const SDLoc &dl) const { 7918 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7919 SDValue Src = Op.getOperand(0); 7920 if (Src.getValueType() == MVT::f32) 7921 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7922 7923 SDValue Tmp; 7924 switch (Op.getSimpleValueType().SimpleTy) { 7925 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7926 case MVT::i32: 7927 Tmp = DAG.getNode( 7928 Op.getOpcode() == ISD::FP_TO_SINT 7929 ? PPCISD::FCTIWZ 7930 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7931 dl, MVT::f64, Src); 7932 break; 7933 case MVT::i64: 7934 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7935 "i64 FP_TO_UINT is supported only with FPCVT"); 7936 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7937 PPCISD::FCTIDUZ, 7938 dl, MVT::f64, Src); 7939 break; 7940 } 7941 7942 // Convert the FP value to an int value through memory. 7943 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7944 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7945 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7946 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7947 MachinePointerInfo MPI = 7948 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7949 7950 // Emit a store to the stack slot. 7951 SDValue Chain; 7952 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 7953 if (i32Stack) { 7954 MachineFunction &MF = DAG.getMachineFunction(); 7955 Alignment = Align(4); 7956 MachineMemOperand *MMO = 7957 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 7958 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7959 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7960 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7961 } else 7962 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 7963 7964 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7965 // add in a bias on big endian. 7966 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7967 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7968 DAG.getConstant(4, dl, FIPtr.getValueType())); 7969 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7970 } 7971 7972 RLI.Chain = Chain; 7973 RLI.Ptr = FIPtr; 7974 RLI.MPI = MPI; 7975 RLI.Alignment = Alignment; 7976 } 7977 7978 /// Custom lowers floating point to integer conversions to use 7979 /// the direct move instructions available in ISA 2.07 to avoid the 7980 /// need for load/store combinations. 7981 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7982 SelectionDAG &DAG, 7983 const SDLoc &dl) const { 7984 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7985 SDValue Src = Op.getOperand(0); 7986 7987 if (Src.getValueType() == MVT::f32) 7988 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7989 7990 SDValue Tmp; 7991 switch (Op.getSimpleValueType().SimpleTy) { 7992 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7993 case MVT::i32: 7994 Tmp = DAG.getNode( 7995 Op.getOpcode() == ISD::FP_TO_SINT 7996 ? PPCISD::FCTIWZ 7997 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7998 dl, MVT::f64, Src); 7999 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8000 break; 8001 case MVT::i64: 8002 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8003 "i64 FP_TO_UINT is supported only with FPCVT"); 8004 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8005 PPCISD::FCTIDUZ, 8006 dl, MVT::f64, Src); 8007 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8008 break; 8009 } 8010 return Tmp; 8011 } 8012 8013 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8014 const SDLoc &dl) const { 8015 8016 // FP to INT conversions are legal for f128. 8017 if (Op->getOperand(0).getValueType() == MVT::f128) 8018 return Op; 8019 8020 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8021 // PPC (the libcall is not available). 8022 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8023 if (Op.getValueType() == MVT::i32) { 8024 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8025 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8026 MVT::f64, Op.getOperand(0), 8027 DAG.getIntPtrConstant(0, dl)); 8028 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8029 MVT::f64, Op.getOperand(0), 8030 DAG.getIntPtrConstant(1, dl)); 8031 8032 // Add the two halves of the long double in round-to-zero mode. 8033 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8034 8035 // Now use a smaller FP_TO_SINT. 8036 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8037 } 8038 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8039 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8040 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8041 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8042 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8043 // FIXME: generated code sucks. 8044 // TODO: Are there fast-math-flags to propagate to this FSUB? 8045 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8046 Op.getOperand(0), Tmp); 8047 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8048 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8049 DAG.getConstant(0x80000000, dl, MVT::i32)); 8050 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8051 Op.getOperand(0)); 8052 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8053 ISD::SETGE); 8054 } 8055 } 8056 8057 return SDValue(); 8058 } 8059 8060 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8061 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8062 8063 ReuseLoadInfo RLI; 8064 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8065 8066 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8067 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8068 } 8069 8070 // We're trying to insert a regular store, S, and then a load, L. If the 8071 // incoming value, O, is a load, we might just be able to have our load use the 8072 // address used by O. However, we don't know if anything else will store to 8073 // that address before we can load from it. To prevent this situation, we need 8074 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8075 // the same chain operand as O, we create a token factor from the chain results 8076 // of O and L, and we replace all uses of O's chain result with that token 8077 // factor (see spliceIntoChain below for this last part). 8078 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8079 ReuseLoadInfo &RLI, 8080 SelectionDAG &DAG, 8081 ISD::LoadExtType ET) const { 8082 SDLoc dl(Op); 8083 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8084 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8085 if (ET == ISD::NON_EXTLOAD && 8086 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8087 isOperationLegalOrCustom(Op.getOpcode(), 8088 Op.getOperand(0).getValueType())) { 8089 8090 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8091 return true; 8092 } 8093 8094 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8095 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8096 LD->isNonTemporal()) 8097 return false; 8098 if (LD->getMemoryVT() != MemVT) 8099 return false; 8100 8101 RLI.Ptr = LD->getBasePtr(); 8102 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8103 assert(LD->getAddressingMode() == ISD::PRE_INC && 8104 "Non-pre-inc AM on PPC?"); 8105 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8106 LD->getOffset()); 8107 } 8108 8109 RLI.Chain = LD->getChain(); 8110 RLI.MPI = LD->getPointerInfo(); 8111 RLI.IsDereferenceable = LD->isDereferenceable(); 8112 RLI.IsInvariant = LD->isInvariant(); 8113 RLI.Alignment = LD->getAlign(); 8114 RLI.AAInfo = LD->getAAInfo(); 8115 RLI.Ranges = LD->getRanges(); 8116 8117 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8118 return true; 8119 } 8120 8121 // Given the head of the old chain, ResChain, insert a token factor containing 8122 // it and NewResChain, and make users of ResChain now be users of that token 8123 // factor. 8124 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8125 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8126 SDValue NewResChain, 8127 SelectionDAG &DAG) const { 8128 if (!ResChain) 8129 return; 8130 8131 SDLoc dl(NewResChain); 8132 8133 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8134 NewResChain, DAG.getUNDEF(MVT::Other)); 8135 assert(TF.getNode() != NewResChain.getNode() && 8136 "A new TF really is required here"); 8137 8138 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8139 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8140 } 8141 8142 /// Analyze profitability of direct move 8143 /// prefer float load to int load plus direct move 8144 /// when there is no integer use of int load 8145 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8146 SDNode *Origin = Op.getOperand(0).getNode(); 8147 if (Origin->getOpcode() != ISD::LOAD) 8148 return true; 8149 8150 // If there is no LXSIBZX/LXSIHZX, like Power8, 8151 // prefer direct move if the memory size is 1 or 2 bytes. 8152 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8153 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8154 return true; 8155 8156 for (SDNode::use_iterator UI = Origin->use_begin(), 8157 UE = Origin->use_end(); 8158 UI != UE; ++UI) { 8159 8160 // Only look at the users of the loaded value. 8161 if (UI.getUse().get().getResNo() != 0) 8162 continue; 8163 8164 if (UI->getOpcode() != ISD::SINT_TO_FP && 8165 UI->getOpcode() != ISD::UINT_TO_FP) 8166 return true; 8167 } 8168 8169 return false; 8170 } 8171 8172 /// Custom lowers integer to floating point conversions to use 8173 /// the direct move instructions available in ISA 2.07 to avoid the 8174 /// need for load/store combinations. 8175 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8176 SelectionDAG &DAG, 8177 const SDLoc &dl) const { 8178 assert((Op.getValueType() == MVT::f32 || 8179 Op.getValueType() == MVT::f64) && 8180 "Invalid floating point type as target of conversion"); 8181 assert(Subtarget.hasFPCVT() && 8182 "Int to FP conversions with direct moves require FPCVT"); 8183 SDValue FP; 8184 SDValue Src = Op.getOperand(0); 8185 bool SinglePrec = Op.getValueType() == MVT::f32; 8186 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8187 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8188 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8189 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8190 8191 if (WordInt) { 8192 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8193 dl, MVT::f64, Src); 8194 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8195 } 8196 else { 8197 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8198 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8199 } 8200 8201 return FP; 8202 } 8203 8204 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8205 8206 EVT VecVT = Vec.getValueType(); 8207 assert(VecVT.isVector() && "Expected a vector type."); 8208 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8209 8210 EVT EltVT = VecVT.getVectorElementType(); 8211 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8212 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8213 8214 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8215 SmallVector<SDValue, 16> Ops(NumConcat); 8216 Ops[0] = Vec; 8217 SDValue UndefVec = DAG.getUNDEF(VecVT); 8218 for (unsigned i = 1; i < NumConcat; ++i) 8219 Ops[i] = UndefVec; 8220 8221 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8222 } 8223 8224 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8225 const SDLoc &dl) const { 8226 8227 unsigned Opc = Op.getOpcode(); 8228 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8229 "Unexpected conversion type"); 8230 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8231 "Supports conversions to v2f64/v4f32 only."); 8232 8233 bool SignedConv = Opc == ISD::SINT_TO_FP; 8234 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8235 8236 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8237 EVT WideVT = Wide.getValueType(); 8238 unsigned WideNumElts = WideVT.getVectorNumElements(); 8239 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8240 8241 SmallVector<int, 16> ShuffV; 8242 for (unsigned i = 0; i < WideNumElts; ++i) 8243 ShuffV.push_back(i + WideNumElts); 8244 8245 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8246 int SaveElts = FourEltRes ? 4 : 2; 8247 if (Subtarget.isLittleEndian()) 8248 for (int i = 0; i < SaveElts; i++) 8249 ShuffV[i * Stride] = i; 8250 else 8251 for (int i = 1; i <= SaveElts; i++) 8252 ShuffV[i * Stride - 1] = i - 1; 8253 8254 SDValue ShuffleSrc2 = 8255 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8256 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8257 8258 SDValue Extend; 8259 if (SignedConv) { 8260 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8261 EVT ExtVT = Op.getOperand(0).getValueType(); 8262 if (Subtarget.hasP9Altivec()) 8263 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8264 IntermediateVT.getVectorNumElements()); 8265 8266 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8267 DAG.getValueType(ExtVT)); 8268 } else 8269 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8270 8271 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8272 } 8273 8274 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8275 SelectionDAG &DAG) const { 8276 SDLoc dl(Op); 8277 8278 EVT InVT = Op.getOperand(0).getValueType(); 8279 EVT OutVT = Op.getValueType(); 8280 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8281 isOperationCustom(Op.getOpcode(), InVT)) 8282 return LowerINT_TO_FPVector(Op, DAG, dl); 8283 8284 // Conversions to f128 are legal. 8285 if (Op.getValueType() == MVT::f128) 8286 return Op; 8287 8288 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8289 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8290 return SDValue(); 8291 8292 if (Op.getOperand(0).getValueType() == MVT::i1) 8293 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8294 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8295 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8296 8297 // If we have direct moves, we can do all the conversion, skip the store/load 8298 // however, without FPCVT we can't do most conversions. 8299 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8300 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8301 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8302 8303 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8304 "UINT_TO_FP is supported only with FPCVT"); 8305 8306 // If we have FCFIDS, then use it when converting to single-precision. 8307 // Otherwise, convert to double-precision and then round. 8308 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8309 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8310 : PPCISD::FCFIDS) 8311 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8312 : PPCISD::FCFID); 8313 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8314 ? MVT::f32 8315 : MVT::f64; 8316 8317 if (Op.getOperand(0).getValueType() == MVT::i64) { 8318 SDValue SINT = Op.getOperand(0); 8319 // When converting to single-precision, we actually need to convert 8320 // to double-precision first and then round to single-precision. 8321 // To avoid double-rounding effects during that operation, we have 8322 // to prepare the input operand. Bits that might be truncated when 8323 // converting to double-precision are replaced by a bit that won't 8324 // be lost at this stage, but is below the single-precision rounding 8325 // position. 8326 // 8327 // However, if -enable-unsafe-fp-math is in effect, accept double 8328 // rounding to avoid the extra overhead. 8329 if (Op.getValueType() == MVT::f32 && 8330 !Subtarget.hasFPCVT() && 8331 !DAG.getTarget().Options.UnsafeFPMath) { 8332 8333 // Twiddle input to make sure the low 11 bits are zero. (If this 8334 // is the case, we are guaranteed the value will fit into the 53 bit 8335 // mantissa of an IEEE double-precision value without rounding.) 8336 // If any of those low 11 bits were not zero originally, make sure 8337 // bit 12 (value 2048) is set instead, so that the final rounding 8338 // to single-precision gets the correct result. 8339 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8340 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8341 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8342 Round, DAG.getConstant(2047, dl, MVT::i64)); 8343 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8344 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8345 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8346 8347 // However, we cannot use that value unconditionally: if the magnitude 8348 // of the input value is small, the bit-twiddling we did above might 8349 // end up visibly changing the output. Fortunately, in that case, we 8350 // don't need to twiddle bits since the original input will convert 8351 // exactly to double-precision floating-point already. Therefore, 8352 // construct a conditional to use the original value if the top 11 8353 // bits are all sign-bit copies, and use the rounded value computed 8354 // above otherwise. 8355 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8356 SINT, DAG.getConstant(53, dl, MVT::i32)); 8357 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8358 Cond, DAG.getConstant(1, dl, MVT::i64)); 8359 Cond = DAG.getSetCC( 8360 dl, 8361 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8362 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8363 8364 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8365 } 8366 8367 ReuseLoadInfo RLI; 8368 SDValue Bits; 8369 8370 MachineFunction &MF = DAG.getMachineFunction(); 8371 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8372 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8373 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8374 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8375 } else if (Subtarget.hasLFIWAX() && 8376 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8377 MachineMemOperand *MMO = 8378 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8379 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8380 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8381 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8382 DAG.getVTList(MVT::f64, MVT::Other), 8383 Ops, MVT::i32, MMO); 8384 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8385 } else if (Subtarget.hasFPCVT() && 8386 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8387 MachineMemOperand *MMO = 8388 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8389 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8390 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8391 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8392 DAG.getVTList(MVT::f64, MVT::Other), 8393 Ops, MVT::i32, MMO); 8394 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8395 } else if (((Subtarget.hasLFIWAX() && 8396 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8397 (Subtarget.hasFPCVT() && 8398 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8399 SINT.getOperand(0).getValueType() == MVT::i32) { 8400 MachineFrameInfo &MFI = MF.getFrameInfo(); 8401 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8402 8403 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8404 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8405 8406 SDValue Store = 8407 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8408 MachinePointerInfo::getFixedStack( 8409 DAG.getMachineFunction(), FrameIdx)); 8410 8411 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8412 "Expected an i32 store"); 8413 8414 RLI.Ptr = FIdx; 8415 RLI.Chain = Store; 8416 RLI.MPI = 8417 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8418 RLI.Alignment = Align(4); 8419 8420 MachineMemOperand *MMO = 8421 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8422 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8423 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8424 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8425 PPCISD::LFIWZX : PPCISD::LFIWAX, 8426 dl, DAG.getVTList(MVT::f64, MVT::Other), 8427 Ops, MVT::i32, MMO); 8428 } else 8429 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8430 8431 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8432 8433 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8434 FP = DAG.getNode(ISD::FP_ROUND, dl, 8435 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8436 return FP; 8437 } 8438 8439 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8440 "Unhandled INT_TO_FP type in custom expander!"); 8441 // Since we only generate this in 64-bit mode, we can take advantage of 8442 // 64-bit registers. In particular, sign extend the input value into the 8443 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8444 // then lfd it and fcfid it. 8445 MachineFunction &MF = DAG.getMachineFunction(); 8446 MachineFrameInfo &MFI = MF.getFrameInfo(); 8447 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8448 8449 SDValue Ld; 8450 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8451 ReuseLoadInfo RLI; 8452 bool ReusingLoad; 8453 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8454 DAG))) { 8455 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8456 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8457 8458 SDValue Store = 8459 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8460 MachinePointerInfo::getFixedStack( 8461 DAG.getMachineFunction(), FrameIdx)); 8462 8463 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8464 "Expected an i32 store"); 8465 8466 RLI.Ptr = FIdx; 8467 RLI.Chain = Store; 8468 RLI.MPI = 8469 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8470 RLI.Alignment = Align(4); 8471 } 8472 8473 MachineMemOperand *MMO = 8474 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8475 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8476 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8477 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8478 PPCISD::LFIWZX : PPCISD::LFIWAX, 8479 dl, DAG.getVTList(MVT::f64, MVT::Other), 8480 Ops, MVT::i32, MMO); 8481 if (ReusingLoad) 8482 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8483 } else { 8484 assert(Subtarget.isPPC64() && 8485 "i32->FP without LFIWAX supported only on PPC64"); 8486 8487 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8488 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8489 8490 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8491 Op.getOperand(0)); 8492 8493 // STD the extended value into the stack slot. 8494 SDValue Store = DAG.getStore( 8495 DAG.getEntryNode(), dl, Ext64, FIdx, 8496 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8497 8498 // Load the value as a double. 8499 Ld = DAG.getLoad( 8500 MVT::f64, dl, Store, FIdx, 8501 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8502 } 8503 8504 // FCFID it and return it. 8505 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8506 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8507 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8508 DAG.getIntPtrConstant(0, dl)); 8509 return FP; 8510 } 8511 8512 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8513 SelectionDAG &DAG) const { 8514 SDLoc dl(Op); 8515 /* 8516 The rounding mode is in bits 30:31 of FPSR, and has the following 8517 settings: 8518 00 Round to nearest 8519 01 Round to 0 8520 10 Round to +inf 8521 11 Round to -inf 8522 8523 FLT_ROUNDS, on the other hand, expects the following: 8524 -1 Undefined 8525 0 Round to 0 8526 1 Round to nearest 8527 2 Round to +inf 8528 3 Round to -inf 8529 8530 To perform the conversion, we do: 8531 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8532 */ 8533 8534 MachineFunction &MF = DAG.getMachineFunction(); 8535 EVT VT = Op.getValueType(); 8536 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8537 8538 // Save FP Control Word to register 8539 SDValue Chain = Op.getOperand(0); 8540 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8541 Chain = MFFS.getValue(1); 8542 8543 // Save FP register to stack slot 8544 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8545 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8546 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8547 8548 // Load FP Control Word from low 32 bits of stack slot. 8549 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8550 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8551 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8552 Chain = CWD.getValue(1); 8553 8554 // Transform as necessary 8555 SDValue CWD1 = 8556 DAG.getNode(ISD::AND, dl, MVT::i32, 8557 CWD, DAG.getConstant(3, dl, MVT::i32)); 8558 SDValue CWD2 = 8559 DAG.getNode(ISD::SRL, dl, MVT::i32, 8560 DAG.getNode(ISD::AND, dl, MVT::i32, 8561 DAG.getNode(ISD::XOR, dl, MVT::i32, 8562 CWD, DAG.getConstant(3, dl, MVT::i32)), 8563 DAG.getConstant(3, dl, MVT::i32)), 8564 DAG.getConstant(1, dl, MVT::i32)); 8565 8566 SDValue RetVal = 8567 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8568 8569 RetVal = 8570 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8571 dl, VT, RetVal); 8572 8573 return DAG.getMergeValues({RetVal, Chain}, dl); 8574 } 8575 8576 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8577 EVT VT = Op.getValueType(); 8578 unsigned BitWidth = VT.getSizeInBits(); 8579 SDLoc dl(Op); 8580 assert(Op.getNumOperands() == 3 && 8581 VT == Op.getOperand(1).getValueType() && 8582 "Unexpected SHL!"); 8583 8584 // Expand into a bunch of logical ops. Note that these ops 8585 // depend on the PPC behavior for oversized shift amounts. 8586 SDValue Lo = Op.getOperand(0); 8587 SDValue Hi = Op.getOperand(1); 8588 SDValue Amt = Op.getOperand(2); 8589 EVT AmtVT = Amt.getValueType(); 8590 8591 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8592 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8593 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8594 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8595 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8596 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8597 DAG.getConstant(-BitWidth, dl, AmtVT)); 8598 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8599 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8600 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8601 SDValue OutOps[] = { OutLo, OutHi }; 8602 return DAG.getMergeValues(OutOps, dl); 8603 } 8604 8605 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8606 EVT VT = Op.getValueType(); 8607 SDLoc dl(Op); 8608 unsigned BitWidth = VT.getSizeInBits(); 8609 assert(Op.getNumOperands() == 3 && 8610 VT == Op.getOperand(1).getValueType() && 8611 "Unexpected SRL!"); 8612 8613 // Expand into a bunch of logical ops. Note that these ops 8614 // depend on the PPC behavior for oversized shift amounts. 8615 SDValue Lo = Op.getOperand(0); 8616 SDValue Hi = Op.getOperand(1); 8617 SDValue Amt = Op.getOperand(2); 8618 EVT AmtVT = Amt.getValueType(); 8619 8620 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8621 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8622 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8623 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8624 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8625 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8626 DAG.getConstant(-BitWidth, dl, AmtVT)); 8627 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8628 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8629 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8630 SDValue OutOps[] = { OutLo, OutHi }; 8631 return DAG.getMergeValues(OutOps, dl); 8632 } 8633 8634 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8635 SDLoc dl(Op); 8636 EVT VT = Op.getValueType(); 8637 unsigned BitWidth = VT.getSizeInBits(); 8638 assert(Op.getNumOperands() == 3 && 8639 VT == Op.getOperand(1).getValueType() && 8640 "Unexpected SRA!"); 8641 8642 // Expand into a bunch of logical ops, followed by a select_cc. 8643 SDValue Lo = Op.getOperand(0); 8644 SDValue Hi = Op.getOperand(1); 8645 SDValue Amt = Op.getOperand(2); 8646 EVT AmtVT = Amt.getValueType(); 8647 8648 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8649 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8650 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8651 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8652 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8653 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8654 DAG.getConstant(-BitWidth, dl, AmtVT)); 8655 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8656 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8657 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8658 Tmp4, Tmp6, ISD::SETLE); 8659 SDValue OutOps[] = { OutLo, OutHi }; 8660 return DAG.getMergeValues(OutOps, dl); 8661 } 8662 8663 //===----------------------------------------------------------------------===// 8664 // Vector related lowering. 8665 // 8666 8667 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8668 /// element size of SplatSize. Cast the result to VT. 8669 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8670 SelectionDAG &DAG, const SDLoc &dl) { 8671 static const MVT VTys[] = { // canonical VT to use for each size. 8672 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8673 }; 8674 8675 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8676 8677 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8678 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8679 SplatSize = 1; 8680 Val = 0xFF; 8681 } 8682 8683 EVT CanonicalVT = VTys[SplatSize-1]; 8684 8685 // Build a canonical splat for this value. 8686 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8687 } 8688 8689 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8690 /// specified intrinsic ID. 8691 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8692 const SDLoc &dl, EVT DestVT = MVT::Other) { 8693 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8694 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8695 DAG.getConstant(IID, dl, MVT::i32), Op); 8696 } 8697 8698 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8699 /// specified intrinsic ID. 8700 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8701 SelectionDAG &DAG, const SDLoc &dl, 8702 EVT DestVT = MVT::Other) { 8703 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8704 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8705 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8706 } 8707 8708 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8709 /// specified intrinsic ID. 8710 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8711 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8712 EVT DestVT = MVT::Other) { 8713 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8714 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8715 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8716 } 8717 8718 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8719 /// amount. The result has the specified value type. 8720 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8721 SelectionDAG &DAG, const SDLoc &dl) { 8722 // Force LHS/RHS to be the right type. 8723 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8724 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8725 8726 int Ops[16]; 8727 for (unsigned i = 0; i != 16; ++i) 8728 Ops[i] = i + Amt; 8729 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8730 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8731 } 8732 8733 /// Do we have an efficient pattern in a .td file for this node? 8734 /// 8735 /// \param V - pointer to the BuildVectorSDNode being matched 8736 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8737 /// 8738 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8739 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8740 /// the opposite is true (expansion is beneficial) are: 8741 /// - The node builds a vector out of integers that are not 32 or 64-bits 8742 /// - The node builds a vector out of constants 8743 /// - The node is a "load-and-splat" 8744 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8745 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8746 bool HasDirectMove, 8747 bool HasP8Vector) { 8748 EVT VecVT = V->getValueType(0); 8749 bool RightType = VecVT == MVT::v2f64 || 8750 (HasP8Vector && VecVT == MVT::v4f32) || 8751 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8752 if (!RightType) 8753 return false; 8754 8755 bool IsSplat = true; 8756 bool IsLoad = false; 8757 SDValue Op0 = V->getOperand(0); 8758 8759 // This function is called in a block that confirms the node is not a constant 8760 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8761 // different constants. 8762 if (V->isConstant()) 8763 return false; 8764 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8765 if (V->getOperand(i).isUndef()) 8766 return false; 8767 // We want to expand nodes that represent load-and-splat even if the 8768 // loaded value is a floating point truncation or conversion to int. 8769 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8770 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8771 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8772 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8773 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8774 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8775 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8776 IsLoad = true; 8777 // If the operands are different or the input is not a load and has more 8778 // uses than just this BV node, then it isn't a splat. 8779 if (V->getOperand(i) != Op0 || 8780 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8781 IsSplat = false; 8782 } 8783 return !(IsSplat && IsLoad); 8784 } 8785 8786 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8787 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8788 8789 SDLoc dl(Op); 8790 SDValue Op0 = Op->getOperand(0); 8791 8792 if ((Op.getValueType() != MVT::f128) || 8793 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8794 (Op0.getOperand(0).getValueType() != MVT::i64) || 8795 (Op0.getOperand(1).getValueType() != MVT::i64)) 8796 return SDValue(); 8797 8798 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8799 Op0.getOperand(1)); 8800 } 8801 8802 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8803 const SDValue *InputLoad = &Op; 8804 if (InputLoad->getOpcode() == ISD::BITCAST) 8805 InputLoad = &InputLoad->getOperand(0); 8806 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8807 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8808 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8809 InputLoad = &InputLoad->getOperand(0); 8810 } 8811 if (InputLoad->getOpcode() != ISD::LOAD) 8812 return nullptr; 8813 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8814 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8815 } 8816 8817 // Convert the argument APFloat to a single precision APFloat if there is no 8818 // loss in information during the conversion to single precision APFloat and the 8819 // resulting number is not a denormal number. Return true if successful. 8820 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8821 APFloat APFloatToConvert = ArgAPFloat; 8822 bool LosesInfo = true; 8823 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8824 &LosesInfo); 8825 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8826 if (Success) 8827 ArgAPFloat = APFloatToConvert; 8828 return Success; 8829 } 8830 8831 // Bitcast the argument APInt to a double and convert it to a single precision 8832 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8833 // argument if there is no loss in information during the conversion from 8834 // double to single precision APFloat and the resulting number is not a denormal 8835 // number. Return true if successful. 8836 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8837 double DpValue = ArgAPInt.bitsToDouble(); 8838 APFloat APFloatDp(DpValue); 8839 bool Success = convertToNonDenormSingle(APFloatDp); 8840 if (Success) 8841 ArgAPInt = APFloatDp.bitcastToAPInt(); 8842 return Success; 8843 } 8844 8845 // If this is a case we can't handle, return null and let the default 8846 // expansion code take care of it. If we CAN select this case, and if it 8847 // selects to a single instruction, return Op. Otherwise, if we can codegen 8848 // this case more efficiently than a constant pool load, lower it to the 8849 // sequence of ops that should be used. 8850 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8851 SelectionDAG &DAG) const { 8852 SDLoc dl(Op); 8853 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8854 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8855 8856 // Check if this is a splat of a constant value. 8857 APInt APSplatBits, APSplatUndef; 8858 unsigned SplatBitSize; 8859 bool HasAnyUndefs; 8860 bool BVNIsConstantSplat = 8861 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8862 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 8863 8864 // If it is a splat of a double, check if we can shrink it to a 32 bit 8865 // non-denormal float which when converted back to double gives us the same 8866 // double. This is to exploit the XXSPLTIDP instruction. 8867 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 8868 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 8869 convertToNonDenormSingle(APSplatBits)) { 8870 SDValue SplatNode = DAG.getNode( 8871 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 8872 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 8873 return DAG.getBitcast(Op.getValueType(), SplatNode); 8874 } 8875 8876 if (!BVNIsConstantSplat || SplatBitSize > 32) { 8877 8878 bool IsPermutedLoad = false; 8879 const SDValue *InputLoad = 8880 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 8881 // Handle load-and-splat patterns as we have instructions that will do this 8882 // in one go. 8883 if (InputLoad && DAG.isSplatValue(Op, true)) { 8884 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8885 8886 // We have handling for 4 and 8 byte elements. 8887 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8888 8889 // Checking for a single use of this load, we have to check for vector 8890 // width (128 bits) / ElementSize uses (since each operand of the 8891 // BUILD_VECTOR is a separate use of the value. 8892 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8893 ((Subtarget.hasVSX() && ElementSize == 64) || 8894 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8895 SDValue Ops[] = { 8896 LD->getChain(), // Chain 8897 LD->getBasePtr(), // Ptr 8898 DAG.getValueType(Op.getValueType()) // VT 8899 }; 8900 return 8901 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8902 DAG.getVTList(Op.getValueType(), MVT::Other), 8903 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8904 } 8905 } 8906 8907 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8908 // lowered to VSX instructions under certain conditions. 8909 // Without VSX, there is no pattern more efficient than expanding the node. 8910 if (Subtarget.hasVSX() && 8911 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8912 Subtarget.hasP8Vector())) 8913 return Op; 8914 return SDValue(); 8915 } 8916 8917 uint64_t SplatBits = APSplatBits.getZExtValue(); 8918 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 8919 unsigned SplatSize = SplatBitSize / 8; 8920 8921 // First, handle single instruction cases. 8922 8923 // All zeros? 8924 if (SplatBits == 0) { 8925 // Canonicalize all zero vectors to be v4i32. 8926 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8927 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8928 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8929 } 8930 return Op; 8931 } 8932 8933 // We have XXSPLTIW for constant splats four bytes wide. 8934 // Given vector length is a multiple of 4, 2-byte splats can be replaced 8935 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 8936 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 8937 // turned into a 4-byte splat of 0xABABABAB. 8938 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 8939 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 8940 Op.getValueType(), DAG, dl); 8941 8942 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 8943 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8944 dl); 8945 8946 // We have XXSPLTIB for constant splats one byte wide. 8947 if (Subtarget.hasP9Vector() && SplatSize == 1) 8948 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8949 dl); 8950 8951 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8952 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8953 (32-SplatBitSize)); 8954 if (SextVal >= -16 && SextVal <= 15) 8955 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 8956 dl); 8957 8958 // Two instruction sequences. 8959 8960 // If this value is in the range [-32,30] and is even, use: 8961 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8962 // If this value is in the range [17,31] and is odd, use: 8963 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8964 // If this value is in the range [-31,-17] and is odd, use: 8965 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8966 // Note the last two are three-instruction sequences. 8967 if (SextVal >= -32 && SextVal <= 31) { 8968 // To avoid having these optimizations undone by constant folding, 8969 // we convert to a pseudo that will be expanded later into one of 8970 // the above forms. 8971 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8972 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8973 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8974 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8975 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8976 if (VT == Op.getValueType()) 8977 return RetVal; 8978 else 8979 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8980 } 8981 8982 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8983 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8984 // for fneg/fabs. 8985 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8986 // Make -1 and vspltisw -1: 8987 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 8988 8989 // Make the VSLW intrinsic, computing 0x8000_0000. 8990 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8991 OnesV, DAG, dl); 8992 8993 // xor by OnesV to invert it. 8994 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8995 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8996 } 8997 8998 // Check to see if this is a wide variety of vsplti*, binop self cases. 8999 static const signed char SplatCsts[] = { 9000 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9001 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9002 }; 9003 9004 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9005 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9006 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9007 int i = SplatCsts[idx]; 9008 9009 // Figure out what shift amount will be used by altivec if shifted by i in 9010 // this splat size. 9011 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9012 9013 // vsplti + shl self. 9014 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9015 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9016 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9017 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9018 Intrinsic::ppc_altivec_vslw 9019 }; 9020 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9021 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9022 } 9023 9024 // vsplti + srl self. 9025 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9026 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9027 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9028 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9029 Intrinsic::ppc_altivec_vsrw 9030 }; 9031 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9032 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9033 } 9034 9035 // vsplti + sra self. 9036 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9037 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9038 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9039 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9040 Intrinsic::ppc_altivec_vsraw 9041 }; 9042 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9043 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9044 } 9045 9046 // vsplti + rol self. 9047 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9048 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9049 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9050 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9051 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9052 Intrinsic::ppc_altivec_vrlw 9053 }; 9054 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9055 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9056 } 9057 9058 // t = vsplti c, result = vsldoi t, t, 1 9059 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9060 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9061 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9062 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9063 } 9064 // t = vsplti c, result = vsldoi t, t, 2 9065 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9066 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9067 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9068 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9069 } 9070 // t = vsplti c, result = vsldoi t, t, 3 9071 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9072 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9073 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9074 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9075 } 9076 } 9077 9078 return SDValue(); 9079 } 9080 9081 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9082 /// the specified operations to build the shuffle. 9083 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9084 SDValue RHS, SelectionDAG &DAG, 9085 const SDLoc &dl) { 9086 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9087 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9088 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9089 9090 enum { 9091 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9092 OP_VMRGHW, 9093 OP_VMRGLW, 9094 OP_VSPLTISW0, 9095 OP_VSPLTISW1, 9096 OP_VSPLTISW2, 9097 OP_VSPLTISW3, 9098 OP_VSLDOI4, 9099 OP_VSLDOI8, 9100 OP_VSLDOI12 9101 }; 9102 9103 if (OpNum == OP_COPY) { 9104 if (LHSID == (1*9+2)*9+3) return LHS; 9105 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9106 return RHS; 9107 } 9108 9109 SDValue OpLHS, OpRHS; 9110 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9111 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9112 9113 int ShufIdxs[16]; 9114 switch (OpNum) { 9115 default: llvm_unreachable("Unknown i32 permute!"); 9116 case OP_VMRGHW: 9117 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9118 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9119 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9120 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9121 break; 9122 case OP_VMRGLW: 9123 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9124 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9125 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9126 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9127 break; 9128 case OP_VSPLTISW0: 9129 for (unsigned i = 0; i != 16; ++i) 9130 ShufIdxs[i] = (i&3)+0; 9131 break; 9132 case OP_VSPLTISW1: 9133 for (unsigned i = 0; i != 16; ++i) 9134 ShufIdxs[i] = (i&3)+4; 9135 break; 9136 case OP_VSPLTISW2: 9137 for (unsigned i = 0; i != 16; ++i) 9138 ShufIdxs[i] = (i&3)+8; 9139 break; 9140 case OP_VSPLTISW3: 9141 for (unsigned i = 0; i != 16; ++i) 9142 ShufIdxs[i] = (i&3)+12; 9143 break; 9144 case OP_VSLDOI4: 9145 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9146 case OP_VSLDOI8: 9147 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9148 case OP_VSLDOI12: 9149 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9150 } 9151 EVT VT = OpLHS.getValueType(); 9152 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9153 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9154 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9155 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9156 } 9157 9158 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9159 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9160 /// SDValue. 9161 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9162 SelectionDAG &DAG) const { 9163 const unsigned BytesInVector = 16; 9164 bool IsLE = Subtarget.isLittleEndian(); 9165 SDLoc dl(N); 9166 SDValue V1 = N->getOperand(0); 9167 SDValue V2 = N->getOperand(1); 9168 unsigned ShiftElts = 0, InsertAtByte = 0; 9169 bool Swap = false; 9170 9171 // Shifts required to get the byte we want at element 7. 9172 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9173 0, 15, 14, 13, 12, 11, 10, 9}; 9174 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9175 1, 2, 3, 4, 5, 6, 7, 8}; 9176 9177 ArrayRef<int> Mask = N->getMask(); 9178 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9179 9180 // For each mask element, find out if we're just inserting something 9181 // from V2 into V1 or vice versa. 9182 // Possible permutations inserting an element from V2 into V1: 9183 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9184 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9185 // ... 9186 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9187 // Inserting from V1 into V2 will be similar, except mask range will be 9188 // [16,31]. 9189 9190 bool FoundCandidate = false; 9191 // If both vector operands for the shuffle are the same vector, the mask 9192 // will contain only elements from the first one and the second one will be 9193 // undef. 9194 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9195 // Go through the mask of half-words to find an element that's being moved 9196 // from one vector to the other. 9197 for (unsigned i = 0; i < BytesInVector; ++i) { 9198 unsigned CurrentElement = Mask[i]; 9199 // If 2nd operand is undefined, we should only look for element 7 in the 9200 // Mask. 9201 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9202 continue; 9203 9204 bool OtherElementsInOrder = true; 9205 // Examine the other elements in the Mask to see if they're in original 9206 // order. 9207 for (unsigned j = 0; j < BytesInVector; ++j) { 9208 if (j == i) 9209 continue; 9210 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9211 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9212 // in which we always assume we're always picking from the 1st operand. 9213 int MaskOffset = 9214 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9215 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9216 OtherElementsInOrder = false; 9217 break; 9218 } 9219 } 9220 // If other elements are in original order, we record the number of shifts 9221 // we need to get the element we want into element 7. Also record which byte 9222 // in the vector we should insert into. 9223 if (OtherElementsInOrder) { 9224 // If 2nd operand is undefined, we assume no shifts and no swapping. 9225 if (V2.isUndef()) { 9226 ShiftElts = 0; 9227 Swap = false; 9228 } else { 9229 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9230 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9231 : BigEndianShifts[CurrentElement & 0xF]; 9232 Swap = CurrentElement < BytesInVector; 9233 } 9234 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9235 FoundCandidate = true; 9236 break; 9237 } 9238 } 9239 9240 if (!FoundCandidate) 9241 return SDValue(); 9242 9243 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9244 // optionally with VECSHL if shift is required. 9245 if (Swap) 9246 std::swap(V1, V2); 9247 if (V2.isUndef()) 9248 V2 = V1; 9249 if (ShiftElts) { 9250 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9251 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9252 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9253 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9254 } 9255 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9256 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9257 } 9258 9259 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9260 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9261 /// SDValue. 9262 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9263 SelectionDAG &DAG) const { 9264 const unsigned NumHalfWords = 8; 9265 const unsigned BytesInVector = NumHalfWords * 2; 9266 // Check that the shuffle is on half-words. 9267 if (!isNByteElemShuffleMask(N, 2, 1)) 9268 return SDValue(); 9269 9270 bool IsLE = Subtarget.isLittleEndian(); 9271 SDLoc dl(N); 9272 SDValue V1 = N->getOperand(0); 9273 SDValue V2 = N->getOperand(1); 9274 unsigned ShiftElts = 0, InsertAtByte = 0; 9275 bool Swap = false; 9276 9277 // Shifts required to get the half-word we want at element 3. 9278 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9279 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9280 9281 uint32_t Mask = 0; 9282 uint32_t OriginalOrderLow = 0x1234567; 9283 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9284 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9285 // 32-bit space, only need 4-bit nibbles per element. 9286 for (unsigned i = 0; i < NumHalfWords; ++i) { 9287 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9288 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9289 } 9290 9291 // For each mask element, find out if we're just inserting something 9292 // from V2 into V1 or vice versa. Possible permutations inserting an element 9293 // from V2 into V1: 9294 // X, 1, 2, 3, 4, 5, 6, 7 9295 // 0, X, 2, 3, 4, 5, 6, 7 9296 // 0, 1, X, 3, 4, 5, 6, 7 9297 // 0, 1, 2, X, 4, 5, 6, 7 9298 // 0, 1, 2, 3, X, 5, 6, 7 9299 // 0, 1, 2, 3, 4, X, 6, 7 9300 // 0, 1, 2, 3, 4, 5, X, 7 9301 // 0, 1, 2, 3, 4, 5, 6, X 9302 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9303 9304 bool FoundCandidate = false; 9305 // Go through the mask of half-words to find an element that's being moved 9306 // from one vector to the other. 9307 for (unsigned i = 0; i < NumHalfWords; ++i) { 9308 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9309 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9310 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9311 uint32_t TargetOrder = 0x0; 9312 9313 // If both vector operands for the shuffle are the same vector, the mask 9314 // will contain only elements from the first one and the second one will be 9315 // undef. 9316 if (V2.isUndef()) { 9317 ShiftElts = 0; 9318 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9319 TargetOrder = OriginalOrderLow; 9320 Swap = false; 9321 // Skip if not the correct element or mask of other elements don't equal 9322 // to our expected order. 9323 if (MaskOneElt == VINSERTHSrcElem && 9324 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9325 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9326 FoundCandidate = true; 9327 break; 9328 } 9329 } else { // If both operands are defined. 9330 // Target order is [8,15] if the current mask is between [0,7]. 9331 TargetOrder = 9332 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9333 // Skip if mask of other elements don't equal our expected order. 9334 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9335 // We only need the last 3 bits for the number of shifts. 9336 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9337 : BigEndianShifts[MaskOneElt & 0x7]; 9338 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9339 Swap = MaskOneElt < NumHalfWords; 9340 FoundCandidate = true; 9341 break; 9342 } 9343 } 9344 } 9345 9346 if (!FoundCandidate) 9347 return SDValue(); 9348 9349 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9350 // optionally with VECSHL if shift is required. 9351 if (Swap) 9352 std::swap(V1, V2); 9353 if (V2.isUndef()) 9354 V2 = V1; 9355 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9356 if (ShiftElts) { 9357 // Double ShiftElts because we're left shifting on v16i8 type. 9358 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9359 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9360 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9361 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9362 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9363 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9364 } 9365 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9366 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9367 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9368 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9369 } 9370 9371 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9372 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9373 /// return the default SDValue. 9374 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9375 SelectionDAG &DAG) const { 9376 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9377 // to v16i8. Peek through the bitcasts to get the actual operands. 9378 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9379 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9380 9381 auto ShuffleMask = SVN->getMask(); 9382 SDValue VecShuffle(SVN, 0); 9383 SDLoc DL(SVN); 9384 9385 // Check that we have a four byte shuffle. 9386 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9387 return SDValue(); 9388 9389 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9390 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9391 std::swap(LHS, RHS); 9392 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9393 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9394 } 9395 9396 // Ensure that the RHS is a vector of constants. 9397 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9398 if (!BVN) 9399 return SDValue(); 9400 9401 // Check if RHS is a splat of 4-bytes (or smaller). 9402 APInt APSplatValue, APSplatUndef; 9403 unsigned SplatBitSize; 9404 bool HasAnyUndefs; 9405 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9406 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9407 SplatBitSize > 32) 9408 return SDValue(); 9409 9410 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9411 // The instruction splats a constant C into two words of the source vector 9412 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9413 // Thus we check that the shuffle mask is the equivalent of 9414 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9415 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9416 // within each word are consecutive, so we only need to check the first byte. 9417 SDValue Index; 9418 bool IsLE = Subtarget.isLittleEndian(); 9419 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9420 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9421 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9422 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9423 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9424 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9425 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9426 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9427 else 9428 return SDValue(); 9429 9430 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9431 // for XXSPLTI32DX. 9432 unsigned SplatVal = APSplatValue.getZExtValue(); 9433 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9434 SplatVal |= (SplatVal << SplatBitSize); 9435 9436 SDValue SplatNode = DAG.getNode( 9437 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9438 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9439 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9440 } 9441 9442 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9443 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9444 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9445 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9446 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9447 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9448 assert(Op.getValueType() == MVT::v1i128 && 9449 "Only set v1i128 as custom, other type shouldn't reach here!"); 9450 SDLoc dl(Op); 9451 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9452 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9453 unsigned SHLAmt = N1.getConstantOperandVal(0); 9454 if (SHLAmt % 8 == 0) { 9455 SmallVector<int, 16> Mask(16, 0); 9456 std::iota(Mask.begin(), Mask.end(), 0); 9457 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9458 if (SDValue Shuffle = 9459 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9460 DAG.getUNDEF(MVT::v16i8), Mask)) 9461 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9462 } 9463 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9464 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9465 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9466 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9467 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9468 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9469 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9470 } 9471 9472 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9473 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9474 /// return the code it can be lowered into. Worst case, it can always be 9475 /// lowered into a vperm. 9476 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9477 SelectionDAG &DAG) const { 9478 SDLoc dl(Op); 9479 SDValue V1 = Op.getOperand(0); 9480 SDValue V2 = Op.getOperand(1); 9481 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9482 9483 // Any nodes that were combined in the target-independent combiner prior 9484 // to vector legalization will not be sent to the target combine. Try to 9485 // combine it here. 9486 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9487 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9488 return NewShuffle; 9489 Op = NewShuffle; 9490 SVOp = cast<ShuffleVectorSDNode>(Op); 9491 V1 = Op.getOperand(0); 9492 V2 = Op.getOperand(1); 9493 } 9494 EVT VT = Op.getValueType(); 9495 bool isLittleEndian = Subtarget.isLittleEndian(); 9496 9497 unsigned ShiftElts, InsertAtByte; 9498 bool Swap = false; 9499 9500 // If this is a load-and-splat, we can do that with a single instruction 9501 // in some cases. However if the load has multiple uses, we don't want to 9502 // combine it because that will just produce multiple loads. 9503 bool IsPermutedLoad = false; 9504 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9505 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9506 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9507 InputLoad->hasOneUse()) { 9508 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9509 int SplatIdx = 9510 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9511 9512 // The splat index for permuted loads will be in the left half of the vector 9513 // which is strictly wider than the loaded value by 8 bytes. So we need to 9514 // adjust the splat index to point to the correct address in memory. 9515 if (IsPermutedLoad) { 9516 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9517 SplatIdx += IsFourByte ? 2 : 1; 9518 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9519 "Splat of a value outside of the loaded memory"); 9520 } 9521 9522 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9523 // For 4-byte load-and-splat, we need Power9. 9524 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9525 uint64_t Offset = 0; 9526 if (IsFourByte) 9527 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9528 else 9529 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9530 9531 SDValue BasePtr = LD->getBasePtr(); 9532 if (Offset != 0) 9533 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9534 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9535 SDValue Ops[] = { 9536 LD->getChain(), // Chain 9537 BasePtr, // BasePtr 9538 DAG.getValueType(Op.getValueType()) // VT 9539 }; 9540 SDVTList VTL = 9541 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9542 SDValue LdSplt = 9543 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9544 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9545 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9546 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9547 return LdSplt; 9548 } 9549 } 9550 if (Subtarget.hasP9Vector() && 9551 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9552 isLittleEndian)) { 9553 if (Swap) 9554 std::swap(V1, V2); 9555 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9556 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9557 if (ShiftElts) { 9558 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9559 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9560 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9561 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9562 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9563 } 9564 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9565 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9566 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9567 } 9568 9569 if (Subtarget.hasPrefixInstrs()) { 9570 SDValue SplatInsertNode; 9571 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9572 return SplatInsertNode; 9573 } 9574 9575 if (Subtarget.hasP9Altivec()) { 9576 SDValue NewISDNode; 9577 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9578 return NewISDNode; 9579 9580 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9581 return NewISDNode; 9582 } 9583 9584 if (Subtarget.hasVSX() && 9585 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9586 if (Swap) 9587 std::swap(V1, V2); 9588 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9589 SDValue Conv2 = 9590 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9591 9592 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9593 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9594 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9595 } 9596 9597 if (Subtarget.hasVSX() && 9598 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9599 if (Swap) 9600 std::swap(V1, V2); 9601 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9602 SDValue Conv2 = 9603 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9604 9605 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9606 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9607 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9608 } 9609 9610 if (Subtarget.hasP9Vector()) { 9611 if (PPC::isXXBRHShuffleMask(SVOp)) { 9612 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9613 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9614 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9615 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9616 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9617 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9618 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9619 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9620 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9621 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9622 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9623 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9624 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9625 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9626 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9627 } 9628 } 9629 9630 if (Subtarget.hasVSX()) { 9631 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9632 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9633 9634 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9635 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9636 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9637 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9638 } 9639 9640 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9641 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9642 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9643 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9644 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9645 } 9646 } 9647 9648 // Cases that are handled by instructions that take permute immediates 9649 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9650 // selected by the instruction selector. 9651 if (V2.isUndef()) { 9652 if (PPC::isSplatShuffleMask(SVOp, 1) || 9653 PPC::isSplatShuffleMask(SVOp, 2) || 9654 PPC::isSplatShuffleMask(SVOp, 4) || 9655 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9656 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9657 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9658 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9659 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9660 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9661 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9662 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9663 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9664 (Subtarget.hasP8Altivec() && ( 9665 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9666 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9667 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9668 return Op; 9669 } 9670 } 9671 9672 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9673 // and produce a fixed permutation. If any of these match, do not lower to 9674 // VPERM. 9675 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9676 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9677 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9678 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9679 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9680 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9681 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9682 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9683 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9684 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9685 (Subtarget.hasP8Altivec() && ( 9686 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9687 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9688 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9689 return Op; 9690 9691 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9692 // perfect shuffle table to emit an optimal matching sequence. 9693 ArrayRef<int> PermMask = SVOp->getMask(); 9694 9695 unsigned PFIndexes[4]; 9696 bool isFourElementShuffle = true; 9697 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9698 unsigned EltNo = 8; // Start out undef. 9699 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9700 if (PermMask[i*4+j] < 0) 9701 continue; // Undef, ignore it. 9702 9703 unsigned ByteSource = PermMask[i*4+j]; 9704 if ((ByteSource & 3) != j) { 9705 isFourElementShuffle = false; 9706 break; 9707 } 9708 9709 if (EltNo == 8) { 9710 EltNo = ByteSource/4; 9711 } else if (EltNo != ByteSource/4) { 9712 isFourElementShuffle = false; 9713 break; 9714 } 9715 } 9716 PFIndexes[i] = EltNo; 9717 } 9718 9719 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9720 // perfect shuffle vector to determine if it is cost effective to do this as 9721 // discrete instructions, or whether we should use a vperm. 9722 // For now, we skip this for little endian until such time as we have a 9723 // little-endian perfect shuffle table. 9724 if (isFourElementShuffle && !isLittleEndian) { 9725 // Compute the index in the perfect shuffle table. 9726 unsigned PFTableIndex = 9727 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9728 9729 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9730 unsigned Cost = (PFEntry >> 30); 9731 9732 // Determining when to avoid vperm is tricky. Many things affect the cost 9733 // of vperm, particularly how many times the perm mask needs to be computed. 9734 // For example, if the perm mask can be hoisted out of a loop or is already 9735 // used (perhaps because there are multiple permutes with the same shuffle 9736 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9737 // the loop requires an extra register. 9738 // 9739 // As a compromise, we only emit discrete instructions if the shuffle can be 9740 // generated in 3 or fewer operations. When we have loop information 9741 // available, if this block is within a loop, we should avoid using vperm 9742 // for 3-operation perms and use a constant pool load instead. 9743 if (Cost < 3) 9744 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9745 } 9746 9747 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9748 // vector that will get spilled to the constant pool. 9749 if (V2.isUndef()) V2 = V1; 9750 9751 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9752 // that it is in input element units, not in bytes. Convert now. 9753 9754 // For little endian, the order of the input vectors is reversed, and 9755 // the permutation mask is complemented with respect to 31. This is 9756 // necessary to produce proper semantics with the big-endian-biased vperm 9757 // instruction. 9758 EVT EltVT = V1.getValueType().getVectorElementType(); 9759 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9760 9761 SmallVector<SDValue, 16> ResultMask; 9762 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9763 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9764 9765 for (unsigned j = 0; j != BytesPerElement; ++j) 9766 if (isLittleEndian) 9767 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9768 dl, MVT::i32)); 9769 else 9770 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9771 MVT::i32)); 9772 } 9773 9774 ShufflesHandledWithVPERM++; 9775 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9776 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9777 LLVM_DEBUG(SVOp->dump()); 9778 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9779 LLVM_DEBUG(VPermMask.dump()); 9780 9781 if (isLittleEndian) 9782 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9783 V2, V1, VPermMask); 9784 else 9785 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9786 V1, V2, VPermMask); 9787 } 9788 9789 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9790 /// vector comparison. If it is, return true and fill in Opc/isDot with 9791 /// information about the intrinsic. 9792 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9793 bool &isDot, const PPCSubtarget &Subtarget) { 9794 unsigned IntrinsicID = 9795 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9796 CompareOpc = -1; 9797 isDot = false; 9798 switch (IntrinsicID) { 9799 default: 9800 return false; 9801 // Comparison predicates. 9802 case Intrinsic::ppc_altivec_vcmpbfp_p: 9803 CompareOpc = 966; 9804 isDot = true; 9805 break; 9806 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9807 CompareOpc = 198; 9808 isDot = true; 9809 break; 9810 case Intrinsic::ppc_altivec_vcmpequb_p: 9811 CompareOpc = 6; 9812 isDot = true; 9813 break; 9814 case Intrinsic::ppc_altivec_vcmpequh_p: 9815 CompareOpc = 70; 9816 isDot = true; 9817 break; 9818 case Intrinsic::ppc_altivec_vcmpequw_p: 9819 CompareOpc = 134; 9820 isDot = true; 9821 break; 9822 case Intrinsic::ppc_altivec_vcmpequd_p: 9823 if (Subtarget.hasP8Altivec()) { 9824 CompareOpc = 199; 9825 isDot = true; 9826 } else 9827 return false; 9828 break; 9829 case Intrinsic::ppc_altivec_vcmpneb_p: 9830 case Intrinsic::ppc_altivec_vcmpneh_p: 9831 case Intrinsic::ppc_altivec_vcmpnew_p: 9832 case Intrinsic::ppc_altivec_vcmpnezb_p: 9833 case Intrinsic::ppc_altivec_vcmpnezh_p: 9834 case Intrinsic::ppc_altivec_vcmpnezw_p: 9835 if (Subtarget.hasP9Altivec()) { 9836 switch (IntrinsicID) { 9837 default: 9838 llvm_unreachable("Unknown comparison intrinsic."); 9839 case Intrinsic::ppc_altivec_vcmpneb_p: 9840 CompareOpc = 7; 9841 break; 9842 case Intrinsic::ppc_altivec_vcmpneh_p: 9843 CompareOpc = 71; 9844 break; 9845 case Intrinsic::ppc_altivec_vcmpnew_p: 9846 CompareOpc = 135; 9847 break; 9848 case Intrinsic::ppc_altivec_vcmpnezb_p: 9849 CompareOpc = 263; 9850 break; 9851 case Intrinsic::ppc_altivec_vcmpnezh_p: 9852 CompareOpc = 327; 9853 break; 9854 case Intrinsic::ppc_altivec_vcmpnezw_p: 9855 CompareOpc = 391; 9856 break; 9857 } 9858 isDot = true; 9859 } else 9860 return false; 9861 break; 9862 case Intrinsic::ppc_altivec_vcmpgefp_p: 9863 CompareOpc = 454; 9864 isDot = true; 9865 break; 9866 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9867 CompareOpc = 710; 9868 isDot = true; 9869 break; 9870 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9871 CompareOpc = 774; 9872 isDot = true; 9873 break; 9874 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9875 CompareOpc = 838; 9876 isDot = true; 9877 break; 9878 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9879 CompareOpc = 902; 9880 isDot = true; 9881 break; 9882 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9883 if (Subtarget.hasP8Altivec()) { 9884 CompareOpc = 967; 9885 isDot = true; 9886 } else 9887 return false; 9888 break; 9889 case Intrinsic::ppc_altivec_vcmpgtub_p: 9890 CompareOpc = 518; 9891 isDot = true; 9892 break; 9893 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9894 CompareOpc = 582; 9895 isDot = true; 9896 break; 9897 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9898 CompareOpc = 646; 9899 isDot = true; 9900 break; 9901 case Intrinsic::ppc_altivec_vcmpgtud_p: 9902 if (Subtarget.hasP8Altivec()) { 9903 CompareOpc = 711; 9904 isDot = true; 9905 } else 9906 return false; 9907 break; 9908 9909 // VSX predicate comparisons use the same infrastructure 9910 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9911 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9912 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9913 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9914 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9915 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9916 if (Subtarget.hasVSX()) { 9917 switch (IntrinsicID) { 9918 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9919 CompareOpc = 99; 9920 break; 9921 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9922 CompareOpc = 115; 9923 break; 9924 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9925 CompareOpc = 107; 9926 break; 9927 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9928 CompareOpc = 67; 9929 break; 9930 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9931 CompareOpc = 83; 9932 break; 9933 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9934 CompareOpc = 75; 9935 break; 9936 } 9937 isDot = true; 9938 } else 9939 return false; 9940 break; 9941 9942 // Normal Comparisons. 9943 case Intrinsic::ppc_altivec_vcmpbfp: 9944 CompareOpc = 966; 9945 break; 9946 case Intrinsic::ppc_altivec_vcmpeqfp: 9947 CompareOpc = 198; 9948 break; 9949 case Intrinsic::ppc_altivec_vcmpequb: 9950 CompareOpc = 6; 9951 break; 9952 case Intrinsic::ppc_altivec_vcmpequh: 9953 CompareOpc = 70; 9954 break; 9955 case Intrinsic::ppc_altivec_vcmpequw: 9956 CompareOpc = 134; 9957 break; 9958 case Intrinsic::ppc_altivec_vcmpequd: 9959 if (Subtarget.hasP8Altivec()) 9960 CompareOpc = 199; 9961 else 9962 return false; 9963 break; 9964 case Intrinsic::ppc_altivec_vcmpneb: 9965 case Intrinsic::ppc_altivec_vcmpneh: 9966 case Intrinsic::ppc_altivec_vcmpnew: 9967 case Intrinsic::ppc_altivec_vcmpnezb: 9968 case Intrinsic::ppc_altivec_vcmpnezh: 9969 case Intrinsic::ppc_altivec_vcmpnezw: 9970 if (Subtarget.hasP9Altivec()) 9971 switch (IntrinsicID) { 9972 default: 9973 llvm_unreachable("Unknown comparison intrinsic."); 9974 case Intrinsic::ppc_altivec_vcmpneb: 9975 CompareOpc = 7; 9976 break; 9977 case Intrinsic::ppc_altivec_vcmpneh: 9978 CompareOpc = 71; 9979 break; 9980 case Intrinsic::ppc_altivec_vcmpnew: 9981 CompareOpc = 135; 9982 break; 9983 case Intrinsic::ppc_altivec_vcmpnezb: 9984 CompareOpc = 263; 9985 break; 9986 case Intrinsic::ppc_altivec_vcmpnezh: 9987 CompareOpc = 327; 9988 break; 9989 case Intrinsic::ppc_altivec_vcmpnezw: 9990 CompareOpc = 391; 9991 break; 9992 } 9993 else 9994 return false; 9995 break; 9996 case Intrinsic::ppc_altivec_vcmpgefp: 9997 CompareOpc = 454; 9998 break; 9999 case Intrinsic::ppc_altivec_vcmpgtfp: 10000 CompareOpc = 710; 10001 break; 10002 case Intrinsic::ppc_altivec_vcmpgtsb: 10003 CompareOpc = 774; 10004 break; 10005 case Intrinsic::ppc_altivec_vcmpgtsh: 10006 CompareOpc = 838; 10007 break; 10008 case Intrinsic::ppc_altivec_vcmpgtsw: 10009 CompareOpc = 902; 10010 break; 10011 case Intrinsic::ppc_altivec_vcmpgtsd: 10012 if (Subtarget.hasP8Altivec()) 10013 CompareOpc = 967; 10014 else 10015 return false; 10016 break; 10017 case Intrinsic::ppc_altivec_vcmpgtub: 10018 CompareOpc = 518; 10019 break; 10020 case Intrinsic::ppc_altivec_vcmpgtuh: 10021 CompareOpc = 582; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpgtuw: 10024 CompareOpc = 646; 10025 break; 10026 case Intrinsic::ppc_altivec_vcmpgtud: 10027 if (Subtarget.hasP8Altivec()) 10028 CompareOpc = 711; 10029 else 10030 return false; 10031 break; 10032 } 10033 return true; 10034 } 10035 10036 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10037 /// lower, do it, otherwise return null. 10038 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10039 SelectionDAG &DAG) const { 10040 unsigned IntrinsicID = 10041 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10042 10043 SDLoc dl(Op); 10044 10045 if (IntrinsicID == Intrinsic::thread_pointer) { 10046 // Reads the thread pointer register, used for __builtin_thread_pointer. 10047 if (Subtarget.isPPC64()) 10048 return DAG.getRegister(PPC::X13, MVT::i64); 10049 return DAG.getRegister(PPC::R2, MVT::i32); 10050 } 10051 10052 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10053 // opcode number of the comparison. 10054 int CompareOpc; 10055 bool isDot; 10056 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10057 return SDValue(); // Don't custom lower most intrinsics. 10058 10059 // If this is a non-dot comparison, make the VCMP node and we are done. 10060 if (!isDot) { 10061 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10062 Op.getOperand(1), Op.getOperand(2), 10063 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10064 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10065 } 10066 10067 // Create the PPCISD altivec 'dot' comparison node. 10068 SDValue Ops[] = { 10069 Op.getOperand(2), // LHS 10070 Op.getOperand(3), // RHS 10071 DAG.getConstant(CompareOpc, dl, MVT::i32) 10072 }; 10073 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10074 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10075 10076 // Now that we have the comparison, emit a copy from the CR to a GPR. 10077 // This is flagged to the above dot comparison. 10078 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10079 DAG.getRegister(PPC::CR6, MVT::i32), 10080 CompNode.getValue(1)); 10081 10082 // Unpack the result based on how the target uses it. 10083 unsigned BitNo; // Bit # of CR6. 10084 bool InvertBit; // Invert result? 10085 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10086 default: // Can't happen, don't crash on invalid number though. 10087 case 0: // Return the value of the EQ bit of CR6. 10088 BitNo = 0; InvertBit = false; 10089 break; 10090 case 1: // Return the inverted value of the EQ bit of CR6. 10091 BitNo = 0; InvertBit = true; 10092 break; 10093 case 2: // Return the value of the LT bit of CR6. 10094 BitNo = 2; InvertBit = false; 10095 break; 10096 case 3: // Return the inverted value of the LT bit of CR6. 10097 BitNo = 2; InvertBit = true; 10098 break; 10099 } 10100 10101 // Shift the bit into the low position. 10102 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10103 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10104 // Isolate the bit. 10105 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10106 DAG.getConstant(1, dl, MVT::i32)); 10107 10108 // If we are supposed to, toggle the bit. 10109 if (InvertBit) 10110 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10111 DAG.getConstant(1, dl, MVT::i32)); 10112 return Flags; 10113 } 10114 10115 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10116 SelectionDAG &DAG) const { 10117 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10118 // the beginning of the argument list. 10119 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10120 SDLoc DL(Op); 10121 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10122 case Intrinsic::ppc_cfence: { 10123 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10124 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10125 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10126 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10127 Op.getOperand(ArgStart + 1)), 10128 Op.getOperand(0)), 10129 0); 10130 } 10131 default: 10132 break; 10133 } 10134 return SDValue(); 10135 } 10136 10137 // Lower scalar BSWAP64 to xxbrd. 10138 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10139 SDLoc dl(Op); 10140 // MTVSRDD 10141 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10142 Op.getOperand(0)); 10143 // XXBRD 10144 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10145 // MFVSRD 10146 int VectorIndex = 0; 10147 if (Subtarget.isLittleEndian()) 10148 VectorIndex = 1; 10149 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10150 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10151 return Op; 10152 } 10153 10154 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10155 // compared to a value that is atomically loaded (atomic loads zero-extend). 10156 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10157 SelectionDAG &DAG) const { 10158 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10159 "Expecting an atomic compare-and-swap here."); 10160 SDLoc dl(Op); 10161 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10162 EVT MemVT = AtomicNode->getMemoryVT(); 10163 if (MemVT.getSizeInBits() >= 32) 10164 return Op; 10165 10166 SDValue CmpOp = Op.getOperand(2); 10167 // If this is already correctly zero-extended, leave it alone. 10168 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10169 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10170 return Op; 10171 10172 // Clear the high bits of the compare operand. 10173 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10174 SDValue NewCmpOp = 10175 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10176 DAG.getConstant(MaskVal, dl, MVT::i32)); 10177 10178 // Replace the existing compare operand with the properly zero-extended one. 10179 SmallVector<SDValue, 4> Ops; 10180 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10181 Ops.push_back(AtomicNode->getOperand(i)); 10182 Ops[2] = NewCmpOp; 10183 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10184 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10185 auto NodeTy = 10186 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10187 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10188 } 10189 10190 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10191 SelectionDAG &DAG) const { 10192 SDLoc dl(Op); 10193 // Create a stack slot that is 16-byte aligned. 10194 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10195 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10196 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10197 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10198 10199 // Store the input value into Value#0 of the stack slot. 10200 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10201 MachinePointerInfo()); 10202 // Load it out. 10203 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10204 } 10205 10206 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10207 SelectionDAG &DAG) const { 10208 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10209 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10210 10211 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10212 // We have legal lowering for constant indices but not for variable ones. 10213 if (!C) 10214 return SDValue(); 10215 10216 EVT VT = Op.getValueType(); 10217 SDLoc dl(Op); 10218 SDValue V1 = Op.getOperand(0); 10219 SDValue V2 = Op.getOperand(1); 10220 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10221 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10222 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10223 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10224 unsigned InsertAtElement = C->getZExtValue(); 10225 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10226 if (Subtarget.isLittleEndian()) { 10227 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10228 } 10229 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10230 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10231 } 10232 return Op; 10233 } 10234 10235 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10236 SDLoc dl(Op); 10237 if (Op.getValueType() == MVT::v4i32) { 10238 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10239 10240 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10241 // +16 as shift amt. 10242 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10243 SDValue RHSSwap = // = vrlw RHS, 16 10244 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10245 10246 // Shrinkify inputs to v8i16. 10247 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10248 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10249 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10250 10251 // Low parts multiplied together, generating 32-bit results (we ignore the 10252 // top parts). 10253 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10254 LHS, RHS, DAG, dl, MVT::v4i32); 10255 10256 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10257 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10258 // Shift the high parts up 16 bits. 10259 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10260 Neg16, DAG, dl); 10261 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10262 } else if (Op.getValueType() == MVT::v16i8) { 10263 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10264 bool isLittleEndian = Subtarget.isLittleEndian(); 10265 10266 // Multiply the even 8-bit parts, producing 16-bit sums. 10267 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10268 LHS, RHS, DAG, dl, MVT::v8i16); 10269 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10270 10271 // Multiply the odd 8-bit parts, producing 16-bit sums. 10272 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10273 LHS, RHS, DAG, dl, MVT::v8i16); 10274 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10275 10276 // Merge the results together. Because vmuleub and vmuloub are 10277 // instructions with a big-endian bias, we must reverse the 10278 // element numbering and reverse the meaning of "odd" and "even" 10279 // when generating little endian code. 10280 int Ops[16]; 10281 for (unsigned i = 0; i != 8; ++i) { 10282 if (isLittleEndian) { 10283 Ops[i*2 ] = 2*i; 10284 Ops[i*2+1] = 2*i+16; 10285 } else { 10286 Ops[i*2 ] = 2*i+1; 10287 Ops[i*2+1] = 2*i+1+16; 10288 } 10289 } 10290 if (isLittleEndian) 10291 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10292 else 10293 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10294 } else { 10295 llvm_unreachable("Unknown mul to lower!"); 10296 } 10297 } 10298 10299 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10300 10301 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10302 10303 EVT VT = Op.getValueType(); 10304 assert(VT.isVector() && 10305 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10306 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10307 VT == MVT::v16i8) && 10308 "Unexpected vector element type!"); 10309 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10310 "Current subtarget doesn't support smax v2i64!"); 10311 10312 // For vector abs, it can be lowered to: 10313 // abs x 10314 // ==> 10315 // y = -x 10316 // smax(x, y) 10317 10318 SDLoc dl(Op); 10319 SDValue X = Op.getOperand(0); 10320 SDValue Zero = DAG.getConstant(0, dl, VT); 10321 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10322 10323 // SMAX patch https://reviews.llvm.org/D47332 10324 // hasn't landed yet, so use intrinsic first here. 10325 // TODO: Should use SMAX directly once SMAX patch landed 10326 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10327 if (VT == MVT::v2i64) 10328 BifID = Intrinsic::ppc_altivec_vmaxsd; 10329 else if (VT == MVT::v8i16) 10330 BifID = Intrinsic::ppc_altivec_vmaxsh; 10331 else if (VT == MVT::v16i8) 10332 BifID = Intrinsic::ppc_altivec_vmaxsb; 10333 10334 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10335 } 10336 10337 // Custom lowering for fpext vf32 to v2f64 10338 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10339 10340 assert(Op.getOpcode() == ISD::FP_EXTEND && 10341 "Should only be called for ISD::FP_EXTEND"); 10342 10343 // FIXME: handle extends from half precision float vectors on P9. 10344 // We only want to custom lower an extend from v2f32 to v2f64. 10345 if (Op.getValueType() != MVT::v2f64 || 10346 Op.getOperand(0).getValueType() != MVT::v2f32) 10347 return SDValue(); 10348 10349 SDLoc dl(Op); 10350 SDValue Op0 = Op.getOperand(0); 10351 10352 switch (Op0.getOpcode()) { 10353 default: 10354 return SDValue(); 10355 case ISD::EXTRACT_SUBVECTOR: { 10356 assert(Op0.getNumOperands() == 2 && 10357 isa<ConstantSDNode>(Op0->getOperand(1)) && 10358 "Node should have 2 operands with second one being a constant!"); 10359 10360 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10361 return SDValue(); 10362 10363 // Custom lower is only done for high or low doubleword. 10364 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10365 if (Idx % 2 != 0) 10366 return SDValue(); 10367 10368 // Since input is v4f32, at this point Idx is either 0 or 2. 10369 // Shift to get the doubleword position we want. 10370 int DWord = Idx >> 1; 10371 10372 // High and low word positions are different on little endian. 10373 if (Subtarget.isLittleEndian()) 10374 DWord ^= 0x1; 10375 10376 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10377 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10378 } 10379 case ISD::FADD: 10380 case ISD::FMUL: 10381 case ISD::FSUB: { 10382 SDValue NewLoad[2]; 10383 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10384 // Ensure both input are loads. 10385 SDValue LdOp = Op0.getOperand(i); 10386 if (LdOp.getOpcode() != ISD::LOAD) 10387 return SDValue(); 10388 // Generate new load node. 10389 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10390 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10391 NewLoad[i] = DAG.getMemIntrinsicNode( 10392 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10393 LD->getMemoryVT(), LD->getMemOperand()); 10394 } 10395 SDValue NewOp = 10396 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10397 NewLoad[1], Op0.getNode()->getFlags()); 10398 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10399 DAG.getConstant(0, dl, MVT::i32)); 10400 } 10401 case ISD::LOAD: { 10402 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10403 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10404 SDValue NewLd = DAG.getMemIntrinsicNode( 10405 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10406 LD->getMemoryVT(), LD->getMemOperand()); 10407 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10408 DAG.getConstant(0, dl, MVT::i32)); 10409 } 10410 } 10411 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10412 } 10413 10414 /// LowerOperation - Provide custom lowering hooks for some operations. 10415 /// 10416 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10417 switch (Op.getOpcode()) { 10418 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10419 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10420 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10421 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10422 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10423 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10424 case ISD::SETCC: return LowerSETCC(Op, DAG); 10425 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10426 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10427 10428 // Variable argument lowering. 10429 case ISD::VASTART: return LowerVASTART(Op, DAG); 10430 case ISD::VAARG: return LowerVAARG(Op, DAG); 10431 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10432 10433 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10434 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10435 case ISD::GET_DYNAMIC_AREA_OFFSET: 10436 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10437 10438 // Exception handling lowering. 10439 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10440 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10441 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10442 10443 case ISD::LOAD: return LowerLOAD(Op, DAG); 10444 case ISD::STORE: return LowerSTORE(Op, DAG); 10445 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10446 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10447 case ISD::FP_TO_UINT: 10448 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10449 case ISD::UINT_TO_FP: 10450 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10451 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10452 10453 // Lower 64-bit shifts. 10454 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10455 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10456 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10457 10458 // Vector-related lowering. 10459 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10460 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10461 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10462 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10463 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10464 case ISD::MUL: return LowerMUL(Op, DAG); 10465 case ISD::ABS: return LowerABS(Op, DAG); 10466 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10467 case ISD::ROTL: return LowerROTL(Op, DAG); 10468 10469 // For counter-based loop handling. 10470 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10471 10472 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10473 10474 // Frame & Return address. 10475 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10476 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10477 10478 case ISD::INTRINSIC_VOID: 10479 return LowerINTRINSIC_VOID(Op, DAG); 10480 case ISD::BSWAP: 10481 return LowerBSWAP(Op, DAG); 10482 case ISD::ATOMIC_CMP_SWAP: 10483 return LowerATOMIC_CMP_SWAP(Op, DAG); 10484 } 10485 } 10486 10487 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10488 SmallVectorImpl<SDValue>&Results, 10489 SelectionDAG &DAG) const { 10490 SDLoc dl(N); 10491 switch (N->getOpcode()) { 10492 default: 10493 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10494 case ISD::READCYCLECOUNTER: { 10495 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10496 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10497 10498 Results.push_back( 10499 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10500 Results.push_back(RTB.getValue(2)); 10501 break; 10502 } 10503 case ISD::INTRINSIC_W_CHAIN: { 10504 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10505 Intrinsic::loop_decrement) 10506 break; 10507 10508 assert(N->getValueType(0) == MVT::i1 && 10509 "Unexpected result type for CTR decrement intrinsic"); 10510 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10511 N->getValueType(0)); 10512 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10513 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10514 N->getOperand(1)); 10515 10516 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10517 Results.push_back(NewInt.getValue(1)); 10518 break; 10519 } 10520 case ISD::VAARG: { 10521 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10522 return; 10523 10524 EVT VT = N->getValueType(0); 10525 10526 if (VT == MVT::i64) { 10527 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10528 10529 Results.push_back(NewNode); 10530 Results.push_back(NewNode.getValue(1)); 10531 } 10532 return; 10533 } 10534 case ISD::FP_TO_SINT: 10535 case ISD::FP_TO_UINT: 10536 // LowerFP_TO_INT() can only handle f32 and f64. 10537 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10538 return; 10539 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10540 return; 10541 case ISD::TRUNCATE: { 10542 EVT TrgVT = N->getValueType(0); 10543 EVT OpVT = N->getOperand(0).getValueType(); 10544 if (TrgVT.isVector() && 10545 isOperationCustom(N->getOpcode(), TrgVT) && 10546 OpVT.getSizeInBits() <= 128 && 10547 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10548 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10549 return; 10550 } 10551 case ISD::BITCAST: 10552 // Don't handle bitcast here. 10553 return; 10554 case ISD::FP_EXTEND: 10555 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10556 if (Lowered) 10557 Results.push_back(Lowered); 10558 return; 10559 } 10560 } 10561 10562 //===----------------------------------------------------------------------===// 10563 // Other Lowering Code 10564 //===----------------------------------------------------------------------===// 10565 10566 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10567 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10568 Function *Func = Intrinsic::getDeclaration(M, Id); 10569 return Builder.CreateCall(Func, {}); 10570 } 10571 10572 // The mappings for emitLeading/TrailingFence is taken from 10573 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10574 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10575 Instruction *Inst, 10576 AtomicOrdering Ord) const { 10577 if (Ord == AtomicOrdering::SequentiallyConsistent) 10578 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10579 if (isReleaseOrStronger(Ord)) 10580 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10581 return nullptr; 10582 } 10583 10584 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10585 Instruction *Inst, 10586 AtomicOrdering Ord) const { 10587 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10588 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10589 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10590 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10591 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10592 return Builder.CreateCall( 10593 Intrinsic::getDeclaration( 10594 Builder.GetInsertBlock()->getParent()->getParent(), 10595 Intrinsic::ppc_cfence, {Inst->getType()}), 10596 {Inst}); 10597 // FIXME: Can use isync for rmw operation. 10598 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10599 } 10600 return nullptr; 10601 } 10602 10603 MachineBasicBlock * 10604 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10605 unsigned AtomicSize, 10606 unsigned BinOpcode, 10607 unsigned CmpOpcode, 10608 unsigned CmpPred) const { 10609 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10610 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10611 10612 auto LoadMnemonic = PPC::LDARX; 10613 auto StoreMnemonic = PPC::STDCX; 10614 switch (AtomicSize) { 10615 default: 10616 llvm_unreachable("Unexpected size of atomic entity"); 10617 case 1: 10618 LoadMnemonic = PPC::LBARX; 10619 StoreMnemonic = PPC::STBCX; 10620 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10621 break; 10622 case 2: 10623 LoadMnemonic = PPC::LHARX; 10624 StoreMnemonic = PPC::STHCX; 10625 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10626 break; 10627 case 4: 10628 LoadMnemonic = PPC::LWARX; 10629 StoreMnemonic = PPC::STWCX; 10630 break; 10631 case 8: 10632 LoadMnemonic = PPC::LDARX; 10633 StoreMnemonic = PPC::STDCX; 10634 break; 10635 } 10636 10637 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10638 MachineFunction *F = BB->getParent(); 10639 MachineFunction::iterator It = ++BB->getIterator(); 10640 10641 Register dest = MI.getOperand(0).getReg(); 10642 Register ptrA = MI.getOperand(1).getReg(); 10643 Register ptrB = MI.getOperand(2).getReg(); 10644 Register incr = MI.getOperand(3).getReg(); 10645 DebugLoc dl = MI.getDebugLoc(); 10646 10647 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10648 MachineBasicBlock *loop2MBB = 10649 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10650 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10651 F->insert(It, loopMBB); 10652 if (CmpOpcode) 10653 F->insert(It, loop2MBB); 10654 F->insert(It, exitMBB); 10655 exitMBB->splice(exitMBB->begin(), BB, 10656 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10657 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10658 10659 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10660 Register TmpReg = (!BinOpcode) ? incr : 10661 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10662 : &PPC::GPRCRegClass); 10663 10664 // thisMBB: 10665 // ... 10666 // fallthrough --> loopMBB 10667 BB->addSuccessor(loopMBB); 10668 10669 // loopMBB: 10670 // l[wd]arx dest, ptr 10671 // add r0, dest, incr 10672 // st[wd]cx. r0, ptr 10673 // bne- loopMBB 10674 // fallthrough --> exitMBB 10675 10676 // For max/min... 10677 // loopMBB: 10678 // l[wd]arx dest, ptr 10679 // cmpl?[wd] incr, dest 10680 // bgt exitMBB 10681 // loop2MBB: 10682 // st[wd]cx. dest, ptr 10683 // bne- loopMBB 10684 // fallthrough --> exitMBB 10685 10686 BB = loopMBB; 10687 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10688 .addReg(ptrA).addReg(ptrB); 10689 if (BinOpcode) 10690 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10691 if (CmpOpcode) { 10692 // Signed comparisons of byte or halfword values must be sign-extended. 10693 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10694 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10695 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10696 ExtReg).addReg(dest); 10697 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10698 .addReg(incr).addReg(ExtReg); 10699 } else 10700 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10701 .addReg(incr).addReg(dest); 10702 10703 BuildMI(BB, dl, TII->get(PPC::BCC)) 10704 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10705 BB->addSuccessor(loop2MBB); 10706 BB->addSuccessor(exitMBB); 10707 BB = loop2MBB; 10708 } 10709 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10710 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10711 BuildMI(BB, dl, TII->get(PPC::BCC)) 10712 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10713 BB->addSuccessor(loopMBB); 10714 BB->addSuccessor(exitMBB); 10715 10716 // exitMBB: 10717 // ... 10718 BB = exitMBB; 10719 return BB; 10720 } 10721 10722 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10723 MachineInstr &MI, MachineBasicBlock *BB, 10724 bool is8bit, // operation 10725 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10726 // If we support part-word atomic mnemonics, just use them 10727 if (Subtarget.hasPartwordAtomics()) 10728 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10729 CmpPred); 10730 10731 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10732 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10733 // In 64 bit mode we have to use 64 bits for addresses, even though the 10734 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10735 // registers without caring whether they're 32 or 64, but here we're 10736 // doing actual arithmetic on the addresses. 10737 bool is64bit = Subtarget.isPPC64(); 10738 bool isLittleEndian = Subtarget.isLittleEndian(); 10739 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10740 10741 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10742 MachineFunction *F = BB->getParent(); 10743 MachineFunction::iterator It = ++BB->getIterator(); 10744 10745 Register dest = MI.getOperand(0).getReg(); 10746 Register ptrA = MI.getOperand(1).getReg(); 10747 Register ptrB = MI.getOperand(2).getReg(); 10748 Register incr = MI.getOperand(3).getReg(); 10749 DebugLoc dl = MI.getDebugLoc(); 10750 10751 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10752 MachineBasicBlock *loop2MBB = 10753 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10754 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10755 F->insert(It, loopMBB); 10756 if (CmpOpcode) 10757 F->insert(It, loop2MBB); 10758 F->insert(It, exitMBB); 10759 exitMBB->splice(exitMBB->begin(), BB, 10760 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10761 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10762 10763 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10764 const TargetRegisterClass *RC = 10765 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10766 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10767 10768 Register PtrReg = RegInfo.createVirtualRegister(RC); 10769 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10770 Register ShiftReg = 10771 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10772 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10773 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10774 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10775 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10776 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10777 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10778 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10779 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10780 Register Ptr1Reg; 10781 Register TmpReg = 10782 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10783 10784 // thisMBB: 10785 // ... 10786 // fallthrough --> loopMBB 10787 BB->addSuccessor(loopMBB); 10788 10789 // The 4-byte load must be aligned, while a char or short may be 10790 // anywhere in the word. Hence all this nasty bookkeeping code. 10791 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10792 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10793 // xori shift, shift1, 24 [16] 10794 // rlwinm ptr, ptr1, 0, 0, 29 10795 // slw incr2, incr, shift 10796 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10797 // slw mask, mask2, shift 10798 // loopMBB: 10799 // lwarx tmpDest, ptr 10800 // add tmp, tmpDest, incr2 10801 // andc tmp2, tmpDest, mask 10802 // and tmp3, tmp, mask 10803 // or tmp4, tmp3, tmp2 10804 // stwcx. tmp4, ptr 10805 // bne- loopMBB 10806 // fallthrough --> exitMBB 10807 // srw dest, tmpDest, shift 10808 if (ptrA != ZeroReg) { 10809 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10810 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10811 .addReg(ptrA) 10812 .addReg(ptrB); 10813 } else { 10814 Ptr1Reg = ptrB; 10815 } 10816 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10817 // mode. 10818 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10819 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10820 .addImm(3) 10821 .addImm(27) 10822 .addImm(is8bit ? 28 : 27); 10823 if (!isLittleEndian) 10824 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10825 .addReg(Shift1Reg) 10826 .addImm(is8bit ? 24 : 16); 10827 if (is64bit) 10828 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10829 .addReg(Ptr1Reg) 10830 .addImm(0) 10831 .addImm(61); 10832 else 10833 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10834 .addReg(Ptr1Reg) 10835 .addImm(0) 10836 .addImm(0) 10837 .addImm(29); 10838 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10839 if (is8bit) 10840 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10841 else { 10842 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10843 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10844 .addReg(Mask3Reg) 10845 .addImm(65535); 10846 } 10847 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10848 .addReg(Mask2Reg) 10849 .addReg(ShiftReg); 10850 10851 BB = loopMBB; 10852 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10853 .addReg(ZeroReg) 10854 .addReg(PtrReg); 10855 if (BinOpcode) 10856 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10857 .addReg(Incr2Reg) 10858 .addReg(TmpDestReg); 10859 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10860 .addReg(TmpDestReg) 10861 .addReg(MaskReg); 10862 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10863 if (CmpOpcode) { 10864 // For unsigned comparisons, we can directly compare the shifted values. 10865 // For signed comparisons we shift and sign extend. 10866 Register SReg = RegInfo.createVirtualRegister(GPRC); 10867 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10868 .addReg(TmpDestReg) 10869 .addReg(MaskReg); 10870 unsigned ValueReg = SReg; 10871 unsigned CmpReg = Incr2Reg; 10872 if (CmpOpcode == PPC::CMPW) { 10873 ValueReg = RegInfo.createVirtualRegister(GPRC); 10874 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10875 .addReg(SReg) 10876 .addReg(ShiftReg); 10877 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10878 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10879 .addReg(ValueReg); 10880 ValueReg = ValueSReg; 10881 CmpReg = incr; 10882 } 10883 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10884 .addReg(CmpReg) 10885 .addReg(ValueReg); 10886 BuildMI(BB, dl, TII->get(PPC::BCC)) 10887 .addImm(CmpPred) 10888 .addReg(PPC::CR0) 10889 .addMBB(exitMBB); 10890 BB->addSuccessor(loop2MBB); 10891 BB->addSuccessor(exitMBB); 10892 BB = loop2MBB; 10893 } 10894 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10895 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10896 .addReg(Tmp4Reg) 10897 .addReg(ZeroReg) 10898 .addReg(PtrReg); 10899 BuildMI(BB, dl, TII->get(PPC::BCC)) 10900 .addImm(PPC::PRED_NE) 10901 .addReg(PPC::CR0) 10902 .addMBB(loopMBB); 10903 BB->addSuccessor(loopMBB); 10904 BB->addSuccessor(exitMBB); 10905 10906 // exitMBB: 10907 // ... 10908 BB = exitMBB; 10909 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10910 .addReg(TmpDestReg) 10911 .addReg(ShiftReg); 10912 return BB; 10913 } 10914 10915 llvm::MachineBasicBlock * 10916 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10917 MachineBasicBlock *MBB) const { 10918 DebugLoc DL = MI.getDebugLoc(); 10919 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10920 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10921 10922 MachineFunction *MF = MBB->getParent(); 10923 MachineRegisterInfo &MRI = MF->getRegInfo(); 10924 10925 const BasicBlock *BB = MBB->getBasicBlock(); 10926 MachineFunction::iterator I = ++MBB->getIterator(); 10927 10928 Register DstReg = MI.getOperand(0).getReg(); 10929 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10930 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10931 Register mainDstReg = MRI.createVirtualRegister(RC); 10932 Register restoreDstReg = MRI.createVirtualRegister(RC); 10933 10934 MVT PVT = getPointerTy(MF->getDataLayout()); 10935 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10936 "Invalid Pointer Size!"); 10937 // For v = setjmp(buf), we generate 10938 // 10939 // thisMBB: 10940 // SjLjSetup mainMBB 10941 // bl mainMBB 10942 // v_restore = 1 10943 // b sinkMBB 10944 // 10945 // mainMBB: 10946 // buf[LabelOffset] = LR 10947 // v_main = 0 10948 // 10949 // sinkMBB: 10950 // v = phi(main, restore) 10951 // 10952 10953 MachineBasicBlock *thisMBB = MBB; 10954 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10955 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10956 MF->insert(I, mainMBB); 10957 MF->insert(I, sinkMBB); 10958 10959 MachineInstrBuilder MIB; 10960 10961 // Transfer the remainder of BB and its successor edges to sinkMBB. 10962 sinkMBB->splice(sinkMBB->begin(), MBB, 10963 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10964 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10965 10966 // Note that the structure of the jmp_buf used here is not compatible 10967 // with that used by libc, and is not designed to be. Specifically, it 10968 // stores only those 'reserved' registers that LLVM does not otherwise 10969 // understand how to spill. Also, by convention, by the time this 10970 // intrinsic is called, Clang has already stored the frame address in the 10971 // first slot of the buffer and stack address in the third. Following the 10972 // X86 target code, we'll store the jump address in the second slot. We also 10973 // need to save the TOC pointer (R2) to handle jumps between shared 10974 // libraries, and that will be stored in the fourth slot. The thread 10975 // identifier (R13) is not affected. 10976 10977 // thisMBB: 10978 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10979 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10980 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10981 10982 // Prepare IP either in reg. 10983 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10984 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10985 Register BufReg = MI.getOperand(1).getReg(); 10986 10987 if (Subtarget.is64BitELFABI()) { 10988 setUsesTOCBasePtr(*MBB->getParent()); 10989 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10990 .addReg(PPC::X2) 10991 .addImm(TOCOffset) 10992 .addReg(BufReg) 10993 .cloneMemRefs(MI); 10994 } 10995 10996 // Naked functions never have a base pointer, and so we use r1. For all 10997 // other functions, this decision must be delayed until during PEI. 10998 unsigned BaseReg; 10999 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11000 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11001 else 11002 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11003 11004 MIB = BuildMI(*thisMBB, MI, DL, 11005 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11006 .addReg(BaseReg) 11007 .addImm(BPOffset) 11008 .addReg(BufReg) 11009 .cloneMemRefs(MI); 11010 11011 // Setup 11012 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11013 MIB.addRegMask(TRI->getNoPreservedMask()); 11014 11015 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11016 11017 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11018 .addMBB(mainMBB); 11019 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11020 11021 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11022 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11023 11024 // mainMBB: 11025 // mainDstReg = 0 11026 MIB = 11027 BuildMI(mainMBB, DL, 11028 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11029 11030 // Store IP 11031 if (Subtarget.isPPC64()) { 11032 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11033 .addReg(LabelReg) 11034 .addImm(LabelOffset) 11035 .addReg(BufReg); 11036 } else { 11037 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11038 .addReg(LabelReg) 11039 .addImm(LabelOffset) 11040 .addReg(BufReg); 11041 } 11042 MIB.cloneMemRefs(MI); 11043 11044 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11045 mainMBB->addSuccessor(sinkMBB); 11046 11047 // sinkMBB: 11048 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11049 TII->get(PPC::PHI), DstReg) 11050 .addReg(mainDstReg).addMBB(mainMBB) 11051 .addReg(restoreDstReg).addMBB(thisMBB); 11052 11053 MI.eraseFromParent(); 11054 return sinkMBB; 11055 } 11056 11057 MachineBasicBlock * 11058 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11059 MachineBasicBlock *MBB) const { 11060 DebugLoc DL = MI.getDebugLoc(); 11061 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11062 11063 MachineFunction *MF = MBB->getParent(); 11064 MachineRegisterInfo &MRI = MF->getRegInfo(); 11065 11066 MVT PVT = getPointerTy(MF->getDataLayout()); 11067 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11068 "Invalid Pointer Size!"); 11069 11070 const TargetRegisterClass *RC = 11071 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11072 Register Tmp = MRI.createVirtualRegister(RC); 11073 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11074 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11075 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11076 unsigned BP = 11077 (PVT == MVT::i64) 11078 ? PPC::X30 11079 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11080 : PPC::R30); 11081 11082 MachineInstrBuilder MIB; 11083 11084 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11085 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11086 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11087 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11088 11089 Register BufReg = MI.getOperand(0).getReg(); 11090 11091 // Reload FP (the jumped-to function may not have had a 11092 // frame pointer, and if so, then its r31 will be restored 11093 // as necessary). 11094 if (PVT == MVT::i64) { 11095 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11096 .addImm(0) 11097 .addReg(BufReg); 11098 } else { 11099 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11100 .addImm(0) 11101 .addReg(BufReg); 11102 } 11103 MIB.cloneMemRefs(MI); 11104 11105 // Reload IP 11106 if (PVT == MVT::i64) { 11107 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11108 .addImm(LabelOffset) 11109 .addReg(BufReg); 11110 } else { 11111 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11112 .addImm(LabelOffset) 11113 .addReg(BufReg); 11114 } 11115 MIB.cloneMemRefs(MI); 11116 11117 // Reload SP 11118 if (PVT == MVT::i64) { 11119 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11120 .addImm(SPOffset) 11121 .addReg(BufReg); 11122 } else { 11123 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11124 .addImm(SPOffset) 11125 .addReg(BufReg); 11126 } 11127 MIB.cloneMemRefs(MI); 11128 11129 // Reload BP 11130 if (PVT == MVT::i64) { 11131 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11132 .addImm(BPOffset) 11133 .addReg(BufReg); 11134 } else { 11135 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11136 .addImm(BPOffset) 11137 .addReg(BufReg); 11138 } 11139 MIB.cloneMemRefs(MI); 11140 11141 // Reload TOC 11142 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11143 setUsesTOCBasePtr(*MBB->getParent()); 11144 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11145 .addImm(TOCOffset) 11146 .addReg(BufReg) 11147 .cloneMemRefs(MI); 11148 } 11149 11150 // Jump 11151 BuildMI(*MBB, MI, DL, 11152 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11153 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11154 11155 MI.eraseFromParent(); 11156 return MBB; 11157 } 11158 11159 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11160 // If the function specifically requests inline stack probes, emit them. 11161 if (MF.getFunction().hasFnAttribute("probe-stack")) 11162 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11163 "inline-asm"; 11164 return false; 11165 } 11166 11167 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11168 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11169 unsigned StackAlign = TFI->getStackAlignment(); 11170 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11171 "Unexpected stack alignment"); 11172 // The default stack probe size is 4096 if the function has no 11173 // stack-probe-size attribute. 11174 unsigned StackProbeSize = 4096; 11175 const Function &Fn = MF.getFunction(); 11176 if (Fn.hasFnAttribute("stack-probe-size")) 11177 Fn.getFnAttribute("stack-probe-size") 11178 .getValueAsString() 11179 .getAsInteger(0, StackProbeSize); 11180 // Round down to the stack alignment. 11181 StackProbeSize &= ~(StackAlign - 1); 11182 return StackProbeSize ? StackProbeSize : StackAlign; 11183 } 11184 11185 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11186 // into three phases. In the first phase, it uses pseudo instruction 11187 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11188 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11189 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11190 // MaxCallFrameSize so that it can calculate correct data area pointer. 11191 MachineBasicBlock * 11192 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11193 MachineBasicBlock *MBB) const { 11194 const bool isPPC64 = Subtarget.isPPC64(); 11195 MachineFunction *MF = MBB->getParent(); 11196 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11197 DebugLoc DL = MI.getDebugLoc(); 11198 const unsigned ProbeSize = getStackProbeSize(*MF); 11199 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11200 MachineRegisterInfo &MRI = MF->getRegInfo(); 11201 // The CFG of probing stack looks as 11202 // +-----+ 11203 // | MBB | 11204 // +--+--+ 11205 // | 11206 // +----v----+ 11207 // +--->+ TestMBB +---+ 11208 // | +----+----+ | 11209 // | | | 11210 // | +-----v----+ | 11211 // +---+ BlockMBB | | 11212 // +----------+ | 11213 // | 11214 // +---------+ | 11215 // | TailMBB +<--+ 11216 // +---------+ 11217 // In MBB, calculate previous frame pointer and final stack pointer. 11218 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11219 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11220 // TailMBB is spliced via \p MI. 11221 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11222 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11223 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11224 11225 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11226 MF->insert(MBBIter, TestMBB); 11227 MF->insert(MBBIter, BlockMBB); 11228 MF->insert(MBBIter, TailMBB); 11229 11230 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11231 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11232 11233 Register DstReg = MI.getOperand(0).getReg(); 11234 Register NegSizeReg = MI.getOperand(1).getReg(); 11235 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11236 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11237 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11238 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11239 11240 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11241 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11242 // NegSize. 11243 unsigned ProbeOpc; 11244 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11245 ProbeOpc = 11246 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11247 else 11248 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11249 // and NegSizeReg will be allocated in the same phyreg to avoid 11250 // redundant copy when NegSizeReg has only one use which is current MI and 11251 // will be replaced by PREPARE_PROBED_ALLOCA then. 11252 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11253 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11254 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11255 .addDef(ActualNegSizeReg) 11256 .addReg(NegSizeReg) 11257 .add(MI.getOperand(2)) 11258 .add(MI.getOperand(3)); 11259 11260 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11261 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11262 FinalStackPtr) 11263 .addReg(SPReg) 11264 .addReg(ActualNegSizeReg); 11265 11266 // Materialize a scratch register for update. 11267 int64_t NegProbeSize = -(int64_t)ProbeSize; 11268 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11269 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11270 if (!isInt<16>(NegProbeSize)) { 11271 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11272 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11273 .addImm(NegProbeSize >> 16); 11274 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11275 ScratchReg) 11276 .addReg(TempReg) 11277 .addImm(NegProbeSize & 0xFFFF); 11278 } else 11279 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11280 .addImm(NegProbeSize); 11281 11282 { 11283 // Probing leading residual part. 11284 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11285 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11286 .addReg(ActualNegSizeReg) 11287 .addReg(ScratchReg); 11288 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11289 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11290 .addReg(Div) 11291 .addReg(ScratchReg); 11292 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11293 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11294 .addReg(Mul) 11295 .addReg(ActualNegSizeReg); 11296 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11297 .addReg(FramePointer) 11298 .addReg(SPReg) 11299 .addReg(NegMod); 11300 } 11301 11302 { 11303 // Remaining part should be multiple of ProbeSize. 11304 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11305 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11306 .addReg(SPReg) 11307 .addReg(FinalStackPtr); 11308 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11309 .addImm(PPC::PRED_EQ) 11310 .addReg(CmpResult) 11311 .addMBB(TailMBB); 11312 TestMBB->addSuccessor(BlockMBB); 11313 TestMBB->addSuccessor(TailMBB); 11314 } 11315 11316 { 11317 // Touch the block. 11318 // |P...|P...|P... 11319 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11320 .addReg(FramePointer) 11321 .addReg(SPReg) 11322 .addReg(ScratchReg); 11323 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11324 BlockMBB->addSuccessor(TestMBB); 11325 } 11326 11327 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11328 // DYNAREAOFFSET pseudo instruction to get the future result. 11329 Register MaxCallFrameSizeReg = 11330 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11331 BuildMI(TailMBB, DL, 11332 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11333 MaxCallFrameSizeReg) 11334 .add(MI.getOperand(2)) 11335 .add(MI.getOperand(3)); 11336 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11337 .addReg(SPReg) 11338 .addReg(MaxCallFrameSizeReg); 11339 11340 // Splice instructions after MI to TailMBB. 11341 TailMBB->splice(TailMBB->end(), MBB, 11342 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11343 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11344 MBB->addSuccessor(TestMBB); 11345 11346 // Delete the pseudo instruction. 11347 MI.eraseFromParent(); 11348 11349 ++NumDynamicAllocaProbed; 11350 return TailMBB; 11351 } 11352 11353 MachineBasicBlock * 11354 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11355 MachineBasicBlock *BB) const { 11356 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11357 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11358 if (Subtarget.is64BitELFABI() && 11359 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11360 !Subtarget.isUsingPCRelativeCalls()) { 11361 // Call lowering should have added an r2 operand to indicate a dependence 11362 // on the TOC base pointer value. It can't however, because there is no 11363 // way to mark the dependence as implicit there, and so the stackmap code 11364 // will confuse it with a regular operand. Instead, add the dependence 11365 // here. 11366 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11367 } 11368 11369 return emitPatchPoint(MI, BB); 11370 } 11371 11372 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11373 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11374 return emitEHSjLjSetJmp(MI, BB); 11375 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11376 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11377 return emitEHSjLjLongJmp(MI, BB); 11378 } 11379 11380 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11381 11382 // To "insert" these instructions we actually have to insert their 11383 // control-flow patterns. 11384 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11385 MachineFunction::iterator It = ++BB->getIterator(); 11386 11387 MachineFunction *F = BB->getParent(); 11388 11389 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11390 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11391 MI.getOpcode() == PPC::SELECT_I8) { 11392 SmallVector<MachineOperand, 2> Cond; 11393 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11394 MI.getOpcode() == PPC::SELECT_CC_I8) 11395 Cond.push_back(MI.getOperand(4)); 11396 else 11397 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11398 Cond.push_back(MI.getOperand(1)); 11399 11400 DebugLoc dl = MI.getDebugLoc(); 11401 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11402 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11403 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11404 MI.getOpcode() == PPC::SELECT_CC_F8 || 11405 MI.getOpcode() == PPC::SELECT_CC_F16 || 11406 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11407 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11408 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11409 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11410 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11411 MI.getOpcode() == PPC::SELECT_CC_SPE || 11412 MI.getOpcode() == PPC::SELECT_F4 || 11413 MI.getOpcode() == PPC::SELECT_F8 || 11414 MI.getOpcode() == PPC::SELECT_F16 || 11415 MI.getOpcode() == PPC::SELECT_SPE || 11416 MI.getOpcode() == PPC::SELECT_SPE4 || 11417 MI.getOpcode() == PPC::SELECT_VRRC || 11418 MI.getOpcode() == PPC::SELECT_VSFRC || 11419 MI.getOpcode() == PPC::SELECT_VSSRC || 11420 MI.getOpcode() == PPC::SELECT_VSRC) { 11421 // The incoming instruction knows the destination vreg to set, the 11422 // condition code register to branch on, the true/false values to 11423 // select between, and a branch opcode to use. 11424 11425 // thisMBB: 11426 // ... 11427 // TrueVal = ... 11428 // cmpTY ccX, r1, r2 11429 // bCC copy1MBB 11430 // fallthrough --> copy0MBB 11431 MachineBasicBlock *thisMBB = BB; 11432 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11433 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11434 DebugLoc dl = MI.getDebugLoc(); 11435 F->insert(It, copy0MBB); 11436 F->insert(It, sinkMBB); 11437 11438 // Transfer the remainder of BB and its successor edges to sinkMBB. 11439 sinkMBB->splice(sinkMBB->begin(), BB, 11440 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11441 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11442 11443 // Next, add the true and fallthrough blocks as its successors. 11444 BB->addSuccessor(copy0MBB); 11445 BB->addSuccessor(sinkMBB); 11446 11447 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11448 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11449 MI.getOpcode() == PPC::SELECT_F16 || 11450 MI.getOpcode() == PPC::SELECT_SPE4 || 11451 MI.getOpcode() == PPC::SELECT_SPE || 11452 MI.getOpcode() == PPC::SELECT_VRRC || 11453 MI.getOpcode() == PPC::SELECT_VSFRC || 11454 MI.getOpcode() == PPC::SELECT_VSSRC || 11455 MI.getOpcode() == PPC::SELECT_VSRC) { 11456 BuildMI(BB, dl, TII->get(PPC::BC)) 11457 .addReg(MI.getOperand(1).getReg()) 11458 .addMBB(sinkMBB); 11459 } else { 11460 unsigned SelectPred = MI.getOperand(4).getImm(); 11461 BuildMI(BB, dl, TII->get(PPC::BCC)) 11462 .addImm(SelectPred) 11463 .addReg(MI.getOperand(1).getReg()) 11464 .addMBB(sinkMBB); 11465 } 11466 11467 // copy0MBB: 11468 // %FalseValue = ... 11469 // # fallthrough to sinkMBB 11470 BB = copy0MBB; 11471 11472 // Update machine-CFG edges 11473 BB->addSuccessor(sinkMBB); 11474 11475 // sinkMBB: 11476 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11477 // ... 11478 BB = sinkMBB; 11479 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11480 .addReg(MI.getOperand(3).getReg()) 11481 .addMBB(copy0MBB) 11482 .addReg(MI.getOperand(2).getReg()) 11483 .addMBB(thisMBB); 11484 } else if (MI.getOpcode() == PPC::ReadTB) { 11485 // To read the 64-bit time-base register on a 32-bit target, we read the 11486 // two halves. Should the counter have wrapped while it was being read, we 11487 // need to try again. 11488 // ... 11489 // readLoop: 11490 // mfspr Rx,TBU # load from TBU 11491 // mfspr Ry,TB # load from TB 11492 // mfspr Rz,TBU # load from TBU 11493 // cmpw crX,Rx,Rz # check if 'old'='new' 11494 // bne readLoop # branch if they're not equal 11495 // ... 11496 11497 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11498 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11499 DebugLoc dl = MI.getDebugLoc(); 11500 F->insert(It, readMBB); 11501 F->insert(It, sinkMBB); 11502 11503 // Transfer the remainder of BB and its successor edges to sinkMBB. 11504 sinkMBB->splice(sinkMBB->begin(), BB, 11505 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11506 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11507 11508 BB->addSuccessor(readMBB); 11509 BB = readMBB; 11510 11511 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11512 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11513 Register LoReg = MI.getOperand(0).getReg(); 11514 Register HiReg = MI.getOperand(1).getReg(); 11515 11516 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11517 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11518 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11519 11520 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11521 11522 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11523 .addReg(HiReg) 11524 .addReg(ReadAgainReg); 11525 BuildMI(BB, dl, TII->get(PPC::BCC)) 11526 .addImm(PPC::PRED_NE) 11527 .addReg(CmpReg) 11528 .addMBB(readMBB); 11529 11530 BB->addSuccessor(readMBB); 11531 BB->addSuccessor(sinkMBB); 11532 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11533 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11534 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11535 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11536 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11537 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11538 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11539 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11540 11541 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11542 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11543 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11544 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11545 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11546 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11547 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11548 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11549 11550 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11551 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11553 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11555 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11556 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11557 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11558 11559 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11560 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11562 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11564 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11565 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11566 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11567 11568 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11569 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11570 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11571 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11573 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11574 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11575 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11576 11577 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11578 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11579 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11580 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11581 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11582 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11583 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11584 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11585 11586 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11587 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11588 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11589 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11590 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11591 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11592 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11593 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11594 11595 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11596 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11597 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11598 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11599 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11600 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11601 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11602 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11603 11604 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11605 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11606 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11607 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11608 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11609 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11610 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11611 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11612 11613 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11614 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11615 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11616 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11617 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11618 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11619 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11620 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11621 11622 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11623 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11624 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11625 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11626 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11627 BB = EmitAtomicBinary(MI, BB, 4, 0); 11628 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11629 BB = EmitAtomicBinary(MI, BB, 8, 0); 11630 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11631 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11632 (Subtarget.hasPartwordAtomics() && 11633 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11634 (Subtarget.hasPartwordAtomics() && 11635 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11636 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11637 11638 auto LoadMnemonic = PPC::LDARX; 11639 auto StoreMnemonic = PPC::STDCX; 11640 switch (MI.getOpcode()) { 11641 default: 11642 llvm_unreachable("Compare and swap of unknown size"); 11643 case PPC::ATOMIC_CMP_SWAP_I8: 11644 LoadMnemonic = PPC::LBARX; 11645 StoreMnemonic = PPC::STBCX; 11646 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11647 break; 11648 case PPC::ATOMIC_CMP_SWAP_I16: 11649 LoadMnemonic = PPC::LHARX; 11650 StoreMnemonic = PPC::STHCX; 11651 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11652 break; 11653 case PPC::ATOMIC_CMP_SWAP_I32: 11654 LoadMnemonic = PPC::LWARX; 11655 StoreMnemonic = PPC::STWCX; 11656 break; 11657 case PPC::ATOMIC_CMP_SWAP_I64: 11658 LoadMnemonic = PPC::LDARX; 11659 StoreMnemonic = PPC::STDCX; 11660 break; 11661 } 11662 Register dest = MI.getOperand(0).getReg(); 11663 Register ptrA = MI.getOperand(1).getReg(); 11664 Register ptrB = MI.getOperand(2).getReg(); 11665 Register oldval = MI.getOperand(3).getReg(); 11666 Register newval = MI.getOperand(4).getReg(); 11667 DebugLoc dl = MI.getDebugLoc(); 11668 11669 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11670 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11671 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11672 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11673 F->insert(It, loop1MBB); 11674 F->insert(It, loop2MBB); 11675 F->insert(It, midMBB); 11676 F->insert(It, exitMBB); 11677 exitMBB->splice(exitMBB->begin(), BB, 11678 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11679 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11680 11681 // thisMBB: 11682 // ... 11683 // fallthrough --> loopMBB 11684 BB->addSuccessor(loop1MBB); 11685 11686 // loop1MBB: 11687 // l[bhwd]arx dest, ptr 11688 // cmp[wd] dest, oldval 11689 // bne- midMBB 11690 // loop2MBB: 11691 // st[bhwd]cx. newval, ptr 11692 // bne- loopMBB 11693 // b exitBB 11694 // midMBB: 11695 // st[bhwd]cx. dest, ptr 11696 // exitBB: 11697 BB = loop1MBB; 11698 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11699 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11700 .addReg(oldval) 11701 .addReg(dest); 11702 BuildMI(BB, dl, TII->get(PPC::BCC)) 11703 .addImm(PPC::PRED_NE) 11704 .addReg(PPC::CR0) 11705 .addMBB(midMBB); 11706 BB->addSuccessor(loop2MBB); 11707 BB->addSuccessor(midMBB); 11708 11709 BB = loop2MBB; 11710 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11711 .addReg(newval) 11712 .addReg(ptrA) 11713 .addReg(ptrB); 11714 BuildMI(BB, dl, TII->get(PPC::BCC)) 11715 .addImm(PPC::PRED_NE) 11716 .addReg(PPC::CR0) 11717 .addMBB(loop1MBB); 11718 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11719 BB->addSuccessor(loop1MBB); 11720 BB->addSuccessor(exitMBB); 11721 11722 BB = midMBB; 11723 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11724 .addReg(dest) 11725 .addReg(ptrA) 11726 .addReg(ptrB); 11727 BB->addSuccessor(exitMBB); 11728 11729 // exitMBB: 11730 // ... 11731 BB = exitMBB; 11732 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11733 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11734 // We must use 64-bit registers for addresses when targeting 64-bit, 11735 // since we're actually doing arithmetic on them. Other registers 11736 // can be 32-bit. 11737 bool is64bit = Subtarget.isPPC64(); 11738 bool isLittleEndian = Subtarget.isLittleEndian(); 11739 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11740 11741 Register dest = MI.getOperand(0).getReg(); 11742 Register ptrA = MI.getOperand(1).getReg(); 11743 Register ptrB = MI.getOperand(2).getReg(); 11744 Register oldval = MI.getOperand(3).getReg(); 11745 Register newval = MI.getOperand(4).getReg(); 11746 DebugLoc dl = MI.getDebugLoc(); 11747 11748 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11749 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11750 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11751 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11752 F->insert(It, loop1MBB); 11753 F->insert(It, loop2MBB); 11754 F->insert(It, midMBB); 11755 F->insert(It, exitMBB); 11756 exitMBB->splice(exitMBB->begin(), BB, 11757 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11758 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11759 11760 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11761 const TargetRegisterClass *RC = 11762 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11763 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11764 11765 Register PtrReg = RegInfo.createVirtualRegister(RC); 11766 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11767 Register ShiftReg = 11768 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11769 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11770 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11771 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11772 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11773 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11774 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11775 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11776 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11777 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11778 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11779 Register Ptr1Reg; 11780 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11781 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11782 // thisMBB: 11783 // ... 11784 // fallthrough --> loopMBB 11785 BB->addSuccessor(loop1MBB); 11786 11787 // The 4-byte load must be aligned, while a char or short may be 11788 // anywhere in the word. Hence all this nasty bookkeeping code. 11789 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11790 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11791 // xori shift, shift1, 24 [16] 11792 // rlwinm ptr, ptr1, 0, 0, 29 11793 // slw newval2, newval, shift 11794 // slw oldval2, oldval,shift 11795 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11796 // slw mask, mask2, shift 11797 // and newval3, newval2, mask 11798 // and oldval3, oldval2, mask 11799 // loop1MBB: 11800 // lwarx tmpDest, ptr 11801 // and tmp, tmpDest, mask 11802 // cmpw tmp, oldval3 11803 // bne- midMBB 11804 // loop2MBB: 11805 // andc tmp2, tmpDest, mask 11806 // or tmp4, tmp2, newval3 11807 // stwcx. tmp4, ptr 11808 // bne- loop1MBB 11809 // b exitBB 11810 // midMBB: 11811 // stwcx. tmpDest, ptr 11812 // exitBB: 11813 // srw dest, tmpDest, shift 11814 if (ptrA != ZeroReg) { 11815 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11816 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11817 .addReg(ptrA) 11818 .addReg(ptrB); 11819 } else { 11820 Ptr1Reg = ptrB; 11821 } 11822 11823 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11824 // mode. 11825 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11826 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11827 .addImm(3) 11828 .addImm(27) 11829 .addImm(is8bit ? 28 : 27); 11830 if (!isLittleEndian) 11831 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11832 .addReg(Shift1Reg) 11833 .addImm(is8bit ? 24 : 16); 11834 if (is64bit) 11835 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11836 .addReg(Ptr1Reg) 11837 .addImm(0) 11838 .addImm(61); 11839 else 11840 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11841 .addReg(Ptr1Reg) 11842 .addImm(0) 11843 .addImm(0) 11844 .addImm(29); 11845 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11846 .addReg(newval) 11847 .addReg(ShiftReg); 11848 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11849 .addReg(oldval) 11850 .addReg(ShiftReg); 11851 if (is8bit) 11852 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11853 else { 11854 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11855 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11856 .addReg(Mask3Reg) 11857 .addImm(65535); 11858 } 11859 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11860 .addReg(Mask2Reg) 11861 .addReg(ShiftReg); 11862 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11863 .addReg(NewVal2Reg) 11864 .addReg(MaskReg); 11865 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11866 .addReg(OldVal2Reg) 11867 .addReg(MaskReg); 11868 11869 BB = loop1MBB; 11870 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11871 .addReg(ZeroReg) 11872 .addReg(PtrReg); 11873 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11874 .addReg(TmpDestReg) 11875 .addReg(MaskReg); 11876 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11877 .addReg(TmpReg) 11878 .addReg(OldVal3Reg); 11879 BuildMI(BB, dl, TII->get(PPC::BCC)) 11880 .addImm(PPC::PRED_NE) 11881 .addReg(PPC::CR0) 11882 .addMBB(midMBB); 11883 BB->addSuccessor(loop2MBB); 11884 BB->addSuccessor(midMBB); 11885 11886 BB = loop2MBB; 11887 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11888 .addReg(TmpDestReg) 11889 .addReg(MaskReg); 11890 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11891 .addReg(Tmp2Reg) 11892 .addReg(NewVal3Reg); 11893 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11894 .addReg(Tmp4Reg) 11895 .addReg(ZeroReg) 11896 .addReg(PtrReg); 11897 BuildMI(BB, dl, TII->get(PPC::BCC)) 11898 .addImm(PPC::PRED_NE) 11899 .addReg(PPC::CR0) 11900 .addMBB(loop1MBB); 11901 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11902 BB->addSuccessor(loop1MBB); 11903 BB->addSuccessor(exitMBB); 11904 11905 BB = midMBB; 11906 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11907 .addReg(TmpDestReg) 11908 .addReg(ZeroReg) 11909 .addReg(PtrReg); 11910 BB->addSuccessor(exitMBB); 11911 11912 // exitMBB: 11913 // ... 11914 BB = exitMBB; 11915 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11916 .addReg(TmpReg) 11917 .addReg(ShiftReg); 11918 } else if (MI.getOpcode() == PPC::FADDrtz) { 11919 // This pseudo performs an FADD with rounding mode temporarily forced 11920 // to round-to-zero. We emit this via custom inserter since the FPSCR 11921 // is not modeled at the SelectionDAG level. 11922 Register Dest = MI.getOperand(0).getReg(); 11923 Register Src1 = MI.getOperand(1).getReg(); 11924 Register Src2 = MI.getOperand(2).getReg(); 11925 DebugLoc dl = MI.getDebugLoc(); 11926 11927 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11928 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11929 11930 // Save FPSCR value. 11931 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11932 11933 // Set rounding mode to round-to-zero. 11934 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11935 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11936 11937 // Perform addition. 11938 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11939 11940 // Restore FPSCR value. 11941 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11942 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11943 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 11944 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11945 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 11946 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11947 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 11948 ? PPC::ANDI8_rec 11949 : PPC::ANDI_rec; 11950 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11951 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 11952 11953 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11954 Register Dest = RegInfo.createVirtualRegister( 11955 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11956 11957 DebugLoc Dl = MI.getDebugLoc(); 11958 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 11959 .addReg(MI.getOperand(1).getReg()) 11960 .addImm(1); 11961 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11962 MI.getOperand(0).getReg()) 11963 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 11964 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11965 DebugLoc Dl = MI.getDebugLoc(); 11966 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11967 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11968 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11969 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11970 MI.getOperand(0).getReg()) 11971 .addReg(CRReg); 11972 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11973 DebugLoc Dl = MI.getDebugLoc(); 11974 unsigned Imm = MI.getOperand(1).getImm(); 11975 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11976 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11977 MI.getOperand(0).getReg()) 11978 .addReg(PPC::CR0EQ); 11979 } else if (MI.getOpcode() == PPC::SETRNDi) { 11980 DebugLoc dl = MI.getDebugLoc(); 11981 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11982 11983 // Save FPSCR value. 11984 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11985 11986 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11987 // the following settings: 11988 // 00 Round to nearest 11989 // 01 Round to 0 11990 // 10 Round to +inf 11991 // 11 Round to -inf 11992 11993 // When the operand is immediate, using the two least significant bits of 11994 // the immediate to set the bits 62:63 of FPSCR. 11995 unsigned Mode = MI.getOperand(1).getImm(); 11996 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11997 .addImm(31); 11998 11999 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12000 .addImm(30); 12001 } else if (MI.getOpcode() == PPC::SETRND) { 12002 DebugLoc dl = MI.getDebugLoc(); 12003 12004 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12005 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12006 // If the target doesn't have DirectMove, we should use stack to do the 12007 // conversion, because the target doesn't have the instructions like mtvsrd 12008 // or mfvsrd to do this conversion directly. 12009 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12010 if (Subtarget.hasDirectMove()) { 12011 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12012 .addReg(SrcReg); 12013 } else { 12014 // Use stack to do the register copy. 12015 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12016 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12017 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12018 if (RC == &PPC::F8RCRegClass) { 12019 // Copy register from F8RCRegClass to G8RCRegclass. 12020 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12021 "Unsupported RegClass."); 12022 12023 StoreOp = PPC::STFD; 12024 LoadOp = PPC::LD; 12025 } else { 12026 // Copy register from G8RCRegClass to F8RCRegclass. 12027 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12028 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12029 "Unsupported RegClass."); 12030 } 12031 12032 MachineFrameInfo &MFI = F->getFrameInfo(); 12033 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12034 12035 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12036 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12037 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12038 MFI.getObjectAlign(FrameIdx)); 12039 12040 // Store the SrcReg into the stack. 12041 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12042 .addReg(SrcReg) 12043 .addImm(0) 12044 .addFrameIndex(FrameIdx) 12045 .addMemOperand(MMOStore); 12046 12047 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12048 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12049 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12050 MFI.getObjectAlign(FrameIdx)); 12051 12052 // Load from the stack where SrcReg is stored, and save to DestReg, 12053 // so we have done the RegClass conversion from RegClass::SrcReg to 12054 // RegClass::DestReg. 12055 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12056 .addImm(0) 12057 .addFrameIndex(FrameIdx) 12058 .addMemOperand(MMOLoad); 12059 } 12060 }; 12061 12062 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12063 12064 // Save FPSCR value. 12065 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12066 12067 // When the operand is gprc register, use two least significant bits of the 12068 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12069 // 12070 // copy OldFPSCRTmpReg, OldFPSCRReg 12071 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12072 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12073 // copy NewFPSCRReg, NewFPSCRTmpReg 12074 // mtfsf 255, NewFPSCRReg 12075 MachineOperand SrcOp = MI.getOperand(1); 12076 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12077 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12078 12079 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12080 12081 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12082 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12083 12084 // The first operand of INSERT_SUBREG should be a register which has 12085 // subregisters, we only care about its RegClass, so we should use an 12086 // IMPLICIT_DEF register. 12087 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12088 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12089 .addReg(ImDefReg) 12090 .add(SrcOp) 12091 .addImm(1); 12092 12093 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12094 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12095 .addReg(OldFPSCRTmpReg) 12096 .addReg(ExtSrcReg) 12097 .addImm(0) 12098 .addImm(62); 12099 12100 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12101 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12102 12103 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12104 // bits of FPSCR. 12105 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12106 .addImm(255) 12107 .addReg(NewFPSCRReg) 12108 .addImm(0) 12109 .addImm(0); 12110 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12111 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12112 return emitProbedAlloca(MI, BB); 12113 } else { 12114 llvm_unreachable("Unexpected instr type to insert"); 12115 } 12116 12117 MI.eraseFromParent(); // The pseudo instruction is gone now. 12118 return BB; 12119 } 12120 12121 //===----------------------------------------------------------------------===// 12122 // Target Optimization Hooks 12123 //===----------------------------------------------------------------------===// 12124 12125 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12126 // For the estimates, convergence is quadratic, so we essentially double the 12127 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12128 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12129 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12130 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12131 if (VT.getScalarType() == MVT::f64) 12132 RefinementSteps++; 12133 return RefinementSteps; 12134 } 12135 12136 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12137 int Enabled, int &RefinementSteps, 12138 bool &UseOneConstNR, 12139 bool Reciprocal) const { 12140 EVT VT = Operand.getValueType(); 12141 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12142 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12143 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12144 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12145 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12146 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12147 12148 // The Newton-Raphson computation with a single constant does not provide 12149 // enough accuracy on some CPUs. 12150 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12151 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12152 } 12153 return SDValue(); 12154 } 12155 12156 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12157 int Enabled, 12158 int &RefinementSteps) const { 12159 EVT VT = Operand.getValueType(); 12160 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12161 (VT == MVT::f64 && Subtarget.hasFRE()) || 12162 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12163 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12164 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12165 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12166 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12167 } 12168 return SDValue(); 12169 } 12170 12171 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12172 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12173 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12174 // enabled for division), this functionality is redundant with the default 12175 // combiner logic (once the division -> reciprocal/multiply transformation 12176 // has taken place). As a result, this matters more for older cores than for 12177 // newer ones. 12178 12179 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12180 // reciprocal if there are two or more FDIVs (for embedded cores with only 12181 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12182 switch (Subtarget.getCPUDirective()) { 12183 default: 12184 return 3; 12185 case PPC::DIR_440: 12186 case PPC::DIR_A2: 12187 case PPC::DIR_E500: 12188 case PPC::DIR_E500mc: 12189 case PPC::DIR_E5500: 12190 return 2; 12191 } 12192 } 12193 12194 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12195 // collapsed, and so we need to look through chains of them. 12196 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12197 int64_t& Offset, SelectionDAG &DAG) { 12198 if (DAG.isBaseWithConstantOffset(Loc)) { 12199 Base = Loc.getOperand(0); 12200 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12201 12202 // The base might itself be a base plus an offset, and if so, accumulate 12203 // that as well. 12204 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12205 } 12206 } 12207 12208 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12209 unsigned Bytes, int Dist, 12210 SelectionDAG &DAG) { 12211 if (VT.getSizeInBits() / 8 != Bytes) 12212 return false; 12213 12214 SDValue BaseLoc = Base->getBasePtr(); 12215 if (Loc.getOpcode() == ISD::FrameIndex) { 12216 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12217 return false; 12218 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12219 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12220 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12221 int FS = MFI.getObjectSize(FI); 12222 int BFS = MFI.getObjectSize(BFI); 12223 if (FS != BFS || FS != (int)Bytes) return false; 12224 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12225 } 12226 12227 SDValue Base1 = Loc, Base2 = BaseLoc; 12228 int64_t Offset1 = 0, Offset2 = 0; 12229 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12230 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12231 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12232 return true; 12233 12234 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12235 const GlobalValue *GV1 = nullptr; 12236 const GlobalValue *GV2 = nullptr; 12237 Offset1 = 0; 12238 Offset2 = 0; 12239 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12240 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12241 if (isGA1 && isGA2 && GV1 == GV2) 12242 return Offset1 == (Offset2 + Dist*Bytes); 12243 return false; 12244 } 12245 12246 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12247 // not enforce equality of the chain operands. 12248 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12249 unsigned Bytes, int Dist, 12250 SelectionDAG &DAG) { 12251 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12252 EVT VT = LS->getMemoryVT(); 12253 SDValue Loc = LS->getBasePtr(); 12254 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12255 } 12256 12257 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12258 EVT VT; 12259 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12260 default: return false; 12261 case Intrinsic::ppc_altivec_lvx: 12262 case Intrinsic::ppc_altivec_lvxl: 12263 case Intrinsic::ppc_vsx_lxvw4x: 12264 case Intrinsic::ppc_vsx_lxvw4x_be: 12265 VT = MVT::v4i32; 12266 break; 12267 case Intrinsic::ppc_vsx_lxvd2x: 12268 case Intrinsic::ppc_vsx_lxvd2x_be: 12269 VT = MVT::v2f64; 12270 break; 12271 case Intrinsic::ppc_altivec_lvebx: 12272 VT = MVT::i8; 12273 break; 12274 case Intrinsic::ppc_altivec_lvehx: 12275 VT = MVT::i16; 12276 break; 12277 case Intrinsic::ppc_altivec_lvewx: 12278 VT = MVT::i32; 12279 break; 12280 } 12281 12282 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12283 } 12284 12285 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12286 EVT VT; 12287 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12288 default: return false; 12289 case Intrinsic::ppc_altivec_stvx: 12290 case Intrinsic::ppc_altivec_stvxl: 12291 case Intrinsic::ppc_vsx_stxvw4x: 12292 VT = MVT::v4i32; 12293 break; 12294 case Intrinsic::ppc_vsx_stxvd2x: 12295 VT = MVT::v2f64; 12296 break; 12297 case Intrinsic::ppc_vsx_stxvw4x_be: 12298 VT = MVT::v4i32; 12299 break; 12300 case Intrinsic::ppc_vsx_stxvd2x_be: 12301 VT = MVT::v2f64; 12302 break; 12303 case Intrinsic::ppc_altivec_stvebx: 12304 VT = MVT::i8; 12305 break; 12306 case Intrinsic::ppc_altivec_stvehx: 12307 VT = MVT::i16; 12308 break; 12309 case Intrinsic::ppc_altivec_stvewx: 12310 VT = MVT::i32; 12311 break; 12312 } 12313 12314 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12315 } 12316 12317 return false; 12318 } 12319 12320 // Return true is there is a nearyby consecutive load to the one provided 12321 // (regardless of alignment). We search up and down the chain, looking though 12322 // token factors and other loads (but nothing else). As a result, a true result 12323 // indicates that it is safe to create a new consecutive load adjacent to the 12324 // load provided. 12325 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12326 SDValue Chain = LD->getChain(); 12327 EVT VT = LD->getMemoryVT(); 12328 12329 SmallSet<SDNode *, 16> LoadRoots; 12330 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12331 SmallSet<SDNode *, 16> Visited; 12332 12333 // First, search up the chain, branching to follow all token-factor operands. 12334 // If we find a consecutive load, then we're done, otherwise, record all 12335 // nodes just above the top-level loads and token factors. 12336 while (!Queue.empty()) { 12337 SDNode *ChainNext = Queue.pop_back_val(); 12338 if (!Visited.insert(ChainNext).second) 12339 continue; 12340 12341 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12342 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12343 return true; 12344 12345 if (!Visited.count(ChainLD->getChain().getNode())) 12346 Queue.push_back(ChainLD->getChain().getNode()); 12347 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12348 for (const SDUse &O : ChainNext->ops()) 12349 if (!Visited.count(O.getNode())) 12350 Queue.push_back(O.getNode()); 12351 } else 12352 LoadRoots.insert(ChainNext); 12353 } 12354 12355 // Second, search down the chain, starting from the top-level nodes recorded 12356 // in the first phase. These top-level nodes are the nodes just above all 12357 // loads and token factors. Starting with their uses, recursively look though 12358 // all loads (just the chain uses) and token factors to find a consecutive 12359 // load. 12360 Visited.clear(); 12361 Queue.clear(); 12362 12363 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12364 IE = LoadRoots.end(); I != IE; ++I) { 12365 Queue.push_back(*I); 12366 12367 while (!Queue.empty()) { 12368 SDNode *LoadRoot = Queue.pop_back_val(); 12369 if (!Visited.insert(LoadRoot).second) 12370 continue; 12371 12372 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12373 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12374 return true; 12375 12376 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12377 UE = LoadRoot->use_end(); UI != UE; ++UI) 12378 if (((isa<MemSDNode>(*UI) && 12379 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12380 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12381 Queue.push_back(*UI); 12382 } 12383 } 12384 12385 return false; 12386 } 12387 12388 /// This function is called when we have proved that a SETCC node can be replaced 12389 /// by subtraction (and other supporting instructions) so that the result of 12390 /// comparison is kept in a GPR instead of CR. This function is purely for 12391 /// codegen purposes and has some flags to guide the codegen process. 12392 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12393 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12394 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12395 12396 // Zero extend the operands to the largest legal integer. Originally, they 12397 // must be of a strictly smaller size. 12398 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12399 DAG.getConstant(Size, DL, MVT::i32)); 12400 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12401 DAG.getConstant(Size, DL, MVT::i32)); 12402 12403 // Swap if needed. Depends on the condition code. 12404 if (Swap) 12405 std::swap(Op0, Op1); 12406 12407 // Subtract extended integers. 12408 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12409 12410 // Move the sign bit to the least significant position and zero out the rest. 12411 // Now the least significant bit carries the result of original comparison. 12412 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12413 DAG.getConstant(Size - 1, DL, MVT::i32)); 12414 auto Final = Shifted; 12415 12416 // Complement the result if needed. Based on the condition code. 12417 if (Complement) 12418 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12419 DAG.getConstant(1, DL, MVT::i64)); 12420 12421 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12422 } 12423 12424 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12425 DAGCombinerInfo &DCI) const { 12426 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12427 12428 SelectionDAG &DAG = DCI.DAG; 12429 SDLoc DL(N); 12430 12431 // Size of integers being compared has a critical role in the following 12432 // analysis, so we prefer to do this when all types are legal. 12433 if (!DCI.isAfterLegalizeDAG()) 12434 return SDValue(); 12435 12436 // If all users of SETCC extend its value to a legal integer type 12437 // then we replace SETCC with a subtraction 12438 for (SDNode::use_iterator UI = N->use_begin(), 12439 UE = N->use_end(); UI != UE; ++UI) { 12440 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12441 return SDValue(); 12442 } 12443 12444 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12445 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12446 12447 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12448 12449 if (OpSize < Size) { 12450 switch (CC) { 12451 default: break; 12452 case ISD::SETULT: 12453 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12454 case ISD::SETULE: 12455 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12456 case ISD::SETUGT: 12457 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12458 case ISD::SETUGE: 12459 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12460 } 12461 } 12462 12463 return SDValue(); 12464 } 12465 12466 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12467 DAGCombinerInfo &DCI) const { 12468 SelectionDAG &DAG = DCI.DAG; 12469 SDLoc dl(N); 12470 12471 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12472 // If we're tracking CR bits, we need to be careful that we don't have: 12473 // trunc(binary-ops(zext(x), zext(y))) 12474 // or 12475 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12476 // such that we're unnecessarily moving things into GPRs when it would be 12477 // better to keep them in CR bits. 12478 12479 // Note that trunc here can be an actual i1 trunc, or can be the effective 12480 // truncation that comes from a setcc or select_cc. 12481 if (N->getOpcode() == ISD::TRUNCATE && 12482 N->getValueType(0) != MVT::i1) 12483 return SDValue(); 12484 12485 if (N->getOperand(0).getValueType() != MVT::i32 && 12486 N->getOperand(0).getValueType() != MVT::i64) 12487 return SDValue(); 12488 12489 if (N->getOpcode() == ISD::SETCC || 12490 N->getOpcode() == ISD::SELECT_CC) { 12491 // If we're looking at a comparison, then we need to make sure that the 12492 // high bits (all except for the first) don't matter the result. 12493 ISD::CondCode CC = 12494 cast<CondCodeSDNode>(N->getOperand( 12495 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12496 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12497 12498 if (ISD::isSignedIntSetCC(CC)) { 12499 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12500 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12501 return SDValue(); 12502 } else if (ISD::isUnsignedIntSetCC(CC)) { 12503 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12504 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12505 !DAG.MaskedValueIsZero(N->getOperand(1), 12506 APInt::getHighBitsSet(OpBits, OpBits-1))) 12507 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12508 : SDValue()); 12509 } else { 12510 // This is neither a signed nor an unsigned comparison, just make sure 12511 // that the high bits are equal. 12512 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12513 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12514 12515 // We don't really care about what is known about the first bit (if 12516 // anything), so clear it in all masks prior to comparing them. 12517 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12518 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12519 12520 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12521 return SDValue(); 12522 } 12523 } 12524 12525 // We now know that the higher-order bits are irrelevant, we just need to 12526 // make sure that all of the intermediate operations are bit operations, and 12527 // all inputs are extensions. 12528 if (N->getOperand(0).getOpcode() != ISD::AND && 12529 N->getOperand(0).getOpcode() != ISD::OR && 12530 N->getOperand(0).getOpcode() != ISD::XOR && 12531 N->getOperand(0).getOpcode() != ISD::SELECT && 12532 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12533 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12534 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12535 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12536 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12537 return SDValue(); 12538 12539 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12540 N->getOperand(1).getOpcode() != ISD::AND && 12541 N->getOperand(1).getOpcode() != ISD::OR && 12542 N->getOperand(1).getOpcode() != ISD::XOR && 12543 N->getOperand(1).getOpcode() != ISD::SELECT && 12544 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12545 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12546 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12547 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12548 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12549 return SDValue(); 12550 12551 SmallVector<SDValue, 4> Inputs; 12552 SmallVector<SDValue, 8> BinOps, PromOps; 12553 SmallPtrSet<SDNode *, 16> Visited; 12554 12555 for (unsigned i = 0; i < 2; ++i) { 12556 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12557 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12558 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12559 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12560 isa<ConstantSDNode>(N->getOperand(i))) 12561 Inputs.push_back(N->getOperand(i)); 12562 else 12563 BinOps.push_back(N->getOperand(i)); 12564 12565 if (N->getOpcode() == ISD::TRUNCATE) 12566 break; 12567 } 12568 12569 // Visit all inputs, collect all binary operations (and, or, xor and 12570 // select) that are all fed by extensions. 12571 while (!BinOps.empty()) { 12572 SDValue BinOp = BinOps.back(); 12573 BinOps.pop_back(); 12574 12575 if (!Visited.insert(BinOp.getNode()).second) 12576 continue; 12577 12578 PromOps.push_back(BinOp); 12579 12580 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12581 // The condition of the select is not promoted. 12582 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12583 continue; 12584 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12585 continue; 12586 12587 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12588 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12589 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12590 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12591 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12592 Inputs.push_back(BinOp.getOperand(i)); 12593 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12594 BinOp.getOperand(i).getOpcode() == ISD::OR || 12595 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12596 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12597 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12598 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12599 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12600 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12601 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12602 BinOps.push_back(BinOp.getOperand(i)); 12603 } else { 12604 // We have an input that is not an extension or another binary 12605 // operation; we'll abort this transformation. 12606 return SDValue(); 12607 } 12608 } 12609 } 12610 12611 // Make sure that this is a self-contained cluster of operations (which 12612 // is not quite the same thing as saying that everything has only one 12613 // use). 12614 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12615 if (isa<ConstantSDNode>(Inputs[i])) 12616 continue; 12617 12618 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12619 UE = Inputs[i].getNode()->use_end(); 12620 UI != UE; ++UI) { 12621 SDNode *User = *UI; 12622 if (User != N && !Visited.count(User)) 12623 return SDValue(); 12624 12625 // Make sure that we're not going to promote the non-output-value 12626 // operand(s) or SELECT or SELECT_CC. 12627 // FIXME: Although we could sometimes handle this, and it does occur in 12628 // practice that one of the condition inputs to the select is also one of 12629 // the outputs, we currently can't deal with this. 12630 if (User->getOpcode() == ISD::SELECT) { 12631 if (User->getOperand(0) == Inputs[i]) 12632 return SDValue(); 12633 } else if (User->getOpcode() == ISD::SELECT_CC) { 12634 if (User->getOperand(0) == Inputs[i] || 12635 User->getOperand(1) == Inputs[i]) 12636 return SDValue(); 12637 } 12638 } 12639 } 12640 12641 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12642 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12643 UE = PromOps[i].getNode()->use_end(); 12644 UI != UE; ++UI) { 12645 SDNode *User = *UI; 12646 if (User != N && !Visited.count(User)) 12647 return SDValue(); 12648 12649 // Make sure that we're not going to promote the non-output-value 12650 // operand(s) or SELECT or SELECT_CC. 12651 // FIXME: Although we could sometimes handle this, and it does occur in 12652 // practice that one of the condition inputs to the select is also one of 12653 // the outputs, we currently can't deal with this. 12654 if (User->getOpcode() == ISD::SELECT) { 12655 if (User->getOperand(0) == PromOps[i]) 12656 return SDValue(); 12657 } else if (User->getOpcode() == ISD::SELECT_CC) { 12658 if (User->getOperand(0) == PromOps[i] || 12659 User->getOperand(1) == PromOps[i]) 12660 return SDValue(); 12661 } 12662 } 12663 } 12664 12665 // Replace all inputs with the extension operand. 12666 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12667 // Constants may have users outside the cluster of to-be-promoted nodes, 12668 // and so we need to replace those as we do the promotions. 12669 if (isa<ConstantSDNode>(Inputs[i])) 12670 continue; 12671 else 12672 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12673 } 12674 12675 std::list<HandleSDNode> PromOpHandles; 12676 for (auto &PromOp : PromOps) 12677 PromOpHandles.emplace_back(PromOp); 12678 12679 // Replace all operations (these are all the same, but have a different 12680 // (i1) return type). DAG.getNode will validate that the types of 12681 // a binary operator match, so go through the list in reverse so that 12682 // we've likely promoted both operands first. Any intermediate truncations or 12683 // extensions disappear. 12684 while (!PromOpHandles.empty()) { 12685 SDValue PromOp = PromOpHandles.back().getValue(); 12686 PromOpHandles.pop_back(); 12687 12688 if (PromOp.getOpcode() == ISD::TRUNCATE || 12689 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12690 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12691 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12692 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12693 PromOp.getOperand(0).getValueType() != MVT::i1) { 12694 // The operand is not yet ready (see comment below). 12695 PromOpHandles.emplace_front(PromOp); 12696 continue; 12697 } 12698 12699 SDValue RepValue = PromOp.getOperand(0); 12700 if (isa<ConstantSDNode>(RepValue)) 12701 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12702 12703 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12704 continue; 12705 } 12706 12707 unsigned C; 12708 switch (PromOp.getOpcode()) { 12709 default: C = 0; break; 12710 case ISD::SELECT: C = 1; break; 12711 case ISD::SELECT_CC: C = 2; break; 12712 } 12713 12714 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12715 PromOp.getOperand(C).getValueType() != MVT::i1) || 12716 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12717 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12718 // The to-be-promoted operands of this node have not yet been 12719 // promoted (this should be rare because we're going through the 12720 // list backward, but if one of the operands has several users in 12721 // this cluster of to-be-promoted nodes, it is possible). 12722 PromOpHandles.emplace_front(PromOp); 12723 continue; 12724 } 12725 12726 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12727 PromOp.getNode()->op_end()); 12728 12729 // If there are any constant inputs, make sure they're replaced now. 12730 for (unsigned i = 0; i < 2; ++i) 12731 if (isa<ConstantSDNode>(Ops[C+i])) 12732 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12733 12734 DAG.ReplaceAllUsesOfValueWith(PromOp, 12735 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12736 } 12737 12738 // Now we're left with the initial truncation itself. 12739 if (N->getOpcode() == ISD::TRUNCATE) 12740 return N->getOperand(0); 12741 12742 // Otherwise, this is a comparison. The operands to be compared have just 12743 // changed type (to i1), but everything else is the same. 12744 return SDValue(N, 0); 12745 } 12746 12747 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12748 DAGCombinerInfo &DCI) const { 12749 SelectionDAG &DAG = DCI.DAG; 12750 SDLoc dl(N); 12751 12752 // If we're tracking CR bits, we need to be careful that we don't have: 12753 // zext(binary-ops(trunc(x), trunc(y))) 12754 // or 12755 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12756 // such that we're unnecessarily moving things into CR bits that can more 12757 // efficiently stay in GPRs. Note that if we're not certain that the high 12758 // bits are set as required by the final extension, we still may need to do 12759 // some masking to get the proper behavior. 12760 12761 // This same functionality is important on PPC64 when dealing with 12762 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12763 // the return values of functions. Because it is so similar, it is handled 12764 // here as well. 12765 12766 if (N->getValueType(0) != MVT::i32 && 12767 N->getValueType(0) != MVT::i64) 12768 return SDValue(); 12769 12770 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12771 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12772 return SDValue(); 12773 12774 if (N->getOperand(0).getOpcode() != ISD::AND && 12775 N->getOperand(0).getOpcode() != ISD::OR && 12776 N->getOperand(0).getOpcode() != ISD::XOR && 12777 N->getOperand(0).getOpcode() != ISD::SELECT && 12778 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12779 return SDValue(); 12780 12781 SmallVector<SDValue, 4> Inputs; 12782 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12783 SmallPtrSet<SDNode *, 16> Visited; 12784 12785 // Visit all inputs, collect all binary operations (and, or, xor and 12786 // select) that are all fed by truncations. 12787 while (!BinOps.empty()) { 12788 SDValue BinOp = BinOps.back(); 12789 BinOps.pop_back(); 12790 12791 if (!Visited.insert(BinOp.getNode()).second) 12792 continue; 12793 12794 PromOps.push_back(BinOp); 12795 12796 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12797 // The condition of the select is not promoted. 12798 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12799 continue; 12800 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12801 continue; 12802 12803 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12804 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12805 Inputs.push_back(BinOp.getOperand(i)); 12806 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12807 BinOp.getOperand(i).getOpcode() == ISD::OR || 12808 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12809 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12810 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12811 BinOps.push_back(BinOp.getOperand(i)); 12812 } else { 12813 // We have an input that is not a truncation or another binary 12814 // operation; we'll abort this transformation. 12815 return SDValue(); 12816 } 12817 } 12818 } 12819 12820 // The operands of a select that must be truncated when the select is 12821 // promoted because the operand is actually part of the to-be-promoted set. 12822 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12823 12824 // Make sure that this is a self-contained cluster of operations (which 12825 // is not quite the same thing as saying that everything has only one 12826 // use). 12827 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12828 if (isa<ConstantSDNode>(Inputs[i])) 12829 continue; 12830 12831 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12832 UE = Inputs[i].getNode()->use_end(); 12833 UI != UE; ++UI) { 12834 SDNode *User = *UI; 12835 if (User != N && !Visited.count(User)) 12836 return SDValue(); 12837 12838 // If we're going to promote the non-output-value operand(s) or SELECT or 12839 // SELECT_CC, record them for truncation. 12840 if (User->getOpcode() == ISD::SELECT) { 12841 if (User->getOperand(0) == Inputs[i]) 12842 SelectTruncOp[0].insert(std::make_pair(User, 12843 User->getOperand(0).getValueType())); 12844 } else if (User->getOpcode() == ISD::SELECT_CC) { 12845 if (User->getOperand(0) == Inputs[i]) 12846 SelectTruncOp[0].insert(std::make_pair(User, 12847 User->getOperand(0).getValueType())); 12848 if (User->getOperand(1) == Inputs[i]) 12849 SelectTruncOp[1].insert(std::make_pair(User, 12850 User->getOperand(1).getValueType())); 12851 } 12852 } 12853 } 12854 12855 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12856 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12857 UE = PromOps[i].getNode()->use_end(); 12858 UI != UE; ++UI) { 12859 SDNode *User = *UI; 12860 if (User != N && !Visited.count(User)) 12861 return SDValue(); 12862 12863 // If we're going to promote the non-output-value operand(s) or SELECT or 12864 // SELECT_CC, record them for truncation. 12865 if (User->getOpcode() == ISD::SELECT) { 12866 if (User->getOperand(0) == PromOps[i]) 12867 SelectTruncOp[0].insert(std::make_pair(User, 12868 User->getOperand(0).getValueType())); 12869 } else if (User->getOpcode() == ISD::SELECT_CC) { 12870 if (User->getOperand(0) == PromOps[i]) 12871 SelectTruncOp[0].insert(std::make_pair(User, 12872 User->getOperand(0).getValueType())); 12873 if (User->getOperand(1) == PromOps[i]) 12874 SelectTruncOp[1].insert(std::make_pair(User, 12875 User->getOperand(1).getValueType())); 12876 } 12877 } 12878 } 12879 12880 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12881 bool ReallyNeedsExt = false; 12882 if (N->getOpcode() != ISD::ANY_EXTEND) { 12883 // If all of the inputs are not already sign/zero extended, then 12884 // we'll still need to do that at the end. 12885 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12886 if (isa<ConstantSDNode>(Inputs[i])) 12887 continue; 12888 12889 unsigned OpBits = 12890 Inputs[i].getOperand(0).getValueSizeInBits(); 12891 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12892 12893 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12894 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12895 APInt::getHighBitsSet(OpBits, 12896 OpBits-PromBits))) || 12897 (N->getOpcode() == ISD::SIGN_EXTEND && 12898 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12899 (OpBits-(PromBits-1)))) { 12900 ReallyNeedsExt = true; 12901 break; 12902 } 12903 } 12904 } 12905 12906 // Replace all inputs, either with the truncation operand, or a 12907 // truncation or extension to the final output type. 12908 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12909 // Constant inputs need to be replaced with the to-be-promoted nodes that 12910 // use them because they might have users outside of the cluster of 12911 // promoted nodes. 12912 if (isa<ConstantSDNode>(Inputs[i])) 12913 continue; 12914 12915 SDValue InSrc = Inputs[i].getOperand(0); 12916 if (Inputs[i].getValueType() == N->getValueType(0)) 12917 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12918 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12919 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12920 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12921 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12922 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12923 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12924 else 12925 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12926 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12927 } 12928 12929 std::list<HandleSDNode> PromOpHandles; 12930 for (auto &PromOp : PromOps) 12931 PromOpHandles.emplace_back(PromOp); 12932 12933 // Replace all operations (these are all the same, but have a different 12934 // (promoted) return type). DAG.getNode will validate that the types of 12935 // a binary operator match, so go through the list in reverse so that 12936 // we've likely promoted both operands first. 12937 while (!PromOpHandles.empty()) { 12938 SDValue PromOp = PromOpHandles.back().getValue(); 12939 PromOpHandles.pop_back(); 12940 12941 unsigned C; 12942 switch (PromOp.getOpcode()) { 12943 default: C = 0; break; 12944 case ISD::SELECT: C = 1; break; 12945 case ISD::SELECT_CC: C = 2; break; 12946 } 12947 12948 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12949 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12950 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12951 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12952 // The to-be-promoted operands of this node have not yet been 12953 // promoted (this should be rare because we're going through the 12954 // list backward, but if one of the operands has several users in 12955 // this cluster of to-be-promoted nodes, it is possible). 12956 PromOpHandles.emplace_front(PromOp); 12957 continue; 12958 } 12959 12960 // For SELECT and SELECT_CC nodes, we do a similar check for any 12961 // to-be-promoted comparison inputs. 12962 if (PromOp.getOpcode() == ISD::SELECT || 12963 PromOp.getOpcode() == ISD::SELECT_CC) { 12964 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12965 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12966 (SelectTruncOp[1].count(PromOp.getNode()) && 12967 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12968 PromOpHandles.emplace_front(PromOp); 12969 continue; 12970 } 12971 } 12972 12973 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12974 PromOp.getNode()->op_end()); 12975 12976 // If this node has constant inputs, then they'll need to be promoted here. 12977 for (unsigned i = 0; i < 2; ++i) { 12978 if (!isa<ConstantSDNode>(Ops[C+i])) 12979 continue; 12980 if (Ops[C+i].getValueType() == N->getValueType(0)) 12981 continue; 12982 12983 if (N->getOpcode() == ISD::SIGN_EXTEND) 12984 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12985 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12986 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12987 else 12988 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12989 } 12990 12991 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12992 // truncate them again to the original value type. 12993 if (PromOp.getOpcode() == ISD::SELECT || 12994 PromOp.getOpcode() == ISD::SELECT_CC) { 12995 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12996 if (SI0 != SelectTruncOp[0].end()) 12997 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12998 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12999 if (SI1 != SelectTruncOp[1].end()) 13000 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13001 } 13002 13003 DAG.ReplaceAllUsesOfValueWith(PromOp, 13004 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13005 } 13006 13007 // Now we're left with the initial extension itself. 13008 if (!ReallyNeedsExt) 13009 return N->getOperand(0); 13010 13011 // To zero extend, just mask off everything except for the first bit (in the 13012 // i1 case). 13013 if (N->getOpcode() == ISD::ZERO_EXTEND) 13014 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13015 DAG.getConstant(APInt::getLowBitsSet( 13016 N->getValueSizeInBits(0), PromBits), 13017 dl, N->getValueType(0))); 13018 13019 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13020 "Invalid extension type"); 13021 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13022 SDValue ShiftCst = 13023 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13024 return DAG.getNode( 13025 ISD::SRA, dl, N->getValueType(0), 13026 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13027 ShiftCst); 13028 } 13029 13030 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13031 DAGCombinerInfo &DCI) const { 13032 assert(N->getOpcode() == ISD::SETCC && 13033 "Should be called with a SETCC node"); 13034 13035 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13036 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13037 SDValue LHS = N->getOperand(0); 13038 SDValue RHS = N->getOperand(1); 13039 13040 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13041 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13042 LHS.hasOneUse()) 13043 std::swap(LHS, RHS); 13044 13045 // x == 0-y --> x+y == 0 13046 // x != 0-y --> x+y != 0 13047 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13048 RHS.hasOneUse()) { 13049 SDLoc DL(N); 13050 SelectionDAG &DAG = DCI.DAG; 13051 EVT VT = N->getValueType(0); 13052 EVT OpVT = LHS.getValueType(); 13053 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13054 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13055 } 13056 } 13057 13058 return DAGCombineTruncBoolExt(N, DCI); 13059 } 13060 13061 // Is this an extending load from an f32 to an f64? 13062 static bool isFPExtLoad(SDValue Op) { 13063 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13064 return LD->getExtensionType() == ISD::EXTLOAD && 13065 Op.getValueType() == MVT::f64; 13066 return false; 13067 } 13068 13069 /// Reduces the number of fp-to-int conversion when building a vector. 13070 /// 13071 /// If this vector is built out of floating to integer conversions, 13072 /// transform it to a vector built out of floating point values followed by a 13073 /// single floating to integer conversion of the vector. 13074 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13075 /// becomes (fptosi (build_vector ($A, $B, ...))) 13076 SDValue PPCTargetLowering:: 13077 combineElementTruncationToVectorTruncation(SDNode *N, 13078 DAGCombinerInfo &DCI) const { 13079 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13080 "Should be called with a BUILD_VECTOR node"); 13081 13082 SelectionDAG &DAG = DCI.DAG; 13083 SDLoc dl(N); 13084 13085 SDValue FirstInput = N->getOperand(0); 13086 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13087 "The input operand must be an fp-to-int conversion."); 13088 13089 // This combine happens after legalization so the fp_to_[su]i nodes are 13090 // already converted to PPCSISD nodes. 13091 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13092 if (FirstConversion == PPCISD::FCTIDZ || 13093 FirstConversion == PPCISD::FCTIDUZ || 13094 FirstConversion == PPCISD::FCTIWZ || 13095 FirstConversion == PPCISD::FCTIWUZ) { 13096 bool IsSplat = true; 13097 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13098 FirstConversion == PPCISD::FCTIWUZ; 13099 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13100 SmallVector<SDValue, 4> Ops; 13101 EVT TargetVT = N->getValueType(0); 13102 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13103 SDValue NextOp = N->getOperand(i); 13104 if (NextOp.getOpcode() != PPCISD::MFVSR) 13105 return SDValue(); 13106 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13107 if (NextConversion != FirstConversion) 13108 return SDValue(); 13109 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13110 // This is not valid if the input was originally double precision. It is 13111 // also not profitable to do unless this is an extending load in which 13112 // case doing this combine will allow us to combine consecutive loads. 13113 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13114 return SDValue(); 13115 if (N->getOperand(i) != FirstInput) 13116 IsSplat = false; 13117 } 13118 13119 // If this is a splat, we leave it as-is since there will be only a single 13120 // fp-to-int conversion followed by a splat of the integer. This is better 13121 // for 32-bit and smaller ints and neutral for 64-bit ints. 13122 if (IsSplat) 13123 return SDValue(); 13124 13125 // Now that we know we have the right type of node, get its operands 13126 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13127 SDValue In = N->getOperand(i).getOperand(0); 13128 if (Is32Bit) { 13129 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13130 // here, we know that all inputs are extending loads so this is safe). 13131 if (In.isUndef()) 13132 Ops.push_back(DAG.getUNDEF(SrcVT)); 13133 else { 13134 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13135 MVT::f32, In.getOperand(0), 13136 DAG.getIntPtrConstant(1, dl)); 13137 Ops.push_back(Trunc); 13138 } 13139 } else 13140 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13141 } 13142 13143 unsigned Opcode; 13144 if (FirstConversion == PPCISD::FCTIDZ || 13145 FirstConversion == PPCISD::FCTIWZ) 13146 Opcode = ISD::FP_TO_SINT; 13147 else 13148 Opcode = ISD::FP_TO_UINT; 13149 13150 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13151 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13152 return DAG.getNode(Opcode, dl, TargetVT, BV); 13153 } 13154 return SDValue(); 13155 } 13156 13157 /// Reduce the number of loads when building a vector. 13158 /// 13159 /// Building a vector out of multiple loads can be converted to a load 13160 /// of the vector type if the loads are consecutive. If the loads are 13161 /// consecutive but in descending order, a shuffle is added at the end 13162 /// to reorder the vector. 13163 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13164 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13165 "Should be called with a BUILD_VECTOR node"); 13166 13167 SDLoc dl(N); 13168 13169 // Return early for non byte-sized type, as they can't be consecutive. 13170 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13171 return SDValue(); 13172 13173 bool InputsAreConsecutiveLoads = true; 13174 bool InputsAreReverseConsecutive = true; 13175 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13176 SDValue FirstInput = N->getOperand(0); 13177 bool IsRoundOfExtLoad = false; 13178 13179 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13180 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13181 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13182 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13183 } 13184 // Not a build vector of (possibly fp_rounded) loads. 13185 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13186 N->getNumOperands() == 1) 13187 return SDValue(); 13188 13189 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13190 // If any inputs are fp_round(extload), they all must be. 13191 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13192 return SDValue(); 13193 13194 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13195 N->getOperand(i); 13196 if (NextInput.getOpcode() != ISD::LOAD) 13197 return SDValue(); 13198 13199 SDValue PreviousInput = 13200 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13201 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13202 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13203 13204 // If any inputs are fp_round(extload), they all must be. 13205 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13206 return SDValue(); 13207 13208 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13209 InputsAreConsecutiveLoads = false; 13210 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13211 InputsAreReverseConsecutive = false; 13212 13213 // Exit early if the loads are neither consecutive nor reverse consecutive. 13214 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13215 return SDValue(); 13216 } 13217 13218 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13219 "The loads cannot be both consecutive and reverse consecutive."); 13220 13221 SDValue FirstLoadOp = 13222 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13223 SDValue LastLoadOp = 13224 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13225 N->getOperand(N->getNumOperands()-1); 13226 13227 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13228 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13229 if (InputsAreConsecutiveLoads) { 13230 assert(LD1 && "Input needs to be a LoadSDNode."); 13231 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13232 LD1->getBasePtr(), LD1->getPointerInfo(), 13233 LD1->getAlignment()); 13234 } 13235 if (InputsAreReverseConsecutive) { 13236 assert(LDL && "Input needs to be a LoadSDNode."); 13237 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13238 LDL->getBasePtr(), LDL->getPointerInfo(), 13239 LDL->getAlignment()); 13240 SmallVector<int, 16> Ops; 13241 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13242 Ops.push_back(i); 13243 13244 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13245 DAG.getUNDEF(N->getValueType(0)), Ops); 13246 } 13247 return SDValue(); 13248 } 13249 13250 // This function adds the required vector_shuffle needed to get 13251 // the elements of the vector extract in the correct position 13252 // as specified by the CorrectElems encoding. 13253 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13254 SDValue Input, uint64_t Elems, 13255 uint64_t CorrectElems) { 13256 SDLoc dl(N); 13257 13258 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13259 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13260 13261 // Knowing the element indices being extracted from the original 13262 // vector and the order in which they're being inserted, just put 13263 // them at element indices required for the instruction. 13264 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13265 if (DAG.getDataLayout().isLittleEndian()) 13266 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13267 else 13268 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13269 CorrectElems = CorrectElems >> 8; 13270 Elems = Elems >> 8; 13271 } 13272 13273 SDValue Shuffle = 13274 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13275 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13276 13277 EVT VT = N->getValueType(0); 13278 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13279 13280 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13281 Input.getValueType().getVectorElementType(), 13282 VT.getVectorNumElements()); 13283 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13284 DAG.getValueType(ExtVT)); 13285 } 13286 13287 // Look for build vector patterns where input operands come from sign 13288 // extended vector_extract elements of specific indices. If the correct indices 13289 // aren't used, add a vector shuffle to fix up the indices and create 13290 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13291 // during instruction selection. 13292 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13293 // This array encodes the indices that the vector sign extend instructions 13294 // extract from when extending from one type to another for both BE and LE. 13295 // The right nibble of each byte corresponds to the LE incides. 13296 // and the left nibble of each byte corresponds to the BE incides. 13297 // For example: 0x3074B8FC byte->word 13298 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13299 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13300 // For example: 0x000070F8 byte->double word 13301 // For LE: the allowed indices are: 0x0,0x8 13302 // For BE: the allowed indices are: 0x7,0xF 13303 uint64_t TargetElems[] = { 13304 0x3074B8FC, // b->w 13305 0x000070F8, // b->d 13306 0x10325476, // h->w 13307 0x00003074, // h->d 13308 0x00001032, // w->d 13309 }; 13310 13311 uint64_t Elems = 0; 13312 int Index; 13313 SDValue Input; 13314 13315 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13316 if (!Op) 13317 return false; 13318 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13319 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13320 return false; 13321 13322 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13323 // of the right width. 13324 SDValue Extract = Op.getOperand(0); 13325 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13326 Extract = Extract.getOperand(0); 13327 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13328 return false; 13329 13330 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13331 if (!ExtOp) 13332 return false; 13333 13334 Index = ExtOp->getZExtValue(); 13335 if (Input && Input != Extract.getOperand(0)) 13336 return false; 13337 13338 if (!Input) 13339 Input = Extract.getOperand(0); 13340 13341 Elems = Elems << 8; 13342 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13343 Elems |= Index; 13344 13345 return true; 13346 }; 13347 13348 // If the build vector operands aren't sign extended vector extracts, 13349 // of the same input vector, then return. 13350 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13351 if (!isSExtOfVecExtract(N->getOperand(i))) { 13352 return SDValue(); 13353 } 13354 } 13355 13356 // If the vector extract indicies are not correct, add the appropriate 13357 // vector_shuffle. 13358 int TgtElemArrayIdx; 13359 int InputSize = Input.getValueType().getScalarSizeInBits(); 13360 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13361 if (InputSize + OutputSize == 40) 13362 TgtElemArrayIdx = 0; 13363 else if (InputSize + OutputSize == 72) 13364 TgtElemArrayIdx = 1; 13365 else if (InputSize + OutputSize == 48) 13366 TgtElemArrayIdx = 2; 13367 else if (InputSize + OutputSize == 80) 13368 TgtElemArrayIdx = 3; 13369 else if (InputSize + OutputSize == 96) 13370 TgtElemArrayIdx = 4; 13371 else 13372 return SDValue(); 13373 13374 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13375 CorrectElems = DAG.getDataLayout().isLittleEndian() 13376 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13377 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13378 if (Elems != CorrectElems) { 13379 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13380 } 13381 13382 // Regular lowering will catch cases where a shuffle is not needed. 13383 return SDValue(); 13384 } 13385 13386 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13387 DAGCombinerInfo &DCI) const { 13388 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13389 "Should be called with a BUILD_VECTOR node"); 13390 13391 SelectionDAG &DAG = DCI.DAG; 13392 SDLoc dl(N); 13393 13394 if (!Subtarget.hasVSX()) 13395 return SDValue(); 13396 13397 // The target independent DAG combiner will leave a build_vector of 13398 // float-to-int conversions intact. We can generate MUCH better code for 13399 // a float-to-int conversion of a vector of floats. 13400 SDValue FirstInput = N->getOperand(0); 13401 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13402 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13403 if (Reduced) 13404 return Reduced; 13405 } 13406 13407 // If we're building a vector out of consecutive loads, just load that 13408 // vector type. 13409 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13410 if (Reduced) 13411 return Reduced; 13412 13413 // If we're building a vector out of extended elements from another vector 13414 // we have P9 vector integer extend instructions. The code assumes legal 13415 // input types (i.e. it can't handle things like v4i16) so do not run before 13416 // legalization. 13417 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13418 Reduced = combineBVOfVecSExt(N, DAG); 13419 if (Reduced) 13420 return Reduced; 13421 } 13422 13423 13424 if (N->getValueType(0) != MVT::v2f64) 13425 return SDValue(); 13426 13427 // Looking for: 13428 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13429 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13430 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13431 return SDValue(); 13432 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13433 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13434 return SDValue(); 13435 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13436 return SDValue(); 13437 13438 SDValue Ext1 = FirstInput.getOperand(0); 13439 SDValue Ext2 = N->getOperand(1).getOperand(0); 13440 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13441 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13442 return SDValue(); 13443 13444 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13445 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13446 if (!Ext1Op || !Ext2Op) 13447 return SDValue(); 13448 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13449 Ext1.getOperand(0) != Ext2.getOperand(0)) 13450 return SDValue(); 13451 13452 int FirstElem = Ext1Op->getZExtValue(); 13453 int SecondElem = Ext2Op->getZExtValue(); 13454 int SubvecIdx; 13455 if (FirstElem == 0 && SecondElem == 1) 13456 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13457 else if (FirstElem == 2 && SecondElem == 3) 13458 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13459 else 13460 return SDValue(); 13461 13462 SDValue SrcVec = Ext1.getOperand(0); 13463 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13464 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13465 return DAG.getNode(NodeType, dl, MVT::v2f64, 13466 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13467 } 13468 13469 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13470 DAGCombinerInfo &DCI) const { 13471 assert((N->getOpcode() == ISD::SINT_TO_FP || 13472 N->getOpcode() == ISD::UINT_TO_FP) && 13473 "Need an int -> FP conversion node here"); 13474 13475 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13476 return SDValue(); 13477 13478 SelectionDAG &DAG = DCI.DAG; 13479 SDLoc dl(N); 13480 SDValue Op(N, 0); 13481 13482 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13483 // from the hardware. 13484 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13485 return SDValue(); 13486 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13487 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13488 return SDValue(); 13489 13490 SDValue FirstOperand(Op.getOperand(0)); 13491 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13492 (FirstOperand.getValueType() == MVT::i8 || 13493 FirstOperand.getValueType() == MVT::i16); 13494 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13495 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13496 bool DstDouble = Op.getValueType() == MVT::f64; 13497 unsigned ConvOp = Signed ? 13498 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13499 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13500 SDValue WidthConst = 13501 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13502 dl, false); 13503 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13504 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13505 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13506 DAG.getVTList(MVT::f64, MVT::Other), 13507 Ops, MVT::i8, LDN->getMemOperand()); 13508 13509 // For signed conversion, we need to sign-extend the value in the VSR 13510 if (Signed) { 13511 SDValue ExtOps[] = { Ld, WidthConst }; 13512 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13513 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13514 } else 13515 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13516 } 13517 13518 13519 // For i32 intermediate values, unfortunately, the conversion functions 13520 // leave the upper 32 bits of the value are undefined. Within the set of 13521 // scalar instructions, we have no method for zero- or sign-extending the 13522 // value. Thus, we cannot handle i32 intermediate values here. 13523 if (Op.getOperand(0).getValueType() == MVT::i32) 13524 return SDValue(); 13525 13526 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13527 "UINT_TO_FP is supported only with FPCVT"); 13528 13529 // If we have FCFIDS, then use it when converting to single-precision. 13530 // Otherwise, convert to double-precision and then round. 13531 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13532 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13533 : PPCISD::FCFIDS) 13534 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13535 : PPCISD::FCFID); 13536 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13537 ? MVT::f32 13538 : MVT::f64; 13539 13540 // If we're converting from a float, to an int, and back to a float again, 13541 // then we don't need the store/load pair at all. 13542 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13543 Subtarget.hasFPCVT()) || 13544 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13545 SDValue Src = Op.getOperand(0).getOperand(0); 13546 if (Src.getValueType() == MVT::f32) { 13547 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13548 DCI.AddToWorklist(Src.getNode()); 13549 } else if (Src.getValueType() != MVT::f64) { 13550 // Make sure that we don't pick up a ppc_fp128 source value. 13551 return SDValue(); 13552 } 13553 13554 unsigned FCTOp = 13555 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13556 PPCISD::FCTIDUZ; 13557 13558 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13559 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13560 13561 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13562 FP = DAG.getNode(ISD::FP_ROUND, dl, 13563 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13564 DCI.AddToWorklist(FP.getNode()); 13565 } 13566 13567 return FP; 13568 } 13569 13570 return SDValue(); 13571 } 13572 13573 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13574 // builtins) into loads with swaps. 13575 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13576 DAGCombinerInfo &DCI) const { 13577 SelectionDAG &DAG = DCI.DAG; 13578 SDLoc dl(N); 13579 SDValue Chain; 13580 SDValue Base; 13581 MachineMemOperand *MMO; 13582 13583 switch (N->getOpcode()) { 13584 default: 13585 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13586 case ISD::LOAD: { 13587 LoadSDNode *LD = cast<LoadSDNode>(N); 13588 Chain = LD->getChain(); 13589 Base = LD->getBasePtr(); 13590 MMO = LD->getMemOperand(); 13591 // If the MMO suggests this isn't a load of a full vector, leave 13592 // things alone. For a built-in, we have to make the change for 13593 // correctness, so if there is a size problem that will be a bug. 13594 if (MMO->getSize() < 16) 13595 return SDValue(); 13596 break; 13597 } 13598 case ISD::INTRINSIC_W_CHAIN: { 13599 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13600 Chain = Intrin->getChain(); 13601 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13602 // us what we want. Get operand 2 instead. 13603 Base = Intrin->getOperand(2); 13604 MMO = Intrin->getMemOperand(); 13605 break; 13606 } 13607 } 13608 13609 MVT VecTy = N->getValueType(0).getSimpleVT(); 13610 13611 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13612 // aligned and the type is a vector with elements up to 4 bytes 13613 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13614 VecTy.getScalarSizeInBits() <= 32) { 13615 return SDValue(); 13616 } 13617 13618 SDValue LoadOps[] = { Chain, Base }; 13619 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13620 DAG.getVTList(MVT::v2f64, MVT::Other), 13621 LoadOps, MVT::v2f64, MMO); 13622 13623 DCI.AddToWorklist(Load.getNode()); 13624 Chain = Load.getValue(1); 13625 SDValue Swap = DAG.getNode( 13626 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13627 DCI.AddToWorklist(Swap.getNode()); 13628 13629 // Add a bitcast if the resulting load type doesn't match v2f64. 13630 if (VecTy != MVT::v2f64) { 13631 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13632 DCI.AddToWorklist(N.getNode()); 13633 // Package {bitcast value, swap's chain} to match Load's shape. 13634 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13635 N, Swap.getValue(1)); 13636 } 13637 13638 return Swap; 13639 } 13640 13641 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13642 // builtins) into stores with swaps. 13643 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13644 DAGCombinerInfo &DCI) const { 13645 SelectionDAG &DAG = DCI.DAG; 13646 SDLoc dl(N); 13647 SDValue Chain; 13648 SDValue Base; 13649 unsigned SrcOpnd; 13650 MachineMemOperand *MMO; 13651 13652 switch (N->getOpcode()) { 13653 default: 13654 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13655 case ISD::STORE: { 13656 StoreSDNode *ST = cast<StoreSDNode>(N); 13657 Chain = ST->getChain(); 13658 Base = ST->getBasePtr(); 13659 MMO = ST->getMemOperand(); 13660 SrcOpnd = 1; 13661 // If the MMO suggests this isn't a store of a full vector, leave 13662 // things alone. For a built-in, we have to make the change for 13663 // correctness, so if there is a size problem that will be a bug. 13664 if (MMO->getSize() < 16) 13665 return SDValue(); 13666 break; 13667 } 13668 case ISD::INTRINSIC_VOID: { 13669 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13670 Chain = Intrin->getChain(); 13671 // Intrin->getBasePtr() oddly does not get what we want. 13672 Base = Intrin->getOperand(3); 13673 MMO = Intrin->getMemOperand(); 13674 SrcOpnd = 2; 13675 break; 13676 } 13677 } 13678 13679 SDValue Src = N->getOperand(SrcOpnd); 13680 MVT VecTy = Src.getValueType().getSimpleVT(); 13681 13682 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13683 // aligned and the type is a vector with elements up to 4 bytes 13684 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13685 VecTy.getScalarSizeInBits() <= 32) { 13686 return SDValue(); 13687 } 13688 13689 // All stores are done as v2f64 and possible bit cast. 13690 if (VecTy != MVT::v2f64) { 13691 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13692 DCI.AddToWorklist(Src.getNode()); 13693 } 13694 13695 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13696 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13697 DCI.AddToWorklist(Swap.getNode()); 13698 Chain = Swap.getValue(1); 13699 SDValue StoreOps[] = { Chain, Swap, Base }; 13700 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13701 DAG.getVTList(MVT::Other), 13702 StoreOps, VecTy, MMO); 13703 DCI.AddToWorklist(Store.getNode()); 13704 return Store; 13705 } 13706 13707 // Handle DAG combine for STORE (FP_TO_INT F). 13708 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13709 DAGCombinerInfo &DCI) const { 13710 13711 SelectionDAG &DAG = DCI.DAG; 13712 SDLoc dl(N); 13713 unsigned Opcode = N->getOperand(1).getOpcode(); 13714 13715 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13716 && "Not a FP_TO_INT Instruction!"); 13717 13718 SDValue Val = N->getOperand(1).getOperand(0); 13719 EVT Op1VT = N->getOperand(1).getValueType(); 13720 EVT ResVT = Val.getValueType(); 13721 13722 // Floating point types smaller than 32 bits are not legal on Power. 13723 if (ResVT.getScalarSizeInBits() < 32) 13724 return SDValue(); 13725 13726 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13727 bool ValidTypeForStoreFltAsInt = 13728 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13729 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13730 13731 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13732 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13733 return SDValue(); 13734 13735 // Extend f32 values to f64 13736 if (ResVT.getScalarSizeInBits() == 32) { 13737 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13738 DCI.AddToWorklist(Val.getNode()); 13739 } 13740 13741 // Set signed or unsigned conversion opcode. 13742 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13743 PPCISD::FP_TO_SINT_IN_VSR : 13744 PPCISD::FP_TO_UINT_IN_VSR; 13745 13746 Val = DAG.getNode(ConvOpcode, 13747 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13748 DCI.AddToWorklist(Val.getNode()); 13749 13750 // Set number of bytes being converted. 13751 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13752 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13753 DAG.getIntPtrConstant(ByteSize, dl, false), 13754 DAG.getValueType(Op1VT) }; 13755 13756 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13757 DAG.getVTList(MVT::Other), Ops, 13758 cast<StoreSDNode>(N)->getMemoryVT(), 13759 cast<StoreSDNode>(N)->getMemOperand()); 13760 13761 DCI.AddToWorklist(Val.getNode()); 13762 return Val; 13763 } 13764 13765 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 13766 // Check that the source of the element keeps flipping 13767 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 13768 bool PrevElemFromFirstVec = Mask[0] < NumElts; 13769 for (int i = 1, e = Mask.size(); i < e; i++) { 13770 if (PrevElemFromFirstVec && Mask[i] < NumElts) 13771 return false; 13772 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 13773 return false; 13774 PrevElemFromFirstVec = !PrevElemFromFirstVec; 13775 } 13776 return true; 13777 } 13778 13779 static bool isSplatBV(SDValue Op) { 13780 if (Op.getOpcode() != ISD::BUILD_VECTOR) 13781 return false; 13782 SDValue FirstOp; 13783 13784 // Find first non-undef input. 13785 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 13786 FirstOp = Op.getOperand(i); 13787 if (!FirstOp.isUndef()) 13788 break; 13789 } 13790 13791 // All inputs are undef or the same as the first non-undef input. 13792 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 13793 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 13794 return false; 13795 return true; 13796 } 13797 13798 static SDValue isScalarToVec(SDValue Op) { 13799 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13800 return Op; 13801 if (Op.getOpcode() != ISD::BITCAST) 13802 return SDValue(); 13803 Op = Op.getOperand(0); 13804 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13805 return Op; 13806 return SDValue(); 13807 } 13808 13809 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 13810 int LHSMaxIdx, int RHSMinIdx, 13811 int RHSMaxIdx, int HalfVec) { 13812 for (int i = 0, e = ShuffV.size(); i < e; i++) { 13813 int Idx = ShuffV[i]; 13814 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 13815 ShuffV[i] += HalfVec; 13816 } 13817 return; 13818 } 13819 13820 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 13821 // the original is: 13822 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 13823 // In such a case, just change the shuffle mask to extract the element 13824 // from the permuted index. 13825 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 13826 SDLoc dl(OrigSToV); 13827 EVT VT = OrigSToV.getValueType(); 13828 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 13829 "Expecting a SCALAR_TO_VECTOR here"); 13830 SDValue Input = OrigSToV.getOperand(0); 13831 13832 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13833 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 13834 SDValue OrigVector = Input.getOperand(0); 13835 13836 // Can't handle non-const element indices or different vector types 13837 // for the input to the extract and the output of the scalar_to_vector. 13838 if (Idx && VT == OrigVector.getValueType()) { 13839 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 13840 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 13841 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 13842 } 13843 } 13844 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 13845 OrigSToV.getOperand(0)); 13846 } 13847 13848 // On little endian subtargets, combine shuffles such as: 13849 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 13850 // into: 13851 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 13852 // because the latter can be matched to a single instruction merge. 13853 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 13854 // to put the value into element zero. Adjust the shuffle mask so that the 13855 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 13856 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 13857 SelectionDAG &DAG) const { 13858 SDValue LHS = SVN->getOperand(0); 13859 SDValue RHS = SVN->getOperand(1); 13860 auto Mask = SVN->getMask(); 13861 int NumElts = LHS.getValueType().getVectorNumElements(); 13862 SDValue Res(SVN, 0); 13863 SDLoc dl(SVN); 13864 13865 // None of these combines are useful on big endian systems since the ISA 13866 // already has a big endian bias. 13867 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13868 return Res; 13869 13870 // If this is not a shuffle of a shuffle and the first element comes from 13871 // the second vector, canonicalize to the commuted form. This will make it 13872 // more likely to match one of the single instruction patterns. 13873 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 13874 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 13875 std::swap(LHS, RHS); 13876 Res = DAG.getCommutedVectorShuffle(*SVN); 13877 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 13878 } 13879 13880 // Adjust the shuffle mask if either input vector comes from a 13881 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 13882 // form (to prevent the need for a swap). 13883 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 13884 SDValue SToVLHS = isScalarToVec(LHS); 13885 SDValue SToVRHS = isScalarToVec(RHS); 13886 if (SToVLHS || SToVRHS) { 13887 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 13888 : SToVRHS.getValueType().getVectorNumElements(); 13889 int NumEltsOut = ShuffV.size(); 13890 13891 // Initially assume that neither input is permuted. These will be adjusted 13892 // accordingly if either input is. 13893 int LHSMaxIdx = -1; 13894 int RHSMinIdx = -1; 13895 int RHSMaxIdx = -1; 13896 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 13897 13898 // Get the permuted scalar to vector nodes for the source(s) that come from 13899 // ISD::SCALAR_TO_VECTOR. 13900 if (SToVLHS) { 13901 // Set up the values for the shuffle vector fixup. 13902 LHSMaxIdx = NumEltsOut / NumEltsIn; 13903 SToVLHS = getSToVPermuted(SToVLHS, DAG); 13904 if (SToVLHS.getValueType() != LHS.getValueType()) 13905 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 13906 LHS = SToVLHS; 13907 } 13908 if (SToVRHS) { 13909 RHSMinIdx = NumEltsOut; 13910 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 13911 SToVRHS = getSToVPermuted(SToVRHS, DAG); 13912 if (SToVRHS.getValueType() != RHS.getValueType()) 13913 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 13914 RHS = SToVRHS; 13915 } 13916 13917 // Fix up the shuffle mask to reflect where the desired element actually is. 13918 // The minimum and maximum indices that correspond to element zero for both 13919 // the LHS and RHS are computed and will control which shuffle mask entries 13920 // are to be changed. For example, if the RHS is permuted, any shuffle mask 13921 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 13922 // HalfVec to refer to the corresponding element in the permuted vector. 13923 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 13924 HalfVec); 13925 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 13926 13927 // We may have simplified away the shuffle. We won't be able to do anything 13928 // further with it here. 13929 if (!isa<ShuffleVectorSDNode>(Res)) 13930 return Res; 13931 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 13932 } 13933 13934 // The common case after we commuted the shuffle is that the RHS is a splat 13935 // and we have elements coming in from the splat at indices that are not 13936 // conducive to using a merge. 13937 // Example: 13938 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 13939 if (!isSplatBV(RHS)) 13940 return Res; 13941 13942 // We are looking for a mask such that all even elements are from 13943 // one vector and all odd elements from the other. 13944 if (!isAlternatingShuffMask(Mask, NumElts)) 13945 return Res; 13946 13947 // Adjust the mask so we are pulling in the same index from the splat 13948 // as the index from the interesting vector in consecutive elements. 13949 // Example (even elements from first vector): 13950 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 13951 if (Mask[0] < NumElts) 13952 for (int i = 1, e = Mask.size(); i < e; i += 2) 13953 ShuffV[i] = (ShuffV[i - 1] + NumElts); 13954 // Example (odd elements from first vector): 13955 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 13956 else 13957 for (int i = 0, e = Mask.size(); i < e; i += 2) 13958 ShuffV[i] = (ShuffV[i + 1] + NumElts); 13959 13960 // If the RHS has undefs, we need to remove them since we may have created 13961 // a shuffle that adds those instead of the splat value. 13962 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 13963 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 13964 13965 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 13966 return Res; 13967 } 13968 13969 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13970 LSBaseSDNode *LSBase, 13971 DAGCombinerInfo &DCI) const { 13972 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13973 "Not a reverse memop pattern!"); 13974 13975 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13976 auto Mask = SVN->getMask(); 13977 int i = 0; 13978 auto I = Mask.rbegin(); 13979 auto E = Mask.rend(); 13980 13981 for (; I != E; ++I) { 13982 if (*I != i) 13983 return false; 13984 i++; 13985 } 13986 return true; 13987 }; 13988 13989 SelectionDAG &DAG = DCI.DAG; 13990 EVT VT = SVN->getValueType(0); 13991 13992 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13993 return SDValue(); 13994 13995 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13996 // See comment in PPCVSXSwapRemoval.cpp. 13997 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13998 if (!Subtarget.hasP9Vector()) 13999 return SDValue(); 14000 14001 if(!IsElementReverse(SVN)) 14002 return SDValue(); 14003 14004 if (LSBase->getOpcode() == ISD::LOAD) { 14005 SDLoc dl(SVN); 14006 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14007 return DAG.getMemIntrinsicNode( 14008 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14009 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14010 } 14011 14012 if (LSBase->getOpcode() == ISD::STORE) { 14013 SDLoc dl(LSBase); 14014 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14015 LSBase->getBasePtr()}; 14016 return DAG.getMemIntrinsicNode( 14017 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14018 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14019 } 14020 14021 llvm_unreachable("Expected a load or store node here"); 14022 } 14023 14024 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14025 DAGCombinerInfo &DCI) const { 14026 SelectionDAG &DAG = DCI.DAG; 14027 SDLoc dl(N); 14028 switch (N->getOpcode()) { 14029 default: break; 14030 case ISD::ADD: 14031 return combineADD(N, DCI); 14032 case ISD::SHL: 14033 return combineSHL(N, DCI); 14034 case ISD::SRA: 14035 return combineSRA(N, DCI); 14036 case ISD::SRL: 14037 return combineSRL(N, DCI); 14038 case ISD::MUL: 14039 return combineMUL(N, DCI); 14040 case ISD::FMA: 14041 case PPCISD::FNMSUB: 14042 return combineFMALike(N, DCI); 14043 case PPCISD::SHL: 14044 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14045 return N->getOperand(0); 14046 break; 14047 case PPCISD::SRL: 14048 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14049 return N->getOperand(0); 14050 break; 14051 case PPCISD::SRA: 14052 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14053 if (C->isNullValue() || // 0 >>s V -> 0. 14054 C->isAllOnesValue()) // -1 >>s V -> -1. 14055 return N->getOperand(0); 14056 } 14057 break; 14058 case ISD::SIGN_EXTEND: 14059 case ISD::ZERO_EXTEND: 14060 case ISD::ANY_EXTEND: 14061 return DAGCombineExtBoolTrunc(N, DCI); 14062 case ISD::TRUNCATE: 14063 return combineTRUNCATE(N, DCI); 14064 case ISD::SETCC: 14065 if (SDValue CSCC = combineSetCC(N, DCI)) 14066 return CSCC; 14067 LLVM_FALLTHROUGH; 14068 case ISD::SELECT_CC: 14069 return DAGCombineTruncBoolExt(N, DCI); 14070 case ISD::SINT_TO_FP: 14071 case ISD::UINT_TO_FP: 14072 return combineFPToIntToFP(N, DCI); 14073 case ISD::VECTOR_SHUFFLE: 14074 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14075 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14076 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14077 } 14078 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14079 case ISD::STORE: { 14080 14081 EVT Op1VT = N->getOperand(1).getValueType(); 14082 unsigned Opcode = N->getOperand(1).getOpcode(); 14083 14084 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14085 SDValue Val= combineStoreFPToInt(N, DCI); 14086 if (Val) 14087 return Val; 14088 } 14089 14090 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14091 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14092 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14093 if (Val) 14094 return Val; 14095 } 14096 14097 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14098 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14099 N->getOperand(1).getNode()->hasOneUse() && 14100 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14101 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14102 14103 // STBRX can only handle simple types and it makes no sense to store less 14104 // two bytes in byte-reversed order. 14105 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14106 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14107 break; 14108 14109 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14110 // Do an any-extend to 32-bits if this is a half-word input. 14111 if (BSwapOp.getValueType() == MVT::i16) 14112 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14113 14114 // If the type of BSWAP operand is wider than stored memory width 14115 // it need to be shifted to the right side before STBRX. 14116 if (Op1VT.bitsGT(mVT)) { 14117 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14118 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14119 DAG.getConstant(Shift, dl, MVT::i32)); 14120 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14121 if (Op1VT == MVT::i64) 14122 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14123 } 14124 14125 SDValue Ops[] = { 14126 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14127 }; 14128 return 14129 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14130 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14131 cast<StoreSDNode>(N)->getMemOperand()); 14132 } 14133 14134 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14135 // So it can increase the chance of CSE constant construction. 14136 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14137 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14138 // Need to sign-extended to 64-bits to handle negative values. 14139 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14140 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14141 MemVT.getSizeInBits()); 14142 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14143 14144 // DAG.getTruncStore() can't be used here because it doesn't accept 14145 // the general (base + offset) addressing mode. 14146 // So we use UpdateNodeOperands and setTruncatingStore instead. 14147 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14148 N->getOperand(3)); 14149 cast<StoreSDNode>(N)->setTruncatingStore(true); 14150 return SDValue(N, 0); 14151 } 14152 14153 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14154 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14155 if (Op1VT.isSimple()) { 14156 MVT StoreVT = Op1VT.getSimpleVT(); 14157 if (Subtarget.needsSwapsForVSXMemOps() && 14158 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14159 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14160 return expandVSXStoreForLE(N, DCI); 14161 } 14162 break; 14163 } 14164 case ISD::LOAD: { 14165 LoadSDNode *LD = cast<LoadSDNode>(N); 14166 EVT VT = LD->getValueType(0); 14167 14168 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14169 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14170 if (VT.isSimple()) { 14171 MVT LoadVT = VT.getSimpleVT(); 14172 if (Subtarget.needsSwapsForVSXMemOps() && 14173 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14174 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14175 return expandVSXLoadForLE(N, DCI); 14176 } 14177 14178 // We sometimes end up with a 64-bit integer load, from which we extract 14179 // two single-precision floating-point numbers. This happens with 14180 // std::complex<float>, and other similar structures, because of the way we 14181 // canonicalize structure copies. However, if we lack direct moves, 14182 // then the final bitcasts from the extracted integer values to the 14183 // floating-point numbers turn into store/load pairs. Even with direct moves, 14184 // just loading the two floating-point numbers is likely better. 14185 auto ReplaceTwoFloatLoad = [&]() { 14186 if (VT != MVT::i64) 14187 return false; 14188 14189 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14190 LD->isVolatile()) 14191 return false; 14192 14193 // We're looking for a sequence like this: 14194 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14195 // t16: i64 = srl t13, Constant:i32<32> 14196 // t17: i32 = truncate t16 14197 // t18: f32 = bitcast t17 14198 // t19: i32 = truncate t13 14199 // t20: f32 = bitcast t19 14200 14201 if (!LD->hasNUsesOfValue(2, 0)) 14202 return false; 14203 14204 auto UI = LD->use_begin(); 14205 while (UI.getUse().getResNo() != 0) ++UI; 14206 SDNode *Trunc = *UI++; 14207 while (UI.getUse().getResNo() != 0) ++UI; 14208 SDNode *RightShift = *UI; 14209 if (Trunc->getOpcode() != ISD::TRUNCATE) 14210 std::swap(Trunc, RightShift); 14211 14212 if (Trunc->getOpcode() != ISD::TRUNCATE || 14213 Trunc->getValueType(0) != MVT::i32 || 14214 !Trunc->hasOneUse()) 14215 return false; 14216 if (RightShift->getOpcode() != ISD::SRL || 14217 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14218 RightShift->getConstantOperandVal(1) != 32 || 14219 !RightShift->hasOneUse()) 14220 return false; 14221 14222 SDNode *Trunc2 = *RightShift->use_begin(); 14223 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14224 Trunc2->getValueType(0) != MVT::i32 || 14225 !Trunc2->hasOneUse()) 14226 return false; 14227 14228 SDNode *Bitcast = *Trunc->use_begin(); 14229 SDNode *Bitcast2 = *Trunc2->use_begin(); 14230 14231 if (Bitcast->getOpcode() != ISD::BITCAST || 14232 Bitcast->getValueType(0) != MVT::f32) 14233 return false; 14234 if (Bitcast2->getOpcode() != ISD::BITCAST || 14235 Bitcast2->getValueType(0) != MVT::f32) 14236 return false; 14237 14238 if (Subtarget.isLittleEndian()) 14239 std::swap(Bitcast, Bitcast2); 14240 14241 // Bitcast has the second float (in memory-layout order) and Bitcast2 14242 // has the first one. 14243 14244 SDValue BasePtr = LD->getBasePtr(); 14245 if (LD->isIndexed()) { 14246 assert(LD->getAddressingMode() == ISD::PRE_INC && 14247 "Non-pre-inc AM on PPC?"); 14248 BasePtr = 14249 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14250 LD->getOffset()); 14251 } 14252 14253 auto MMOFlags = 14254 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14255 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14256 LD->getPointerInfo(), LD->getAlignment(), 14257 MMOFlags, LD->getAAInfo()); 14258 SDValue AddPtr = 14259 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14260 BasePtr, DAG.getIntPtrConstant(4, dl)); 14261 SDValue FloatLoad2 = DAG.getLoad( 14262 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14263 LD->getPointerInfo().getWithOffset(4), 14264 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14265 14266 if (LD->isIndexed()) { 14267 // Note that DAGCombine should re-form any pre-increment load(s) from 14268 // what is produced here if that makes sense. 14269 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14270 } 14271 14272 DCI.CombineTo(Bitcast2, FloatLoad); 14273 DCI.CombineTo(Bitcast, FloatLoad2); 14274 14275 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14276 SDValue(FloatLoad2.getNode(), 1)); 14277 return true; 14278 }; 14279 14280 if (ReplaceTwoFloatLoad()) 14281 return SDValue(N, 0); 14282 14283 EVT MemVT = LD->getMemoryVT(); 14284 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14285 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14286 if (LD->isUnindexed() && VT.isVector() && 14287 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14288 // P8 and later hardware should just use LOAD. 14289 !Subtarget.hasP8Vector() && 14290 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14291 VT == MVT::v4f32))) && 14292 LD->getAlign() < ABIAlignment) { 14293 // This is a type-legal unaligned Altivec load. 14294 SDValue Chain = LD->getChain(); 14295 SDValue Ptr = LD->getBasePtr(); 14296 bool isLittleEndian = Subtarget.isLittleEndian(); 14297 14298 // This implements the loading of unaligned vectors as described in 14299 // the venerable Apple Velocity Engine overview. Specifically: 14300 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14301 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14302 // 14303 // The general idea is to expand a sequence of one or more unaligned 14304 // loads into an alignment-based permutation-control instruction (lvsl 14305 // or lvsr), a series of regular vector loads (which always truncate 14306 // their input address to an aligned address), and a series of 14307 // permutations. The results of these permutations are the requested 14308 // loaded values. The trick is that the last "extra" load is not taken 14309 // from the address you might suspect (sizeof(vector) bytes after the 14310 // last requested load), but rather sizeof(vector) - 1 bytes after the 14311 // last requested vector. The point of this is to avoid a page fault if 14312 // the base address happened to be aligned. This works because if the 14313 // base address is aligned, then adding less than a full vector length 14314 // will cause the last vector in the sequence to be (re)loaded. 14315 // Otherwise, the next vector will be fetched as you might suspect was 14316 // necessary. 14317 14318 // We might be able to reuse the permutation generation from 14319 // a different base address offset from this one by an aligned amount. 14320 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14321 // optimization later. 14322 Intrinsic::ID Intr, IntrLD, IntrPerm; 14323 MVT PermCntlTy, PermTy, LDTy; 14324 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14325 : Intrinsic::ppc_altivec_lvsl; 14326 IntrLD = Intrinsic::ppc_altivec_lvx; 14327 IntrPerm = Intrinsic::ppc_altivec_vperm; 14328 PermCntlTy = MVT::v16i8; 14329 PermTy = MVT::v4i32; 14330 LDTy = MVT::v4i32; 14331 14332 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14333 14334 // Create the new MMO for the new base load. It is like the original MMO, 14335 // but represents an area in memory almost twice the vector size centered 14336 // on the original address. If the address is unaligned, we might start 14337 // reading up to (sizeof(vector)-1) bytes below the address of the 14338 // original unaligned load. 14339 MachineFunction &MF = DAG.getMachineFunction(); 14340 MachineMemOperand *BaseMMO = 14341 MF.getMachineMemOperand(LD->getMemOperand(), 14342 -(long)MemVT.getStoreSize()+1, 14343 2*MemVT.getStoreSize()-1); 14344 14345 // Create the new base load. 14346 SDValue LDXIntID = 14347 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14348 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14349 SDValue BaseLoad = 14350 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14351 DAG.getVTList(PermTy, MVT::Other), 14352 BaseLoadOps, LDTy, BaseMMO); 14353 14354 // Note that the value of IncOffset (which is provided to the next 14355 // load's pointer info offset value, and thus used to calculate the 14356 // alignment), and the value of IncValue (which is actually used to 14357 // increment the pointer value) are different! This is because we 14358 // require the next load to appear to be aligned, even though it 14359 // is actually offset from the base pointer by a lesser amount. 14360 int IncOffset = VT.getSizeInBits() / 8; 14361 int IncValue = IncOffset; 14362 14363 // Walk (both up and down) the chain looking for another load at the real 14364 // (aligned) offset (the alignment of the other load does not matter in 14365 // this case). If found, then do not use the offset reduction trick, as 14366 // that will prevent the loads from being later combined (as they would 14367 // otherwise be duplicates). 14368 if (!findConsecutiveLoad(LD, DAG)) 14369 --IncValue; 14370 14371 SDValue Increment = 14372 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14373 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14374 14375 MachineMemOperand *ExtraMMO = 14376 MF.getMachineMemOperand(LD->getMemOperand(), 14377 1, 2*MemVT.getStoreSize()-1); 14378 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14379 SDValue ExtraLoad = 14380 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14381 DAG.getVTList(PermTy, MVT::Other), 14382 ExtraLoadOps, LDTy, ExtraMMO); 14383 14384 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14385 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14386 14387 // Because vperm has a big-endian bias, we must reverse the order 14388 // of the input vectors and complement the permute control vector 14389 // when generating little endian code. We have already handled the 14390 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14391 // and ExtraLoad here. 14392 SDValue Perm; 14393 if (isLittleEndian) 14394 Perm = BuildIntrinsicOp(IntrPerm, 14395 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14396 else 14397 Perm = BuildIntrinsicOp(IntrPerm, 14398 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14399 14400 if (VT != PermTy) 14401 Perm = Subtarget.hasAltivec() 14402 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14403 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14404 DAG.getTargetConstant(1, dl, MVT::i64)); 14405 // second argument is 1 because this rounding 14406 // is always exact. 14407 14408 // The output of the permutation is our loaded result, the TokenFactor is 14409 // our new chain. 14410 DCI.CombineTo(N, Perm, TF); 14411 return SDValue(N, 0); 14412 } 14413 } 14414 break; 14415 case ISD::INTRINSIC_WO_CHAIN: { 14416 bool isLittleEndian = Subtarget.isLittleEndian(); 14417 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14418 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14419 : Intrinsic::ppc_altivec_lvsl); 14420 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14421 SDValue Add = N->getOperand(1); 14422 14423 int Bits = 4 /* 16 byte alignment */; 14424 14425 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14426 APInt::getAllOnesValue(Bits /* alignment */) 14427 .zext(Add.getScalarValueSizeInBits()))) { 14428 SDNode *BasePtr = Add->getOperand(0).getNode(); 14429 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14430 UE = BasePtr->use_end(); 14431 UI != UE; ++UI) { 14432 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14433 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14434 IID) { 14435 // We've found another LVSL/LVSR, and this address is an aligned 14436 // multiple of that one. The results will be the same, so use the 14437 // one we've just found instead. 14438 14439 return SDValue(*UI, 0); 14440 } 14441 } 14442 } 14443 14444 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14445 SDNode *BasePtr = Add->getOperand(0).getNode(); 14446 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14447 UE = BasePtr->use_end(); UI != UE; ++UI) { 14448 if (UI->getOpcode() == ISD::ADD && 14449 isa<ConstantSDNode>(UI->getOperand(1)) && 14450 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14451 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14452 (1ULL << Bits) == 0) { 14453 SDNode *OtherAdd = *UI; 14454 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14455 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14456 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14457 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14458 return SDValue(*VI, 0); 14459 } 14460 } 14461 } 14462 } 14463 } 14464 } 14465 14466 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14467 // Expose the vabsduw/h/b opportunity for down stream 14468 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14469 (IID == Intrinsic::ppc_altivec_vmaxsw || 14470 IID == Intrinsic::ppc_altivec_vmaxsh || 14471 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14472 SDValue V1 = N->getOperand(1); 14473 SDValue V2 = N->getOperand(2); 14474 if ((V1.getSimpleValueType() == MVT::v4i32 || 14475 V1.getSimpleValueType() == MVT::v8i16 || 14476 V1.getSimpleValueType() == MVT::v16i8) && 14477 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14478 // (0-a, a) 14479 if (V1.getOpcode() == ISD::SUB && 14480 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14481 V1.getOperand(1) == V2) { 14482 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14483 } 14484 // (a, 0-a) 14485 if (V2.getOpcode() == ISD::SUB && 14486 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14487 V2.getOperand(1) == V1) { 14488 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14489 } 14490 // (x-y, y-x) 14491 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14492 V1.getOperand(0) == V2.getOperand(1) && 14493 V1.getOperand(1) == V2.getOperand(0)) { 14494 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14495 } 14496 } 14497 } 14498 } 14499 14500 break; 14501 case ISD::INTRINSIC_W_CHAIN: 14502 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14503 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14504 if (Subtarget.needsSwapsForVSXMemOps()) { 14505 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14506 default: 14507 break; 14508 case Intrinsic::ppc_vsx_lxvw4x: 14509 case Intrinsic::ppc_vsx_lxvd2x: 14510 return expandVSXLoadForLE(N, DCI); 14511 } 14512 } 14513 break; 14514 case ISD::INTRINSIC_VOID: 14515 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14516 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14517 if (Subtarget.needsSwapsForVSXMemOps()) { 14518 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14519 default: 14520 break; 14521 case Intrinsic::ppc_vsx_stxvw4x: 14522 case Intrinsic::ppc_vsx_stxvd2x: 14523 return expandVSXStoreForLE(N, DCI); 14524 } 14525 } 14526 break; 14527 case ISD::BSWAP: 14528 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14529 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14530 N->getOperand(0).hasOneUse() && 14531 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14532 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14533 N->getValueType(0) == MVT::i64))) { 14534 SDValue Load = N->getOperand(0); 14535 LoadSDNode *LD = cast<LoadSDNode>(Load); 14536 // Create the byte-swapping load. 14537 SDValue Ops[] = { 14538 LD->getChain(), // Chain 14539 LD->getBasePtr(), // Ptr 14540 DAG.getValueType(N->getValueType(0)) // VT 14541 }; 14542 SDValue BSLoad = 14543 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14544 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14545 MVT::i64 : MVT::i32, MVT::Other), 14546 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14547 14548 // If this is an i16 load, insert the truncate. 14549 SDValue ResVal = BSLoad; 14550 if (N->getValueType(0) == MVT::i16) 14551 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14552 14553 // First, combine the bswap away. This makes the value produced by the 14554 // load dead. 14555 DCI.CombineTo(N, ResVal); 14556 14557 // Next, combine the load away, we give it a bogus result value but a real 14558 // chain result. The result value is dead because the bswap is dead. 14559 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14560 14561 // Return N so it doesn't get rechecked! 14562 return SDValue(N, 0); 14563 } 14564 break; 14565 case PPCISD::VCMP: 14566 // If a VCMPo node already exists with exactly the same operands as this 14567 // node, use its result instead of this node (VCMPo computes both a CR6 and 14568 // a normal output). 14569 // 14570 if (!N->getOperand(0).hasOneUse() && 14571 !N->getOperand(1).hasOneUse() && 14572 !N->getOperand(2).hasOneUse()) { 14573 14574 // Scan all of the users of the LHS, looking for VCMPo's that match. 14575 SDNode *VCMPoNode = nullptr; 14576 14577 SDNode *LHSN = N->getOperand(0).getNode(); 14578 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14579 UI != E; ++UI) 14580 if (UI->getOpcode() == PPCISD::VCMPo && 14581 UI->getOperand(1) == N->getOperand(1) && 14582 UI->getOperand(2) == N->getOperand(2) && 14583 UI->getOperand(0) == N->getOperand(0)) { 14584 VCMPoNode = *UI; 14585 break; 14586 } 14587 14588 // If there is no VCMPo node, or if the flag value has a single use, don't 14589 // transform this. 14590 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14591 break; 14592 14593 // Look at the (necessarily single) use of the flag value. If it has a 14594 // chain, this transformation is more complex. Note that multiple things 14595 // could use the value result, which we should ignore. 14596 SDNode *FlagUser = nullptr; 14597 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14598 FlagUser == nullptr; ++UI) { 14599 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14600 SDNode *User = *UI; 14601 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14602 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14603 FlagUser = User; 14604 break; 14605 } 14606 } 14607 } 14608 14609 // If the user is a MFOCRF instruction, we know this is safe. 14610 // Otherwise we give up for right now. 14611 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14612 return SDValue(VCMPoNode, 0); 14613 } 14614 break; 14615 case ISD::BRCOND: { 14616 SDValue Cond = N->getOperand(1); 14617 SDValue Target = N->getOperand(2); 14618 14619 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14620 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14621 Intrinsic::loop_decrement) { 14622 14623 // We now need to make the intrinsic dead (it cannot be instruction 14624 // selected). 14625 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14626 assert(Cond.getNode()->hasOneUse() && 14627 "Counter decrement has more than one use"); 14628 14629 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14630 N->getOperand(0), Target); 14631 } 14632 } 14633 break; 14634 case ISD::BR_CC: { 14635 // If this is a branch on an altivec predicate comparison, lower this so 14636 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14637 // lowering is done pre-legalize, because the legalizer lowers the predicate 14638 // compare down to code that is difficult to reassemble. 14639 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14640 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14641 14642 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14643 // value. If so, pass-through the AND to get to the intrinsic. 14644 if (LHS.getOpcode() == ISD::AND && 14645 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14646 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14647 Intrinsic::loop_decrement && 14648 isa<ConstantSDNode>(LHS.getOperand(1)) && 14649 !isNullConstant(LHS.getOperand(1))) 14650 LHS = LHS.getOperand(0); 14651 14652 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14653 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14654 Intrinsic::loop_decrement && 14655 isa<ConstantSDNode>(RHS)) { 14656 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14657 "Counter decrement comparison is not EQ or NE"); 14658 14659 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14660 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14661 (CC == ISD::SETNE && !Val); 14662 14663 // We now need to make the intrinsic dead (it cannot be instruction 14664 // selected). 14665 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14666 assert(LHS.getNode()->hasOneUse() && 14667 "Counter decrement has more than one use"); 14668 14669 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14670 N->getOperand(0), N->getOperand(4)); 14671 } 14672 14673 int CompareOpc; 14674 bool isDot; 14675 14676 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14677 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14678 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14679 assert(isDot && "Can't compare against a vector result!"); 14680 14681 // If this is a comparison against something other than 0/1, then we know 14682 // that the condition is never/always true. 14683 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14684 if (Val != 0 && Val != 1) { 14685 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14686 return N->getOperand(0); 14687 // Always !=, turn it into an unconditional branch. 14688 return DAG.getNode(ISD::BR, dl, MVT::Other, 14689 N->getOperand(0), N->getOperand(4)); 14690 } 14691 14692 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14693 14694 // Create the PPCISD altivec 'dot' comparison node. 14695 SDValue Ops[] = { 14696 LHS.getOperand(2), // LHS of compare 14697 LHS.getOperand(3), // RHS of compare 14698 DAG.getConstant(CompareOpc, dl, MVT::i32) 14699 }; 14700 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14701 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14702 14703 // Unpack the result based on how the target uses it. 14704 PPC::Predicate CompOpc; 14705 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14706 default: // Can't happen, don't crash on invalid number though. 14707 case 0: // Branch on the value of the EQ bit of CR6. 14708 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14709 break; 14710 case 1: // Branch on the inverted value of the EQ bit of CR6. 14711 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14712 break; 14713 case 2: // Branch on the value of the LT bit of CR6. 14714 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14715 break; 14716 case 3: // Branch on the inverted value of the LT bit of CR6. 14717 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14718 break; 14719 } 14720 14721 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14722 DAG.getConstant(CompOpc, dl, MVT::i32), 14723 DAG.getRegister(PPC::CR6, MVT::i32), 14724 N->getOperand(4), CompNode.getValue(1)); 14725 } 14726 break; 14727 } 14728 case ISD::BUILD_VECTOR: 14729 return DAGCombineBuildVector(N, DCI); 14730 case ISD::ABS: 14731 return combineABS(N, DCI); 14732 case ISD::VSELECT: 14733 return combineVSelect(N, DCI); 14734 } 14735 14736 return SDValue(); 14737 } 14738 14739 SDValue 14740 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14741 SelectionDAG &DAG, 14742 SmallVectorImpl<SDNode *> &Created) const { 14743 // fold (sdiv X, pow2) 14744 EVT VT = N->getValueType(0); 14745 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14746 return SDValue(); 14747 if ((VT != MVT::i32 && VT != MVT::i64) || 14748 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14749 return SDValue(); 14750 14751 SDLoc DL(N); 14752 SDValue N0 = N->getOperand(0); 14753 14754 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14755 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14756 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14757 14758 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14759 Created.push_back(Op.getNode()); 14760 14761 if (IsNegPow2) { 14762 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14763 Created.push_back(Op.getNode()); 14764 } 14765 14766 return Op; 14767 } 14768 14769 //===----------------------------------------------------------------------===// 14770 // Inline Assembly Support 14771 //===----------------------------------------------------------------------===// 14772 14773 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14774 KnownBits &Known, 14775 const APInt &DemandedElts, 14776 const SelectionDAG &DAG, 14777 unsigned Depth) const { 14778 Known.resetAll(); 14779 switch (Op.getOpcode()) { 14780 default: break; 14781 case PPCISD::LBRX: { 14782 // lhbrx is known to have the top bits cleared out. 14783 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14784 Known.Zero = 0xFFFF0000; 14785 break; 14786 } 14787 case ISD::INTRINSIC_WO_CHAIN: { 14788 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14789 default: break; 14790 case Intrinsic::ppc_altivec_vcmpbfp_p: 14791 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14792 case Intrinsic::ppc_altivec_vcmpequb_p: 14793 case Intrinsic::ppc_altivec_vcmpequh_p: 14794 case Intrinsic::ppc_altivec_vcmpequw_p: 14795 case Intrinsic::ppc_altivec_vcmpequd_p: 14796 case Intrinsic::ppc_altivec_vcmpgefp_p: 14797 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14798 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14799 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14800 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14801 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14802 case Intrinsic::ppc_altivec_vcmpgtub_p: 14803 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14804 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14805 case Intrinsic::ppc_altivec_vcmpgtud_p: 14806 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14807 break; 14808 } 14809 } 14810 } 14811 } 14812 14813 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14814 switch (Subtarget.getCPUDirective()) { 14815 default: break; 14816 case PPC::DIR_970: 14817 case PPC::DIR_PWR4: 14818 case PPC::DIR_PWR5: 14819 case PPC::DIR_PWR5X: 14820 case PPC::DIR_PWR6: 14821 case PPC::DIR_PWR6X: 14822 case PPC::DIR_PWR7: 14823 case PPC::DIR_PWR8: 14824 case PPC::DIR_PWR9: 14825 case PPC::DIR_PWR10: 14826 case PPC::DIR_PWR_FUTURE: { 14827 if (!ML) 14828 break; 14829 14830 if (!DisableInnermostLoopAlign32) { 14831 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14832 // so that we can decrease cache misses and branch-prediction misses. 14833 // Actual alignment of the loop will depend on the hotness check and other 14834 // logic in alignBlocks. 14835 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14836 return Align(32); 14837 } 14838 14839 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14840 14841 // For small loops (between 5 and 8 instructions), align to a 32-byte 14842 // boundary so that the entire loop fits in one instruction-cache line. 14843 uint64_t LoopSize = 0; 14844 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14845 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14846 LoopSize += TII->getInstSizeInBytes(*J); 14847 if (LoopSize > 32) 14848 break; 14849 } 14850 14851 if (LoopSize > 16 && LoopSize <= 32) 14852 return Align(32); 14853 14854 break; 14855 } 14856 } 14857 14858 return TargetLowering::getPrefLoopAlignment(ML); 14859 } 14860 14861 /// getConstraintType - Given a constraint, return the type of 14862 /// constraint it is for this target. 14863 PPCTargetLowering::ConstraintType 14864 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14865 if (Constraint.size() == 1) { 14866 switch (Constraint[0]) { 14867 default: break; 14868 case 'b': 14869 case 'r': 14870 case 'f': 14871 case 'd': 14872 case 'v': 14873 case 'y': 14874 return C_RegisterClass; 14875 case 'Z': 14876 // FIXME: While Z does indicate a memory constraint, it specifically 14877 // indicates an r+r address (used in conjunction with the 'y' modifier 14878 // in the replacement string). Currently, we're forcing the base 14879 // register to be r0 in the asm printer (which is interpreted as zero) 14880 // and forming the complete address in the second register. This is 14881 // suboptimal. 14882 return C_Memory; 14883 } 14884 } else if (Constraint == "wc") { // individual CR bits. 14885 return C_RegisterClass; 14886 } else if (Constraint == "wa" || Constraint == "wd" || 14887 Constraint == "wf" || Constraint == "ws" || 14888 Constraint == "wi" || Constraint == "ww") { 14889 return C_RegisterClass; // VSX registers. 14890 } 14891 return TargetLowering::getConstraintType(Constraint); 14892 } 14893 14894 /// Examine constraint type and operand type and determine a weight value. 14895 /// This object must already have been set up with the operand type 14896 /// and the current alternative constraint selected. 14897 TargetLowering::ConstraintWeight 14898 PPCTargetLowering::getSingleConstraintMatchWeight( 14899 AsmOperandInfo &info, const char *constraint) const { 14900 ConstraintWeight weight = CW_Invalid; 14901 Value *CallOperandVal = info.CallOperandVal; 14902 // If we don't have a value, we can't do a match, 14903 // but allow it at the lowest weight. 14904 if (!CallOperandVal) 14905 return CW_Default; 14906 Type *type = CallOperandVal->getType(); 14907 14908 // Look at the constraint type. 14909 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14910 return CW_Register; // an individual CR bit. 14911 else if ((StringRef(constraint) == "wa" || 14912 StringRef(constraint) == "wd" || 14913 StringRef(constraint) == "wf") && 14914 type->isVectorTy()) 14915 return CW_Register; 14916 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14917 return CW_Register; // just hold 64-bit integers data. 14918 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14919 return CW_Register; 14920 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14921 return CW_Register; 14922 14923 switch (*constraint) { 14924 default: 14925 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14926 break; 14927 case 'b': 14928 if (type->isIntegerTy()) 14929 weight = CW_Register; 14930 break; 14931 case 'f': 14932 if (type->isFloatTy()) 14933 weight = CW_Register; 14934 break; 14935 case 'd': 14936 if (type->isDoubleTy()) 14937 weight = CW_Register; 14938 break; 14939 case 'v': 14940 if (type->isVectorTy()) 14941 weight = CW_Register; 14942 break; 14943 case 'y': 14944 weight = CW_Register; 14945 break; 14946 case 'Z': 14947 weight = CW_Memory; 14948 break; 14949 } 14950 return weight; 14951 } 14952 14953 std::pair<unsigned, const TargetRegisterClass *> 14954 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14955 StringRef Constraint, 14956 MVT VT) const { 14957 if (Constraint.size() == 1) { 14958 // GCC RS6000 Constraint Letters 14959 switch (Constraint[0]) { 14960 case 'b': // R1-R31 14961 if (VT == MVT::i64 && Subtarget.isPPC64()) 14962 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14963 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14964 case 'r': // R0-R31 14965 if (VT == MVT::i64 && Subtarget.isPPC64()) 14966 return std::make_pair(0U, &PPC::G8RCRegClass); 14967 return std::make_pair(0U, &PPC::GPRCRegClass); 14968 // 'd' and 'f' constraints are both defined to be "the floating point 14969 // registers", where one is for 32-bit and the other for 64-bit. We don't 14970 // really care overly much here so just give them all the same reg classes. 14971 case 'd': 14972 case 'f': 14973 if (Subtarget.hasSPE()) { 14974 if (VT == MVT::f32 || VT == MVT::i32) 14975 return std::make_pair(0U, &PPC::GPRCRegClass); 14976 if (VT == MVT::f64 || VT == MVT::i64) 14977 return std::make_pair(0U, &PPC::SPERCRegClass); 14978 } else { 14979 if (VT == MVT::f32 || VT == MVT::i32) 14980 return std::make_pair(0U, &PPC::F4RCRegClass); 14981 if (VT == MVT::f64 || VT == MVT::i64) 14982 return std::make_pair(0U, &PPC::F8RCRegClass); 14983 } 14984 break; 14985 case 'v': 14986 if (Subtarget.hasAltivec()) 14987 return std::make_pair(0U, &PPC::VRRCRegClass); 14988 break; 14989 case 'y': // crrc 14990 return std::make_pair(0U, &PPC::CRRCRegClass); 14991 } 14992 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14993 // An individual CR bit. 14994 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14995 } else if ((Constraint == "wa" || Constraint == "wd" || 14996 Constraint == "wf" || Constraint == "wi") && 14997 Subtarget.hasVSX()) { 14998 return std::make_pair(0U, &PPC::VSRCRegClass); 14999 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15000 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15001 return std::make_pair(0U, &PPC::VSSRCRegClass); 15002 else 15003 return std::make_pair(0U, &PPC::VSFRCRegClass); 15004 } 15005 15006 // If we name a VSX register, we can't defer to the base class because it 15007 // will not recognize the correct register (their names will be VSL{0-31} 15008 // and V{0-31} so they won't match). So we match them here. 15009 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15010 int VSNum = atoi(Constraint.data() + 3); 15011 assert(VSNum >= 0 && VSNum <= 63 && 15012 "Attempted to access a vsr out of range"); 15013 if (VSNum < 32) 15014 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15015 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15016 } 15017 std::pair<unsigned, const TargetRegisterClass *> R = 15018 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15019 15020 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15021 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15022 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15023 // register. 15024 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15025 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15026 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15027 PPC::GPRCRegClass.contains(R.first)) 15028 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15029 PPC::sub_32, &PPC::G8RCRegClass), 15030 &PPC::G8RCRegClass); 15031 15032 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15033 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15034 R.first = PPC::CR0; 15035 R.second = &PPC::CRRCRegClass; 15036 } 15037 15038 return R; 15039 } 15040 15041 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15042 /// vector. If it is invalid, don't add anything to Ops. 15043 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15044 std::string &Constraint, 15045 std::vector<SDValue>&Ops, 15046 SelectionDAG &DAG) const { 15047 SDValue Result; 15048 15049 // Only support length 1 constraints. 15050 if (Constraint.length() > 1) return; 15051 15052 char Letter = Constraint[0]; 15053 switch (Letter) { 15054 default: break; 15055 case 'I': 15056 case 'J': 15057 case 'K': 15058 case 'L': 15059 case 'M': 15060 case 'N': 15061 case 'O': 15062 case 'P': { 15063 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15064 if (!CST) return; // Must be an immediate to match. 15065 SDLoc dl(Op); 15066 int64_t Value = CST->getSExtValue(); 15067 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15068 // numbers are printed as such. 15069 switch (Letter) { 15070 default: llvm_unreachable("Unknown constraint letter!"); 15071 case 'I': // "I" is a signed 16-bit constant. 15072 if (isInt<16>(Value)) 15073 Result = DAG.getTargetConstant(Value, dl, TCVT); 15074 break; 15075 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15076 if (isShiftedUInt<16, 16>(Value)) 15077 Result = DAG.getTargetConstant(Value, dl, TCVT); 15078 break; 15079 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15080 if (isShiftedInt<16, 16>(Value)) 15081 Result = DAG.getTargetConstant(Value, dl, TCVT); 15082 break; 15083 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15084 if (isUInt<16>(Value)) 15085 Result = DAG.getTargetConstant(Value, dl, TCVT); 15086 break; 15087 case 'M': // "M" is a constant that is greater than 31. 15088 if (Value > 31) 15089 Result = DAG.getTargetConstant(Value, dl, TCVT); 15090 break; 15091 case 'N': // "N" is a positive constant that is an exact power of two. 15092 if (Value > 0 && isPowerOf2_64(Value)) 15093 Result = DAG.getTargetConstant(Value, dl, TCVT); 15094 break; 15095 case 'O': // "O" is the constant zero. 15096 if (Value == 0) 15097 Result = DAG.getTargetConstant(Value, dl, TCVT); 15098 break; 15099 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15100 if (isInt<16>(-Value)) 15101 Result = DAG.getTargetConstant(Value, dl, TCVT); 15102 break; 15103 } 15104 break; 15105 } 15106 } 15107 15108 if (Result.getNode()) { 15109 Ops.push_back(Result); 15110 return; 15111 } 15112 15113 // Handle standard constraint letters. 15114 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15115 } 15116 15117 // isLegalAddressingMode - Return true if the addressing mode represented 15118 // by AM is legal for this target, for a load/store of the specified type. 15119 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15120 const AddrMode &AM, Type *Ty, 15121 unsigned AS, Instruction *I) const { 15122 // PPC does not allow r+i addressing modes for vectors! 15123 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15124 return false; 15125 15126 // PPC allows a sign-extended 16-bit immediate field. 15127 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15128 return false; 15129 15130 // No global is ever allowed as a base. 15131 if (AM.BaseGV) 15132 return false; 15133 15134 // PPC only support r+r, 15135 switch (AM.Scale) { 15136 case 0: // "r+i" or just "i", depending on HasBaseReg. 15137 break; 15138 case 1: 15139 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15140 return false; 15141 // Otherwise we have r+r or r+i. 15142 break; 15143 case 2: 15144 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15145 return false; 15146 // Allow 2*r as r+r. 15147 break; 15148 default: 15149 // No other scales are supported. 15150 return false; 15151 } 15152 15153 return true; 15154 } 15155 15156 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15157 SelectionDAG &DAG) const { 15158 MachineFunction &MF = DAG.getMachineFunction(); 15159 MachineFrameInfo &MFI = MF.getFrameInfo(); 15160 MFI.setReturnAddressIsTaken(true); 15161 15162 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15163 return SDValue(); 15164 15165 SDLoc dl(Op); 15166 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15167 15168 // Make sure the function does not optimize away the store of the RA to 15169 // the stack. 15170 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15171 FuncInfo->setLRStoreRequired(); 15172 bool isPPC64 = Subtarget.isPPC64(); 15173 auto PtrVT = getPointerTy(MF.getDataLayout()); 15174 15175 if (Depth > 0) { 15176 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15177 SDValue Offset = 15178 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15179 isPPC64 ? MVT::i64 : MVT::i32); 15180 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15181 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15182 MachinePointerInfo()); 15183 } 15184 15185 // Just load the return address off the stack. 15186 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15187 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15188 MachinePointerInfo()); 15189 } 15190 15191 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15192 SelectionDAG &DAG) const { 15193 SDLoc dl(Op); 15194 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15195 15196 MachineFunction &MF = DAG.getMachineFunction(); 15197 MachineFrameInfo &MFI = MF.getFrameInfo(); 15198 MFI.setFrameAddressIsTaken(true); 15199 15200 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15201 bool isPPC64 = PtrVT == MVT::i64; 15202 15203 // Naked functions never have a frame pointer, and so we use r1. For all 15204 // other functions, this decision must be delayed until during PEI. 15205 unsigned FrameReg; 15206 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15207 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15208 else 15209 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15210 15211 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15212 PtrVT); 15213 while (Depth--) 15214 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15215 FrameAddr, MachinePointerInfo()); 15216 return FrameAddr; 15217 } 15218 15219 // FIXME? Maybe this could be a TableGen attribute on some registers and 15220 // this table could be generated automatically from RegInfo. 15221 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15222 const MachineFunction &MF) const { 15223 bool isPPC64 = Subtarget.isPPC64(); 15224 15225 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15226 if (!is64Bit && VT != LLT::scalar(32)) 15227 report_fatal_error("Invalid register global variable type"); 15228 15229 Register Reg = StringSwitch<Register>(RegName) 15230 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15231 .Case("r2", isPPC64 ? Register() : PPC::R2) 15232 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15233 .Default(Register()); 15234 15235 if (Reg) 15236 return Reg; 15237 report_fatal_error("Invalid register name global variable"); 15238 } 15239 15240 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15241 // 32-bit SVR4 ABI access everything as got-indirect. 15242 if (Subtarget.is32BitELFABI()) 15243 return true; 15244 15245 // AIX accesses everything indirectly through the TOC, which is similar to 15246 // the GOT. 15247 if (Subtarget.isAIXABI()) 15248 return true; 15249 15250 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15251 // If it is small or large code model, module locals are accessed 15252 // indirectly by loading their address from .toc/.got. 15253 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15254 return true; 15255 15256 // JumpTable and BlockAddress are accessed as got-indirect. 15257 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15258 return true; 15259 15260 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15261 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15262 15263 return false; 15264 } 15265 15266 bool 15267 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15268 // The PowerPC target isn't yet aware of offsets. 15269 return false; 15270 } 15271 15272 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15273 const CallInst &I, 15274 MachineFunction &MF, 15275 unsigned Intrinsic) const { 15276 switch (Intrinsic) { 15277 case Intrinsic::ppc_altivec_lvx: 15278 case Intrinsic::ppc_altivec_lvxl: 15279 case Intrinsic::ppc_altivec_lvebx: 15280 case Intrinsic::ppc_altivec_lvehx: 15281 case Intrinsic::ppc_altivec_lvewx: 15282 case Intrinsic::ppc_vsx_lxvd2x: 15283 case Intrinsic::ppc_vsx_lxvw4x: { 15284 EVT VT; 15285 switch (Intrinsic) { 15286 case Intrinsic::ppc_altivec_lvebx: 15287 VT = MVT::i8; 15288 break; 15289 case Intrinsic::ppc_altivec_lvehx: 15290 VT = MVT::i16; 15291 break; 15292 case Intrinsic::ppc_altivec_lvewx: 15293 VT = MVT::i32; 15294 break; 15295 case Intrinsic::ppc_vsx_lxvd2x: 15296 VT = MVT::v2f64; 15297 break; 15298 default: 15299 VT = MVT::v4i32; 15300 break; 15301 } 15302 15303 Info.opc = ISD::INTRINSIC_W_CHAIN; 15304 Info.memVT = VT; 15305 Info.ptrVal = I.getArgOperand(0); 15306 Info.offset = -VT.getStoreSize()+1; 15307 Info.size = 2*VT.getStoreSize()-1; 15308 Info.align = Align(1); 15309 Info.flags = MachineMemOperand::MOLoad; 15310 return true; 15311 } 15312 case Intrinsic::ppc_altivec_stvx: 15313 case Intrinsic::ppc_altivec_stvxl: 15314 case Intrinsic::ppc_altivec_stvebx: 15315 case Intrinsic::ppc_altivec_stvehx: 15316 case Intrinsic::ppc_altivec_stvewx: 15317 case Intrinsic::ppc_vsx_stxvd2x: 15318 case Intrinsic::ppc_vsx_stxvw4x: { 15319 EVT VT; 15320 switch (Intrinsic) { 15321 case Intrinsic::ppc_altivec_stvebx: 15322 VT = MVT::i8; 15323 break; 15324 case Intrinsic::ppc_altivec_stvehx: 15325 VT = MVT::i16; 15326 break; 15327 case Intrinsic::ppc_altivec_stvewx: 15328 VT = MVT::i32; 15329 break; 15330 case Intrinsic::ppc_vsx_stxvd2x: 15331 VT = MVT::v2f64; 15332 break; 15333 default: 15334 VT = MVT::v4i32; 15335 break; 15336 } 15337 15338 Info.opc = ISD::INTRINSIC_VOID; 15339 Info.memVT = VT; 15340 Info.ptrVal = I.getArgOperand(1); 15341 Info.offset = -VT.getStoreSize()+1; 15342 Info.size = 2*VT.getStoreSize()-1; 15343 Info.align = Align(1); 15344 Info.flags = MachineMemOperand::MOStore; 15345 return true; 15346 } 15347 default: 15348 break; 15349 } 15350 15351 return false; 15352 } 15353 15354 /// It returns EVT::Other if the type should be determined using generic 15355 /// target-independent logic. 15356 EVT PPCTargetLowering::getOptimalMemOpType( 15357 const MemOp &Op, const AttributeList &FuncAttributes) const { 15358 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15359 // We should use Altivec/VSX loads and stores when available. For unaligned 15360 // addresses, unaligned VSX loads are only fast starting with the P8. 15361 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15362 (Op.isAligned(Align(16)) || 15363 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15364 return MVT::v4i32; 15365 } 15366 15367 if (Subtarget.isPPC64()) { 15368 return MVT::i64; 15369 } 15370 15371 return MVT::i32; 15372 } 15373 15374 /// Returns true if it is beneficial to convert a load of a constant 15375 /// to just the constant itself. 15376 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15377 Type *Ty) const { 15378 assert(Ty->isIntegerTy()); 15379 15380 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15381 return !(BitSize == 0 || BitSize > 64); 15382 } 15383 15384 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15385 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15386 return false; 15387 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15388 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15389 return NumBits1 == 64 && NumBits2 == 32; 15390 } 15391 15392 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15393 if (!VT1.isInteger() || !VT2.isInteger()) 15394 return false; 15395 unsigned NumBits1 = VT1.getSizeInBits(); 15396 unsigned NumBits2 = VT2.getSizeInBits(); 15397 return NumBits1 == 64 && NumBits2 == 32; 15398 } 15399 15400 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15401 // Generally speaking, zexts are not free, but they are free when they can be 15402 // folded with other operations. 15403 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15404 EVT MemVT = LD->getMemoryVT(); 15405 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15406 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15407 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15408 LD->getExtensionType() == ISD::ZEXTLOAD)) 15409 return true; 15410 } 15411 15412 // FIXME: Add other cases... 15413 // - 32-bit shifts with a zext to i64 15414 // - zext after ctlz, bswap, etc. 15415 // - zext after and by a constant mask 15416 15417 return TargetLowering::isZExtFree(Val, VT2); 15418 } 15419 15420 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15421 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15422 "invalid fpext types"); 15423 // Extending to float128 is not free. 15424 if (DestVT == MVT::f128) 15425 return false; 15426 return true; 15427 } 15428 15429 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15430 return isInt<16>(Imm) || isUInt<16>(Imm); 15431 } 15432 15433 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15434 return isInt<16>(Imm) || isUInt<16>(Imm); 15435 } 15436 15437 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15438 unsigned, 15439 unsigned, 15440 MachineMemOperand::Flags, 15441 bool *Fast) const { 15442 if (DisablePPCUnaligned) 15443 return false; 15444 15445 // PowerPC supports unaligned memory access for simple non-vector types. 15446 // Although accessing unaligned addresses is not as efficient as accessing 15447 // aligned addresses, it is generally more efficient than manual expansion, 15448 // and generally only traps for software emulation when crossing page 15449 // boundaries. 15450 15451 if (!VT.isSimple()) 15452 return false; 15453 15454 if (VT.isFloatingPoint() && !VT.isVector() && 15455 !Subtarget.allowsUnalignedFPAccess()) 15456 return false; 15457 15458 if (VT.getSimpleVT().isVector()) { 15459 if (Subtarget.hasVSX()) { 15460 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15461 VT != MVT::v4f32 && VT != MVT::v4i32) 15462 return false; 15463 } else { 15464 return false; 15465 } 15466 } 15467 15468 if (VT == MVT::ppcf128) 15469 return false; 15470 15471 if (Fast) 15472 *Fast = true; 15473 15474 return true; 15475 } 15476 15477 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15478 EVT VT) const { 15479 return isFMAFasterThanFMulAndFAdd( 15480 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15481 } 15482 15483 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15484 Type *Ty) const { 15485 switch (Ty->getScalarType()->getTypeID()) { 15486 case Type::FloatTyID: 15487 case Type::DoubleTyID: 15488 return true; 15489 case Type::FP128TyID: 15490 return Subtarget.hasP9Vector(); 15491 default: 15492 return false; 15493 } 15494 } 15495 15496 // FIXME: add more patterns which are not profitable to hoist. 15497 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15498 if (!I->hasOneUse()) 15499 return true; 15500 15501 Instruction *User = I->user_back(); 15502 assert(User && "A single use instruction with no uses."); 15503 15504 switch (I->getOpcode()) { 15505 case Instruction::FMul: { 15506 // Don't break FMA, PowerPC prefers FMA. 15507 if (User->getOpcode() != Instruction::FSub && 15508 User->getOpcode() != Instruction::FAdd) 15509 return true; 15510 15511 const TargetOptions &Options = getTargetMachine().Options; 15512 const Function *F = I->getFunction(); 15513 const DataLayout &DL = F->getParent()->getDataLayout(); 15514 Type *Ty = User->getOperand(0)->getType(); 15515 15516 return !( 15517 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15518 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15519 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15520 } 15521 case Instruction::Load: { 15522 // Don't break "store (load float*)" pattern, this pattern will be combined 15523 // to "store (load int32)" in later InstCombine pass. See function 15524 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15525 // cycles than loading a 32 bit integer. 15526 LoadInst *LI = cast<LoadInst>(I); 15527 // For the loads that combineLoadToOperationType does nothing, like 15528 // ordered load, it should be profitable to hoist them. 15529 // For swifterror load, it can only be used for pointer to pointer type, so 15530 // later type check should get rid of this case. 15531 if (!LI->isUnordered()) 15532 return true; 15533 15534 if (User->getOpcode() != Instruction::Store) 15535 return true; 15536 15537 if (I->getType()->getTypeID() != Type::FloatTyID) 15538 return true; 15539 15540 return false; 15541 } 15542 default: 15543 return true; 15544 } 15545 return true; 15546 } 15547 15548 const MCPhysReg * 15549 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15550 // LR is a callee-save register, but we must treat it as clobbered by any call 15551 // site. Hence we include LR in the scratch registers, which are in turn added 15552 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15553 // to CTR, which is used by any indirect call. 15554 static const MCPhysReg ScratchRegs[] = { 15555 PPC::X12, PPC::LR8, PPC::CTR8, 0 15556 }; 15557 15558 return ScratchRegs; 15559 } 15560 15561 Register PPCTargetLowering::getExceptionPointerRegister( 15562 const Constant *PersonalityFn) const { 15563 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15564 } 15565 15566 Register PPCTargetLowering::getExceptionSelectorRegister( 15567 const Constant *PersonalityFn) const { 15568 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15569 } 15570 15571 bool 15572 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15573 EVT VT , unsigned DefinedValues) const { 15574 if (VT == MVT::v2i64) 15575 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15576 15577 if (Subtarget.hasVSX()) 15578 return true; 15579 15580 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15581 } 15582 15583 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15584 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15585 return TargetLowering::getSchedulingPreference(N); 15586 15587 return Sched::ILP; 15588 } 15589 15590 // Create a fast isel object. 15591 FastISel * 15592 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15593 const TargetLibraryInfo *LibInfo) const { 15594 return PPC::createFastISel(FuncInfo, LibInfo); 15595 } 15596 15597 // 'Inverted' means the FMA opcode after negating one multiplicand. 15598 // For example, (fma -a b c) = (fnmsub a b c) 15599 static unsigned invertFMAOpcode(unsigned Opc) { 15600 switch (Opc) { 15601 default: 15602 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15603 case ISD::FMA: 15604 return PPCISD::FNMSUB; 15605 case PPCISD::FNMSUB: 15606 return ISD::FMA; 15607 } 15608 } 15609 15610 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15611 bool LegalOps, bool OptForSize, 15612 NegatibleCost &Cost, 15613 unsigned Depth) const { 15614 if (Depth > SelectionDAG::MaxRecursionDepth) 15615 return SDValue(); 15616 15617 unsigned Opc = Op.getOpcode(); 15618 EVT VT = Op.getValueType(); 15619 SDNodeFlags Flags = Op.getNode()->getFlags(); 15620 15621 switch (Opc) { 15622 case PPCISD::FNMSUB: 15623 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15624 break; 15625 15626 const TargetOptions &Options = getTargetMachine().Options; 15627 SDValue N0 = Op.getOperand(0); 15628 SDValue N1 = Op.getOperand(1); 15629 SDValue N2 = Op.getOperand(2); 15630 SDLoc Loc(Op); 15631 15632 NegatibleCost N2Cost = NegatibleCost::Expensive; 15633 SDValue NegN2 = 15634 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15635 15636 if (!NegN2) 15637 return SDValue(); 15638 15639 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 15640 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 15641 // These transformations may change sign of zeroes. For example, 15642 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 15643 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 15644 // Try and choose the cheaper one to negate. 15645 NegatibleCost N0Cost = NegatibleCost::Expensive; 15646 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 15647 N0Cost, Depth + 1); 15648 15649 NegatibleCost N1Cost = NegatibleCost::Expensive; 15650 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 15651 N1Cost, Depth + 1); 15652 15653 if (NegN0 && N0Cost <= N1Cost) { 15654 Cost = std::min(N0Cost, N2Cost); 15655 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 15656 } else if (NegN1) { 15657 Cost = std::min(N1Cost, N2Cost); 15658 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 15659 } 15660 } 15661 15662 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 15663 if (isOperationLegal(ISD::FMA, VT)) { 15664 Cost = N2Cost; 15665 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 15666 } 15667 15668 break; 15669 } 15670 15671 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 15672 Cost, Depth); 15673 } 15674 15675 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15676 bool PPCTargetLowering::useLoadStackGuardNode() const { 15677 if (!Subtarget.isTargetLinux()) 15678 return TargetLowering::useLoadStackGuardNode(); 15679 return true; 15680 } 15681 15682 // Override to disable global variable loading on Linux. 15683 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15684 if (!Subtarget.isTargetLinux()) 15685 return TargetLowering::insertSSPDeclarations(M); 15686 } 15687 15688 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15689 bool ForCodeSize) const { 15690 if (!VT.isSimple() || !Subtarget.hasVSX()) 15691 return false; 15692 15693 switch(VT.getSimpleVT().SimpleTy) { 15694 default: 15695 // For FP types that are currently not supported by PPC backend, return 15696 // false. Examples: f16, f80. 15697 return false; 15698 case MVT::f32: 15699 case MVT::f64: 15700 if (Subtarget.hasPrefixInstrs()) { 15701 // With prefixed instructions, we can materialize anything that can be 15702 // represented with a 32-bit immediate, not just positive zero. 15703 APFloat APFloatOfImm = Imm; 15704 return convertToNonDenormSingle(APFloatOfImm); 15705 } 15706 LLVM_FALLTHROUGH; 15707 case MVT::ppcf128: 15708 return Imm.isPosZero(); 15709 } 15710 } 15711 15712 // For vector shift operation op, fold 15713 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15714 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15715 SelectionDAG &DAG) { 15716 SDValue N0 = N->getOperand(0); 15717 SDValue N1 = N->getOperand(1); 15718 EVT VT = N0.getValueType(); 15719 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15720 unsigned Opcode = N->getOpcode(); 15721 unsigned TargetOpcode; 15722 15723 switch (Opcode) { 15724 default: 15725 llvm_unreachable("Unexpected shift operation"); 15726 case ISD::SHL: 15727 TargetOpcode = PPCISD::SHL; 15728 break; 15729 case ISD::SRL: 15730 TargetOpcode = PPCISD::SRL; 15731 break; 15732 case ISD::SRA: 15733 TargetOpcode = PPCISD::SRA; 15734 break; 15735 } 15736 15737 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15738 N1->getOpcode() == ISD::AND) 15739 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15740 if (Mask->getZExtValue() == OpSizeInBits - 1) 15741 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15742 15743 return SDValue(); 15744 } 15745 15746 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15747 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15748 return Value; 15749 15750 SDValue N0 = N->getOperand(0); 15751 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15752 if (!Subtarget.isISA3_0() || 15753 N0.getOpcode() != ISD::SIGN_EXTEND || 15754 N0.getOperand(0).getValueType() != MVT::i32 || 15755 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15756 return SDValue(); 15757 15758 // We can't save an operation here if the value is already extended, and 15759 // the existing shift is easier to combine. 15760 SDValue ExtsSrc = N0.getOperand(0); 15761 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15762 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15763 return SDValue(); 15764 15765 SDLoc DL(N0); 15766 SDValue ShiftBy = SDValue(CN1, 0); 15767 // We want the shift amount to be i32 on the extswli, but the shift could 15768 // have an i64. 15769 if (ShiftBy.getValueType() == MVT::i64) 15770 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15771 15772 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15773 ShiftBy); 15774 } 15775 15776 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15777 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15778 return Value; 15779 15780 return SDValue(); 15781 } 15782 15783 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15784 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15785 return Value; 15786 15787 return SDValue(); 15788 } 15789 15790 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15791 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15792 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15793 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15794 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15795 const PPCSubtarget &Subtarget) { 15796 if (!Subtarget.isPPC64()) 15797 return SDValue(); 15798 15799 SDValue LHS = N->getOperand(0); 15800 SDValue RHS = N->getOperand(1); 15801 15802 auto isZextOfCompareWithConstant = [](SDValue Op) { 15803 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15804 Op.getValueType() != MVT::i64) 15805 return false; 15806 15807 SDValue Cmp = Op.getOperand(0); 15808 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15809 Cmp.getOperand(0).getValueType() != MVT::i64) 15810 return false; 15811 15812 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15813 int64_t NegConstant = 0 - Constant->getSExtValue(); 15814 // Due to the limitations of the addi instruction, 15815 // -C is required to be [-32768, 32767]. 15816 return isInt<16>(NegConstant); 15817 } 15818 15819 return false; 15820 }; 15821 15822 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15823 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15824 15825 // If there is a pattern, canonicalize a zext operand to the RHS. 15826 if (LHSHasPattern && !RHSHasPattern) 15827 std::swap(LHS, RHS); 15828 else if (!LHSHasPattern && !RHSHasPattern) 15829 return SDValue(); 15830 15831 SDLoc DL(N); 15832 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15833 SDValue Cmp = RHS.getOperand(0); 15834 SDValue Z = Cmp.getOperand(0); 15835 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15836 15837 assert(Constant && "Constant Should not be a null pointer."); 15838 int64_t NegConstant = 0 - Constant->getSExtValue(); 15839 15840 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15841 default: break; 15842 case ISD::SETNE: { 15843 // when C == 0 15844 // --> addze X, (addic Z, -1).carry 15845 // / 15846 // add X, (zext(setne Z, C))-- 15847 // \ when -32768 <= -C <= 32767 && C != 0 15848 // --> addze X, (addic (addi Z, -C), -1).carry 15849 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15850 DAG.getConstant(NegConstant, DL, MVT::i64)); 15851 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15852 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15853 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15854 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15855 SDValue(Addc.getNode(), 1)); 15856 } 15857 case ISD::SETEQ: { 15858 // when C == 0 15859 // --> addze X, (subfic Z, 0).carry 15860 // / 15861 // add X, (zext(sete Z, C))-- 15862 // \ when -32768 <= -C <= 32767 && C != 0 15863 // --> addze X, (subfic (addi Z, -C), 0).carry 15864 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15865 DAG.getConstant(NegConstant, DL, MVT::i64)); 15866 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15867 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15868 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15869 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15870 SDValue(Subc.getNode(), 1)); 15871 } 15872 } 15873 15874 return SDValue(); 15875 } 15876 15877 // Transform 15878 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 15879 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 15880 // In this case both C1 and C2 must be known constants. 15881 // C1+C2 must fit into a 34 bit signed integer. 15882 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 15883 const PPCSubtarget &Subtarget) { 15884 if (!Subtarget.isUsingPCRelativeCalls()) 15885 return SDValue(); 15886 15887 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 15888 // If we find that node try to cast the Global Address and the Constant. 15889 SDValue LHS = N->getOperand(0); 15890 SDValue RHS = N->getOperand(1); 15891 15892 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15893 std::swap(LHS, RHS); 15894 15895 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15896 return SDValue(); 15897 15898 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 15899 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 15900 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 15901 15902 // Check that both casts succeeded. 15903 if (!GSDN || !ConstNode) 15904 return SDValue(); 15905 15906 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 15907 SDLoc DL(GSDN); 15908 15909 // The signed int offset needs to fit in 34 bits. 15910 if (!isInt<34>(NewOffset)) 15911 return SDValue(); 15912 15913 // The new global address is a copy of the old global address except 15914 // that it has the updated Offset. 15915 SDValue GA = 15916 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 15917 NewOffset, GSDN->getTargetFlags()); 15918 SDValue MatPCRel = 15919 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 15920 return MatPCRel; 15921 } 15922 15923 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15924 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15925 return Value; 15926 15927 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 15928 return Value; 15929 15930 return SDValue(); 15931 } 15932 15933 // Detect TRUNCATE operations on bitcasts of float128 values. 15934 // What we are looking for here is the situtation where we extract a subset 15935 // of bits from a 128 bit float. 15936 // This can be of two forms: 15937 // 1) BITCAST of f128 feeding TRUNCATE 15938 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15939 // The reason this is required is because we do not have a legal i128 type 15940 // and so we want to prevent having to store the f128 and then reload part 15941 // of it. 15942 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15943 DAGCombinerInfo &DCI) const { 15944 // If we are using CRBits then try that first. 15945 if (Subtarget.useCRBits()) { 15946 // Check if CRBits did anything and return that if it did. 15947 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15948 return CRTruncValue; 15949 } 15950 15951 SDLoc dl(N); 15952 SDValue Op0 = N->getOperand(0); 15953 15954 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 15955 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 15956 EVT VT = N->getValueType(0); 15957 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15958 return SDValue(); 15959 SDValue Sub = Op0.getOperand(0); 15960 if (Sub.getOpcode() == ISD::SUB) { 15961 SDValue SubOp0 = Sub.getOperand(0); 15962 SDValue SubOp1 = Sub.getOperand(1); 15963 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 15964 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 15965 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 15966 SubOp1.getOperand(0), 15967 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 15968 } 15969 } 15970 } 15971 15972 // Looking for a truncate of i128 to i64. 15973 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15974 return SDValue(); 15975 15976 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15977 15978 // SRL feeding TRUNCATE. 15979 if (Op0.getOpcode() == ISD::SRL) { 15980 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15981 // The right shift has to be by 64 bits. 15982 if (!ConstNode || ConstNode->getZExtValue() != 64) 15983 return SDValue(); 15984 15985 // Switch the element number to extract. 15986 EltToExtract = EltToExtract ? 0 : 1; 15987 // Update Op0 past the SRL. 15988 Op0 = Op0.getOperand(0); 15989 } 15990 15991 // BITCAST feeding a TRUNCATE possibly via SRL. 15992 if (Op0.getOpcode() == ISD::BITCAST && 15993 Op0.getValueType() == MVT::i128 && 15994 Op0.getOperand(0).getValueType() == MVT::f128) { 15995 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15996 return DCI.DAG.getNode( 15997 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15998 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15999 } 16000 return SDValue(); 16001 } 16002 16003 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16004 SelectionDAG &DAG = DCI.DAG; 16005 16006 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16007 if (!ConstOpOrElement) 16008 return SDValue(); 16009 16010 // An imul is usually smaller than the alternative sequence for legal type. 16011 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16012 isOperationLegal(ISD::MUL, N->getValueType(0))) 16013 return SDValue(); 16014 16015 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16016 switch (this->Subtarget.getCPUDirective()) { 16017 default: 16018 // TODO: enhance the condition for subtarget before pwr8 16019 return false; 16020 case PPC::DIR_PWR8: 16021 // type mul add shl 16022 // scalar 4 1 1 16023 // vector 7 2 2 16024 return true; 16025 case PPC::DIR_PWR9: 16026 case PPC::DIR_PWR10: 16027 case PPC::DIR_PWR_FUTURE: 16028 // type mul add shl 16029 // scalar 5 2 2 16030 // vector 7 2 2 16031 16032 // The cycle RATIO of related operations are showed as a table above. 16033 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16034 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16035 // are 4, it is always profitable; but for 3 instrs patterns 16036 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16037 // So we should only do it for vector type. 16038 return IsAddOne && IsNeg ? VT.isVector() : true; 16039 } 16040 }; 16041 16042 EVT VT = N->getValueType(0); 16043 SDLoc DL(N); 16044 16045 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16046 bool IsNeg = MulAmt.isNegative(); 16047 APInt MulAmtAbs = MulAmt.abs(); 16048 16049 if ((MulAmtAbs - 1).isPowerOf2()) { 16050 // (mul x, 2^N + 1) => (add (shl x, N), x) 16051 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16052 16053 if (!IsProfitable(IsNeg, true, VT)) 16054 return SDValue(); 16055 16056 SDValue Op0 = N->getOperand(0); 16057 SDValue Op1 = 16058 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16059 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16060 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16061 16062 if (!IsNeg) 16063 return Res; 16064 16065 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16066 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16067 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16068 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16069 16070 if (!IsProfitable(IsNeg, false, VT)) 16071 return SDValue(); 16072 16073 SDValue Op0 = N->getOperand(0); 16074 SDValue Op1 = 16075 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16076 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16077 16078 if (!IsNeg) 16079 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16080 else 16081 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16082 16083 } else { 16084 return SDValue(); 16085 } 16086 } 16087 16088 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16089 // in combiner since we need to check SD flags and other subtarget features. 16090 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16091 DAGCombinerInfo &DCI) const { 16092 SDValue N0 = N->getOperand(0); 16093 SDValue N1 = N->getOperand(1); 16094 SDValue N2 = N->getOperand(2); 16095 SDNodeFlags Flags = N->getFlags(); 16096 EVT VT = N->getValueType(0); 16097 SelectionDAG &DAG = DCI.DAG; 16098 const TargetOptions &Options = getTargetMachine().Options; 16099 unsigned Opc = N->getOpcode(); 16100 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16101 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16102 SDLoc Loc(N); 16103 16104 if (!isOperationLegal(ISD::FMA, VT)) 16105 return SDValue(); 16106 16107 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16108 // since (fnmsub a b c)=-0 while c-ab=+0. 16109 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16110 return SDValue(); 16111 16112 // (fma (fneg a) b c) => (fnmsub a b c) 16113 // (fnmsub (fneg a) b c) => (fma a b c) 16114 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16115 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16116 16117 // (fma a (fneg b) c) => (fnmsub a b c) 16118 // (fnmsub a (fneg b) c) => (fma a b c) 16119 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16120 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16121 16122 return SDValue(); 16123 } 16124 16125 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16126 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16127 if (!Subtarget.is64BitELFABI()) 16128 return false; 16129 16130 // If not a tail call then no need to proceed. 16131 if (!CI->isTailCall()) 16132 return false; 16133 16134 // If sibling calls have been disabled and tail-calls aren't guaranteed 16135 // there is no reason to duplicate. 16136 auto &TM = getTargetMachine(); 16137 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16138 return false; 16139 16140 // Can't tail call a function called indirectly, or if it has variadic args. 16141 const Function *Callee = CI->getCalledFunction(); 16142 if (!Callee || Callee->isVarArg()) 16143 return false; 16144 16145 // Make sure the callee and caller calling conventions are eligible for tco. 16146 const Function *Caller = CI->getParent()->getParent(); 16147 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16148 CI->getCallingConv())) 16149 return false; 16150 16151 // If the function is local then we have a good chance at tail-calling it 16152 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16153 } 16154 16155 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16156 if (!Subtarget.hasVSX()) 16157 return false; 16158 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16159 return true; 16160 return VT == MVT::f32 || VT == MVT::f64 || 16161 VT == MVT::v4f32 || VT == MVT::v2f64; 16162 } 16163 16164 bool PPCTargetLowering:: 16165 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16166 const Value *Mask = AndI.getOperand(1); 16167 // If the mask is suitable for andi. or andis. we should sink the and. 16168 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16169 // Can't handle constants wider than 64-bits. 16170 if (CI->getBitWidth() > 64) 16171 return false; 16172 int64_t ConstVal = CI->getZExtValue(); 16173 return isUInt<16>(ConstVal) || 16174 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16175 } 16176 16177 // For non-constant masks, we can always use the record-form and. 16178 return true; 16179 } 16180 16181 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16182 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16183 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16184 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16185 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16186 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16187 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16188 assert(Subtarget.hasP9Altivec() && 16189 "Only combine this when P9 altivec supported!"); 16190 EVT VT = N->getValueType(0); 16191 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16192 return SDValue(); 16193 16194 SelectionDAG &DAG = DCI.DAG; 16195 SDLoc dl(N); 16196 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16197 // Even for signed integers, if it's known to be positive (as signed 16198 // integer) due to zero-extended inputs. 16199 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16200 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16201 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16202 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16203 (SubOpcd1 == ISD::ZERO_EXTEND || 16204 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16205 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16206 N->getOperand(0)->getOperand(0), 16207 N->getOperand(0)->getOperand(1), 16208 DAG.getTargetConstant(0, dl, MVT::i32)); 16209 } 16210 16211 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16212 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16213 N->getOperand(0).hasOneUse()) { 16214 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16215 N->getOperand(0)->getOperand(0), 16216 N->getOperand(0)->getOperand(1), 16217 DAG.getTargetConstant(1, dl, MVT::i32)); 16218 } 16219 } 16220 16221 return SDValue(); 16222 } 16223 16224 // For type v4i32/v8ii16/v16i8, transform 16225 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16226 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16227 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16228 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16229 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16230 DAGCombinerInfo &DCI) const { 16231 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16232 assert(Subtarget.hasP9Altivec() && 16233 "Only combine this when P9 altivec supported!"); 16234 16235 SelectionDAG &DAG = DCI.DAG; 16236 SDLoc dl(N); 16237 SDValue Cond = N->getOperand(0); 16238 SDValue TrueOpnd = N->getOperand(1); 16239 SDValue FalseOpnd = N->getOperand(2); 16240 EVT VT = N->getOperand(1).getValueType(); 16241 16242 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16243 FalseOpnd.getOpcode() != ISD::SUB) 16244 return SDValue(); 16245 16246 // ABSD only available for type v4i32/v8i16/v16i8 16247 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16248 return SDValue(); 16249 16250 // At least to save one more dependent computation 16251 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16252 return SDValue(); 16253 16254 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16255 16256 // Can only handle unsigned comparison here 16257 switch (CC) { 16258 default: 16259 return SDValue(); 16260 case ISD::SETUGT: 16261 case ISD::SETUGE: 16262 break; 16263 case ISD::SETULT: 16264 case ISD::SETULE: 16265 std::swap(TrueOpnd, FalseOpnd); 16266 break; 16267 } 16268 16269 SDValue CmpOpnd1 = Cond.getOperand(0); 16270 SDValue CmpOpnd2 = Cond.getOperand(1); 16271 16272 // SETCC CmpOpnd1 CmpOpnd2 cond 16273 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16274 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16275 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16276 TrueOpnd.getOperand(1) == CmpOpnd2 && 16277 FalseOpnd.getOperand(0) == CmpOpnd2 && 16278 FalseOpnd.getOperand(1) == CmpOpnd1) { 16279 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16280 CmpOpnd1, CmpOpnd2, 16281 DAG.getTargetConstant(0, dl, MVT::i32)); 16282 } 16283 16284 return SDValue(); 16285 } 16286