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 // TODO - Remove this option if soft fp128 has been fully supported . 125 static cl::opt<bool> 126 EnableSoftFP128("enable-soft-fp128", 127 cl::desc("temp option to enable soft fp128"), cl::Hidden); 128 129 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 // FIXME: Remove this once the bug has been fixed! 139 extern cl::opt<bool> ANDIGlueBug; 140 141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 142 const PPCSubtarget &STI) 143 : TargetLowering(TM), Subtarget(STI) { 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 // EFPU2 APU only supports f32 155 if (!Subtarget.hasEFPU2()) 156 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 157 } else { 158 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 159 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 160 } 161 } 162 163 // Match BITREVERSE to customized fast code sequence in the td file. 164 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 165 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 166 167 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 168 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 169 170 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 171 for (MVT VT : MVT::integer_valuetypes()) { 172 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 173 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 174 } 175 176 if (Subtarget.isISA3_0()) { 177 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 178 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 179 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 180 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 181 } else { 182 // No extending loads from f16 or HW conversions back and forth. 183 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 184 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 185 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 186 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 187 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 188 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 189 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 190 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 191 } 192 193 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 194 195 // PowerPC has pre-inc load and store's. 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 199 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 200 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 204 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 205 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 206 if (!Subtarget.hasSPE()) { 207 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 209 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 210 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 211 } 212 213 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 214 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 215 for (MVT VT : ScalarIntVTs) { 216 setOperationAction(ISD::ADDC, VT, Legal); 217 setOperationAction(ISD::ADDE, VT, Legal); 218 setOperationAction(ISD::SUBC, VT, Legal); 219 setOperationAction(ISD::SUBE, VT, Legal); 220 } 221 222 if (Subtarget.useCRBits()) { 223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 224 225 if (isPPC64 || Subtarget.hasFPCVT()) { 226 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 227 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 228 isPPC64 ? MVT::i64 : MVT::i32); 229 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 230 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 231 isPPC64 ? MVT::i64 : MVT::i32); 232 233 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 234 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 235 isPPC64 ? MVT::i64 : MVT::i32); 236 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 237 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 238 isPPC64 ? MVT::i64 : MVT::i32); 239 240 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 241 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 242 isPPC64 ? MVT::i64 : MVT::i32); 243 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 244 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 245 isPPC64 ? MVT::i64 : MVT::i32); 246 247 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 248 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 249 isPPC64 ? MVT::i64 : MVT::i32); 250 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 251 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 252 isPPC64 ? MVT::i64 : MVT::i32); 253 } else { 254 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 255 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 256 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 257 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 258 } 259 260 // PowerPC does not support direct load/store of condition registers. 261 setOperationAction(ISD::LOAD, MVT::i1, Custom); 262 setOperationAction(ISD::STORE, MVT::i1, Custom); 263 264 // FIXME: Remove this once the ANDI glue bug is fixed: 265 if (ANDIGlueBug) 266 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 267 268 for (MVT VT : MVT::integer_valuetypes()) { 269 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 270 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 271 setTruncStoreAction(VT, MVT::i1, Expand); 272 } 273 274 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 275 } 276 277 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 278 // PPC (the libcall is not available). 279 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 280 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 281 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 282 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 283 284 // We do not currently implement these libm ops for PowerPC. 285 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 286 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 287 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 288 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 289 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 290 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 291 292 // PowerPC has no SREM/UREM instructions unless we are on P9 293 // On P9 we may use a hardware instruction to compute the remainder. 294 // When the result of both the remainder and the division is required it is 295 // more efficient to compute the remainder from the result of the division 296 // rather than use the remainder instruction. The instructions are legalized 297 // directly because the DivRemPairsPass performs the transformation at the IR 298 // level. 299 if (Subtarget.isISA3_0()) { 300 setOperationAction(ISD::SREM, MVT::i32, Legal); 301 setOperationAction(ISD::UREM, MVT::i32, Legal); 302 setOperationAction(ISD::SREM, MVT::i64, Legal); 303 setOperationAction(ISD::UREM, MVT::i64, Legal); 304 } else { 305 setOperationAction(ISD::SREM, MVT::i32, Expand); 306 setOperationAction(ISD::UREM, MVT::i32, Expand); 307 setOperationAction(ISD::SREM, MVT::i64, Expand); 308 setOperationAction(ISD::UREM, MVT::i64, Expand); 309 } 310 311 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 312 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 313 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 314 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 315 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 316 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 317 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 318 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 319 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 320 321 // Handle constrained floating-point operations of scalar. 322 // TODO: Handle SPE specific operation. 323 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 324 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 325 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 326 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 327 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 328 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 329 330 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 331 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 332 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 333 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 334 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 335 if (Subtarget.hasVSX()) { 336 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 337 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 338 } 339 340 if (Subtarget.hasFSQRT()) { 341 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 342 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 343 } 344 345 if (Subtarget.hasFPRND()) { 346 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 347 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 348 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 349 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 350 351 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 352 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 353 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 354 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 355 } 356 357 // We don't support sin/cos/sqrt/fmod/pow 358 setOperationAction(ISD::FSIN , MVT::f64, Expand); 359 setOperationAction(ISD::FCOS , MVT::f64, Expand); 360 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 361 setOperationAction(ISD::FREM , MVT::f64, Expand); 362 setOperationAction(ISD::FPOW , MVT::f64, Expand); 363 setOperationAction(ISD::FSIN , MVT::f32, Expand); 364 setOperationAction(ISD::FCOS , MVT::f32, Expand); 365 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 366 setOperationAction(ISD::FREM , MVT::f32, Expand); 367 setOperationAction(ISD::FPOW , MVT::f32, Expand); 368 if (Subtarget.hasSPE()) { 369 setOperationAction(ISD::FMA , MVT::f64, Expand); 370 setOperationAction(ISD::FMA , MVT::f32, Expand); 371 } else { 372 setOperationAction(ISD::FMA , MVT::f64, Legal); 373 setOperationAction(ISD::FMA , MVT::f32, Legal); 374 } 375 376 if (Subtarget.hasSPE()) 377 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 378 379 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 380 381 // If we're enabling GP optimizations, use hardware square root 382 if (!Subtarget.hasFSQRT() && 383 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 384 Subtarget.hasFRE())) 385 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 386 387 if (!Subtarget.hasFSQRT() && 388 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 389 Subtarget.hasFRES())) 390 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 391 392 if (Subtarget.hasFCPSGN()) { 393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 395 } else { 396 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 397 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 398 } 399 400 if (Subtarget.hasFPRND()) { 401 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 402 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 403 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 404 setOperationAction(ISD::FROUND, MVT::f64, Legal); 405 406 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 407 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 408 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 409 setOperationAction(ISD::FROUND, MVT::f32, Legal); 410 } 411 412 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 413 // to speed up scalar BSWAP64. 414 // CTPOP or CTTZ were introduced in P8/P9 respectively 415 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 416 if (Subtarget.hasP9Vector()) 417 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 418 else 419 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 420 if (Subtarget.isISA3_0()) { 421 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 422 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 423 } else { 424 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 425 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 426 } 427 428 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 429 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 430 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 431 } else { 432 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 433 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 434 } 435 436 // PowerPC does not have ROTR 437 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 438 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 439 440 if (!Subtarget.useCRBits()) { 441 // PowerPC does not have Select 442 setOperationAction(ISD::SELECT, MVT::i32, Expand); 443 setOperationAction(ISD::SELECT, MVT::i64, Expand); 444 setOperationAction(ISD::SELECT, MVT::f32, Expand); 445 setOperationAction(ISD::SELECT, MVT::f64, Expand); 446 } 447 448 // PowerPC wants to turn select_cc of FP into fsel when possible. 449 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 450 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 451 452 // PowerPC wants to optimize integer setcc a bit 453 if (!Subtarget.useCRBits()) 454 setOperationAction(ISD::SETCC, MVT::i32, Custom); 455 456 if (Subtarget.hasFPU()) { 457 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 458 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 459 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 460 461 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 462 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 463 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 464 } 465 466 // PowerPC does not have BRCOND which requires SetCC 467 if (!Subtarget.useCRBits()) 468 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 469 470 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 471 472 if (Subtarget.hasSPE()) { 473 // SPE has built-in conversions 474 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 475 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 476 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 477 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 478 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 479 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 480 } else { 481 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 482 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 483 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 484 485 // PowerPC does not have [U|S]INT_TO_FP 486 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 487 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 488 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 489 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 490 } 491 492 if (Subtarget.hasDirectMove() && isPPC64) { 493 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 494 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 495 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 496 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 497 if (TM.Options.UnsafeFPMath) { 498 setOperationAction(ISD::LRINT, MVT::f64, Legal); 499 setOperationAction(ISD::LRINT, MVT::f32, Legal); 500 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 501 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 502 setOperationAction(ISD::LROUND, MVT::f64, Legal); 503 setOperationAction(ISD::LROUND, MVT::f32, Legal); 504 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 505 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 506 } 507 } else { 508 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 509 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 510 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 511 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 512 } 513 514 // We cannot sextinreg(i1). Expand to shifts. 515 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 516 517 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 518 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 519 // support continuation, user-level threading, and etc.. As a result, no 520 // other SjLj exception interfaces are implemented and please don't build 521 // your own exception handling based on them. 522 // LLVM/Clang supports zero-cost DWARF exception handling. 523 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 524 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 525 526 // We want to legalize GlobalAddress and ConstantPool nodes into the 527 // appropriate instructions to materialize the address. 528 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 529 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 530 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 531 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 532 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 533 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 534 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 535 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 536 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 537 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 538 539 // TRAP is legal. 540 setOperationAction(ISD::TRAP, MVT::Other, Legal); 541 542 // TRAMPOLINE is custom lowered. 543 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 544 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 545 546 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 547 setOperationAction(ISD::VASTART , MVT::Other, Custom); 548 549 if (Subtarget.is64BitELFABI()) { 550 // VAARG always uses double-word chunks, so promote anything smaller. 551 setOperationAction(ISD::VAARG, MVT::i1, Promote); 552 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 553 setOperationAction(ISD::VAARG, MVT::i8, Promote); 554 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 555 setOperationAction(ISD::VAARG, MVT::i16, Promote); 556 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 557 setOperationAction(ISD::VAARG, MVT::i32, Promote); 558 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 559 setOperationAction(ISD::VAARG, MVT::Other, Expand); 560 } else if (Subtarget.is32BitELFABI()) { 561 // VAARG is custom lowered with the 32-bit SVR4 ABI. 562 setOperationAction(ISD::VAARG, MVT::Other, Custom); 563 setOperationAction(ISD::VAARG, MVT::i64, Custom); 564 } else 565 setOperationAction(ISD::VAARG, MVT::Other, Expand); 566 567 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 568 if (Subtarget.is32BitELFABI()) 569 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 570 else 571 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 572 573 // Use the default implementation. 574 setOperationAction(ISD::VAEND , MVT::Other, Expand); 575 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 576 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 577 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 578 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 579 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 580 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 581 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 582 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 583 584 // We want to custom lower some of our intrinsics. 585 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 586 587 // To handle counter-based loop conditions. 588 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 589 590 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 591 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 592 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 593 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 594 595 // Comparisons that require checking two conditions. 596 if (Subtarget.hasSPE()) { 597 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 598 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 599 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 600 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 601 } 602 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 603 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 604 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 605 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 606 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 607 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 608 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 609 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 610 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 611 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 612 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 613 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 614 615 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 616 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 617 618 if (Subtarget.has64BitSupport()) { 619 // They also have instructions for converting between i64 and fp. 620 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 621 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 622 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 623 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 624 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 625 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 626 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 627 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 628 // This is just the low 32 bits of a (signed) fp->i64 conversion. 629 // We cannot do this with Promote because i64 is not a legal type. 630 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 631 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 632 633 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 634 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 635 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 636 } 637 } else { 638 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 639 if (Subtarget.hasSPE()) { 640 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 641 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 642 } else { 643 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 644 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 645 } 646 } 647 648 // With the instructions enabled under FPCVT, we can do everything. 649 if (Subtarget.hasFPCVT()) { 650 if (Subtarget.has64BitSupport()) { 651 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 652 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 653 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 654 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 655 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 656 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 657 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 658 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 659 } 660 661 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 662 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 663 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 664 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 665 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 666 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 667 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 668 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 669 } 670 671 if (Subtarget.use64BitRegs()) { 672 // 64-bit PowerPC implementations can support i64 types directly 673 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 674 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 675 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 676 // 64-bit PowerPC wants to expand i128 shifts itself. 677 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 678 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 679 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 680 } else { 681 // 32-bit PowerPC wants to expand i64 shifts itself. 682 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 683 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 684 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 685 } 686 687 // PowerPC has better expansions for funnel shifts than the generic 688 // TargetLowering::expandFunnelShift. 689 if (Subtarget.has64BitSupport()) { 690 setOperationAction(ISD::FSHL, MVT::i64, Custom); 691 setOperationAction(ISD::FSHR, MVT::i64, Custom); 692 } 693 setOperationAction(ISD::FSHL, MVT::i32, Custom); 694 setOperationAction(ISD::FSHR, MVT::i32, Custom); 695 696 if (Subtarget.hasVSX()) { 697 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 698 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 699 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 701 } 702 703 if (Subtarget.hasAltivec()) { 704 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 705 setOperationAction(ISD::SADDSAT, VT, Legal); 706 setOperationAction(ISD::SSUBSAT, VT, Legal); 707 setOperationAction(ISD::UADDSAT, VT, Legal); 708 setOperationAction(ISD::USUBSAT, VT, Legal); 709 } 710 // First set operation action for all vector types to expand. Then we 711 // will selectively turn on ones that can be effectively codegen'd. 712 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 713 // add/sub are legal for all supported vector VT's. 714 setOperationAction(ISD::ADD, VT, Legal); 715 setOperationAction(ISD::SUB, VT, Legal); 716 717 // For v2i64, these are only valid with P8Vector. This is corrected after 718 // the loop. 719 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 720 setOperationAction(ISD::SMAX, VT, Legal); 721 setOperationAction(ISD::SMIN, VT, Legal); 722 setOperationAction(ISD::UMAX, VT, Legal); 723 setOperationAction(ISD::UMIN, VT, Legal); 724 } 725 else { 726 setOperationAction(ISD::SMAX, VT, Expand); 727 setOperationAction(ISD::SMIN, VT, Expand); 728 setOperationAction(ISD::UMAX, VT, Expand); 729 setOperationAction(ISD::UMIN, VT, Expand); 730 } 731 732 if (Subtarget.hasVSX()) { 733 setOperationAction(ISD::FMAXNUM, VT, Legal); 734 setOperationAction(ISD::FMINNUM, VT, Legal); 735 } 736 737 // Vector instructions introduced in P8 738 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 739 setOperationAction(ISD::CTPOP, VT, Legal); 740 setOperationAction(ISD::CTLZ, VT, Legal); 741 } 742 else { 743 setOperationAction(ISD::CTPOP, VT, Expand); 744 setOperationAction(ISD::CTLZ, VT, Expand); 745 } 746 747 // Vector instructions introduced in P9 748 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 749 setOperationAction(ISD::CTTZ, VT, Legal); 750 else 751 setOperationAction(ISD::CTTZ, VT, Expand); 752 753 // We promote all shuffles to v16i8. 754 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 755 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 756 757 // We promote all non-typed operations to v4i32. 758 setOperationAction(ISD::AND , VT, Promote); 759 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 760 setOperationAction(ISD::OR , VT, Promote); 761 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 762 setOperationAction(ISD::XOR , VT, Promote); 763 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 764 setOperationAction(ISD::LOAD , VT, Promote); 765 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 766 setOperationAction(ISD::SELECT, VT, Promote); 767 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 768 setOperationAction(ISD::VSELECT, VT, Legal); 769 setOperationAction(ISD::SELECT_CC, VT, Promote); 770 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 771 setOperationAction(ISD::STORE, VT, Promote); 772 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 773 774 // No other operations are legal. 775 setOperationAction(ISD::MUL , VT, Expand); 776 setOperationAction(ISD::SDIV, VT, Expand); 777 setOperationAction(ISD::SREM, VT, Expand); 778 setOperationAction(ISD::UDIV, VT, Expand); 779 setOperationAction(ISD::UREM, VT, Expand); 780 setOperationAction(ISD::FDIV, VT, Expand); 781 setOperationAction(ISD::FREM, VT, Expand); 782 setOperationAction(ISD::FNEG, VT, Expand); 783 setOperationAction(ISD::FSQRT, VT, Expand); 784 setOperationAction(ISD::FLOG, VT, Expand); 785 setOperationAction(ISD::FLOG10, VT, Expand); 786 setOperationAction(ISD::FLOG2, VT, Expand); 787 setOperationAction(ISD::FEXP, VT, Expand); 788 setOperationAction(ISD::FEXP2, VT, Expand); 789 setOperationAction(ISD::FSIN, VT, Expand); 790 setOperationAction(ISD::FCOS, VT, Expand); 791 setOperationAction(ISD::FABS, VT, Expand); 792 setOperationAction(ISD::FFLOOR, VT, Expand); 793 setOperationAction(ISD::FCEIL, VT, Expand); 794 setOperationAction(ISD::FTRUNC, VT, Expand); 795 setOperationAction(ISD::FRINT, VT, Expand); 796 setOperationAction(ISD::FNEARBYINT, VT, Expand); 797 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 798 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 799 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 800 setOperationAction(ISD::MULHU, VT, Expand); 801 setOperationAction(ISD::MULHS, VT, Expand); 802 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 803 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 804 setOperationAction(ISD::UDIVREM, VT, Expand); 805 setOperationAction(ISD::SDIVREM, VT, Expand); 806 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 807 setOperationAction(ISD::FPOW, VT, Expand); 808 setOperationAction(ISD::BSWAP, VT, Expand); 809 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 810 setOperationAction(ISD::ROTL, VT, Expand); 811 setOperationAction(ISD::ROTR, VT, Expand); 812 813 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 814 setTruncStoreAction(VT, InnerVT, Expand); 815 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 816 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 817 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 818 } 819 } 820 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 821 if (!Subtarget.hasP8Vector()) { 822 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 823 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 824 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 825 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 826 } 827 828 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 829 // with merges, splats, etc. 830 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 831 832 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 833 // are cheap, so handle them before they get expanded to scalar. 834 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 835 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 836 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 837 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 838 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 839 840 setOperationAction(ISD::AND , MVT::v4i32, Legal); 841 setOperationAction(ISD::OR , MVT::v4i32, Legal); 842 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 843 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 844 setOperationAction(ISD::SELECT, MVT::v4i32, 845 Subtarget.useCRBits() ? Legal : Expand); 846 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 847 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 848 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 849 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 850 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 851 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 852 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 853 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 854 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 855 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 856 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 857 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 858 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 859 860 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 861 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 862 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 863 if (Subtarget.hasAltivec()) 864 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 865 setOperationAction(ISD::ROTL, VT, Legal); 866 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 867 if (Subtarget.hasP8Altivec()) 868 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 869 870 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 871 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 872 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 873 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 874 875 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 876 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 877 878 if (Subtarget.hasVSX()) { 879 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 880 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 881 } 882 883 if (Subtarget.hasP8Altivec()) 884 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 885 else 886 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 887 888 if (Subtarget.isISA3_1()) { 889 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 890 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 891 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 892 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 893 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 894 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 895 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 896 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 897 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 898 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 899 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 900 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 901 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 902 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 903 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 904 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 905 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 906 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 907 } 908 909 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 910 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 911 912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 914 915 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 916 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 917 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 918 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 919 920 // Altivec does not contain unordered floating-point compare instructions 921 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 922 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 923 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 924 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 925 926 if (Subtarget.hasVSX()) { 927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 928 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 929 if (Subtarget.hasP8Vector()) { 930 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 931 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 932 } 933 if (Subtarget.hasDirectMove() && isPPC64) { 934 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 935 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 936 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 937 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 942 } 943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 944 945 // The nearbyint variants are not allowed to raise the inexact exception 946 // so we can only code-gen them with unsafe math. 947 if (TM.Options.UnsafeFPMath) { 948 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 949 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 950 } 951 952 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 953 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 954 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 955 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 956 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 957 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 958 setOperationAction(ISD::FROUND, MVT::f64, Legal); 959 setOperationAction(ISD::FRINT, MVT::f64, Legal); 960 961 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 962 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 963 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 964 setOperationAction(ISD::FROUND, MVT::f32, Legal); 965 setOperationAction(ISD::FRINT, MVT::f32, Legal); 966 967 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 968 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 969 970 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 971 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 972 973 // Share the Altivec comparison restrictions. 974 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 975 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 976 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 977 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 978 979 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 980 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 981 982 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 983 984 if (Subtarget.hasP8Vector()) 985 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 986 987 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 988 989 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 990 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 991 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 992 993 if (Subtarget.hasP8Altivec()) { 994 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 995 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 996 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 997 998 // 128 bit shifts can be accomplished via 3 instructions for SHL and 999 // SRL, but not for SRA because of the instructions available: 1000 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1001 // doing 1002 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1003 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1004 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1005 1006 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1007 } 1008 else { 1009 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1010 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1011 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1012 1013 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1014 1015 // VSX v2i64 only supports non-arithmetic operations. 1016 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1017 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1018 } 1019 1020 if (Subtarget.isISA3_1()) 1021 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1022 else 1023 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1024 1025 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1026 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1027 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1028 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1029 1030 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1031 1032 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1033 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1034 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1035 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1036 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1037 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1038 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1039 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1040 1041 // Custom handling for partial vectors of integers converted to 1042 // floating point. We already have optimal handling for v2i32 through 1043 // the DAG combine, so those aren't necessary. 1044 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1045 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1046 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1047 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1048 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1049 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1050 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1051 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1052 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1053 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1054 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1055 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1056 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1057 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1058 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1059 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1060 1061 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1062 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1063 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1064 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1065 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1066 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1067 1068 if (Subtarget.hasDirectMove()) 1069 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1070 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1071 1072 // Handle constrained floating-point operations of vector. 1073 // The predictor is `hasVSX` because altivec instruction has 1074 // no exception but VSX vector instruction has. 1075 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1076 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1077 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1078 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1079 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1080 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1081 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1082 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1083 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1084 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1085 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1086 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1087 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1088 1089 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1090 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1091 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1092 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1093 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1094 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1095 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1096 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1097 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1098 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1099 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1100 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1101 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1102 1103 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1104 } 1105 1106 if (Subtarget.hasP8Altivec()) { 1107 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1108 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1109 } 1110 1111 if (Subtarget.hasP9Vector()) { 1112 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1113 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1114 1115 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1116 // SRL, but not for SRA because of the instructions available: 1117 // VS{RL} and VS{RL}O. 1118 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1119 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1120 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1121 1122 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1123 setOperationAction(ISD::FADD, MVT::f128, Legal); 1124 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1125 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1126 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1127 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1128 // No extending loads to f128 on PPC. 1129 for (MVT FPT : MVT::fp_valuetypes()) 1130 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1131 setOperationAction(ISD::FMA, MVT::f128, Legal); 1132 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1133 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1134 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1135 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1136 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1137 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1138 1139 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1140 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1141 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1142 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1143 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1144 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1145 1146 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1147 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1148 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1149 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1150 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1151 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1152 // No implementation for these ops for PowerPC. 1153 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1154 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1155 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1156 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1157 setOperationAction(ISD::FREM, MVT::f128, Expand); 1158 1159 // Handle constrained floating-point operations of fp128 1160 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1161 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1162 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1163 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1164 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1165 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1166 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1167 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1168 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1169 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1170 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1171 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1172 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1173 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1174 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1175 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1176 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1177 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1178 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1179 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1180 } else if (Subtarget.hasAltivec() && EnableSoftFP128) { 1181 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1182 1183 for (MVT FPT : MVT::fp_valuetypes()) 1184 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1185 1186 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1187 setOperationAction(ISD::STORE, MVT::f128, Promote); 1188 1189 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1190 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1191 1192 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1193 // fp_to_uint and int_to_fp. 1194 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1195 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1196 1197 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1198 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1199 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1200 setOperationAction(ISD::FABS, MVT::f128, Expand); 1201 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1202 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1203 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1204 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1205 setOperationAction(ISD::FREM, MVT::f128, Expand); 1206 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1207 setOperationAction(ISD::FMA, MVT::f128, Expand); 1208 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1209 1210 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1211 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1212 1213 // Expand the fp_extend if the target type is fp128. 1214 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1215 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1216 1217 // Expand the fp_round if the source type is fp128. 1218 for (MVT VT : {MVT::f32, MVT::f64}) { 1219 setOperationAction(ISD::FP_ROUND, VT, Custom); 1220 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1221 } 1222 } 1223 1224 if (Subtarget.hasP9Altivec()) { 1225 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1226 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1227 1228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1235 } 1236 1237 if (Subtarget.isISA3_1()) { 1238 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1239 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 1240 } 1241 } 1242 1243 if (Subtarget.pairedVectorMemops()) { 1244 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1245 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1246 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1247 } 1248 if (Subtarget.hasMMA()) { 1249 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1250 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1251 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1252 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1253 } 1254 1255 if (Subtarget.has64BitSupport()) 1256 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1257 1258 if (Subtarget.isISA3_1()) 1259 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1260 1261 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1262 1263 if (!isPPC64) { 1264 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1265 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1266 } 1267 1268 setBooleanContents(ZeroOrOneBooleanContent); 1269 1270 if (Subtarget.hasAltivec()) { 1271 // Altivec instructions set fields to all zeros or all ones. 1272 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1273 } 1274 1275 if (!isPPC64) { 1276 // These libcalls are not available in 32-bit. 1277 setLibcallName(RTLIB::SHL_I128, nullptr); 1278 setLibcallName(RTLIB::SRL_I128, nullptr); 1279 setLibcallName(RTLIB::SRA_I128, nullptr); 1280 } 1281 1282 if (!isPPC64) 1283 setMaxAtomicSizeInBitsSupported(32); 1284 1285 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1286 1287 // We have target-specific dag combine patterns for the following nodes: 1288 setTargetDAGCombine(ISD::ADD); 1289 setTargetDAGCombine(ISD::SHL); 1290 setTargetDAGCombine(ISD::SRA); 1291 setTargetDAGCombine(ISD::SRL); 1292 setTargetDAGCombine(ISD::MUL); 1293 setTargetDAGCombine(ISD::FMA); 1294 setTargetDAGCombine(ISD::SINT_TO_FP); 1295 setTargetDAGCombine(ISD::BUILD_VECTOR); 1296 if (Subtarget.hasFPCVT()) 1297 setTargetDAGCombine(ISD::UINT_TO_FP); 1298 setTargetDAGCombine(ISD::LOAD); 1299 setTargetDAGCombine(ISD::STORE); 1300 setTargetDAGCombine(ISD::BR_CC); 1301 if (Subtarget.useCRBits()) 1302 setTargetDAGCombine(ISD::BRCOND); 1303 setTargetDAGCombine(ISD::BSWAP); 1304 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1305 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1306 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1307 1308 setTargetDAGCombine(ISD::SIGN_EXTEND); 1309 setTargetDAGCombine(ISD::ZERO_EXTEND); 1310 setTargetDAGCombine(ISD::ANY_EXTEND); 1311 1312 setTargetDAGCombine(ISD::TRUNCATE); 1313 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1314 1315 1316 if (Subtarget.useCRBits()) { 1317 setTargetDAGCombine(ISD::TRUNCATE); 1318 setTargetDAGCombine(ISD::SETCC); 1319 setTargetDAGCombine(ISD::SELECT_CC); 1320 } 1321 1322 if (Subtarget.hasP9Altivec()) { 1323 setTargetDAGCombine(ISD::ABS); 1324 setTargetDAGCombine(ISD::VSELECT); 1325 } 1326 1327 setLibcallName(RTLIB::LOG_F128, "logf128"); 1328 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1329 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1330 setLibcallName(RTLIB::EXP_F128, "expf128"); 1331 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1332 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1333 setLibcallName(RTLIB::COS_F128, "cosf128"); 1334 setLibcallName(RTLIB::POW_F128, "powf128"); 1335 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1336 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1337 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1338 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1339 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1340 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1341 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1342 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1343 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1344 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1345 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1346 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1347 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1348 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1349 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1350 1351 // With 32 condition bits, we don't need to sink (and duplicate) compares 1352 // aggressively in CodeGenPrep. 1353 if (Subtarget.useCRBits()) { 1354 setHasMultipleConditionRegisters(); 1355 setJumpIsExpensive(); 1356 } 1357 1358 setMinFunctionAlignment(Align(4)); 1359 1360 switch (Subtarget.getCPUDirective()) { 1361 default: break; 1362 case PPC::DIR_970: 1363 case PPC::DIR_A2: 1364 case PPC::DIR_E500: 1365 case PPC::DIR_E500mc: 1366 case PPC::DIR_E5500: 1367 case PPC::DIR_PWR4: 1368 case PPC::DIR_PWR5: 1369 case PPC::DIR_PWR5X: 1370 case PPC::DIR_PWR6: 1371 case PPC::DIR_PWR6X: 1372 case PPC::DIR_PWR7: 1373 case PPC::DIR_PWR8: 1374 case PPC::DIR_PWR9: 1375 case PPC::DIR_PWR10: 1376 case PPC::DIR_PWR_FUTURE: 1377 setPrefLoopAlignment(Align(16)); 1378 setPrefFunctionAlignment(Align(16)); 1379 break; 1380 } 1381 1382 if (Subtarget.enableMachineScheduler()) 1383 setSchedulingPreference(Sched::Source); 1384 else 1385 setSchedulingPreference(Sched::Hybrid); 1386 1387 computeRegisterProperties(STI.getRegisterInfo()); 1388 1389 // The Freescale cores do better with aggressive inlining of memcpy and 1390 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1391 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1392 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1393 MaxStoresPerMemset = 32; 1394 MaxStoresPerMemsetOptSize = 16; 1395 MaxStoresPerMemcpy = 32; 1396 MaxStoresPerMemcpyOptSize = 8; 1397 MaxStoresPerMemmove = 32; 1398 MaxStoresPerMemmoveOptSize = 8; 1399 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1400 // The A2 also benefits from (very) aggressive inlining of memcpy and 1401 // friends. The overhead of a the function call, even when warm, can be 1402 // over one hundred cycles. 1403 MaxStoresPerMemset = 128; 1404 MaxStoresPerMemcpy = 128; 1405 MaxStoresPerMemmove = 128; 1406 MaxLoadsPerMemcmp = 128; 1407 } else { 1408 MaxLoadsPerMemcmp = 8; 1409 MaxLoadsPerMemcmpOptSize = 4; 1410 } 1411 1412 IsStrictFPEnabled = true; 1413 1414 // Let the subtarget (CPU) decide if a predictable select is more expensive 1415 // than the corresponding branch. This information is used in CGP to decide 1416 // when to convert selects into branches. 1417 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1418 } 1419 1420 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1421 /// the desired ByVal argument alignment. 1422 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1423 if (MaxAlign == MaxMaxAlign) 1424 return; 1425 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1426 if (MaxMaxAlign >= 32 && 1427 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1428 MaxAlign = Align(32); 1429 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1430 MaxAlign < 16) 1431 MaxAlign = Align(16); 1432 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1433 Align EltAlign; 1434 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1435 if (EltAlign > MaxAlign) 1436 MaxAlign = EltAlign; 1437 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1438 for (auto *EltTy : STy->elements()) { 1439 Align EltAlign; 1440 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1441 if (EltAlign > MaxAlign) 1442 MaxAlign = EltAlign; 1443 if (MaxAlign == MaxMaxAlign) 1444 break; 1445 } 1446 } 1447 } 1448 1449 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1450 /// function arguments in the caller parameter area. 1451 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1452 const DataLayout &DL) const { 1453 // 16byte and wider vectors are passed on 16byte boundary. 1454 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1455 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1456 if (Subtarget.hasAltivec()) 1457 getMaxByValAlign(Ty, Alignment, Align(16)); 1458 return Alignment.value(); 1459 } 1460 1461 bool PPCTargetLowering::useSoftFloat() const { 1462 return Subtarget.useSoftFloat(); 1463 } 1464 1465 bool PPCTargetLowering::hasSPE() const { 1466 return Subtarget.hasSPE(); 1467 } 1468 1469 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1470 return VT.isScalarInteger(); 1471 } 1472 1473 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1474 switch ((PPCISD::NodeType)Opcode) { 1475 case PPCISD::FIRST_NUMBER: break; 1476 case PPCISD::FSEL: return "PPCISD::FSEL"; 1477 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1478 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1479 case PPCISD::FCFID: return "PPCISD::FCFID"; 1480 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1481 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1482 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1483 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1484 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1485 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1486 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1487 case PPCISD::FP_TO_UINT_IN_VSR: 1488 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1489 case PPCISD::FP_TO_SINT_IN_VSR: 1490 return "PPCISD::FP_TO_SINT_IN_VSR"; 1491 case PPCISD::FRE: return "PPCISD::FRE"; 1492 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1493 case PPCISD::FTSQRT: 1494 return "PPCISD::FTSQRT"; 1495 case PPCISD::FSQRT: 1496 return "PPCISD::FSQRT"; 1497 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1498 case PPCISD::VPERM: return "PPCISD::VPERM"; 1499 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1500 case PPCISD::XXSPLTI_SP_TO_DP: 1501 return "PPCISD::XXSPLTI_SP_TO_DP"; 1502 case PPCISD::XXSPLTI32DX: 1503 return "PPCISD::XXSPLTI32DX"; 1504 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1505 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1506 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1507 case PPCISD::CMPB: return "PPCISD::CMPB"; 1508 case PPCISD::Hi: return "PPCISD::Hi"; 1509 case PPCISD::Lo: return "PPCISD::Lo"; 1510 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1511 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1512 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1513 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1514 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1515 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1516 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1517 case PPCISD::SRL: return "PPCISD::SRL"; 1518 case PPCISD::SRA: return "PPCISD::SRA"; 1519 case PPCISD::SHL: return "PPCISD::SHL"; 1520 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1521 case PPCISD::CALL: return "PPCISD::CALL"; 1522 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1523 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1524 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1525 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1526 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1527 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1528 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1529 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1530 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1531 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1532 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1533 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1534 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1535 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1536 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1537 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1538 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1539 case PPCISD::ANDI_rec_1_EQ_BIT: 1540 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1541 case PPCISD::ANDI_rec_1_GT_BIT: 1542 return "PPCISD::ANDI_rec_1_GT_BIT"; 1543 case PPCISD::VCMP: return "PPCISD::VCMP"; 1544 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1545 case PPCISD::LBRX: return "PPCISD::LBRX"; 1546 case PPCISD::STBRX: return "PPCISD::STBRX"; 1547 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1548 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1549 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1550 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1551 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1552 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1553 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1554 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1555 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1556 case PPCISD::ST_VSR_SCAL_INT: 1557 return "PPCISD::ST_VSR_SCAL_INT"; 1558 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1559 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1560 case PPCISD::BDZ: return "PPCISD::BDZ"; 1561 case PPCISD::MFFS: return "PPCISD::MFFS"; 1562 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1563 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1564 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1565 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1566 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1567 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1568 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1569 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1570 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1571 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1572 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1573 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1574 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1575 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1576 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1577 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1578 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1579 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1580 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1581 case PPCISD::PADDI_DTPREL: 1582 return "PPCISD::PADDI_DTPREL"; 1583 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1584 case PPCISD::SC: return "PPCISD::SC"; 1585 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1586 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1587 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1588 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1589 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1590 case PPCISD::VABSD: return "PPCISD::VABSD"; 1591 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1592 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1593 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1594 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1595 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1596 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1597 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1598 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1599 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1600 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1601 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1602 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1603 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1604 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1605 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1606 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1607 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1608 case PPCISD::STRICT_FADDRTZ: 1609 return "PPCISD::STRICT_FADDRTZ"; 1610 case PPCISD::STRICT_FCTIDZ: 1611 return "PPCISD::STRICT_FCTIDZ"; 1612 case PPCISD::STRICT_FCTIWZ: 1613 return "PPCISD::STRICT_FCTIWZ"; 1614 case PPCISD::STRICT_FCTIDUZ: 1615 return "PPCISD::STRICT_FCTIDUZ"; 1616 case PPCISD::STRICT_FCTIWUZ: 1617 return "PPCISD::STRICT_FCTIWUZ"; 1618 case PPCISD::STRICT_FCFID: 1619 return "PPCISD::STRICT_FCFID"; 1620 case PPCISD::STRICT_FCFIDU: 1621 return "PPCISD::STRICT_FCFIDU"; 1622 case PPCISD::STRICT_FCFIDS: 1623 return "PPCISD::STRICT_FCFIDS"; 1624 case PPCISD::STRICT_FCFIDUS: 1625 return "PPCISD::STRICT_FCFIDUS"; 1626 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1627 } 1628 return nullptr; 1629 } 1630 1631 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1632 EVT VT) const { 1633 if (!VT.isVector()) 1634 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1635 1636 return VT.changeVectorElementTypeToInteger(); 1637 } 1638 1639 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1640 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1641 return true; 1642 } 1643 1644 //===----------------------------------------------------------------------===// 1645 // Node matching predicates, for use by the tblgen matching code. 1646 //===----------------------------------------------------------------------===// 1647 1648 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1649 static bool isFloatingPointZero(SDValue Op) { 1650 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1651 return CFP->getValueAPF().isZero(); 1652 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1653 // Maybe this has already been legalized into the constant pool? 1654 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1655 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1656 return CFP->getValueAPF().isZero(); 1657 } 1658 return false; 1659 } 1660 1661 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1662 /// true if Op is undef or if it matches the specified value. 1663 static bool isConstantOrUndef(int Op, int Val) { 1664 return Op < 0 || Op == Val; 1665 } 1666 1667 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1668 /// VPKUHUM instruction. 1669 /// The ShuffleKind distinguishes between big-endian operations with 1670 /// two different inputs (0), either-endian operations with two identical 1671 /// inputs (1), and little-endian operations with two different inputs (2). 1672 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1673 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1674 SelectionDAG &DAG) { 1675 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1676 if (ShuffleKind == 0) { 1677 if (IsLE) 1678 return false; 1679 for (unsigned i = 0; i != 16; ++i) 1680 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1681 return false; 1682 } else if (ShuffleKind == 2) { 1683 if (!IsLE) 1684 return false; 1685 for (unsigned i = 0; i != 16; ++i) 1686 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1687 return false; 1688 } else if (ShuffleKind == 1) { 1689 unsigned j = IsLE ? 0 : 1; 1690 for (unsigned i = 0; i != 8; ++i) 1691 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1692 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1693 return false; 1694 } 1695 return true; 1696 } 1697 1698 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1699 /// VPKUWUM instruction. 1700 /// The ShuffleKind distinguishes between big-endian operations with 1701 /// two different inputs (0), either-endian operations with two identical 1702 /// inputs (1), and little-endian operations with two different inputs (2). 1703 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1704 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1705 SelectionDAG &DAG) { 1706 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1707 if (ShuffleKind == 0) { 1708 if (IsLE) 1709 return false; 1710 for (unsigned i = 0; i != 16; i += 2) 1711 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1712 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1713 return false; 1714 } else if (ShuffleKind == 2) { 1715 if (!IsLE) 1716 return false; 1717 for (unsigned i = 0; i != 16; i += 2) 1718 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1719 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1720 return false; 1721 } else if (ShuffleKind == 1) { 1722 unsigned j = IsLE ? 0 : 2; 1723 for (unsigned i = 0; i != 8; i += 2) 1724 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1725 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1726 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1727 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1728 return false; 1729 } 1730 return true; 1731 } 1732 1733 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1734 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1735 /// current subtarget. 1736 /// 1737 /// The ShuffleKind distinguishes between big-endian operations with 1738 /// two different inputs (0), either-endian operations with two identical 1739 /// inputs (1), and little-endian operations with two different inputs (2). 1740 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1741 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1742 SelectionDAG &DAG) { 1743 const PPCSubtarget& Subtarget = 1744 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1745 if (!Subtarget.hasP8Vector()) 1746 return false; 1747 1748 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1749 if (ShuffleKind == 0) { 1750 if (IsLE) 1751 return false; 1752 for (unsigned i = 0; i != 16; i += 4) 1753 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1754 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1755 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1756 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1757 return false; 1758 } else if (ShuffleKind == 2) { 1759 if (!IsLE) 1760 return false; 1761 for (unsigned i = 0; i != 16; i += 4) 1762 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1763 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1764 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1765 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1766 return false; 1767 } else if (ShuffleKind == 1) { 1768 unsigned j = IsLE ? 0 : 4; 1769 for (unsigned i = 0; i != 8; i += 4) 1770 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1771 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1772 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1773 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1774 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1775 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1776 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1777 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1778 return false; 1779 } 1780 return true; 1781 } 1782 1783 /// isVMerge - Common function, used to match vmrg* shuffles. 1784 /// 1785 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1786 unsigned LHSStart, unsigned RHSStart) { 1787 if (N->getValueType(0) != MVT::v16i8) 1788 return false; 1789 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1790 "Unsupported merge size!"); 1791 1792 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1793 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1794 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1795 LHSStart+j+i*UnitSize) || 1796 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1797 RHSStart+j+i*UnitSize)) 1798 return false; 1799 } 1800 return true; 1801 } 1802 1803 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1804 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1805 /// The ShuffleKind distinguishes between big-endian merges with two 1806 /// different inputs (0), either-endian merges with two identical inputs (1), 1807 /// and little-endian merges with two different inputs (2). For the latter, 1808 /// the input operands are swapped (see PPCInstrAltivec.td). 1809 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1810 unsigned ShuffleKind, SelectionDAG &DAG) { 1811 if (DAG.getDataLayout().isLittleEndian()) { 1812 if (ShuffleKind == 1) // unary 1813 return isVMerge(N, UnitSize, 0, 0); 1814 else if (ShuffleKind == 2) // swapped 1815 return isVMerge(N, UnitSize, 0, 16); 1816 else 1817 return false; 1818 } else { 1819 if (ShuffleKind == 1) // unary 1820 return isVMerge(N, UnitSize, 8, 8); 1821 else if (ShuffleKind == 0) // normal 1822 return isVMerge(N, UnitSize, 8, 24); 1823 else 1824 return false; 1825 } 1826 } 1827 1828 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1829 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1830 /// The ShuffleKind distinguishes between big-endian merges with two 1831 /// different inputs (0), either-endian merges with two identical inputs (1), 1832 /// and little-endian merges with two different inputs (2). For the latter, 1833 /// the input operands are swapped (see PPCInstrAltivec.td). 1834 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1835 unsigned ShuffleKind, SelectionDAG &DAG) { 1836 if (DAG.getDataLayout().isLittleEndian()) { 1837 if (ShuffleKind == 1) // unary 1838 return isVMerge(N, UnitSize, 8, 8); 1839 else if (ShuffleKind == 2) // swapped 1840 return isVMerge(N, UnitSize, 8, 24); 1841 else 1842 return false; 1843 } else { 1844 if (ShuffleKind == 1) // unary 1845 return isVMerge(N, UnitSize, 0, 0); 1846 else if (ShuffleKind == 0) // normal 1847 return isVMerge(N, UnitSize, 0, 16); 1848 else 1849 return false; 1850 } 1851 } 1852 1853 /** 1854 * Common function used to match vmrgew and vmrgow shuffles 1855 * 1856 * The indexOffset determines whether to look for even or odd words in 1857 * the shuffle mask. This is based on the of the endianness of the target 1858 * machine. 1859 * - Little Endian: 1860 * - Use offset of 0 to check for odd elements 1861 * - Use offset of 4 to check for even elements 1862 * - Big Endian: 1863 * - Use offset of 0 to check for even elements 1864 * - Use offset of 4 to check for odd elements 1865 * A detailed description of the vector element ordering for little endian and 1866 * big endian can be found at 1867 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1868 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1869 * compiler differences mean to you 1870 * 1871 * The mask to the shuffle vector instruction specifies the indices of the 1872 * elements from the two input vectors to place in the result. The elements are 1873 * numbered in array-access order, starting with the first vector. These vectors 1874 * are always of type v16i8, thus each vector will contain 16 elements of size 1875 * 8. More info on the shuffle vector can be found in the 1876 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1877 * Language Reference. 1878 * 1879 * The RHSStartValue indicates whether the same input vectors are used (unary) 1880 * or two different input vectors are used, based on the following: 1881 * - If the instruction uses the same vector for both inputs, the range of the 1882 * indices will be 0 to 15. In this case, the RHSStart value passed should 1883 * be 0. 1884 * - If the instruction has two different vectors then the range of the 1885 * indices will be 0 to 31. In this case, the RHSStart value passed should 1886 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1887 * to 31 specify elements in the second vector). 1888 * 1889 * \param[in] N The shuffle vector SD Node to analyze 1890 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1891 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1892 * vector to the shuffle_vector instruction 1893 * \return true iff this shuffle vector represents an even or odd word merge 1894 */ 1895 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1896 unsigned RHSStartValue) { 1897 if (N->getValueType(0) != MVT::v16i8) 1898 return false; 1899 1900 for (unsigned i = 0; i < 2; ++i) 1901 for (unsigned j = 0; j < 4; ++j) 1902 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1903 i*RHSStartValue+j+IndexOffset) || 1904 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1905 i*RHSStartValue+j+IndexOffset+8)) 1906 return false; 1907 return true; 1908 } 1909 1910 /** 1911 * Determine if the specified shuffle mask is suitable for the vmrgew or 1912 * vmrgow instructions. 1913 * 1914 * \param[in] N The shuffle vector SD Node to analyze 1915 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1916 * \param[in] ShuffleKind Identify the type of merge: 1917 * - 0 = big-endian merge with two different inputs; 1918 * - 1 = either-endian merge with two identical inputs; 1919 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1920 * little-endian merges). 1921 * \param[in] DAG The current SelectionDAG 1922 * \return true iff this shuffle mask 1923 */ 1924 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1925 unsigned ShuffleKind, SelectionDAG &DAG) { 1926 if (DAG.getDataLayout().isLittleEndian()) { 1927 unsigned indexOffset = CheckEven ? 4 : 0; 1928 if (ShuffleKind == 1) // Unary 1929 return isVMerge(N, indexOffset, 0); 1930 else if (ShuffleKind == 2) // swapped 1931 return isVMerge(N, indexOffset, 16); 1932 else 1933 return false; 1934 } 1935 else { 1936 unsigned indexOffset = CheckEven ? 0 : 4; 1937 if (ShuffleKind == 1) // Unary 1938 return isVMerge(N, indexOffset, 0); 1939 else if (ShuffleKind == 0) // Normal 1940 return isVMerge(N, indexOffset, 16); 1941 else 1942 return false; 1943 } 1944 return false; 1945 } 1946 1947 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1948 /// amount, otherwise return -1. 1949 /// The ShuffleKind distinguishes between big-endian operations with two 1950 /// different inputs (0), either-endian operations with two identical inputs 1951 /// (1), and little-endian operations with two different inputs (2). For the 1952 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1953 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1954 SelectionDAG &DAG) { 1955 if (N->getValueType(0) != MVT::v16i8) 1956 return -1; 1957 1958 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1959 1960 // Find the first non-undef value in the shuffle mask. 1961 unsigned i; 1962 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1963 /*search*/; 1964 1965 if (i == 16) return -1; // all undef. 1966 1967 // Otherwise, check to see if the rest of the elements are consecutively 1968 // numbered from this value. 1969 unsigned ShiftAmt = SVOp->getMaskElt(i); 1970 if (ShiftAmt < i) return -1; 1971 1972 ShiftAmt -= i; 1973 bool isLE = DAG.getDataLayout().isLittleEndian(); 1974 1975 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1976 // Check the rest of the elements to see if they are consecutive. 1977 for (++i; i != 16; ++i) 1978 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1979 return -1; 1980 } else if (ShuffleKind == 1) { 1981 // Check the rest of the elements to see if they are consecutive. 1982 for (++i; i != 16; ++i) 1983 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1984 return -1; 1985 } else 1986 return -1; 1987 1988 if (isLE) 1989 ShiftAmt = 16 - ShiftAmt; 1990 1991 return ShiftAmt; 1992 } 1993 1994 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1995 /// specifies a splat of a single element that is suitable for input to 1996 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1997 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1998 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1999 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2000 2001 // The consecutive indices need to specify an element, not part of two 2002 // different elements. So abandon ship early if this isn't the case. 2003 if (N->getMaskElt(0) % EltSize != 0) 2004 return false; 2005 2006 // This is a splat operation if each element of the permute is the same, and 2007 // if the value doesn't reference the second vector. 2008 unsigned ElementBase = N->getMaskElt(0); 2009 2010 // FIXME: Handle UNDEF elements too! 2011 if (ElementBase >= 16) 2012 return false; 2013 2014 // Check that the indices are consecutive, in the case of a multi-byte element 2015 // splatted with a v16i8 mask. 2016 for (unsigned i = 1; i != EltSize; ++i) 2017 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2018 return false; 2019 2020 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2021 if (N->getMaskElt(i) < 0) continue; 2022 for (unsigned j = 0; j != EltSize; ++j) 2023 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2024 return false; 2025 } 2026 return true; 2027 } 2028 2029 /// Check that the mask is shuffling N byte elements. Within each N byte 2030 /// element of the mask, the indices could be either in increasing or 2031 /// decreasing order as long as they are consecutive. 2032 /// \param[in] N the shuffle vector SD Node to analyze 2033 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2034 /// Word/DoubleWord/QuadWord). 2035 /// \param[in] StepLen the delta indices number among the N byte element, if 2036 /// the mask is in increasing/decreasing order then it is 1/-1. 2037 /// \return true iff the mask is shuffling N byte elements. 2038 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2039 int StepLen) { 2040 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2041 "Unexpected element width."); 2042 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2043 2044 unsigned NumOfElem = 16 / Width; 2045 unsigned MaskVal[16]; // Width is never greater than 16 2046 for (unsigned i = 0; i < NumOfElem; ++i) { 2047 MaskVal[0] = N->getMaskElt(i * Width); 2048 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2049 return false; 2050 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2051 return false; 2052 } 2053 2054 for (unsigned int j = 1; j < Width; ++j) { 2055 MaskVal[j] = N->getMaskElt(i * Width + j); 2056 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2057 return false; 2058 } 2059 } 2060 } 2061 2062 return true; 2063 } 2064 2065 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2066 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2067 if (!isNByteElemShuffleMask(N, 4, 1)) 2068 return false; 2069 2070 // Now we look at mask elements 0,4,8,12 2071 unsigned M0 = N->getMaskElt(0) / 4; 2072 unsigned M1 = N->getMaskElt(4) / 4; 2073 unsigned M2 = N->getMaskElt(8) / 4; 2074 unsigned M3 = N->getMaskElt(12) / 4; 2075 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2076 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2077 2078 // Below, let H and L be arbitrary elements of the shuffle mask 2079 // where H is in the range [4,7] and L is in the range [0,3]. 2080 // H, 1, 2, 3 or L, 5, 6, 7 2081 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2082 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2083 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2084 InsertAtByte = IsLE ? 12 : 0; 2085 Swap = M0 < 4; 2086 return true; 2087 } 2088 // 0, H, 2, 3 or 4, L, 6, 7 2089 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2090 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2091 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2092 InsertAtByte = IsLE ? 8 : 4; 2093 Swap = M1 < 4; 2094 return true; 2095 } 2096 // 0, 1, H, 3 or 4, 5, L, 7 2097 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2098 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2099 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2100 InsertAtByte = IsLE ? 4 : 8; 2101 Swap = M2 < 4; 2102 return true; 2103 } 2104 // 0, 1, 2, H or 4, 5, 6, L 2105 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2106 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2107 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2108 InsertAtByte = IsLE ? 0 : 12; 2109 Swap = M3 < 4; 2110 return true; 2111 } 2112 2113 // If both vector operands for the shuffle are the same vector, the mask will 2114 // contain only elements from the first one and the second one will be undef. 2115 if (N->getOperand(1).isUndef()) { 2116 ShiftElts = 0; 2117 Swap = true; 2118 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2119 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2120 InsertAtByte = IsLE ? 12 : 0; 2121 return true; 2122 } 2123 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2124 InsertAtByte = IsLE ? 8 : 4; 2125 return true; 2126 } 2127 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2128 InsertAtByte = IsLE ? 4 : 8; 2129 return true; 2130 } 2131 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2132 InsertAtByte = IsLE ? 0 : 12; 2133 return true; 2134 } 2135 } 2136 2137 return false; 2138 } 2139 2140 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2141 bool &Swap, bool IsLE) { 2142 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2143 // Ensure each byte index of the word is consecutive. 2144 if (!isNByteElemShuffleMask(N, 4, 1)) 2145 return false; 2146 2147 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2148 unsigned M0 = N->getMaskElt(0) / 4; 2149 unsigned M1 = N->getMaskElt(4) / 4; 2150 unsigned M2 = N->getMaskElt(8) / 4; 2151 unsigned M3 = N->getMaskElt(12) / 4; 2152 2153 // If both vector operands for the shuffle are the same vector, the mask will 2154 // contain only elements from the first one and the second one will be undef. 2155 if (N->getOperand(1).isUndef()) { 2156 assert(M0 < 4 && "Indexing into an undef vector?"); 2157 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2158 return false; 2159 2160 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2161 Swap = false; 2162 return true; 2163 } 2164 2165 // Ensure each word index of the ShuffleVector Mask is consecutive. 2166 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2167 return false; 2168 2169 if (IsLE) { 2170 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2171 // Input vectors don't need to be swapped if the leading element 2172 // of the result is one of the 3 left elements of the second vector 2173 // (or if there is no shift to be done at all). 2174 Swap = false; 2175 ShiftElts = (8 - M0) % 8; 2176 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2177 // Input vectors need to be swapped if the leading element 2178 // of the result is one of the 3 left elements of the first vector 2179 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2180 Swap = true; 2181 ShiftElts = (4 - M0) % 4; 2182 } 2183 2184 return true; 2185 } else { // BE 2186 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2187 // Input vectors don't need to be swapped if the leading element 2188 // of the result is one of the 4 elements of the first vector. 2189 Swap = false; 2190 ShiftElts = M0; 2191 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2192 // Input vectors need to be swapped if the leading element 2193 // of the result is one of the 4 elements of the right vector. 2194 Swap = true; 2195 ShiftElts = M0 - 4; 2196 } 2197 2198 return true; 2199 } 2200 } 2201 2202 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2203 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2204 2205 if (!isNByteElemShuffleMask(N, Width, -1)) 2206 return false; 2207 2208 for (int i = 0; i < 16; i += Width) 2209 if (N->getMaskElt(i) != i + Width - 1) 2210 return false; 2211 2212 return true; 2213 } 2214 2215 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2216 return isXXBRShuffleMaskHelper(N, 2); 2217 } 2218 2219 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2220 return isXXBRShuffleMaskHelper(N, 4); 2221 } 2222 2223 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2224 return isXXBRShuffleMaskHelper(N, 8); 2225 } 2226 2227 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2228 return isXXBRShuffleMaskHelper(N, 16); 2229 } 2230 2231 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2232 /// if the inputs to the instruction should be swapped and set \p DM to the 2233 /// value for the immediate. 2234 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2235 /// AND element 0 of the result comes from the first input (LE) or second input 2236 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2237 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2238 /// mask. 2239 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2240 bool &Swap, bool IsLE) { 2241 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2242 2243 // Ensure each byte index of the double word is consecutive. 2244 if (!isNByteElemShuffleMask(N, 8, 1)) 2245 return false; 2246 2247 unsigned M0 = N->getMaskElt(0) / 8; 2248 unsigned M1 = N->getMaskElt(8) / 8; 2249 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2250 2251 // If both vector operands for the shuffle are the same vector, the mask will 2252 // contain only elements from the first one and the second one will be undef. 2253 if (N->getOperand(1).isUndef()) { 2254 if ((M0 | M1) < 2) { 2255 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2256 Swap = false; 2257 return true; 2258 } else 2259 return false; 2260 } 2261 2262 if (IsLE) { 2263 if (M0 > 1 && M1 < 2) { 2264 Swap = false; 2265 } else if (M0 < 2 && M1 > 1) { 2266 M0 = (M0 + 2) % 4; 2267 M1 = (M1 + 2) % 4; 2268 Swap = true; 2269 } else 2270 return false; 2271 2272 // Note: if control flow comes here that means Swap is already set above 2273 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2274 return true; 2275 } else { // BE 2276 if (M0 < 2 && M1 > 1) { 2277 Swap = false; 2278 } else if (M0 > 1 && M1 < 2) { 2279 M0 = (M0 + 2) % 4; 2280 M1 = (M1 + 2) % 4; 2281 Swap = true; 2282 } else 2283 return false; 2284 2285 // Note: if control flow comes here that means Swap is already set above 2286 DM = (M0 << 1) + (M1 & 1); 2287 return true; 2288 } 2289 } 2290 2291 2292 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2293 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2294 /// elements are counted from the left of the vector register). 2295 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2296 SelectionDAG &DAG) { 2297 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2298 assert(isSplatShuffleMask(SVOp, EltSize)); 2299 if (DAG.getDataLayout().isLittleEndian()) 2300 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2301 else 2302 return SVOp->getMaskElt(0) / EltSize; 2303 } 2304 2305 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2306 /// by using a vspltis[bhw] instruction of the specified element size, return 2307 /// the constant being splatted. The ByteSize field indicates the number of 2308 /// bytes of each element [124] -> [bhw]. 2309 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2310 SDValue OpVal(nullptr, 0); 2311 2312 // If ByteSize of the splat is bigger than the element size of the 2313 // build_vector, then we have a case where we are checking for a splat where 2314 // multiple elements of the buildvector are folded together into a single 2315 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2316 unsigned EltSize = 16/N->getNumOperands(); 2317 if (EltSize < ByteSize) { 2318 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2319 SDValue UniquedVals[4]; 2320 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2321 2322 // See if all of the elements in the buildvector agree across. 2323 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2324 if (N->getOperand(i).isUndef()) continue; 2325 // If the element isn't a constant, bail fully out. 2326 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2327 2328 if (!UniquedVals[i&(Multiple-1)].getNode()) 2329 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2330 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2331 return SDValue(); // no match. 2332 } 2333 2334 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2335 // either constant or undef values that are identical for each chunk. See 2336 // if these chunks can form into a larger vspltis*. 2337 2338 // Check to see if all of the leading entries are either 0 or -1. If 2339 // neither, then this won't fit into the immediate field. 2340 bool LeadingZero = true; 2341 bool LeadingOnes = true; 2342 for (unsigned i = 0; i != Multiple-1; ++i) { 2343 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2344 2345 LeadingZero &= isNullConstant(UniquedVals[i]); 2346 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2347 } 2348 // Finally, check the least significant entry. 2349 if (LeadingZero) { 2350 if (!UniquedVals[Multiple-1].getNode()) 2351 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2352 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2353 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2354 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2355 } 2356 if (LeadingOnes) { 2357 if (!UniquedVals[Multiple-1].getNode()) 2358 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2359 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2360 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2361 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2362 } 2363 2364 return SDValue(); 2365 } 2366 2367 // Check to see if this buildvec has a single non-undef value in its elements. 2368 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2369 if (N->getOperand(i).isUndef()) continue; 2370 if (!OpVal.getNode()) 2371 OpVal = N->getOperand(i); 2372 else if (OpVal != N->getOperand(i)) 2373 return SDValue(); 2374 } 2375 2376 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2377 2378 unsigned ValSizeInBytes = EltSize; 2379 uint64_t Value = 0; 2380 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2381 Value = CN->getZExtValue(); 2382 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2383 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2384 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2385 } 2386 2387 // If the splat value is larger than the element value, then we can never do 2388 // this splat. The only case that we could fit the replicated bits into our 2389 // immediate field for would be zero, and we prefer to use vxor for it. 2390 if (ValSizeInBytes < ByteSize) return SDValue(); 2391 2392 // If the element value is larger than the splat value, check if it consists 2393 // of a repeated bit pattern of size ByteSize. 2394 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2395 return SDValue(); 2396 2397 // Properly sign extend the value. 2398 int MaskVal = SignExtend32(Value, ByteSize * 8); 2399 2400 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2401 if (MaskVal == 0) return SDValue(); 2402 2403 // Finally, if this value fits in a 5 bit sext field, return it 2404 if (SignExtend32<5>(MaskVal) == MaskVal) 2405 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2406 return SDValue(); 2407 } 2408 2409 //===----------------------------------------------------------------------===// 2410 // Addressing Mode Selection 2411 //===----------------------------------------------------------------------===// 2412 2413 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2414 /// or 64-bit immediate, and if the value can be accurately represented as a 2415 /// sign extension from a 16-bit value. If so, this returns true and the 2416 /// immediate. 2417 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2418 if (!isa<ConstantSDNode>(N)) 2419 return false; 2420 2421 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2422 if (N->getValueType(0) == MVT::i32) 2423 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2424 else 2425 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2426 } 2427 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2428 return isIntS16Immediate(Op.getNode(), Imm); 2429 } 2430 2431 2432 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2433 /// be represented as an indexed [r+r] operation. 2434 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2435 SDValue &Index, 2436 SelectionDAG &DAG) const { 2437 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2438 UI != E; ++UI) { 2439 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2440 if (Memop->getMemoryVT() == MVT::f64) { 2441 Base = N.getOperand(0); 2442 Index = N.getOperand(1); 2443 return true; 2444 } 2445 } 2446 } 2447 return false; 2448 } 2449 2450 /// isIntS34Immediate - This method tests if value of node given can be 2451 /// accurately represented as a sign extension from a 34-bit value. If so, 2452 /// this returns true and the immediate. 2453 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2454 if (!isa<ConstantSDNode>(N)) 2455 return false; 2456 2457 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2458 return isInt<34>(Imm); 2459 } 2460 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2461 return isIntS34Immediate(Op.getNode(), Imm); 2462 } 2463 2464 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2465 /// can be represented as an indexed [r+r] operation. Returns false if it 2466 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2467 /// non-zero and N can be represented by a base register plus a signed 16-bit 2468 /// displacement, make a more precise judgement by checking (displacement % \p 2469 /// EncodingAlignment). 2470 bool PPCTargetLowering::SelectAddressRegReg( 2471 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2472 MaybeAlign EncodingAlignment) const { 2473 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2474 // a [pc+imm]. 2475 if (SelectAddressPCRel(N, Base)) 2476 return false; 2477 2478 int16_t Imm = 0; 2479 if (N.getOpcode() == ISD::ADD) { 2480 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2481 // SPE load/store can only handle 8-bit offsets. 2482 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2483 return true; 2484 if (isIntS16Immediate(N.getOperand(1), Imm) && 2485 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2486 return false; // r+i 2487 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2488 return false; // r+i 2489 2490 Base = N.getOperand(0); 2491 Index = N.getOperand(1); 2492 return true; 2493 } else if (N.getOpcode() == ISD::OR) { 2494 if (isIntS16Immediate(N.getOperand(1), Imm) && 2495 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2496 return false; // r+i can fold it if we can. 2497 2498 // If this is an or of disjoint bitfields, we can codegen this as an add 2499 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2500 // disjoint. 2501 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2502 2503 if (LHSKnown.Zero.getBoolValue()) { 2504 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2505 // If all of the bits are known zero on the LHS or RHS, the add won't 2506 // carry. 2507 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2508 Base = N.getOperand(0); 2509 Index = N.getOperand(1); 2510 return true; 2511 } 2512 } 2513 } 2514 2515 return false; 2516 } 2517 2518 // If we happen to be doing an i64 load or store into a stack slot that has 2519 // less than a 4-byte alignment, then the frame-index elimination may need to 2520 // use an indexed load or store instruction (because the offset may not be a 2521 // multiple of 4). The extra register needed to hold the offset comes from the 2522 // register scavenger, and it is possible that the scavenger will need to use 2523 // an emergency spill slot. As a result, we need to make sure that a spill slot 2524 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2525 // stack slot. 2526 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2527 // FIXME: This does not handle the LWA case. 2528 if (VT != MVT::i64) 2529 return; 2530 2531 // NOTE: We'll exclude negative FIs here, which come from argument 2532 // lowering, because there are no known test cases triggering this problem 2533 // using packed structures (or similar). We can remove this exclusion if 2534 // we find such a test case. The reason why this is so test-case driven is 2535 // because this entire 'fixup' is only to prevent crashes (from the 2536 // register scavenger) on not-really-valid inputs. For example, if we have: 2537 // %a = alloca i1 2538 // %b = bitcast i1* %a to i64* 2539 // store i64* a, i64 b 2540 // then the store should really be marked as 'align 1', but is not. If it 2541 // were marked as 'align 1' then the indexed form would have been 2542 // instruction-selected initially, and the problem this 'fixup' is preventing 2543 // won't happen regardless. 2544 if (FrameIdx < 0) 2545 return; 2546 2547 MachineFunction &MF = DAG.getMachineFunction(); 2548 MachineFrameInfo &MFI = MF.getFrameInfo(); 2549 2550 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2551 return; 2552 2553 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2554 FuncInfo->setHasNonRISpills(); 2555 } 2556 2557 /// Returns true if the address N can be represented by a base register plus 2558 /// a signed 16-bit displacement [r+imm], and if it is not better 2559 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2560 /// displacements that are multiples of that value. 2561 bool PPCTargetLowering::SelectAddressRegImm( 2562 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2563 MaybeAlign EncodingAlignment) const { 2564 // FIXME dl should come from parent load or store, not from address 2565 SDLoc dl(N); 2566 2567 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2568 // a [pc+imm]. 2569 if (SelectAddressPCRel(N, Base)) 2570 return false; 2571 2572 // If this can be more profitably realized as r+r, fail. 2573 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2574 return false; 2575 2576 if (N.getOpcode() == ISD::ADD) { 2577 int16_t imm = 0; 2578 if (isIntS16Immediate(N.getOperand(1), imm) && 2579 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2580 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2581 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2582 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2583 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2584 } else { 2585 Base = N.getOperand(0); 2586 } 2587 return true; // [r+i] 2588 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2589 // Match LOAD (ADD (X, Lo(G))). 2590 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2591 && "Cannot handle constant offsets yet!"); 2592 Disp = N.getOperand(1).getOperand(0); // The global address. 2593 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2594 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2595 Disp.getOpcode() == ISD::TargetConstantPool || 2596 Disp.getOpcode() == ISD::TargetJumpTable); 2597 Base = N.getOperand(0); 2598 return true; // [&g+r] 2599 } 2600 } else if (N.getOpcode() == ISD::OR) { 2601 int16_t imm = 0; 2602 if (isIntS16Immediate(N.getOperand(1), imm) && 2603 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2604 // If this is an or of disjoint bitfields, we can codegen this as an add 2605 // (for better address arithmetic) if the LHS and RHS of the OR are 2606 // provably disjoint. 2607 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2608 2609 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2610 // If all of the bits are known zero on the LHS or RHS, the add won't 2611 // carry. 2612 if (FrameIndexSDNode *FI = 2613 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2614 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2615 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2616 } else { 2617 Base = N.getOperand(0); 2618 } 2619 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2620 return true; 2621 } 2622 } 2623 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2624 // Loading from a constant address. 2625 2626 // If this address fits entirely in a 16-bit sext immediate field, codegen 2627 // this as "d, 0" 2628 int16_t Imm; 2629 if (isIntS16Immediate(CN, Imm) && 2630 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2631 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2632 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2633 CN->getValueType(0)); 2634 return true; 2635 } 2636 2637 // Handle 32-bit sext immediates with LIS + addr mode. 2638 if ((CN->getValueType(0) == MVT::i32 || 2639 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2640 (!EncodingAlignment || 2641 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2642 int Addr = (int)CN->getZExtValue(); 2643 2644 // Otherwise, break this down into an LIS + disp. 2645 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2646 2647 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2648 MVT::i32); 2649 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2650 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2651 return true; 2652 } 2653 } 2654 2655 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2656 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2657 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2658 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2659 } else 2660 Base = N; 2661 return true; // [r+0] 2662 } 2663 2664 /// Similar to the 16-bit case but for instructions that take a 34-bit 2665 /// displacement field (prefixed loads/stores). 2666 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2667 SDValue &Base, 2668 SelectionDAG &DAG) const { 2669 // Only on 64-bit targets. 2670 if (N.getValueType() != MVT::i64) 2671 return false; 2672 2673 SDLoc dl(N); 2674 int64_t Imm = 0; 2675 2676 if (N.getOpcode() == ISD::ADD) { 2677 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2678 return false; 2679 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2680 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2681 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2682 else 2683 Base = N.getOperand(0); 2684 return true; 2685 } 2686 2687 if (N.getOpcode() == ISD::OR) { 2688 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2689 return false; 2690 // If this is an or of disjoint bitfields, we can codegen this as an add 2691 // (for better address arithmetic) if the LHS and RHS of the OR are 2692 // provably disjoint. 2693 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2694 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2695 return false; 2696 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2697 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2698 else 2699 Base = N.getOperand(0); 2700 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2701 return true; 2702 } 2703 2704 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2705 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2706 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2707 return true; 2708 } 2709 2710 return false; 2711 } 2712 2713 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2714 /// represented as an indexed [r+r] operation. 2715 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2716 SDValue &Index, 2717 SelectionDAG &DAG) const { 2718 // Check to see if we can easily represent this as an [r+r] address. This 2719 // will fail if it thinks that the address is more profitably represented as 2720 // reg+imm, e.g. where imm = 0. 2721 if (SelectAddressRegReg(N, Base, Index, DAG)) 2722 return true; 2723 2724 // If the address is the result of an add, we will utilize the fact that the 2725 // address calculation includes an implicit add. However, we can reduce 2726 // register pressure if we do not materialize a constant just for use as the 2727 // index register. We only get rid of the add if it is not an add of a 2728 // value and a 16-bit signed constant and both have a single use. 2729 int16_t imm = 0; 2730 if (N.getOpcode() == ISD::ADD && 2731 (!isIntS16Immediate(N.getOperand(1), imm) || 2732 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2733 Base = N.getOperand(0); 2734 Index = N.getOperand(1); 2735 return true; 2736 } 2737 2738 // Otherwise, do it the hard way, using R0 as the base register. 2739 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2740 N.getValueType()); 2741 Index = N; 2742 return true; 2743 } 2744 2745 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2746 Ty *PCRelCand = dyn_cast<Ty>(N); 2747 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2748 } 2749 2750 /// Returns true if this address is a PC Relative address. 2751 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2752 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2753 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2754 // This is a materialize PC Relative node. Always select this as PC Relative. 2755 Base = N; 2756 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2757 return true; 2758 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2759 isValidPCRelNode<GlobalAddressSDNode>(N) || 2760 isValidPCRelNode<JumpTableSDNode>(N) || 2761 isValidPCRelNode<BlockAddressSDNode>(N)) 2762 return true; 2763 return false; 2764 } 2765 2766 /// Returns true if we should use a direct load into vector instruction 2767 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2768 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2769 2770 // If there are any other uses other than scalar to vector, then we should 2771 // keep it as a scalar load -> direct move pattern to prevent multiple 2772 // loads. 2773 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2774 if (!LD) 2775 return false; 2776 2777 EVT MemVT = LD->getMemoryVT(); 2778 if (!MemVT.isSimple()) 2779 return false; 2780 switch(MemVT.getSimpleVT().SimpleTy) { 2781 case MVT::i64: 2782 break; 2783 case MVT::i32: 2784 if (!ST.hasP8Vector()) 2785 return false; 2786 break; 2787 case MVT::i16: 2788 case MVT::i8: 2789 if (!ST.hasP9Vector()) 2790 return false; 2791 break; 2792 default: 2793 return false; 2794 } 2795 2796 SDValue LoadedVal(N, 0); 2797 if (!LoadedVal.hasOneUse()) 2798 return false; 2799 2800 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2801 UI != UE; ++UI) 2802 if (UI.getUse().get().getResNo() == 0 && 2803 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2804 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2805 return false; 2806 2807 return true; 2808 } 2809 2810 /// getPreIndexedAddressParts - returns true by value, base pointer and 2811 /// offset pointer and addressing mode by reference if the node's address 2812 /// can be legally represented as pre-indexed load / store address. 2813 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2814 SDValue &Offset, 2815 ISD::MemIndexedMode &AM, 2816 SelectionDAG &DAG) const { 2817 if (DisablePPCPreinc) return false; 2818 2819 bool isLoad = true; 2820 SDValue Ptr; 2821 EVT VT; 2822 unsigned Alignment; 2823 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2824 Ptr = LD->getBasePtr(); 2825 VT = LD->getMemoryVT(); 2826 Alignment = LD->getAlignment(); 2827 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2828 Ptr = ST->getBasePtr(); 2829 VT = ST->getMemoryVT(); 2830 Alignment = ST->getAlignment(); 2831 isLoad = false; 2832 } else 2833 return false; 2834 2835 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2836 // instructions because we can fold these into a more efficient instruction 2837 // instead, (such as LXSD). 2838 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2839 return false; 2840 } 2841 2842 // PowerPC doesn't have preinc load/store instructions for vectors 2843 if (VT.isVector()) 2844 return false; 2845 2846 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2847 // Common code will reject creating a pre-inc form if the base pointer 2848 // is a frame index, or if N is a store and the base pointer is either 2849 // the same as or a predecessor of the value being stored. Check for 2850 // those situations here, and try with swapped Base/Offset instead. 2851 bool Swap = false; 2852 2853 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2854 Swap = true; 2855 else if (!isLoad) { 2856 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2857 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2858 Swap = true; 2859 } 2860 2861 if (Swap) 2862 std::swap(Base, Offset); 2863 2864 AM = ISD::PRE_INC; 2865 return true; 2866 } 2867 2868 // LDU/STU can only handle immediates that are a multiple of 4. 2869 if (VT != MVT::i64) { 2870 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2871 return false; 2872 } else { 2873 // LDU/STU need an address with at least 4-byte alignment. 2874 if (Alignment < 4) 2875 return false; 2876 2877 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2878 return false; 2879 } 2880 2881 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2882 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2883 // sext i32 to i64 when addr mode is r+i. 2884 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2885 LD->getExtensionType() == ISD::SEXTLOAD && 2886 isa<ConstantSDNode>(Offset)) 2887 return false; 2888 } 2889 2890 AM = ISD::PRE_INC; 2891 return true; 2892 } 2893 2894 //===----------------------------------------------------------------------===// 2895 // LowerOperation implementation 2896 //===----------------------------------------------------------------------===// 2897 2898 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2899 /// and LoOpFlags to the target MO flags. 2900 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2901 unsigned &HiOpFlags, unsigned &LoOpFlags, 2902 const GlobalValue *GV = nullptr) { 2903 HiOpFlags = PPCII::MO_HA; 2904 LoOpFlags = PPCII::MO_LO; 2905 2906 // Don't use the pic base if not in PIC relocation model. 2907 if (IsPIC) { 2908 HiOpFlags |= PPCII::MO_PIC_FLAG; 2909 LoOpFlags |= PPCII::MO_PIC_FLAG; 2910 } 2911 } 2912 2913 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2914 SelectionDAG &DAG) { 2915 SDLoc DL(HiPart); 2916 EVT PtrVT = HiPart.getValueType(); 2917 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2918 2919 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2920 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2921 2922 // With PIC, the first instruction is actually "GR+hi(&G)". 2923 if (isPIC) 2924 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2925 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2926 2927 // Generate non-pic code that has direct accesses to the constant pool. 2928 // The address of the global is just (hi(&g)+lo(&g)). 2929 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2930 } 2931 2932 static void setUsesTOCBasePtr(MachineFunction &MF) { 2933 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2934 FuncInfo->setUsesTOCBasePtr(); 2935 } 2936 2937 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2938 setUsesTOCBasePtr(DAG.getMachineFunction()); 2939 } 2940 2941 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2942 SDValue GA) const { 2943 const bool Is64Bit = Subtarget.isPPC64(); 2944 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2945 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2946 : Subtarget.isAIXABI() 2947 ? DAG.getRegister(PPC::R2, VT) 2948 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2949 SDValue Ops[] = { GA, Reg }; 2950 return DAG.getMemIntrinsicNode( 2951 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2952 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2953 MachineMemOperand::MOLoad); 2954 } 2955 2956 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2957 SelectionDAG &DAG) const { 2958 EVT PtrVT = Op.getValueType(); 2959 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2960 const Constant *C = CP->getConstVal(); 2961 2962 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2963 // The actual address of the GlobalValue is stored in the TOC. 2964 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2965 if (Subtarget.isUsingPCRelativeCalls()) { 2966 SDLoc DL(CP); 2967 EVT Ty = getPointerTy(DAG.getDataLayout()); 2968 SDValue ConstPool = DAG.getTargetConstantPool( 2969 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2970 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2971 } 2972 setUsesTOCBasePtr(DAG); 2973 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2974 return getTOCEntry(DAG, SDLoc(CP), GA); 2975 } 2976 2977 unsigned MOHiFlag, MOLoFlag; 2978 bool IsPIC = isPositionIndependent(); 2979 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2980 2981 if (IsPIC && Subtarget.isSVR4ABI()) { 2982 SDValue GA = 2983 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2984 return getTOCEntry(DAG, SDLoc(CP), GA); 2985 } 2986 2987 SDValue CPIHi = 2988 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2989 SDValue CPILo = 2990 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2991 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2992 } 2993 2994 // For 64-bit PowerPC, prefer the more compact relative encodings. 2995 // This trades 32 bits per jump table entry for one or two instructions 2996 // on the jump site. 2997 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2998 if (isJumpTableRelative()) 2999 return MachineJumpTableInfo::EK_LabelDifference32; 3000 3001 return TargetLowering::getJumpTableEncoding(); 3002 } 3003 3004 bool PPCTargetLowering::isJumpTableRelative() const { 3005 if (UseAbsoluteJumpTables) 3006 return false; 3007 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3008 return true; 3009 return TargetLowering::isJumpTableRelative(); 3010 } 3011 3012 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3013 SelectionDAG &DAG) const { 3014 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3015 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3016 3017 switch (getTargetMachine().getCodeModel()) { 3018 case CodeModel::Small: 3019 case CodeModel::Medium: 3020 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3021 default: 3022 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3023 getPointerTy(DAG.getDataLayout())); 3024 } 3025 } 3026 3027 const MCExpr * 3028 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3029 unsigned JTI, 3030 MCContext &Ctx) const { 3031 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3032 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3033 3034 switch (getTargetMachine().getCodeModel()) { 3035 case CodeModel::Small: 3036 case CodeModel::Medium: 3037 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3038 default: 3039 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3040 } 3041 } 3042 3043 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3044 EVT PtrVT = Op.getValueType(); 3045 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3046 3047 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3048 if (Subtarget.isUsingPCRelativeCalls()) { 3049 SDLoc DL(JT); 3050 EVT Ty = getPointerTy(DAG.getDataLayout()); 3051 SDValue GA = 3052 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3053 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3054 return MatAddr; 3055 } 3056 3057 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3058 // The actual address of the GlobalValue is stored in the TOC. 3059 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3060 setUsesTOCBasePtr(DAG); 3061 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3062 return getTOCEntry(DAG, SDLoc(JT), GA); 3063 } 3064 3065 unsigned MOHiFlag, MOLoFlag; 3066 bool IsPIC = isPositionIndependent(); 3067 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3068 3069 if (IsPIC && Subtarget.isSVR4ABI()) { 3070 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3071 PPCII::MO_PIC_FLAG); 3072 return getTOCEntry(DAG, SDLoc(GA), GA); 3073 } 3074 3075 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3076 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3077 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3078 } 3079 3080 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3081 SelectionDAG &DAG) const { 3082 EVT PtrVT = Op.getValueType(); 3083 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3084 const BlockAddress *BA = BASDN->getBlockAddress(); 3085 3086 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3087 if (Subtarget.isUsingPCRelativeCalls()) { 3088 SDLoc DL(BASDN); 3089 EVT Ty = getPointerTy(DAG.getDataLayout()); 3090 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3091 PPCII::MO_PCREL_FLAG); 3092 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3093 return MatAddr; 3094 } 3095 3096 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3097 // The actual BlockAddress is stored in the TOC. 3098 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3099 setUsesTOCBasePtr(DAG); 3100 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3101 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3102 } 3103 3104 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3105 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3106 return getTOCEntry( 3107 DAG, SDLoc(BASDN), 3108 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3109 3110 unsigned MOHiFlag, MOLoFlag; 3111 bool IsPIC = isPositionIndependent(); 3112 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3113 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3114 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3115 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3116 } 3117 3118 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3119 SelectionDAG &DAG) const { 3120 if (Subtarget.isAIXABI()) 3121 report_fatal_error("TLS is not yet supported on AIX."); 3122 // FIXME: TLS addresses currently use medium model code sequences, 3123 // which is the most useful form. Eventually support for small and 3124 // large models could be added if users need it, at the cost of 3125 // additional complexity. 3126 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3127 if (DAG.getTarget().useEmulatedTLS()) 3128 return LowerToTLSEmulatedModel(GA, DAG); 3129 3130 SDLoc dl(GA); 3131 const GlobalValue *GV = GA->getGlobal(); 3132 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3133 bool is64bit = Subtarget.isPPC64(); 3134 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3135 PICLevel::Level picLevel = M->getPICLevel(); 3136 3137 const TargetMachine &TM = getTargetMachine(); 3138 TLSModel::Model Model = TM.getTLSModel(GV); 3139 3140 if (Model == TLSModel::LocalExec) { 3141 if (Subtarget.isUsingPCRelativeCalls()) { 3142 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3143 SDValue TGA = DAG.getTargetGlobalAddress( 3144 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3145 SDValue MatAddr = 3146 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3147 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3148 } 3149 3150 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3151 PPCII::MO_TPREL_HA); 3152 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3153 PPCII::MO_TPREL_LO); 3154 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3155 : DAG.getRegister(PPC::R2, MVT::i32); 3156 3157 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3158 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3159 } 3160 3161 if (Model == TLSModel::InitialExec) { 3162 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3163 SDValue TGA = DAG.getTargetGlobalAddress( 3164 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3165 SDValue TGATLS = DAG.getTargetGlobalAddress( 3166 GV, dl, PtrVT, 0, 3167 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3168 SDValue TPOffset; 3169 if (IsPCRel) { 3170 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3171 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3172 MachinePointerInfo()); 3173 } else { 3174 SDValue GOTPtr; 3175 if (is64bit) { 3176 setUsesTOCBasePtr(DAG); 3177 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3178 GOTPtr = 3179 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3180 } else { 3181 if (!TM.isPositionIndependent()) 3182 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3183 else if (picLevel == PICLevel::SmallPIC) 3184 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3185 else 3186 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3187 } 3188 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3189 } 3190 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3191 } 3192 3193 if (Model == TLSModel::GeneralDynamic) { 3194 if (Subtarget.isUsingPCRelativeCalls()) { 3195 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3196 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3197 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3198 } 3199 3200 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3201 SDValue GOTPtr; 3202 if (is64bit) { 3203 setUsesTOCBasePtr(DAG); 3204 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3205 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3206 GOTReg, TGA); 3207 } else { 3208 if (picLevel == PICLevel::SmallPIC) 3209 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3210 else 3211 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3212 } 3213 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3214 GOTPtr, TGA, TGA); 3215 } 3216 3217 if (Model == TLSModel::LocalDynamic) { 3218 if (Subtarget.isUsingPCRelativeCalls()) { 3219 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3220 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3221 SDValue MatPCRel = 3222 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3223 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3224 } 3225 3226 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3227 SDValue GOTPtr; 3228 if (is64bit) { 3229 setUsesTOCBasePtr(DAG); 3230 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3231 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3232 GOTReg, TGA); 3233 } else { 3234 if (picLevel == PICLevel::SmallPIC) 3235 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3236 else 3237 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3238 } 3239 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3240 PtrVT, GOTPtr, TGA, TGA); 3241 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3242 PtrVT, TLSAddr, TGA); 3243 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3244 } 3245 3246 llvm_unreachable("Unknown TLS model!"); 3247 } 3248 3249 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3250 SelectionDAG &DAG) const { 3251 EVT PtrVT = Op.getValueType(); 3252 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3253 SDLoc DL(GSDN); 3254 const GlobalValue *GV = GSDN->getGlobal(); 3255 3256 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3257 // The actual address of the GlobalValue is stored in the TOC. 3258 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3259 if (Subtarget.isUsingPCRelativeCalls()) { 3260 EVT Ty = getPointerTy(DAG.getDataLayout()); 3261 if (isAccessedAsGotIndirect(Op)) { 3262 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3263 PPCII::MO_PCREL_FLAG | 3264 PPCII::MO_GOT_FLAG); 3265 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3266 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3267 MachinePointerInfo()); 3268 return Load; 3269 } else { 3270 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3271 PPCII::MO_PCREL_FLAG); 3272 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3273 } 3274 } 3275 setUsesTOCBasePtr(DAG); 3276 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3277 return getTOCEntry(DAG, DL, GA); 3278 } 3279 3280 unsigned MOHiFlag, MOLoFlag; 3281 bool IsPIC = isPositionIndependent(); 3282 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3283 3284 if (IsPIC && Subtarget.isSVR4ABI()) { 3285 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3286 GSDN->getOffset(), 3287 PPCII::MO_PIC_FLAG); 3288 return getTOCEntry(DAG, DL, GA); 3289 } 3290 3291 SDValue GAHi = 3292 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3293 SDValue GALo = 3294 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3295 3296 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3297 } 3298 3299 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3300 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3301 SDLoc dl(Op); 3302 3303 if (Op.getValueType() == MVT::v2i64) { 3304 // When the operands themselves are v2i64 values, we need to do something 3305 // special because VSX has no underlying comparison operations for these. 3306 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3307 // Equality can be handled by casting to the legal type for Altivec 3308 // comparisons, everything else needs to be expanded. 3309 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3310 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3311 DAG.getSetCC(dl, MVT::v4i32, 3312 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3313 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3314 CC)); 3315 } 3316 3317 return SDValue(); 3318 } 3319 3320 // We handle most of these in the usual way. 3321 return Op; 3322 } 3323 3324 // If we're comparing for equality to zero, expose the fact that this is 3325 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3326 // fold the new nodes. 3327 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3328 return V; 3329 3330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3331 // Leave comparisons against 0 and -1 alone for now, since they're usually 3332 // optimized. FIXME: revisit this when we can custom lower all setcc 3333 // optimizations. 3334 if (C->isAllOnesValue() || C->isNullValue()) 3335 return SDValue(); 3336 } 3337 3338 // If we have an integer seteq/setne, turn it into a compare against zero 3339 // by xor'ing the rhs with the lhs, which is faster than setting a 3340 // condition register, reading it back out, and masking the correct bit. The 3341 // normal approach here uses sub to do this instead of xor. Using xor exposes 3342 // the result to other bit-twiddling opportunities. 3343 EVT LHSVT = Op.getOperand(0).getValueType(); 3344 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3345 EVT VT = Op.getValueType(); 3346 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3347 Op.getOperand(1)); 3348 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3349 } 3350 return SDValue(); 3351 } 3352 3353 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3354 SDNode *Node = Op.getNode(); 3355 EVT VT = Node->getValueType(0); 3356 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3357 SDValue InChain = Node->getOperand(0); 3358 SDValue VAListPtr = Node->getOperand(1); 3359 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3360 SDLoc dl(Node); 3361 3362 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3363 3364 // gpr_index 3365 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3366 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3367 InChain = GprIndex.getValue(1); 3368 3369 if (VT == MVT::i64) { 3370 // Check if GprIndex is even 3371 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3372 DAG.getConstant(1, dl, MVT::i32)); 3373 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3374 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3375 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3376 DAG.getConstant(1, dl, MVT::i32)); 3377 // Align GprIndex to be even if it isn't 3378 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3379 GprIndex); 3380 } 3381 3382 // fpr index is 1 byte after gpr 3383 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3384 DAG.getConstant(1, dl, MVT::i32)); 3385 3386 // fpr 3387 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3388 FprPtr, MachinePointerInfo(SV), MVT::i8); 3389 InChain = FprIndex.getValue(1); 3390 3391 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3392 DAG.getConstant(8, dl, MVT::i32)); 3393 3394 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3395 DAG.getConstant(4, dl, MVT::i32)); 3396 3397 // areas 3398 SDValue OverflowArea = 3399 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3400 InChain = OverflowArea.getValue(1); 3401 3402 SDValue RegSaveArea = 3403 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3404 InChain = RegSaveArea.getValue(1); 3405 3406 // select overflow_area if index > 8 3407 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3408 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3409 3410 // adjustment constant gpr_index * 4/8 3411 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3412 VT.isInteger() ? GprIndex : FprIndex, 3413 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3414 MVT::i32)); 3415 3416 // OurReg = RegSaveArea + RegConstant 3417 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3418 RegConstant); 3419 3420 // Floating types are 32 bytes into RegSaveArea 3421 if (VT.isFloatingPoint()) 3422 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3423 DAG.getConstant(32, dl, MVT::i32)); 3424 3425 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3426 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3427 VT.isInteger() ? GprIndex : FprIndex, 3428 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3429 MVT::i32)); 3430 3431 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3432 VT.isInteger() ? VAListPtr : FprPtr, 3433 MachinePointerInfo(SV), MVT::i8); 3434 3435 // determine if we should load from reg_save_area or overflow_area 3436 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3437 3438 // increase overflow_area by 4/8 if gpr/fpr > 8 3439 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3440 DAG.getConstant(VT.isInteger() ? 4 : 8, 3441 dl, MVT::i32)); 3442 3443 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3444 OverflowAreaPlusN); 3445 3446 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3447 MachinePointerInfo(), MVT::i32); 3448 3449 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3450 } 3451 3452 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3453 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3454 3455 // We have to copy the entire va_list struct: 3456 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3457 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3458 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3459 false, true, false, MachinePointerInfo(), 3460 MachinePointerInfo()); 3461 } 3462 3463 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3464 SelectionDAG &DAG) const { 3465 if (Subtarget.isAIXABI()) 3466 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3467 3468 return Op.getOperand(0); 3469 } 3470 3471 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3472 SelectionDAG &DAG) const { 3473 if (Subtarget.isAIXABI()) 3474 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3475 3476 SDValue Chain = Op.getOperand(0); 3477 SDValue Trmp = Op.getOperand(1); // trampoline 3478 SDValue FPtr = Op.getOperand(2); // nested function 3479 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3480 SDLoc dl(Op); 3481 3482 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3483 bool isPPC64 = (PtrVT == MVT::i64); 3484 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3485 3486 TargetLowering::ArgListTy Args; 3487 TargetLowering::ArgListEntry Entry; 3488 3489 Entry.Ty = IntPtrTy; 3490 Entry.Node = Trmp; Args.push_back(Entry); 3491 3492 // TrampSize == (isPPC64 ? 48 : 40); 3493 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3494 isPPC64 ? MVT::i64 : MVT::i32); 3495 Args.push_back(Entry); 3496 3497 Entry.Node = FPtr; Args.push_back(Entry); 3498 Entry.Node = Nest; Args.push_back(Entry); 3499 3500 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3501 TargetLowering::CallLoweringInfo CLI(DAG); 3502 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3503 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3504 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3505 3506 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3507 return CallResult.second; 3508 } 3509 3510 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3511 MachineFunction &MF = DAG.getMachineFunction(); 3512 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3513 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3514 3515 SDLoc dl(Op); 3516 3517 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3518 // vastart just stores the address of the VarArgsFrameIndex slot into the 3519 // memory location argument. 3520 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3521 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3522 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3523 MachinePointerInfo(SV)); 3524 } 3525 3526 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3527 // We suppose the given va_list is already allocated. 3528 // 3529 // typedef struct { 3530 // char gpr; /* index into the array of 8 GPRs 3531 // * stored in the register save area 3532 // * gpr=0 corresponds to r3, 3533 // * gpr=1 to r4, etc. 3534 // */ 3535 // char fpr; /* index into the array of 8 FPRs 3536 // * stored in the register save area 3537 // * fpr=0 corresponds to f1, 3538 // * fpr=1 to f2, etc. 3539 // */ 3540 // char *overflow_arg_area; 3541 // /* location on stack that holds 3542 // * the next overflow argument 3543 // */ 3544 // char *reg_save_area; 3545 // /* where r3:r10 and f1:f8 (if saved) 3546 // * are stored 3547 // */ 3548 // } va_list[1]; 3549 3550 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3551 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3552 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3553 PtrVT); 3554 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3555 PtrVT); 3556 3557 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3558 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3559 3560 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3561 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3562 3563 uint64_t FPROffset = 1; 3564 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3565 3566 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3567 3568 // Store first byte : number of int regs 3569 SDValue firstStore = 3570 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3571 MachinePointerInfo(SV), MVT::i8); 3572 uint64_t nextOffset = FPROffset; 3573 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3574 ConstFPROffset); 3575 3576 // Store second byte : number of float regs 3577 SDValue secondStore = 3578 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3579 MachinePointerInfo(SV, nextOffset), MVT::i8); 3580 nextOffset += StackOffset; 3581 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3582 3583 // Store second word : arguments given on stack 3584 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3585 MachinePointerInfo(SV, nextOffset)); 3586 nextOffset += FrameOffset; 3587 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3588 3589 // Store third word : arguments given in registers 3590 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3591 MachinePointerInfo(SV, nextOffset)); 3592 } 3593 3594 /// FPR - The set of FP registers that should be allocated for arguments 3595 /// on Darwin and AIX. 3596 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3597 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3598 PPC::F11, PPC::F12, PPC::F13}; 3599 3600 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3601 /// the stack. 3602 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3603 unsigned PtrByteSize) { 3604 unsigned ArgSize = ArgVT.getStoreSize(); 3605 if (Flags.isByVal()) 3606 ArgSize = Flags.getByValSize(); 3607 3608 // Round up to multiples of the pointer size, except for array members, 3609 // which are always packed. 3610 if (!Flags.isInConsecutiveRegs()) 3611 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3612 3613 return ArgSize; 3614 } 3615 3616 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3617 /// on the stack. 3618 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3619 ISD::ArgFlagsTy Flags, 3620 unsigned PtrByteSize) { 3621 Align Alignment(PtrByteSize); 3622 3623 // Altivec parameters are padded to a 16 byte boundary. 3624 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3625 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3626 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3627 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3628 Alignment = Align(16); 3629 3630 // ByVal parameters are aligned as requested. 3631 if (Flags.isByVal()) { 3632 auto BVAlign = Flags.getNonZeroByValAlign(); 3633 if (BVAlign > PtrByteSize) { 3634 if (BVAlign.value() % PtrByteSize != 0) 3635 llvm_unreachable( 3636 "ByVal alignment is not a multiple of the pointer size"); 3637 3638 Alignment = BVAlign; 3639 } 3640 } 3641 3642 // Array members are always packed to their original alignment. 3643 if (Flags.isInConsecutiveRegs()) { 3644 // If the array member was split into multiple registers, the first 3645 // needs to be aligned to the size of the full type. (Except for 3646 // ppcf128, which is only aligned as its f64 components.) 3647 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3648 Alignment = Align(OrigVT.getStoreSize()); 3649 else 3650 Alignment = Align(ArgVT.getStoreSize()); 3651 } 3652 3653 return Alignment; 3654 } 3655 3656 /// CalculateStackSlotUsed - Return whether this argument will use its 3657 /// stack slot (instead of being passed in registers). ArgOffset, 3658 /// AvailableFPRs, and AvailableVRs must hold the current argument 3659 /// position, and will be updated to account for this argument. 3660 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3661 unsigned PtrByteSize, unsigned LinkageSize, 3662 unsigned ParamAreaSize, unsigned &ArgOffset, 3663 unsigned &AvailableFPRs, 3664 unsigned &AvailableVRs) { 3665 bool UseMemory = false; 3666 3667 // Respect alignment of argument on the stack. 3668 Align Alignment = 3669 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3670 ArgOffset = alignTo(ArgOffset, Alignment); 3671 // If there's no space left in the argument save area, we must 3672 // use memory (this check also catches zero-sized arguments). 3673 if (ArgOffset >= LinkageSize + ParamAreaSize) 3674 UseMemory = true; 3675 3676 // Allocate argument on the stack. 3677 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3678 if (Flags.isInConsecutiveRegsLast()) 3679 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3680 // If we overran the argument save area, we must use memory 3681 // (this check catches arguments passed partially in memory) 3682 if (ArgOffset > LinkageSize + ParamAreaSize) 3683 UseMemory = true; 3684 3685 // However, if the argument is actually passed in an FPR or a VR, 3686 // we don't use memory after all. 3687 if (!Flags.isByVal()) { 3688 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3689 if (AvailableFPRs > 0) { 3690 --AvailableFPRs; 3691 return false; 3692 } 3693 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3694 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3695 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3696 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3697 if (AvailableVRs > 0) { 3698 --AvailableVRs; 3699 return false; 3700 } 3701 } 3702 3703 return UseMemory; 3704 } 3705 3706 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3707 /// ensure minimum alignment required for target. 3708 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3709 unsigned NumBytes) { 3710 return alignTo(NumBytes, Lowering->getStackAlign()); 3711 } 3712 3713 SDValue PPCTargetLowering::LowerFormalArguments( 3714 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3715 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3716 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3717 if (Subtarget.isAIXABI()) 3718 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3719 InVals); 3720 if (Subtarget.is64BitELFABI()) 3721 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3722 InVals); 3723 assert(Subtarget.is32BitELFABI()); 3724 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3725 InVals); 3726 } 3727 3728 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3729 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3730 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3731 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3732 3733 // 32-bit SVR4 ABI Stack Frame Layout: 3734 // +-----------------------------------+ 3735 // +--> | Back chain | 3736 // | +-----------------------------------+ 3737 // | | Floating-point register save area | 3738 // | +-----------------------------------+ 3739 // | | General register save area | 3740 // | +-----------------------------------+ 3741 // | | CR save word | 3742 // | +-----------------------------------+ 3743 // | | VRSAVE save word | 3744 // | +-----------------------------------+ 3745 // | | Alignment padding | 3746 // | +-----------------------------------+ 3747 // | | Vector register save area | 3748 // | +-----------------------------------+ 3749 // | | Local variable space | 3750 // | +-----------------------------------+ 3751 // | | Parameter list area | 3752 // | +-----------------------------------+ 3753 // | | LR save word | 3754 // | +-----------------------------------+ 3755 // SP--> +--- | Back chain | 3756 // +-----------------------------------+ 3757 // 3758 // Specifications: 3759 // System V Application Binary Interface PowerPC Processor Supplement 3760 // AltiVec Technology Programming Interface Manual 3761 3762 MachineFunction &MF = DAG.getMachineFunction(); 3763 MachineFrameInfo &MFI = MF.getFrameInfo(); 3764 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3765 3766 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3767 // Potential tail calls could cause overwriting of argument stack slots. 3768 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3769 (CallConv == CallingConv::Fast)); 3770 const Align PtrAlign(4); 3771 3772 // Assign locations to all of the incoming arguments. 3773 SmallVector<CCValAssign, 16> ArgLocs; 3774 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3775 *DAG.getContext()); 3776 3777 // Reserve space for the linkage area on the stack. 3778 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3779 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3780 if (useSoftFloat()) 3781 CCInfo.PreAnalyzeFormalArguments(Ins); 3782 3783 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3784 CCInfo.clearWasPPCF128(); 3785 3786 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3787 CCValAssign &VA = ArgLocs[i]; 3788 3789 // Arguments stored in registers. 3790 if (VA.isRegLoc()) { 3791 const TargetRegisterClass *RC; 3792 EVT ValVT = VA.getValVT(); 3793 3794 switch (ValVT.getSimpleVT().SimpleTy) { 3795 default: 3796 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3797 case MVT::i1: 3798 case MVT::i32: 3799 RC = &PPC::GPRCRegClass; 3800 break; 3801 case MVT::f32: 3802 if (Subtarget.hasP8Vector()) 3803 RC = &PPC::VSSRCRegClass; 3804 else if (Subtarget.hasSPE()) 3805 RC = &PPC::GPRCRegClass; 3806 else 3807 RC = &PPC::F4RCRegClass; 3808 break; 3809 case MVT::f64: 3810 if (Subtarget.hasVSX()) 3811 RC = &PPC::VSFRCRegClass; 3812 else if (Subtarget.hasSPE()) 3813 // SPE passes doubles in GPR pairs. 3814 RC = &PPC::GPRCRegClass; 3815 else 3816 RC = &PPC::F8RCRegClass; 3817 break; 3818 case MVT::v16i8: 3819 case MVT::v8i16: 3820 case MVT::v4i32: 3821 RC = &PPC::VRRCRegClass; 3822 break; 3823 case MVT::v4f32: 3824 RC = &PPC::VRRCRegClass; 3825 break; 3826 case MVT::v2f64: 3827 case MVT::v2i64: 3828 RC = &PPC::VRRCRegClass; 3829 break; 3830 } 3831 3832 SDValue ArgValue; 3833 // Transform the arguments stored in physical registers into 3834 // virtual ones. 3835 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3836 assert(i + 1 < e && "No second half of double precision argument"); 3837 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3838 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3839 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3840 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3841 if (!Subtarget.isLittleEndian()) 3842 std::swap (ArgValueLo, ArgValueHi); 3843 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3844 ArgValueHi); 3845 } else { 3846 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3847 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3848 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3849 if (ValVT == MVT::i1) 3850 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3851 } 3852 3853 InVals.push_back(ArgValue); 3854 } else { 3855 // Argument stored in memory. 3856 assert(VA.isMemLoc()); 3857 3858 // Get the extended size of the argument type in stack 3859 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3860 // Get the actual size of the argument type 3861 unsigned ObjSize = VA.getValVT().getStoreSize(); 3862 unsigned ArgOffset = VA.getLocMemOffset(); 3863 // Stack objects in PPC32 are right justified. 3864 ArgOffset += ArgSize - ObjSize; 3865 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3866 3867 // Create load nodes to retrieve arguments from the stack. 3868 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3869 InVals.push_back( 3870 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3871 } 3872 } 3873 3874 // Assign locations to all of the incoming aggregate by value arguments. 3875 // Aggregates passed by value are stored in the local variable space of the 3876 // caller's stack frame, right above the parameter list area. 3877 SmallVector<CCValAssign, 16> ByValArgLocs; 3878 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3879 ByValArgLocs, *DAG.getContext()); 3880 3881 // Reserve stack space for the allocations in CCInfo. 3882 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3883 3884 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3885 3886 // Area that is at least reserved in the caller of this function. 3887 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3888 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3889 3890 // Set the size that is at least reserved in caller of this function. Tail 3891 // call optimized function's reserved stack space needs to be aligned so that 3892 // taking the difference between two stack areas will result in an aligned 3893 // stack. 3894 MinReservedArea = 3895 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3896 FuncInfo->setMinReservedArea(MinReservedArea); 3897 3898 SmallVector<SDValue, 8> MemOps; 3899 3900 // If the function takes variable number of arguments, make a frame index for 3901 // the start of the first vararg value... for expansion of llvm.va_start. 3902 if (isVarArg) { 3903 static const MCPhysReg GPArgRegs[] = { 3904 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3905 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3906 }; 3907 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3908 3909 static const MCPhysReg FPArgRegs[] = { 3910 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3911 PPC::F8 3912 }; 3913 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3914 3915 if (useSoftFloat() || hasSPE()) 3916 NumFPArgRegs = 0; 3917 3918 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3919 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3920 3921 // Make room for NumGPArgRegs and NumFPArgRegs. 3922 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3923 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3924 3925 FuncInfo->setVarArgsStackOffset( 3926 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3927 CCInfo.getNextStackOffset(), true)); 3928 3929 FuncInfo->setVarArgsFrameIndex( 3930 MFI.CreateStackObject(Depth, Align(8), false)); 3931 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3932 3933 // The fixed integer arguments of a variadic function are stored to the 3934 // VarArgsFrameIndex on the stack so that they may be loaded by 3935 // dereferencing the result of va_next. 3936 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3937 // Get an existing live-in vreg, or add a new one. 3938 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3939 if (!VReg) 3940 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3941 3942 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3943 SDValue Store = 3944 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3945 MemOps.push_back(Store); 3946 // Increment the address by four for the next argument to store 3947 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3948 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3949 } 3950 3951 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3952 // is set. 3953 // The double arguments are stored to the VarArgsFrameIndex 3954 // on the stack. 3955 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3956 // Get an existing live-in vreg, or add a new one. 3957 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3958 if (!VReg) 3959 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3960 3961 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3962 SDValue Store = 3963 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3964 MemOps.push_back(Store); 3965 // Increment the address by eight for the next argument to store 3966 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3967 PtrVT); 3968 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3969 } 3970 } 3971 3972 if (!MemOps.empty()) 3973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3974 3975 return Chain; 3976 } 3977 3978 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3979 // value to MVT::i64 and then truncate to the correct register size. 3980 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3981 EVT ObjectVT, SelectionDAG &DAG, 3982 SDValue ArgVal, 3983 const SDLoc &dl) const { 3984 if (Flags.isSExt()) 3985 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3986 DAG.getValueType(ObjectVT)); 3987 else if (Flags.isZExt()) 3988 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3989 DAG.getValueType(ObjectVT)); 3990 3991 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3992 } 3993 3994 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3995 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3996 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3997 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3998 // TODO: add description of PPC stack frame format, or at least some docs. 3999 // 4000 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4001 bool isLittleEndian = Subtarget.isLittleEndian(); 4002 MachineFunction &MF = DAG.getMachineFunction(); 4003 MachineFrameInfo &MFI = MF.getFrameInfo(); 4004 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4005 4006 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4007 "fastcc not supported on varargs functions"); 4008 4009 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4010 // Potential tail calls could cause overwriting of argument stack slots. 4011 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4012 (CallConv == CallingConv::Fast)); 4013 unsigned PtrByteSize = 8; 4014 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4015 4016 static const MCPhysReg GPR[] = { 4017 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4018 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4019 }; 4020 static const MCPhysReg VR[] = { 4021 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4022 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4023 }; 4024 4025 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4026 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4027 const unsigned Num_VR_Regs = array_lengthof(VR); 4028 4029 // Do a first pass over the arguments to determine whether the ABI 4030 // guarantees that our caller has allocated the parameter save area 4031 // on its stack frame. In the ELFv1 ABI, this is always the case; 4032 // in the ELFv2 ABI, it is true if this is a vararg function or if 4033 // any parameter is located in a stack slot. 4034 4035 bool HasParameterArea = !isELFv2ABI || isVarArg; 4036 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4037 unsigned NumBytes = LinkageSize; 4038 unsigned AvailableFPRs = Num_FPR_Regs; 4039 unsigned AvailableVRs = Num_VR_Regs; 4040 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4041 if (Ins[i].Flags.isNest()) 4042 continue; 4043 4044 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4045 PtrByteSize, LinkageSize, ParamAreaSize, 4046 NumBytes, AvailableFPRs, AvailableVRs)) 4047 HasParameterArea = true; 4048 } 4049 4050 // Add DAG nodes to load the arguments or copy them out of registers. On 4051 // entry to a function on PPC, the arguments start after the linkage area, 4052 // although the first ones are often in registers. 4053 4054 unsigned ArgOffset = LinkageSize; 4055 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4056 SmallVector<SDValue, 8> MemOps; 4057 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4058 unsigned CurArgIdx = 0; 4059 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4060 SDValue ArgVal; 4061 bool needsLoad = false; 4062 EVT ObjectVT = Ins[ArgNo].VT; 4063 EVT OrigVT = Ins[ArgNo].ArgVT; 4064 unsigned ObjSize = ObjectVT.getStoreSize(); 4065 unsigned ArgSize = ObjSize; 4066 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4067 if (Ins[ArgNo].isOrigArg()) { 4068 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4069 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4070 } 4071 // We re-align the argument offset for each argument, except when using the 4072 // fast calling convention, when we need to make sure we do that only when 4073 // we'll actually use a stack slot. 4074 unsigned CurArgOffset; 4075 Align Alignment; 4076 auto ComputeArgOffset = [&]() { 4077 /* Respect alignment of argument on the stack. */ 4078 Alignment = 4079 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4080 ArgOffset = alignTo(ArgOffset, Alignment); 4081 CurArgOffset = ArgOffset; 4082 }; 4083 4084 if (CallConv != CallingConv::Fast) { 4085 ComputeArgOffset(); 4086 4087 /* Compute GPR index associated with argument offset. */ 4088 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4089 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4090 } 4091 4092 // FIXME the codegen can be much improved in some cases. 4093 // We do not have to keep everything in memory. 4094 if (Flags.isByVal()) { 4095 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4096 4097 if (CallConv == CallingConv::Fast) 4098 ComputeArgOffset(); 4099 4100 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4101 ObjSize = Flags.getByValSize(); 4102 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4103 // Empty aggregate parameters do not take up registers. Examples: 4104 // struct { } a; 4105 // union { } b; 4106 // int c[0]; 4107 // etc. However, we have to provide a place-holder in InVals, so 4108 // pretend we have an 8-byte item at the current address for that 4109 // purpose. 4110 if (!ObjSize) { 4111 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4112 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4113 InVals.push_back(FIN); 4114 continue; 4115 } 4116 4117 // Create a stack object covering all stack doublewords occupied 4118 // by the argument. If the argument is (fully or partially) on 4119 // the stack, or if the argument is fully in registers but the 4120 // caller has allocated the parameter save anyway, we can refer 4121 // directly to the caller's stack frame. Otherwise, create a 4122 // local copy in our own frame. 4123 int FI; 4124 if (HasParameterArea || 4125 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4126 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4127 else 4128 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4129 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4130 4131 // Handle aggregates smaller than 8 bytes. 4132 if (ObjSize < PtrByteSize) { 4133 // The value of the object is its address, which differs from the 4134 // address of the enclosing doubleword on big-endian systems. 4135 SDValue Arg = FIN; 4136 if (!isLittleEndian) { 4137 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4138 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4139 } 4140 InVals.push_back(Arg); 4141 4142 if (GPR_idx != Num_GPR_Regs) { 4143 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4144 FuncInfo->addLiveInAttr(VReg, Flags); 4145 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4146 SDValue Store; 4147 4148 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4149 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4150 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4151 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4152 MachinePointerInfo(&*FuncArg), ObjType); 4153 } else { 4154 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4155 // store the whole register as-is to the parameter save area 4156 // slot. 4157 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4158 MachinePointerInfo(&*FuncArg)); 4159 } 4160 4161 MemOps.push_back(Store); 4162 } 4163 // Whether we copied from a register or not, advance the offset 4164 // into the parameter save area by a full doubleword. 4165 ArgOffset += PtrByteSize; 4166 continue; 4167 } 4168 4169 // The value of the object is its address, which is the address of 4170 // its first stack doubleword. 4171 InVals.push_back(FIN); 4172 4173 // Store whatever pieces of the object are in registers to memory. 4174 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4175 if (GPR_idx == Num_GPR_Regs) 4176 break; 4177 4178 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4179 FuncInfo->addLiveInAttr(VReg, Flags); 4180 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4181 SDValue Addr = FIN; 4182 if (j) { 4183 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4184 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4185 } 4186 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4187 MachinePointerInfo(&*FuncArg, j)); 4188 MemOps.push_back(Store); 4189 ++GPR_idx; 4190 } 4191 ArgOffset += ArgSize; 4192 continue; 4193 } 4194 4195 switch (ObjectVT.getSimpleVT().SimpleTy) { 4196 default: llvm_unreachable("Unhandled argument type!"); 4197 case MVT::i1: 4198 case MVT::i32: 4199 case MVT::i64: 4200 if (Flags.isNest()) { 4201 // The 'nest' parameter, if any, is passed in R11. 4202 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4203 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4204 4205 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4206 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4207 4208 break; 4209 } 4210 4211 // These can be scalar arguments or elements of an integer array type 4212 // passed directly. Clang may use those instead of "byval" aggregate 4213 // types to avoid forcing arguments to memory unnecessarily. 4214 if (GPR_idx != Num_GPR_Regs) { 4215 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4216 FuncInfo->addLiveInAttr(VReg, Flags); 4217 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4218 4219 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4220 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4221 // value to MVT::i64 and then truncate to the correct register size. 4222 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4223 } else { 4224 if (CallConv == CallingConv::Fast) 4225 ComputeArgOffset(); 4226 4227 needsLoad = true; 4228 ArgSize = PtrByteSize; 4229 } 4230 if (CallConv != CallingConv::Fast || needsLoad) 4231 ArgOffset += 8; 4232 break; 4233 4234 case MVT::f32: 4235 case MVT::f64: 4236 // These can be scalar arguments or elements of a float array type 4237 // passed directly. The latter are used to implement ELFv2 homogenous 4238 // float aggregates. 4239 if (FPR_idx != Num_FPR_Regs) { 4240 unsigned VReg; 4241 4242 if (ObjectVT == MVT::f32) 4243 VReg = MF.addLiveIn(FPR[FPR_idx], 4244 Subtarget.hasP8Vector() 4245 ? &PPC::VSSRCRegClass 4246 : &PPC::F4RCRegClass); 4247 else 4248 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4249 ? &PPC::VSFRCRegClass 4250 : &PPC::F8RCRegClass); 4251 4252 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4253 ++FPR_idx; 4254 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4255 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4256 // once we support fp <-> gpr moves. 4257 4258 // This can only ever happen in the presence of f32 array types, 4259 // since otherwise we never run out of FPRs before running out 4260 // of GPRs. 4261 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4262 FuncInfo->addLiveInAttr(VReg, Flags); 4263 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4264 4265 if (ObjectVT == MVT::f32) { 4266 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4267 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4268 DAG.getConstant(32, dl, MVT::i32)); 4269 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4270 } 4271 4272 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4273 } else { 4274 if (CallConv == CallingConv::Fast) 4275 ComputeArgOffset(); 4276 4277 needsLoad = true; 4278 } 4279 4280 // When passing an array of floats, the array occupies consecutive 4281 // space in the argument area; only round up to the next doubleword 4282 // at the end of the array. Otherwise, each float takes 8 bytes. 4283 if (CallConv != CallingConv::Fast || needsLoad) { 4284 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4285 ArgOffset += ArgSize; 4286 if (Flags.isInConsecutiveRegsLast()) 4287 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4288 } 4289 break; 4290 case MVT::v4f32: 4291 case MVT::v4i32: 4292 case MVT::v8i16: 4293 case MVT::v16i8: 4294 case MVT::v2f64: 4295 case MVT::v2i64: 4296 case MVT::v1i128: 4297 case MVT::f128: 4298 // These can be scalar arguments or elements of a vector array type 4299 // passed directly. The latter are used to implement ELFv2 homogenous 4300 // vector aggregates. 4301 if (VR_idx != Num_VR_Regs) { 4302 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4303 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4304 ++VR_idx; 4305 } else { 4306 if (CallConv == CallingConv::Fast) 4307 ComputeArgOffset(); 4308 needsLoad = true; 4309 } 4310 if (CallConv != CallingConv::Fast || needsLoad) 4311 ArgOffset += 16; 4312 break; 4313 } 4314 4315 // We need to load the argument to a virtual register if we determined 4316 // above that we ran out of physical registers of the appropriate type. 4317 if (needsLoad) { 4318 if (ObjSize < ArgSize && !isLittleEndian) 4319 CurArgOffset += ArgSize - ObjSize; 4320 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4321 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4322 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4323 } 4324 4325 InVals.push_back(ArgVal); 4326 } 4327 4328 // Area that is at least reserved in the caller of this function. 4329 unsigned MinReservedArea; 4330 if (HasParameterArea) 4331 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4332 else 4333 MinReservedArea = LinkageSize; 4334 4335 // Set the size that is at least reserved in caller of this function. Tail 4336 // call optimized functions' reserved stack space needs to be aligned so that 4337 // taking the difference between two stack areas will result in an aligned 4338 // stack. 4339 MinReservedArea = 4340 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4341 FuncInfo->setMinReservedArea(MinReservedArea); 4342 4343 // If the function takes variable number of arguments, make a frame index for 4344 // the start of the first vararg value... for expansion of llvm.va_start. 4345 // On ELFv2ABI spec, it writes: 4346 // C programs that are intended to be *portable* across different compilers 4347 // and architectures must use the header file <stdarg.h> to deal with variable 4348 // argument lists. 4349 if (isVarArg && MFI.hasVAStart()) { 4350 int Depth = ArgOffset; 4351 4352 FuncInfo->setVarArgsFrameIndex( 4353 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4354 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4355 4356 // If this function is vararg, store any remaining integer argument regs 4357 // to their spots on the stack so that they may be loaded by dereferencing 4358 // the result of va_next. 4359 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4360 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4361 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4362 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4363 SDValue Store = 4364 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4365 MemOps.push_back(Store); 4366 // Increment the address by four for the next argument to store 4367 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4368 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4369 } 4370 } 4371 4372 if (!MemOps.empty()) 4373 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4374 4375 return Chain; 4376 } 4377 4378 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4379 /// adjusted to accommodate the arguments for the tailcall. 4380 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4381 unsigned ParamSize) { 4382 4383 if (!isTailCall) return 0; 4384 4385 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4386 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4387 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4388 // Remember only if the new adjustment is bigger. 4389 if (SPDiff < FI->getTailCallSPDelta()) 4390 FI->setTailCallSPDelta(SPDiff); 4391 4392 return SPDiff; 4393 } 4394 4395 static bool isFunctionGlobalAddress(SDValue Callee); 4396 4397 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4398 const TargetMachine &TM) { 4399 // It does not make sense to call callsShareTOCBase() with a caller that 4400 // is PC Relative since PC Relative callers do not have a TOC. 4401 #ifndef NDEBUG 4402 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4403 assert(!STICaller->isUsingPCRelativeCalls() && 4404 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4405 #endif 4406 4407 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4408 // don't have enough information to determine if the caller and callee share 4409 // the same TOC base, so we have to pessimistically assume they don't for 4410 // correctness. 4411 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4412 if (!G) 4413 return false; 4414 4415 const GlobalValue *GV = G->getGlobal(); 4416 4417 // If the callee is preemptable, then the static linker will use a plt-stub 4418 // which saves the toc to the stack, and needs a nop after the call 4419 // instruction to convert to a toc-restore. 4420 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4421 return false; 4422 4423 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4424 // We may need a TOC restore in the situation where the caller requires a 4425 // valid TOC but the callee is PC Relative and does not. 4426 const Function *F = dyn_cast<Function>(GV); 4427 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4428 4429 // If we have an Alias we can try to get the function from there. 4430 if (Alias) { 4431 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4432 F = dyn_cast<Function>(GlobalObj); 4433 } 4434 4435 // If we still have no valid function pointer we do not have enough 4436 // information to determine if the callee uses PC Relative calls so we must 4437 // assume that it does. 4438 if (!F) 4439 return false; 4440 4441 // If the callee uses PC Relative we cannot guarantee that the callee won't 4442 // clobber the TOC of the caller and so we must assume that the two 4443 // functions do not share a TOC base. 4444 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4445 if (STICallee->isUsingPCRelativeCalls()) 4446 return false; 4447 4448 // If the GV is not a strong definition then we need to assume it can be 4449 // replaced by another function at link time. The function that replaces 4450 // it may not share the same TOC as the caller since the callee may be 4451 // replaced by a PC Relative version of the same function. 4452 if (!GV->isStrongDefinitionForLinker()) 4453 return false; 4454 4455 // The medium and large code models are expected to provide a sufficiently 4456 // large TOC to provide all data addressing needs of a module with a 4457 // single TOC. 4458 if (CodeModel::Medium == TM.getCodeModel() || 4459 CodeModel::Large == TM.getCodeModel()) 4460 return true; 4461 4462 // Any explicitly-specified sections and section prefixes must also match. 4463 // Also, if we're using -ffunction-sections, then each function is always in 4464 // a different section (the same is true for COMDAT functions). 4465 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4466 GV->getSection() != Caller->getSection()) 4467 return false; 4468 if (const auto *F = dyn_cast<Function>(GV)) { 4469 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4470 return false; 4471 } 4472 4473 return true; 4474 } 4475 4476 static bool 4477 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4478 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4479 assert(Subtarget.is64BitELFABI()); 4480 4481 const unsigned PtrByteSize = 8; 4482 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4483 4484 static const MCPhysReg GPR[] = { 4485 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4486 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4487 }; 4488 static const MCPhysReg VR[] = { 4489 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4490 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4491 }; 4492 4493 const unsigned NumGPRs = array_lengthof(GPR); 4494 const unsigned NumFPRs = 13; 4495 const unsigned NumVRs = array_lengthof(VR); 4496 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4497 4498 unsigned NumBytes = LinkageSize; 4499 unsigned AvailableFPRs = NumFPRs; 4500 unsigned AvailableVRs = NumVRs; 4501 4502 for (const ISD::OutputArg& Param : Outs) { 4503 if (Param.Flags.isNest()) continue; 4504 4505 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4506 LinkageSize, ParamAreaSize, NumBytes, 4507 AvailableFPRs, AvailableVRs)) 4508 return true; 4509 } 4510 return false; 4511 } 4512 4513 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4514 if (CB.arg_size() != CallerFn->arg_size()) 4515 return false; 4516 4517 auto CalleeArgIter = CB.arg_begin(); 4518 auto CalleeArgEnd = CB.arg_end(); 4519 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4520 4521 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4522 const Value* CalleeArg = *CalleeArgIter; 4523 const Value* CallerArg = &(*CallerArgIter); 4524 if (CalleeArg == CallerArg) 4525 continue; 4526 4527 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4528 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4529 // } 4530 // 1st argument of callee is undef and has the same type as caller. 4531 if (CalleeArg->getType() == CallerArg->getType() && 4532 isa<UndefValue>(CalleeArg)) 4533 continue; 4534 4535 return false; 4536 } 4537 4538 return true; 4539 } 4540 4541 // Returns true if TCO is possible between the callers and callees 4542 // calling conventions. 4543 static bool 4544 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4545 CallingConv::ID CalleeCC) { 4546 // Tail calls are possible with fastcc and ccc. 4547 auto isTailCallableCC = [] (CallingConv::ID CC){ 4548 return CC == CallingConv::C || CC == CallingConv::Fast; 4549 }; 4550 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4551 return false; 4552 4553 // We can safely tail call both fastcc and ccc callees from a c calling 4554 // convention caller. If the caller is fastcc, we may have less stack space 4555 // than a non-fastcc caller with the same signature so disable tail-calls in 4556 // that case. 4557 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4558 } 4559 4560 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4561 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4562 const SmallVectorImpl<ISD::OutputArg> &Outs, 4563 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4564 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4565 4566 if (DisableSCO && !TailCallOpt) return false; 4567 4568 // Variadic argument functions are not supported. 4569 if (isVarArg) return false; 4570 4571 auto &Caller = DAG.getMachineFunction().getFunction(); 4572 // Check that the calling conventions are compatible for tco. 4573 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4574 return false; 4575 4576 // Caller contains any byval parameter is not supported. 4577 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4578 return false; 4579 4580 // Callee contains any byval parameter is not supported, too. 4581 // Note: This is a quick work around, because in some cases, e.g. 4582 // caller's stack size > callee's stack size, we are still able to apply 4583 // sibling call optimization. For example, gcc is able to do SCO for caller1 4584 // in the following example, but not for caller2. 4585 // struct test { 4586 // long int a; 4587 // char ary[56]; 4588 // } gTest; 4589 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4590 // b->a = v.a; 4591 // return 0; 4592 // } 4593 // void caller1(struct test a, struct test c, struct test *b) { 4594 // callee(gTest, b); } 4595 // void caller2(struct test *b) { callee(gTest, b); } 4596 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4597 return false; 4598 4599 // If callee and caller use different calling conventions, we cannot pass 4600 // parameters on stack since offsets for the parameter area may be different. 4601 if (Caller.getCallingConv() != CalleeCC && 4602 needStackSlotPassParameters(Subtarget, Outs)) 4603 return false; 4604 4605 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4606 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4607 // callee potentially have different TOC bases then we cannot tail call since 4608 // we need to restore the TOC pointer after the call. 4609 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4610 // We cannot guarantee this for indirect calls or calls to external functions. 4611 // When PC-Relative addressing is used, the concept of the TOC is no longer 4612 // applicable so this check is not required. 4613 // Check first for indirect calls. 4614 if (!Subtarget.isUsingPCRelativeCalls() && 4615 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4616 return false; 4617 4618 // Check if we share the TOC base. 4619 if (!Subtarget.isUsingPCRelativeCalls() && 4620 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4621 return false; 4622 4623 // TCO allows altering callee ABI, so we don't have to check further. 4624 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4625 return true; 4626 4627 if (DisableSCO) return false; 4628 4629 // If callee use the same argument list that caller is using, then we can 4630 // apply SCO on this case. If it is not, then we need to check if callee needs 4631 // stack for passing arguments. 4632 // PC Relative tail calls may not have a CallBase. 4633 // If there is no CallBase we cannot verify if we have the same argument 4634 // list so assume that we don't have the same argument list. 4635 if (CB && !hasSameArgumentList(&Caller, *CB) && 4636 needStackSlotPassParameters(Subtarget, Outs)) 4637 return false; 4638 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4639 return false; 4640 4641 return true; 4642 } 4643 4644 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4645 /// for tail call optimization. Targets which want to do tail call 4646 /// optimization should implement this function. 4647 bool 4648 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4649 CallingConv::ID CalleeCC, 4650 bool isVarArg, 4651 const SmallVectorImpl<ISD::InputArg> &Ins, 4652 SelectionDAG& DAG) const { 4653 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4654 return false; 4655 4656 // Variable argument functions are not supported. 4657 if (isVarArg) 4658 return false; 4659 4660 MachineFunction &MF = DAG.getMachineFunction(); 4661 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4662 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4663 // Functions containing by val parameters are not supported. 4664 for (unsigned i = 0; i != Ins.size(); i++) { 4665 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4666 if (Flags.isByVal()) return false; 4667 } 4668 4669 // Non-PIC/GOT tail calls are supported. 4670 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4671 return true; 4672 4673 // At the moment we can only do local tail calls (in same module, hidden 4674 // or protected) if we are generating PIC. 4675 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4676 return G->getGlobal()->hasHiddenVisibility() 4677 || G->getGlobal()->hasProtectedVisibility(); 4678 } 4679 4680 return false; 4681 } 4682 4683 /// isCallCompatibleAddress - Return the immediate to use if the specified 4684 /// 32-bit value is representable in the immediate field of a BxA instruction. 4685 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4686 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4687 if (!C) return nullptr; 4688 4689 int Addr = C->getZExtValue(); 4690 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4691 SignExtend32<26>(Addr) != Addr) 4692 return nullptr; // Top 6 bits have to be sext of immediate. 4693 4694 return DAG 4695 .getConstant( 4696 (int)C->getZExtValue() >> 2, SDLoc(Op), 4697 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4698 .getNode(); 4699 } 4700 4701 namespace { 4702 4703 struct TailCallArgumentInfo { 4704 SDValue Arg; 4705 SDValue FrameIdxOp; 4706 int FrameIdx = 0; 4707 4708 TailCallArgumentInfo() = default; 4709 }; 4710 4711 } // end anonymous namespace 4712 4713 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4714 static void StoreTailCallArgumentsToStackSlot( 4715 SelectionDAG &DAG, SDValue Chain, 4716 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4717 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4718 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4719 SDValue Arg = TailCallArgs[i].Arg; 4720 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4721 int FI = TailCallArgs[i].FrameIdx; 4722 // Store relative to framepointer. 4723 MemOpChains.push_back(DAG.getStore( 4724 Chain, dl, Arg, FIN, 4725 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4726 } 4727 } 4728 4729 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4730 /// the appropriate stack slot for the tail call optimized function call. 4731 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4732 SDValue OldRetAddr, SDValue OldFP, 4733 int SPDiff, const SDLoc &dl) { 4734 if (SPDiff) { 4735 // Calculate the new stack slot for the return address. 4736 MachineFunction &MF = DAG.getMachineFunction(); 4737 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4738 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4739 bool isPPC64 = Subtarget.isPPC64(); 4740 int SlotSize = isPPC64 ? 8 : 4; 4741 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4742 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4743 NewRetAddrLoc, true); 4744 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4745 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4746 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4747 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4748 } 4749 return Chain; 4750 } 4751 4752 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4753 /// the position of the argument. 4754 static void 4755 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4756 SDValue Arg, int SPDiff, unsigned ArgOffset, 4757 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4758 int Offset = ArgOffset + SPDiff; 4759 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4760 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4761 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4762 SDValue FIN = DAG.getFrameIndex(FI, VT); 4763 TailCallArgumentInfo Info; 4764 Info.Arg = Arg; 4765 Info.FrameIdxOp = FIN; 4766 Info.FrameIdx = FI; 4767 TailCallArguments.push_back(Info); 4768 } 4769 4770 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4771 /// stack slot. Returns the chain as result and the loaded frame pointers in 4772 /// LROpOut/FPOpout. Used when tail calling. 4773 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4774 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4775 SDValue &FPOpOut, const SDLoc &dl) const { 4776 if (SPDiff) { 4777 // Load the LR and FP stack slot for later adjusting. 4778 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4779 LROpOut = getReturnAddrFrameIndex(DAG); 4780 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4781 Chain = SDValue(LROpOut.getNode(), 1); 4782 } 4783 return Chain; 4784 } 4785 4786 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4787 /// by "Src" to address "Dst" of size "Size". Alignment information is 4788 /// specified by the specific parameter attribute. The copy will be passed as 4789 /// a byval function parameter. 4790 /// Sometimes what we are copying is the end of a larger object, the part that 4791 /// does not fit in registers. 4792 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4793 SDValue Chain, ISD::ArgFlagsTy Flags, 4794 SelectionDAG &DAG, const SDLoc &dl) { 4795 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4796 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4797 Flags.getNonZeroByValAlign(), false, false, false, 4798 MachinePointerInfo(), MachinePointerInfo()); 4799 } 4800 4801 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4802 /// tail calls. 4803 static void LowerMemOpCallTo( 4804 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4805 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4806 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4807 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4808 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4809 if (!isTailCall) { 4810 if (isVector) { 4811 SDValue StackPtr; 4812 if (isPPC64) 4813 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4814 else 4815 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4816 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4817 DAG.getConstant(ArgOffset, dl, PtrVT)); 4818 } 4819 MemOpChains.push_back( 4820 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4821 // Calculate and remember argument location. 4822 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4823 TailCallArguments); 4824 } 4825 4826 static void 4827 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4828 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4829 SDValue FPOp, 4830 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4831 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4832 // might overwrite each other in case of tail call optimization. 4833 SmallVector<SDValue, 8> MemOpChains2; 4834 // Do not flag preceding copytoreg stuff together with the following stuff. 4835 InFlag = SDValue(); 4836 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4837 MemOpChains2, dl); 4838 if (!MemOpChains2.empty()) 4839 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4840 4841 // Store the return address to the appropriate stack slot. 4842 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4843 4844 // Emit callseq_end just before tailcall node. 4845 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4846 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4847 InFlag = Chain.getValue(1); 4848 } 4849 4850 // Is this global address that of a function that can be called by name? (as 4851 // opposed to something that must hold a descriptor for an indirect call). 4852 static bool isFunctionGlobalAddress(SDValue Callee) { 4853 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4854 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4855 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4856 return false; 4857 4858 return G->getGlobal()->getValueType()->isFunctionTy(); 4859 } 4860 4861 return false; 4862 } 4863 4864 SDValue PPCTargetLowering::LowerCallResult( 4865 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4866 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4867 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4868 SmallVector<CCValAssign, 16> RVLocs; 4869 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4870 *DAG.getContext()); 4871 4872 CCRetInfo.AnalyzeCallResult( 4873 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4874 ? RetCC_PPC_Cold 4875 : RetCC_PPC); 4876 4877 // Copy all of the result registers out of their specified physreg. 4878 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4879 CCValAssign &VA = RVLocs[i]; 4880 assert(VA.isRegLoc() && "Can only return in registers!"); 4881 4882 SDValue Val; 4883 4884 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4885 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4886 InFlag); 4887 Chain = Lo.getValue(1); 4888 InFlag = Lo.getValue(2); 4889 VA = RVLocs[++i]; // skip ahead to next loc 4890 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4891 InFlag); 4892 Chain = Hi.getValue(1); 4893 InFlag = Hi.getValue(2); 4894 if (!Subtarget.isLittleEndian()) 4895 std::swap (Lo, Hi); 4896 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4897 } else { 4898 Val = DAG.getCopyFromReg(Chain, dl, 4899 VA.getLocReg(), VA.getLocVT(), InFlag); 4900 Chain = Val.getValue(1); 4901 InFlag = Val.getValue(2); 4902 } 4903 4904 switch (VA.getLocInfo()) { 4905 default: llvm_unreachable("Unknown loc info!"); 4906 case CCValAssign::Full: break; 4907 case CCValAssign::AExt: 4908 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4909 break; 4910 case CCValAssign::ZExt: 4911 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4912 DAG.getValueType(VA.getValVT())); 4913 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4914 break; 4915 case CCValAssign::SExt: 4916 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4917 DAG.getValueType(VA.getValVT())); 4918 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4919 break; 4920 } 4921 4922 InVals.push_back(Val); 4923 } 4924 4925 return Chain; 4926 } 4927 4928 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 4929 const PPCSubtarget &Subtarget, bool isPatchPoint) { 4930 // PatchPoint calls are not indirect. 4931 if (isPatchPoint) 4932 return false; 4933 4934 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 4935 return false; 4936 4937 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 4938 // becuase the immediate function pointer points to a descriptor instead of 4939 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 4940 // pointer immediate points to the global entry point, while the BLA would 4941 // need to jump to the local entry point (see rL211174). 4942 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 4943 isBLACompatibleAddress(Callee, DAG)) 4944 return false; 4945 4946 return true; 4947 } 4948 4949 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 4950 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 4951 return Subtarget.isAIXABI() || 4952 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 4953 } 4954 4955 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 4956 const Function &Caller, 4957 const SDValue &Callee, 4958 const PPCSubtarget &Subtarget, 4959 const TargetMachine &TM) { 4960 if (CFlags.IsTailCall) 4961 return PPCISD::TC_RETURN; 4962 4963 // This is a call through a function pointer. 4964 if (CFlags.IsIndirect) { 4965 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 4966 // indirect calls. The save of the caller's TOC pointer to the stack will be 4967 // inserted into the DAG as part of call lowering. The restore of the TOC 4968 // pointer is modeled by using a pseudo instruction for the call opcode that 4969 // represents the 2 instruction sequence of an indirect branch and link, 4970 // immediately followed by a load of the TOC pointer from the the stack save 4971 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 4972 // as it is not saved or used. 4973 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 4974 : PPCISD::BCTRL; 4975 } 4976 4977 if (Subtarget.isUsingPCRelativeCalls()) { 4978 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 4979 return PPCISD::CALL_NOTOC; 4980 } 4981 4982 // The ABIs that maintain a TOC pointer accross calls need to have a nop 4983 // immediately following the call instruction if the caller and callee may 4984 // have different TOC bases. At link time if the linker determines the calls 4985 // may not share a TOC base, the call is redirected to a trampoline inserted 4986 // by the linker. The trampoline will (among other things) save the callers 4987 // TOC pointer at an ABI designated offset in the linkage area and the linker 4988 // will rewrite the nop to be a load of the TOC pointer from the linkage area 4989 // into gpr2. 4990 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 4991 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 4992 : PPCISD::CALL_NOP; 4993 4994 return PPCISD::CALL; 4995 } 4996 4997 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 4998 const SDLoc &dl, const PPCSubtarget &Subtarget) { 4999 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5000 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5001 return SDValue(Dest, 0); 5002 5003 // Returns true if the callee is local, and false otherwise. 5004 auto isLocalCallee = [&]() { 5005 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5006 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5007 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5008 5009 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5010 !dyn_cast_or_null<GlobalIFunc>(GV); 5011 }; 5012 5013 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5014 // a static relocation model causes some versions of GNU LD (2.17.50, at 5015 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5016 // built with secure-PLT. 5017 bool UsePlt = 5018 Subtarget.is32BitELFABI() && !isLocalCallee() && 5019 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5020 5021 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5022 const TargetMachine &TM = Subtarget.getTargetMachine(); 5023 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5024 MCSymbolXCOFF *S = 5025 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5026 5027 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5028 return DAG.getMCSymbol(S, PtrVT); 5029 }; 5030 5031 if (isFunctionGlobalAddress(Callee)) { 5032 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5033 5034 if (Subtarget.isAIXABI()) { 5035 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5036 return getAIXFuncEntryPointSymbolSDNode(GV); 5037 } 5038 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5039 UsePlt ? PPCII::MO_PLT : 0); 5040 } 5041 5042 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5043 const char *SymName = S->getSymbol(); 5044 if (Subtarget.isAIXABI()) { 5045 // If there exists a user-declared function whose name is the same as the 5046 // ExternalSymbol's, then we pick up the user-declared version. 5047 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5048 if (const Function *F = 5049 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5050 return getAIXFuncEntryPointSymbolSDNode(F); 5051 5052 // On AIX, direct function calls reference the symbol for the function's 5053 // entry point, which is named by prepending a "." before the function's 5054 // C-linkage name. A Qualname is returned here because an external 5055 // function entry point is a csect with XTY_ER property. 5056 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5057 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5058 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5059 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5060 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5061 return Sec->getQualNameSymbol(); 5062 }; 5063 5064 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5065 } 5066 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5067 UsePlt ? PPCII::MO_PLT : 0); 5068 } 5069 5070 // No transformation needed. 5071 assert(Callee.getNode() && "What no callee?"); 5072 return Callee; 5073 } 5074 5075 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5076 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5077 "Expected a CALLSEQ_STARTSDNode."); 5078 5079 // The last operand is the chain, except when the node has glue. If the node 5080 // has glue, then the last operand is the glue, and the chain is the second 5081 // last operand. 5082 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5083 if (LastValue.getValueType() != MVT::Glue) 5084 return LastValue; 5085 5086 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5087 } 5088 5089 // Creates the node that moves a functions address into the count register 5090 // to prepare for an indirect call instruction. 5091 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5092 SDValue &Glue, SDValue &Chain, 5093 const SDLoc &dl) { 5094 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5095 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5096 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5097 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5098 // The glue is the second value produced. 5099 Glue = Chain.getValue(1); 5100 } 5101 5102 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5103 SDValue &Glue, SDValue &Chain, 5104 SDValue CallSeqStart, 5105 const CallBase *CB, const SDLoc &dl, 5106 bool hasNest, 5107 const PPCSubtarget &Subtarget) { 5108 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5109 // entry point, but to the function descriptor (the function entry point 5110 // address is part of the function descriptor though). 5111 // The function descriptor is a three doubleword structure with the 5112 // following fields: function entry point, TOC base address and 5113 // environment pointer. 5114 // Thus for a call through a function pointer, the following actions need 5115 // to be performed: 5116 // 1. Save the TOC of the caller in the TOC save area of its stack 5117 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5118 // 2. Load the address of the function entry point from the function 5119 // descriptor. 5120 // 3. Load the TOC of the callee from the function descriptor into r2. 5121 // 4. Load the environment pointer from the function descriptor into 5122 // r11. 5123 // 5. Branch to the function entry point address. 5124 // 6. On return of the callee, the TOC of the caller needs to be 5125 // restored (this is done in FinishCall()). 5126 // 5127 // The loads are scheduled at the beginning of the call sequence, and the 5128 // register copies are flagged together to ensure that no other 5129 // operations can be scheduled in between. E.g. without flagging the 5130 // copies together, a TOC access in the caller could be scheduled between 5131 // the assignment of the callee TOC and the branch to the callee, which leads 5132 // to incorrect code. 5133 5134 // Start by loading the function address from the descriptor. 5135 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5136 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5137 ? (MachineMemOperand::MODereferenceable | 5138 MachineMemOperand::MOInvariant) 5139 : MachineMemOperand::MONone; 5140 5141 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5142 5143 // Registers used in building the DAG. 5144 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5145 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5146 5147 // Offsets of descriptor members. 5148 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5149 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5150 5151 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5152 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5153 5154 // One load for the functions entry point address. 5155 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5156 Alignment, MMOFlags); 5157 5158 // One for loading the TOC anchor for the module that contains the called 5159 // function. 5160 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5161 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5162 SDValue TOCPtr = 5163 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5164 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5165 5166 // One for loading the environment pointer. 5167 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5168 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5169 SDValue LoadEnvPtr = 5170 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5171 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5172 5173 5174 // Then copy the newly loaded TOC anchor to the TOC pointer. 5175 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5176 Chain = TOCVal.getValue(0); 5177 Glue = TOCVal.getValue(1); 5178 5179 // If the function call has an explicit 'nest' parameter, it takes the 5180 // place of the environment pointer. 5181 assert((!hasNest || !Subtarget.isAIXABI()) && 5182 "Nest parameter is not supported on AIX."); 5183 if (!hasNest) { 5184 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5185 Chain = EnvVal.getValue(0); 5186 Glue = EnvVal.getValue(1); 5187 } 5188 5189 // The rest of the indirect call sequence is the same as the non-descriptor 5190 // DAG. 5191 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5192 } 5193 5194 static void 5195 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5196 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5197 SelectionDAG &DAG, 5198 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5199 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5200 const PPCSubtarget &Subtarget) { 5201 const bool IsPPC64 = Subtarget.isPPC64(); 5202 // MVT for a general purpose register. 5203 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5204 5205 // First operand is always the chain. 5206 Ops.push_back(Chain); 5207 5208 // If it's a direct call pass the callee as the second operand. 5209 if (!CFlags.IsIndirect) 5210 Ops.push_back(Callee); 5211 else { 5212 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5213 5214 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5215 // on the stack (this would have been done in `LowerCall_64SVR4` or 5216 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5217 // represents both the indirect branch and a load that restores the TOC 5218 // pointer from the linkage area. The operand for the TOC restore is an add 5219 // of the TOC save offset to the stack pointer. This must be the second 5220 // operand: after the chain input but before any other variadic arguments. 5221 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5222 // saved or used. 5223 if (isTOCSaveRestoreRequired(Subtarget)) { 5224 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5225 5226 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5227 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5228 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5229 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5230 Ops.push_back(AddTOC); 5231 } 5232 5233 // Add the register used for the environment pointer. 5234 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5235 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5236 RegVT)); 5237 5238 5239 // Add CTR register as callee so a bctr can be emitted later. 5240 if (CFlags.IsTailCall) 5241 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5242 } 5243 5244 // If this is a tail call add stack pointer delta. 5245 if (CFlags.IsTailCall) 5246 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5247 5248 // Add argument registers to the end of the list so that they are known live 5249 // into the call. 5250 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5251 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5252 RegsToPass[i].second.getValueType())); 5253 5254 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5255 // no way to mark dependencies as implicit here. 5256 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5257 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5258 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5259 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5260 5261 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5262 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5263 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5264 5265 // Add a register mask operand representing the call-preserved registers. 5266 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5267 const uint32_t *Mask = 5268 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5269 assert(Mask && "Missing call preserved mask for calling convention"); 5270 Ops.push_back(DAG.getRegisterMask(Mask)); 5271 5272 // If the glue is valid, it is the last operand. 5273 if (Glue.getNode()) 5274 Ops.push_back(Glue); 5275 } 5276 5277 SDValue PPCTargetLowering::FinishCall( 5278 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5279 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5280 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5281 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5282 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5283 5284 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5285 Subtarget.isAIXABI()) 5286 setUsesTOCBasePtr(DAG); 5287 5288 unsigned CallOpc = 5289 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5290 Subtarget, DAG.getTarget()); 5291 5292 if (!CFlags.IsIndirect) 5293 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5294 else if (Subtarget.usesFunctionDescriptors()) 5295 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5296 dl, CFlags.HasNest, Subtarget); 5297 else 5298 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5299 5300 // Build the operand list for the call instruction. 5301 SmallVector<SDValue, 8> Ops; 5302 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5303 SPDiff, Subtarget); 5304 5305 // Emit tail call. 5306 if (CFlags.IsTailCall) { 5307 // Indirect tail call when using PC Relative calls do not have the same 5308 // constraints. 5309 assert(((Callee.getOpcode() == ISD::Register && 5310 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5311 Callee.getOpcode() == ISD::TargetExternalSymbol || 5312 Callee.getOpcode() == ISD::TargetGlobalAddress || 5313 isa<ConstantSDNode>(Callee) || 5314 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5315 "Expecting a global address, external symbol, absolute value, " 5316 "register or an indirect tail call when PC Relative calls are " 5317 "used."); 5318 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5319 assert(CallOpc == PPCISD::TC_RETURN && 5320 "Unexpected call opcode for a tail call."); 5321 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5322 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5323 } 5324 5325 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5326 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5327 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5328 Glue = Chain.getValue(1); 5329 5330 // When performing tail call optimization the callee pops its arguments off 5331 // the stack. Account for this here so these bytes can be pushed back on in 5332 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5333 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5334 getTargetMachine().Options.GuaranteedTailCallOpt) 5335 ? NumBytes 5336 : 0; 5337 5338 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5339 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5340 Glue, dl); 5341 Glue = Chain.getValue(1); 5342 5343 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5344 DAG, InVals); 5345 } 5346 5347 SDValue 5348 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5349 SmallVectorImpl<SDValue> &InVals) const { 5350 SelectionDAG &DAG = CLI.DAG; 5351 SDLoc &dl = CLI.DL; 5352 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5353 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5354 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5355 SDValue Chain = CLI.Chain; 5356 SDValue Callee = CLI.Callee; 5357 bool &isTailCall = CLI.IsTailCall; 5358 CallingConv::ID CallConv = CLI.CallConv; 5359 bool isVarArg = CLI.IsVarArg; 5360 bool isPatchPoint = CLI.IsPatchPoint; 5361 const CallBase *CB = CLI.CB; 5362 5363 if (isTailCall) { 5364 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5365 isTailCall = false; 5366 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5367 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5368 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5369 else 5370 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5371 Ins, DAG); 5372 if (isTailCall) { 5373 ++NumTailCalls; 5374 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5375 ++NumSiblingCalls; 5376 5377 // PC Relative calls no longer guarantee that the callee is a Global 5378 // Address Node. The callee could be an indirect tail call in which 5379 // case the SDValue for the callee could be a load (to load the address 5380 // of a function pointer) or it may be a register copy (to move the 5381 // address of the callee from a function parameter into a virtual 5382 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5383 assert((Subtarget.isUsingPCRelativeCalls() || 5384 isa<GlobalAddressSDNode>(Callee)) && 5385 "Callee should be an llvm::Function object."); 5386 5387 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5388 << "\nTCO callee: "); 5389 LLVM_DEBUG(Callee.dump()); 5390 } 5391 } 5392 5393 if (!isTailCall && CB && CB->isMustTailCall()) 5394 report_fatal_error("failed to perform tail call elimination on a call " 5395 "site marked musttail"); 5396 5397 // When long calls (i.e. indirect calls) are always used, calls are always 5398 // made via function pointer. If we have a function name, first translate it 5399 // into a pointer. 5400 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5401 !isTailCall) 5402 Callee = LowerGlobalAddress(Callee, DAG); 5403 5404 CallFlags CFlags( 5405 CallConv, isTailCall, isVarArg, isPatchPoint, 5406 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5407 // hasNest 5408 Subtarget.is64BitELFABI() && 5409 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5410 CLI.NoMerge); 5411 5412 if (Subtarget.isAIXABI()) 5413 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5414 InVals, CB); 5415 5416 assert(Subtarget.isSVR4ABI()); 5417 if (Subtarget.isPPC64()) 5418 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5419 InVals, CB); 5420 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5421 InVals, CB); 5422 } 5423 5424 SDValue PPCTargetLowering::LowerCall_32SVR4( 5425 SDValue Chain, SDValue Callee, CallFlags CFlags, 5426 const SmallVectorImpl<ISD::OutputArg> &Outs, 5427 const SmallVectorImpl<SDValue> &OutVals, 5428 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5429 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5430 const CallBase *CB) const { 5431 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5432 // of the 32-bit SVR4 ABI stack frame layout. 5433 5434 const CallingConv::ID CallConv = CFlags.CallConv; 5435 const bool IsVarArg = CFlags.IsVarArg; 5436 const bool IsTailCall = CFlags.IsTailCall; 5437 5438 assert((CallConv == CallingConv::C || 5439 CallConv == CallingConv::Cold || 5440 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5441 5442 const Align PtrAlign(4); 5443 5444 MachineFunction &MF = DAG.getMachineFunction(); 5445 5446 // Mark this function as potentially containing a function that contains a 5447 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5448 // and restoring the callers stack pointer in this functions epilog. This is 5449 // done because by tail calling the called function might overwrite the value 5450 // in this function's (MF) stack pointer stack slot 0(SP). 5451 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5452 CallConv == CallingConv::Fast) 5453 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5454 5455 // Count how many bytes are to be pushed on the stack, including the linkage 5456 // area, parameter list area and the part of the local variable space which 5457 // contains copies of aggregates which are passed by value. 5458 5459 // Assign locations to all of the outgoing arguments. 5460 SmallVector<CCValAssign, 16> ArgLocs; 5461 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5462 5463 // Reserve space for the linkage area on the stack. 5464 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5465 PtrAlign); 5466 if (useSoftFloat()) 5467 CCInfo.PreAnalyzeCallOperands(Outs); 5468 5469 if (IsVarArg) { 5470 // Handle fixed and variable vector arguments differently. 5471 // Fixed vector arguments go into registers as long as registers are 5472 // available. Variable vector arguments always go into memory. 5473 unsigned NumArgs = Outs.size(); 5474 5475 for (unsigned i = 0; i != NumArgs; ++i) { 5476 MVT ArgVT = Outs[i].VT; 5477 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5478 bool Result; 5479 5480 if (Outs[i].IsFixed) { 5481 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5482 CCInfo); 5483 } else { 5484 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5485 ArgFlags, CCInfo); 5486 } 5487 5488 if (Result) { 5489 #ifndef NDEBUG 5490 errs() << "Call operand #" << i << " has unhandled type " 5491 << EVT(ArgVT).getEVTString() << "\n"; 5492 #endif 5493 llvm_unreachable(nullptr); 5494 } 5495 } 5496 } else { 5497 // All arguments are treated the same. 5498 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5499 } 5500 CCInfo.clearWasPPCF128(); 5501 5502 // Assign locations to all of the outgoing aggregate by value arguments. 5503 SmallVector<CCValAssign, 16> ByValArgLocs; 5504 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5505 5506 // Reserve stack space for the allocations in CCInfo. 5507 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5508 5509 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5510 5511 // Size of the linkage area, parameter list area and the part of the local 5512 // space variable where copies of aggregates which are passed by value are 5513 // stored. 5514 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5515 5516 // Calculate by how many bytes the stack has to be adjusted in case of tail 5517 // call optimization. 5518 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5519 5520 // Adjust the stack pointer for the new arguments... 5521 // These operations are automatically eliminated by the prolog/epilog pass 5522 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5523 SDValue CallSeqStart = Chain; 5524 5525 // Load the return address and frame pointer so it can be moved somewhere else 5526 // later. 5527 SDValue LROp, FPOp; 5528 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5529 5530 // Set up a copy of the stack pointer for use loading and storing any 5531 // arguments that may not fit in the registers available for argument 5532 // passing. 5533 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5534 5535 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5536 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5537 SmallVector<SDValue, 8> MemOpChains; 5538 5539 bool seenFloatArg = false; 5540 // Walk the register/memloc assignments, inserting copies/loads. 5541 // i - Tracks the index into the list of registers allocated for the call 5542 // RealArgIdx - Tracks the index into the list of actual function arguments 5543 // j - Tracks the index into the list of byval arguments 5544 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5545 i != e; 5546 ++i, ++RealArgIdx) { 5547 CCValAssign &VA = ArgLocs[i]; 5548 SDValue Arg = OutVals[RealArgIdx]; 5549 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5550 5551 if (Flags.isByVal()) { 5552 // Argument is an aggregate which is passed by value, thus we need to 5553 // create a copy of it in the local variable space of the current stack 5554 // frame (which is the stack frame of the caller) and pass the address of 5555 // this copy to the callee. 5556 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5557 CCValAssign &ByValVA = ByValArgLocs[j++]; 5558 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5559 5560 // Memory reserved in the local variable space of the callers stack frame. 5561 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5562 5563 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5564 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5565 StackPtr, PtrOff); 5566 5567 // Create a copy of the argument in the local area of the current 5568 // stack frame. 5569 SDValue MemcpyCall = 5570 CreateCopyOfByValArgument(Arg, PtrOff, 5571 CallSeqStart.getNode()->getOperand(0), 5572 Flags, DAG, dl); 5573 5574 // This must go outside the CALLSEQ_START..END. 5575 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5576 SDLoc(MemcpyCall)); 5577 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5578 NewCallSeqStart.getNode()); 5579 Chain = CallSeqStart = NewCallSeqStart; 5580 5581 // Pass the address of the aggregate copy on the stack either in a 5582 // physical register or in the parameter list area of the current stack 5583 // frame to the callee. 5584 Arg = PtrOff; 5585 } 5586 5587 // When useCRBits() is true, there can be i1 arguments. 5588 // It is because getRegisterType(MVT::i1) => MVT::i1, 5589 // and for other integer types getRegisterType() => MVT::i32. 5590 // Extend i1 and ensure callee will get i32. 5591 if (Arg.getValueType() == MVT::i1) 5592 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5593 dl, MVT::i32, Arg); 5594 5595 if (VA.isRegLoc()) { 5596 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5597 // Put argument in a physical register. 5598 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5599 bool IsLE = Subtarget.isLittleEndian(); 5600 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5601 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5602 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5603 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5604 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5605 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5606 SVal.getValue(0))); 5607 } else 5608 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5609 } else { 5610 // Put argument in the parameter list area of the current stack frame. 5611 assert(VA.isMemLoc()); 5612 unsigned LocMemOffset = VA.getLocMemOffset(); 5613 5614 if (!IsTailCall) { 5615 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5616 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5617 StackPtr, PtrOff); 5618 5619 MemOpChains.push_back( 5620 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5621 } else { 5622 // Calculate and remember argument location. 5623 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5624 TailCallArguments); 5625 } 5626 } 5627 } 5628 5629 if (!MemOpChains.empty()) 5630 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5631 5632 // Build a sequence of copy-to-reg nodes chained together with token chain 5633 // and flag operands which copy the outgoing args into the appropriate regs. 5634 SDValue InFlag; 5635 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5636 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5637 RegsToPass[i].second, InFlag); 5638 InFlag = Chain.getValue(1); 5639 } 5640 5641 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5642 // registers. 5643 if (IsVarArg) { 5644 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5645 SDValue Ops[] = { Chain, InFlag }; 5646 5647 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5648 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5649 5650 InFlag = Chain.getValue(1); 5651 } 5652 5653 if (IsTailCall) 5654 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5655 TailCallArguments); 5656 5657 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5658 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5659 } 5660 5661 // Copy an argument into memory, being careful to do this outside the 5662 // call sequence for the call to which the argument belongs. 5663 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5664 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5665 SelectionDAG &DAG, const SDLoc &dl) const { 5666 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5667 CallSeqStart.getNode()->getOperand(0), 5668 Flags, DAG, dl); 5669 // The MEMCPY must go outside the CALLSEQ_START..END. 5670 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5671 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5672 SDLoc(MemcpyCall)); 5673 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5674 NewCallSeqStart.getNode()); 5675 return NewCallSeqStart; 5676 } 5677 5678 SDValue PPCTargetLowering::LowerCall_64SVR4( 5679 SDValue Chain, SDValue Callee, CallFlags CFlags, 5680 const SmallVectorImpl<ISD::OutputArg> &Outs, 5681 const SmallVectorImpl<SDValue> &OutVals, 5682 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5683 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5684 const CallBase *CB) const { 5685 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5686 bool isLittleEndian = Subtarget.isLittleEndian(); 5687 unsigned NumOps = Outs.size(); 5688 bool IsSibCall = false; 5689 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5690 5691 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5692 unsigned PtrByteSize = 8; 5693 5694 MachineFunction &MF = DAG.getMachineFunction(); 5695 5696 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5697 IsSibCall = true; 5698 5699 // Mark this function as potentially containing a function that contains a 5700 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5701 // and restoring the callers stack pointer in this functions epilog. This is 5702 // done because by tail calling the called function might overwrite the value 5703 // in this function's (MF) stack pointer stack slot 0(SP). 5704 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5705 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5706 5707 assert(!(IsFastCall && CFlags.IsVarArg) && 5708 "fastcc not supported on varargs functions"); 5709 5710 // Count how many bytes are to be pushed on the stack, including the linkage 5711 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5712 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5713 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5714 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5715 unsigned NumBytes = LinkageSize; 5716 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5717 5718 static const MCPhysReg GPR[] = { 5719 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5720 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5721 }; 5722 static const MCPhysReg VR[] = { 5723 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5724 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5725 }; 5726 5727 const unsigned NumGPRs = array_lengthof(GPR); 5728 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5729 const unsigned NumVRs = array_lengthof(VR); 5730 5731 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5732 // can be passed to the callee in registers. 5733 // For the fast calling convention, there is another check below. 5734 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5735 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5736 if (!HasParameterArea) { 5737 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5738 unsigned AvailableFPRs = NumFPRs; 5739 unsigned AvailableVRs = NumVRs; 5740 unsigned NumBytesTmp = NumBytes; 5741 for (unsigned i = 0; i != NumOps; ++i) { 5742 if (Outs[i].Flags.isNest()) continue; 5743 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5744 PtrByteSize, LinkageSize, ParamAreaSize, 5745 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5746 HasParameterArea = true; 5747 } 5748 } 5749 5750 // When using the fast calling convention, we don't provide backing for 5751 // arguments that will be in registers. 5752 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5753 5754 // Avoid allocating parameter area for fastcc functions if all the arguments 5755 // can be passed in the registers. 5756 if (IsFastCall) 5757 HasParameterArea = false; 5758 5759 // Add up all the space actually used. 5760 for (unsigned i = 0; i != NumOps; ++i) { 5761 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5762 EVT ArgVT = Outs[i].VT; 5763 EVT OrigVT = Outs[i].ArgVT; 5764 5765 if (Flags.isNest()) 5766 continue; 5767 5768 if (IsFastCall) { 5769 if (Flags.isByVal()) { 5770 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5771 if (NumGPRsUsed > NumGPRs) 5772 HasParameterArea = true; 5773 } else { 5774 switch (ArgVT.getSimpleVT().SimpleTy) { 5775 default: llvm_unreachable("Unexpected ValueType for argument!"); 5776 case MVT::i1: 5777 case MVT::i32: 5778 case MVT::i64: 5779 if (++NumGPRsUsed <= NumGPRs) 5780 continue; 5781 break; 5782 case MVT::v4i32: 5783 case MVT::v8i16: 5784 case MVT::v16i8: 5785 case MVT::v2f64: 5786 case MVT::v2i64: 5787 case MVT::v1i128: 5788 case MVT::f128: 5789 if (++NumVRsUsed <= NumVRs) 5790 continue; 5791 break; 5792 case MVT::v4f32: 5793 if (++NumVRsUsed <= NumVRs) 5794 continue; 5795 break; 5796 case MVT::f32: 5797 case MVT::f64: 5798 if (++NumFPRsUsed <= NumFPRs) 5799 continue; 5800 break; 5801 } 5802 HasParameterArea = true; 5803 } 5804 } 5805 5806 /* Respect alignment of argument on the stack. */ 5807 auto Alignement = 5808 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5809 NumBytes = alignTo(NumBytes, Alignement); 5810 5811 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5812 if (Flags.isInConsecutiveRegsLast()) 5813 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5814 } 5815 5816 unsigned NumBytesActuallyUsed = NumBytes; 5817 5818 // In the old ELFv1 ABI, 5819 // the prolog code of the callee may store up to 8 GPR argument registers to 5820 // the stack, allowing va_start to index over them in memory if its varargs. 5821 // Because we cannot tell if this is needed on the caller side, we have to 5822 // conservatively assume that it is needed. As such, make sure we have at 5823 // least enough stack space for the caller to store the 8 GPRs. 5824 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5825 // really requires memory operands, e.g. a vararg function. 5826 if (HasParameterArea) 5827 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5828 else 5829 NumBytes = LinkageSize; 5830 5831 // Tail call needs the stack to be aligned. 5832 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5833 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5834 5835 int SPDiff = 0; 5836 5837 // Calculate by how many bytes the stack has to be adjusted in case of tail 5838 // call optimization. 5839 if (!IsSibCall) 5840 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5841 5842 // To protect arguments on the stack from being clobbered in a tail call, 5843 // force all the loads to happen before doing any other lowering. 5844 if (CFlags.IsTailCall) 5845 Chain = DAG.getStackArgumentTokenFactor(Chain); 5846 5847 // Adjust the stack pointer for the new arguments... 5848 // These operations are automatically eliminated by the prolog/epilog pass 5849 if (!IsSibCall) 5850 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5851 SDValue CallSeqStart = Chain; 5852 5853 // Load the return address and frame pointer so it can be move somewhere else 5854 // later. 5855 SDValue LROp, FPOp; 5856 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5857 5858 // Set up a copy of the stack pointer for use loading and storing any 5859 // arguments that may not fit in the registers available for argument 5860 // passing. 5861 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5862 5863 // Figure out which arguments are going to go in registers, and which in 5864 // memory. Also, if this is a vararg function, floating point operations 5865 // must be stored to our stack, and loaded into integer regs as well, if 5866 // any integer regs are available for argument passing. 5867 unsigned ArgOffset = LinkageSize; 5868 5869 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5870 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5871 5872 SmallVector<SDValue, 8> MemOpChains; 5873 for (unsigned i = 0; i != NumOps; ++i) { 5874 SDValue Arg = OutVals[i]; 5875 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5876 EVT ArgVT = Outs[i].VT; 5877 EVT OrigVT = Outs[i].ArgVT; 5878 5879 // PtrOff will be used to store the current argument to the stack if a 5880 // register cannot be found for it. 5881 SDValue PtrOff; 5882 5883 // We re-align the argument offset for each argument, except when using the 5884 // fast calling convention, when we need to make sure we do that only when 5885 // we'll actually use a stack slot. 5886 auto ComputePtrOff = [&]() { 5887 /* Respect alignment of argument on the stack. */ 5888 auto Alignment = 5889 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5890 ArgOffset = alignTo(ArgOffset, Alignment); 5891 5892 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5893 5894 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5895 }; 5896 5897 if (!IsFastCall) { 5898 ComputePtrOff(); 5899 5900 /* Compute GPR index associated with argument offset. */ 5901 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5902 GPR_idx = std::min(GPR_idx, NumGPRs); 5903 } 5904 5905 // Promote integers to 64-bit values. 5906 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5907 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5908 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5909 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5910 } 5911 5912 // FIXME memcpy is used way more than necessary. Correctness first. 5913 // Note: "by value" is code for passing a structure by value, not 5914 // basic types. 5915 if (Flags.isByVal()) { 5916 // Note: Size includes alignment padding, so 5917 // struct x { short a; char b; } 5918 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5919 // These are the proper values we need for right-justifying the 5920 // aggregate in a parameter register. 5921 unsigned Size = Flags.getByValSize(); 5922 5923 // An empty aggregate parameter takes up no storage and no 5924 // registers. 5925 if (Size == 0) 5926 continue; 5927 5928 if (IsFastCall) 5929 ComputePtrOff(); 5930 5931 // All aggregates smaller than 8 bytes must be passed right-justified. 5932 if (Size==1 || Size==2 || Size==4) { 5933 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5934 if (GPR_idx != NumGPRs) { 5935 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5936 MachinePointerInfo(), VT); 5937 MemOpChains.push_back(Load.getValue(1)); 5938 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5939 5940 ArgOffset += PtrByteSize; 5941 continue; 5942 } 5943 } 5944 5945 if (GPR_idx == NumGPRs && Size < 8) { 5946 SDValue AddPtr = PtrOff; 5947 if (!isLittleEndian) { 5948 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5949 PtrOff.getValueType()); 5950 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5951 } 5952 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5953 CallSeqStart, 5954 Flags, DAG, dl); 5955 ArgOffset += PtrByteSize; 5956 continue; 5957 } 5958 // Copy entire object into memory. There are cases where gcc-generated 5959 // code assumes it is there, even if it could be put entirely into 5960 // registers. (This is not what the doc says.) 5961 5962 // FIXME: The above statement is likely due to a misunderstanding of the 5963 // documents. All arguments must be copied into the parameter area BY 5964 // THE CALLEE in the event that the callee takes the address of any 5965 // formal argument. That has not yet been implemented. However, it is 5966 // reasonable to use the stack area as a staging area for the register 5967 // load. 5968 5969 // Skip this for small aggregates, as we will use the same slot for a 5970 // right-justified copy, below. 5971 if (Size >= 8) 5972 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5973 CallSeqStart, 5974 Flags, DAG, dl); 5975 5976 // When a register is available, pass a small aggregate right-justified. 5977 if (Size < 8 && GPR_idx != NumGPRs) { 5978 // The easiest way to get this right-justified in a register 5979 // is to copy the structure into the rightmost portion of a 5980 // local variable slot, then load the whole slot into the 5981 // register. 5982 // FIXME: The memcpy seems to produce pretty awful code for 5983 // small aggregates, particularly for packed ones. 5984 // FIXME: It would be preferable to use the slot in the 5985 // parameter save area instead of a new local variable. 5986 SDValue AddPtr = PtrOff; 5987 if (!isLittleEndian) { 5988 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5989 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5990 } 5991 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5992 CallSeqStart, 5993 Flags, DAG, dl); 5994 5995 // Load the slot into the register. 5996 SDValue Load = 5997 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5998 MemOpChains.push_back(Load.getValue(1)); 5999 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6000 6001 // Done with this argument. 6002 ArgOffset += PtrByteSize; 6003 continue; 6004 } 6005 6006 // For aggregates larger than PtrByteSize, copy the pieces of the 6007 // object that fit into registers from the parameter save area. 6008 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6009 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6010 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6011 if (GPR_idx != NumGPRs) { 6012 SDValue Load = 6013 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6014 MemOpChains.push_back(Load.getValue(1)); 6015 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6016 ArgOffset += PtrByteSize; 6017 } else { 6018 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6019 break; 6020 } 6021 } 6022 continue; 6023 } 6024 6025 switch (Arg.getSimpleValueType().SimpleTy) { 6026 default: llvm_unreachable("Unexpected ValueType for argument!"); 6027 case MVT::i1: 6028 case MVT::i32: 6029 case MVT::i64: 6030 if (Flags.isNest()) { 6031 // The 'nest' parameter, if any, is passed in R11. 6032 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6033 break; 6034 } 6035 6036 // These can be scalar arguments or elements of an integer array type 6037 // passed directly. Clang may use those instead of "byval" aggregate 6038 // types to avoid forcing arguments to memory unnecessarily. 6039 if (GPR_idx != NumGPRs) { 6040 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6041 } else { 6042 if (IsFastCall) 6043 ComputePtrOff(); 6044 6045 assert(HasParameterArea && 6046 "Parameter area must exist to pass an argument in memory."); 6047 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6048 true, CFlags.IsTailCall, false, MemOpChains, 6049 TailCallArguments, dl); 6050 if (IsFastCall) 6051 ArgOffset += PtrByteSize; 6052 } 6053 if (!IsFastCall) 6054 ArgOffset += PtrByteSize; 6055 break; 6056 case MVT::f32: 6057 case MVT::f64: { 6058 // These can be scalar arguments or elements of a float array type 6059 // passed directly. The latter are used to implement ELFv2 homogenous 6060 // float aggregates. 6061 6062 // Named arguments go into FPRs first, and once they overflow, the 6063 // remaining arguments go into GPRs and then the parameter save area. 6064 // Unnamed arguments for vararg functions always go to GPRs and 6065 // then the parameter save area. For now, put all arguments to vararg 6066 // routines always in both locations (FPR *and* GPR or stack slot). 6067 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6068 bool NeededLoad = false; 6069 6070 // First load the argument into the next available FPR. 6071 if (FPR_idx != NumFPRs) 6072 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6073 6074 // Next, load the argument into GPR or stack slot if needed. 6075 if (!NeedGPROrStack) 6076 ; 6077 else if (GPR_idx != NumGPRs && !IsFastCall) { 6078 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6079 // once we support fp <-> gpr moves. 6080 6081 // In the non-vararg case, this can only ever happen in the 6082 // presence of f32 array types, since otherwise we never run 6083 // out of FPRs before running out of GPRs. 6084 SDValue ArgVal; 6085 6086 // Double values are always passed in a single GPR. 6087 if (Arg.getValueType() != MVT::f32) { 6088 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6089 6090 // Non-array float values are extended and passed in a GPR. 6091 } else if (!Flags.isInConsecutiveRegs()) { 6092 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6093 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6094 6095 // If we have an array of floats, we collect every odd element 6096 // together with its predecessor into one GPR. 6097 } else if (ArgOffset % PtrByteSize != 0) { 6098 SDValue Lo, Hi; 6099 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6100 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6101 if (!isLittleEndian) 6102 std::swap(Lo, Hi); 6103 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6104 6105 // The final element, if even, goes into the first half of a GPR. 6106 } else if (Flags.isInConsecutiveRegsLast()) { 6107 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6108 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6109 if (!isLittleEndian) 6110 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6111 DAG.getConstant(32, dl, MVT::i32)); 6112 6113 // Non-final even elements are skipped; they will be handled 6114 // together the with subsequent argument on the next go-around. 6115 } else 6116 ArgVal = SDValue(); 6117 6118 if (ArgVal.getNode()) 6119 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6120 } else { 6121 if (IsFastCall) 6122 ComputePtrOff(); 6123 6124 // Single-precision floating-point values are mapped to the 6125 // second (rightmost) word of the stack doubleword. 6126 if (Arg.getValueType() == MVT::f32 && 6127 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6128 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6129 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6130 } 6131 6132 assert(HasParameterArea && 6133 "Parameter area must exist to pass an argument in memory."); 6134 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6135 true, CFlags.IsTailCall, false, MemOpChains, 6136 TailCallArguments, dl); 6137 6138 NeededLoad = true; 6139 } 6140 // When passing an array of floats, the array occupies consecutive 6141 // space in the argument area; only round up to the next doubleword 6142 // at the end of the array. Otherwise, each float takes 8 bytes. 6143 if (!IsFastCall || NeededLoad) { 6144 ArgOffset += (Arg.getValueType() == MVT::f32 && 6145 Flags.isInConsecutiveRegs()) ? 4 : 8; 6146 if (Flags.isInConsecutiveRegsLast()) 6147 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6148 } 6149 break; 6150 } 6151 case MVT::v4f32: 6152 case MVT::v4i32: 6153 case MVT::v8i16: 6154 case MVT::v16i8: 6155 case MVT::v2f64: 6156 case MVT::v2i64: 6157 case MVT::v1i128: 6158 case MVT::f128: 6159 // These can be scalar arguments or elements of a vector array type 6160 // passed directly. The latter are used to implement ELFv2 homogenous 6161 // vector aggregates. 6162 6163 // For a varargs call, named arguments go into VRs or on the stack as 6164 // usual; unnamed arguments always go to the stack or the corresponding 6165 // GPRs when within range. For now, we always put the value in both 6166 // locations (or even all three). 6167 if (CFlags.IsVarArg) { 6168 assert(HasParameterArea && 6169 "Parameter area must exist if we have a varargs call."); 6170 // We could elide this store in the case where the object fits 6171 // entirely in R registers. Maybe later. 6172 SDValue Store = 6173 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6174 MemOpChains.push_back(Store); 6175 if (VR_idx != NumVRs) { 6176 SDValue Load = 6177 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6178 MemOpChains.push_back(Load.getValue(1)); 6179 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6180 } 6181 ArgOffset += 16; 6182 for (unsigned i=0; i<16; i+=PtrByteSize) { 6183 if (GPR_idx == NumGPRs) 6184 break; 6185 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6186 DAG.getConstant(i, dl, PtrVT)); 6187 SDValue Load = 6188 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6189 MemOpChains.push_back(Load.getValue(1)); 6190 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6191 } 6192 break; 6193 } 6194 6195 // Non-varargs Altivec params go into VRs or on the stack. 6196 if (VR_idx != NumVRs) { 6197 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6198 } else { 6199 if (IsFastCall) 6200 ComputePtrOff(); 6201 6202 assert(HasParameterArea && 6203 "Parameter area must exist to pass an argument in memory."); 6204 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6205 true, CFlags.IsTailCall, true, MemOpChains, 6206 TailCallArguments, dl); 6207 if (IsFastCall) 6208 ArgOffset += 16; 6209 } 6210 6211 if (!IsFastCall) 6212 ArgOffset += 16; 6213 break; 6214 } 6215 } 6216 6217 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6218 "mismatch in size of parameter area"); 6219 (void)NumBytesActuallyUsed; 6220 6221 if (!MemOpChains.empty()) 6222 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6223 6224 // Check if this is an indirect call (MTCTR/BCTRL). 6225 // See prepareDescriptorIndirectCall and buildCallOperands for more 6226 // information about calls through function pointers in the 64-bit SVR4 ABI. 6227 if (CFlags.IsIndirect) { 6228 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6229 // caller in the TOC save area. 6230 if (isTOCSaveRestoreRequired(Subtarget)) { 6231 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6232 // Load r2 into a virtual register and store it to the TOC save area. 6233 setUsesTOCBasePtr(DAG); 6234 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6235 // TOC save area offset. 6236 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6237 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6238 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6239 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6240 MachinePointerInfo::getStack( 6241 DAG.getMachineFunction(), TOCSaveOffset)); 6242 } 6243 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6244 // This does not mean the MTCTR instruction must use R12; it's easier 6245 // to model this as an extra parameter, so do that. 6246 if (isELFv2ABI && !CFlags.IsPatchPoint) 6247 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6248 } 6249 6250 // Build a sequence of copy-to-reg nodes chained together with token chain 6251 // and flag operands which copy the outgoing args into the appropriate regs. 6252 SDValue InFlag; 6253 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6254 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6255 RegsToPass[i].second, InFlag); 6256 InFlag = Chain.getValue(1); 6257 } 6258 6259 if (CFlags.IsTailCall && !IsSibCall) 6260 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6261 TailCallArguments); 6262 6263 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6264 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6265 } 6266 6267 // Returns true when the shadow of a general purpose argument register 6268 // in the parameter save area is aligned to at least 'RequiredAlign'. 6269 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6270 assert(RequiredAlign.value() <= 16 && 6271 "Required alignment greater than stack alignment."); 6272 switch (Reg) { 6273 default: 6274 report_fatal_error("called on invalid register."); 6275 case PPC::R5: 6276 case PPC::R9: 6277 case PPC::X3: 6278 case PPC::X5: 6279 case PPC::X7: 6280 case PPC::X9: 6281 // These registers are 16 byte aligned which is the most strict aligment 6282 // we can support. 6283 return true; 6284 case PPC::R3: 6285 case PPC::R7: 6286 case PPC::X4: 6287 case PPC::X6: 6288 case PPC::X8: 6289 case PPC::X10: 6290 // The shadow of these registers in the PSA is 8 byte aligned. 6291 return RequiredAlign <= 8; 6292 case PPC::R4: 6293 case PPC::R6: 6294 case PPC::R8: 6295 case PPC::R10: 6296 return RequiredAlign <= 4; 6297 } 6298 } 6299 6300 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6301 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6302 CCState &S) { 6303 AIXCCState &State = static_cast<AIXCCState &>(S); 6304 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6305 State.getMachineFunction().getSubtarget()); 6306 const bool IsPPC64 = Subtarget.isPPC64(); 6307 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6308 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6309 6310 if (ValVT == MVT::f128) 6311 report_fatal_error("f128 is unimplemented on AIX."); 6312 6313 if (ArgFlags.isNest()) 6314 report_fatal_error("Nest arguments are unimplemented."); 6315 6316 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6317 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6318 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6319 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6320 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6321 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6322 6323 static const MCPhysReg VR[] = {// Vector registers. 6324 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6325 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6326 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6327 6328 if (ArgFlags.isByVal()) { 6329 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6330 report_fatal_error("Pass-by-value arguments with alignment greater than " 6331 "register width are not supported."); 6332 6333 const unsigned ByValSize = ArgFlags.getByValSize(); 6334 6335 // An empty aggregate parameter takes up no storage and no registers, 6336 // but needs a MemLoc for a stack slot for the formal arguments side. 6337 if (ByValSize == 0) { 6338 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6339 State.getNextStackOffset(), RegVT, 6340 LocInfo)); 6341 return false; 6342 } 6343 6344 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6345 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6346 for (const unsigned E = Offset + StackSize; Offset < E; 6347 Offset += PtrAlign.value()) { 6348 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6349 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6350 else { 6351 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6352 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6353 LocInfo)); 6354 break; 6355 } 6356 } 6357 return false; 6358 } 6359 6360 // Arguments always reserve parameter save area. 6361 switch (ValVT.SimpleTy) { 6362 default: 6363 report_fatal_error("Unhandled value type for argument."); 6364 case MVT::i64: 6365 // i64 arguments should have been split to i32 for PPC32. 6366 assert(IsPPC64 && "PPC32 should have split i64 values."); 6367 LLVM_FALLTHROUGH; 6368 case MVT::i1: 6369 case MVT::i32: { 6370 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6371 // AIX integer arguments are always passed in register width. 6372 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6373 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6374 : CCValAssign::LocInfo::ZExt; 6375 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6376 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6377 else 6378 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6379 6380 return false; 6381 } 6382 case MVT::f32: 6383 case MVT::f64: { 6384 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6385 const unsigned StoreSize = LocVT.getStoreSize(); 6386 // Floats are always 4-byte aligned in the PSA on AIX. 6387 // This includes f64 in 64-bit mode for ABI compatibility. 6388 const unsigned Offset = 6389 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6390 unsigned FReg = State.AllocateReg(FPR); 6391 if (FReg) 6392 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6393 6394 // Reserve and initialize GPRs or initialize the PSA as required. 6395 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6396 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6397 assert(FReg && "An FPR should be available when a GPR is reserved."); 6398 if (State.isVarArg()) { 6399 // Successfully reserved GPRs are only initialized for vararg calls. 6400 // Custom handling is required for: 6401 // f64 in PPC32 needs to be split into 2 GPRs. 6402 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6403 State.addLoc( 6404 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6405 } 6406 } else { 6407 // If there are insufficient GPRs, the PSA needs to be initialized. 6408 // Initialization occurs even if an FPR was initialized for 6409 // compatibility with the AIX XL compiler. The full memory for the 6410 // argument will be initialized even if a prior word is saved in GPR. 6411 // A custom memLoc is used when the argument also passes in FPR so 6412 // that the callee handling can skip over it easily. 6413 State.addLoc( 6414 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6415 LocInfo) 6416 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6417 break; 6418 } 6419 } 6420 6421 return false; 6422 } 6423 case MVT::v4f32: 6424 case MVT::v4i32: 6425 case MVT::v8i16: 6426 case MVT::v16i8: 6427 case MVT::v2i64: 6428 case MVT::v2f64: 6429 case MVT::v1i128: { 6430 const unsigned VecSize = 16; 6431 const Align VecAlign(VecSize); 6432 6433 if (!State.isVarArg()) { 6434 // If there are vector registers remaining we don't consume any stack 6435 // space. 6436 if (unsigned VReg = State.AllocateReg(VR)) { 6437 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6438 return false; 6439 } 6440 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6441 // might be allocated in the portion of the PSA that is shadowed by the 6442 // GPRs. 6443 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6444 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6445 return false; 6446 } 6447 6448 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6449 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6450 6451 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6452 // Burn any underaligned registers and their shadowed stack space until 6453 // we reach the required alignment. 6454 while (NextRegIndex != GPRs.size() && 6455 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6456 // Shadow allocate register and its stack shadow. 6457 unsigned Reg = State.AllocateReg(GPRs); 6458 State.AllocateStack(PtrSize, PtrAlign); 6459 assert(Reg && "Allocating register unexpectedly failed."); 6460 (void)Reg; 6461 NextRegIndex = State.getFirstUnallocated(GPRs); 6462 } 6463 6464 // Vectors that are passed as fixed arguments are handled differently. 6465 // They are passed in VRs if any are available (unlike arguments passed 6466 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6467 // functions) 6468 if (State.isFixed(ValNo)) { 6469 if (unsigned VReg = State.AllocateReg(VR)) { 6470 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6471 // Shadow allocate GPRs and stack space even though we pass in a VR. 6472 for (unsigned I = 0; I != VecSize; I += PtrSize) 6473 State.AllocateReg(GPRs); 6474 State.AllocateStack(VecSize, VecAlign); 6475 return false; 6476 } 6477 // No vector registers remain so pass on the stack. 6478 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6479 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6480 return false; 6481 } 6482 6483 // If all GPRS are consumed then we pass the argument fully on the stack. 6484 if (NextRegIndex == GPRs.size()) { 6485 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6486 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6487 return false; 6488 } 6489 6490 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6491 // half of the argument, and then need to pass the remaining half on the 6492 // stack. 6493 if (GPRs[NextRegIndex] == PPC::R9) { 6494 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6495 State.addLoc( 6496 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6497 6498 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6499 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6500 assert(FirstReg && SecondReg && 6501 "Allocating R9 or R10 unexpectedly failed."); 6502 State.addLoc( 6503 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6504 State.addLoc( 6505 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6506 return false; 6507 } 6508 6509 // We have enough GPRs to fully pass the vector argument, and we have 6510 // already consumed any underaligned registers. Start with the custom 6511 // MemLoc and then the custom RegLocs. 6512 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6513 State.addLoc( 6514 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6515 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6516 const unsigned Reg = State.AllocateReg(GPRs); 6517 assert(Reg && "Failed to allocated register for vararg vector argument"); 6518 State.addLoc( 6519 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6520 } 6521 return false; 6522 } 6523 } 6524 return true; 6525 } 6526 6527 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6528 bool IsPPC64) { 6529 assert((IsPPC64 || SVT != MVT::i64) && 6530 "i64 should have been split for 32-bit codegen."); 6531 6532 switch (SVT) { 6533 default: 6534 report_fatal_error("Unexpected value type for formal argument"); 6535 case MVT::i1: 6536 case MVT::i32: 6537 case MVT::i64: 6538 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6539 case MVT::f32: 6540 return &PPC::F4RCRegClass; 6541 case MVT::f64: 6542 return &PPC::F8RCRegClass; 6543 case MVT::v4f32: 6544 case MVT::v4i32: 6545 case MVT::v8i16: 6546 case MVT::v16i8: 6547 case MVT::v2i64: 6548 case MVT::v2f64: 6549 case MVT::v1i128: 6550 return &PPC::VRRCRegClass; 6551 } 6552 } 6553 6554 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6555 SelectionDAG &DAG, SDValue ArgValue, 6556 MVT LocVT, const SDLoc &dl) { 6557 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6558 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6559 6560 if (Flags.isSExt()) 6561 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6562 DAG.getValueType(ValVT)); 6563 else if (Flags.isZExt()) 6564 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6565 DAG.getValueType(ValVT)); 6566 6567 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6568 } 6569 6570 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6571 const unsigned LASize = FL->getLinkageSize(); 6572 6573 if (PPC::GPRCRegClass.contains(Reg)) { 6574 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6575 "Reg must be a valid argument register!"); 6576 return LASize + 4 * (Reg - PPC::R3); 6577 } 6578 6579 if (PPC::G8RCRegClass.contains(Reg)) { 6580 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6581 "Reg must be a valid argument register!"); 6582 return LASize + 8 * (Reg - PPC::X3); 6583 } 6584 6585 llvm_unreachable("Only general purpose registers expected."); 6586 } 6587 6588 // AIX ABI Stack Frame Layout: 6589 // 6590 // Low Memory +--------------------------------------------+ 6591 // SP +---> | Back chain | ---+ 6592 // | +--------------------------------------------+ | 6593 // | | Saved Condition Register | | 6594 // | +--------------------------------------------+ | 6595 // | | Saved Linkage Register | | 6596 // | +--------------------------------------------+ | Linkage Area 6597 // | | Reserved for compilers | | 6598 // | +--------------------------------------------+ | 6599 // | | Reserved for binders | | 6600 // | +--------------------------------------------+ | 6601 // | | Saved TOC pointer | ---+ 6602 // | +--------------------------------------------+ 6603 // | | Parameter save area | 6604 // | +--------------------------------------------+ 6605 // | | Alloca space | 6606 // | +--------------------------------------------+ 6607 // | | Local variable space | 6608 // | +--------------------------------------------+ 6609 // | | Float/int conversion temporary | 6610 // | +--------------------------------------------+ 6611 // | | Save area for AltiVec registers | 6612 // | +--------------------------------------------+ 6613 // | | AltiVec alignment padding | 6614 // | +--------------------------------------------+ 6615 // | | Save area for VRSAVE register | 6616 // | +--------------------------------------------+ 6617 // | | Save area for General Purpose registers | 6618 // | +--------------------------------------------+ 6619 // | | Save area for Floating Point registers | 6620 // | +--------------------------------------------+ 6621 // +---- | Back chain | 6622 // High Memory +--------------------------------------------+ 6623 // 6624 // Specifications: 6625 // AIX 7.2 Assembler Language Reference 6626 // Subroutine linkage convention 6627 6628 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6629 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6630 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6631 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6632 6633 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6634 CallConv == CallingConv::Fast) && 6635 "Unexpected calling convention!"); 6636 6637 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6638 report_fatal_error("Tail call support is unimplemented on AIX."); 6639 6640 if (useSoftFloat()) 6641 report_fatal_error("Soft float support is unimplemented on AIX."); 6642 6643 const PPCSubtarget &Subtarget = 6644 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6645 6646 const bool IsPPC64 = Subtarget.isPPC64(); 6647 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6648 6649 // Assign locations to all of the incoming arguments. 6650 SmallVector<CCValAssign, 16> ArgLocs; 6651 MachineFunction &MF = DAG.getMachineFunction(); 6652 MachineFrameInfo &MFI = MF.getFrameInfo(); 6653 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6654 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6655 6656 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6657 // Reserve space for the linkage area on the stack. 6658 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6659 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6660 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6661 6662 SmallVector<SDValue, 8> MemOps; 6663 6664 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6665 CCValAssign &VA = ArgLocs[I++]; 6666 MVT LocVT = VA.getLocVT(); 6667 MVT ValVT = VA.getValVT(); 6668 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6669 // For compatibility with the AIX XL compiler, the float args in the 6670 // parameter save area are initialized even if the argument is available 6671 // in register. The caller is required to initialize both the register 6672 // and memory, however, the callee can choose to expect it in either. 6673 // The memloc is dismissed here because the argument is retrieved from 6674 // the register. 6675 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6676 continue; 6677 6678 auto HandleMemLoc = [&]() { 6679 const unsigned LocSize = LocVT.getStoreSize(); 6680 const unsigned ValSize = ValVT.getStoreSize(); 6681 assert((ValSize <= LocSize) && 6682 "Object size is larger than size of MemLoc"); 6683 int CurArgOffset = VA.getLocMemOffset(); 6684 // Objects are right-justified because AIX is big-endian. 6685 if (LocSize > ValSize) 6686 CurArgOffset += LocSize - ValSize; 6687 // Potential tail calls could cause overwriting of argument stack slots. 6688 const bool IsImmutable = 6689 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6690 (CallConv == CallingConv::Fast)); 6691 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6692 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6693 SDValue ArgValue = 6694 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6695 InVals.push_back(ArgValue); 6696 }; 6697 6698 // Vector arguments to VaArg functions are passed both on the stack, and 6699 // in any available GPRs. Load the value from the stack and add the GPRs 6700 // as live ins. 6701 if (VA.isMemLoc() && VA.needsCustom()) { 6702 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6703 assert(isVarArg && "Only use custom memloc for vararg."); 6704 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6705 // matching custom RegLocs. 6706 const unsigned OriginalValNo = VA.getValNo(); 6707 (void)OriginalValNo; 6708 6709 auto HandleCustomVecRegLoc = [&]() { 6710 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6711 "Missing custom RegLoc."); 6712 VA = ArgLocs[I++]; 6713 assert(VA.getValVT().isVector() && 6714 "Unexpected Val type for custom RegLoc."); 6715 assert(VA.getValNo() == OriginalValNo && 6716 "ValNo mismatch between custom MemLoc and RegLoc."); 6717 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6718 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6719 }; 6720 6721 HandleMemLoc(); 6722 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6723 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6724 // R10. 6725 HandleCustomVecRegLoc(); 6726 HandleCustomVecRegLoc(); 6727 6728 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 6729 // we passed the vector in R5, R6, R7 and R8. 6730 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 6731 assert(!IsPPC64 && 6732 "Only 2 custom RegLocs expected for 64-bit codegen."); 6733 HandleCustomVecRegLoc(); 6734 HandleCustomVecRegLoc(); 6735 } 6736 6737 continue; 6738 } 6739 6740 if (VA.isRegLoc()) { 6741 if (VA.getValVT().isScalarInteger()) 6742 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6743 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) 6744 FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32 6745 ? PPCFunctionInfo::ShortFloatPoint 6746 : PPCFunctionInfo::LongFloatPoint); 6747 } 6748 6749 if (Flags.isByVal() && VA.isMemLoc()) { 6750 const unsigned Size = 6751 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 6752 PtrByteSize); 6753 const int FI = MF.getFrameInfo().CreateFixedObject( 6754 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 6755 /* IsAliased */ true); 6756 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6757 InVals.push_back(FIN); 6758 6759 continue; 6760 } 6761 6762 if (Flags.isByVal()) { 6763 assert(VA.isRegLoc() && "MemLocs should already be handled."); 6764 6765 const MCPhysReg ArgReg = VA.getLocReg(); 6766 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 6767 6768 if (Flags.getNonZeroByValAlign() > PtrByteSize) 6769 report_fatal_error("Over aligned byvals not supported yet."); 6770 6771 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 6772 const int FI = MF.getFrameInfo().CreateFixedObject( 6773 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 6774 /* IsAliased */ true); 6775 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6776 InVals.push_back(FIN); 6777 6778 // Add live ins for all the RegLocs for the same ByVal. 6779 const TargetRegisterClass *RegClass = 6780 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6781 6782 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 6783 unsigned Offset) { 6784 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 6785 // Since the callers side has left justified the aggregate in the 6786 // register, we can simply store the entire register into the stack 6787 // slot. 6788 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6789 // The store to the fixedstack object is needed becuase accessing a 6790 // field of the ByVal will use a gep and load. Ideally we will optimize 6791 // to extracting the value from the register directly, and elide the 6792 // stores when the arguments address is not taken, but that will need to 6793 // be future work. 6794 SDValue Store = DAG.getStore( 6795 CopyFrom.getValue(1), dl, CopyFrom, 6796 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 6797 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 6798 6799 MemOps.push_back(Store); 6800 }; 6801 6802 unsigned Offset = 0; 6803 HandleRegLoc(VA.getLocReg(), Offset); 6804 Offset += PtrByteSize; 6805 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 6806 Offset += PtrByteSize) { 6807 assert(ArgLocs[I].getValNo() == VA.getValNo() && 6808 "RegLocs should be for ByVal argument."); 6809 6810 const CCValAssign RL = ArgLocs[I++]; 6811 HandleRegLoc(RL.getLocReg(), Offset); 6812 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6813 } 6814 6815 if (Offset != StackSize) { 6816 assert(ArgLocs[I].getValNo() == VA.getValNo() && 6817 "Expected MemLoc for remaining bytes."); 6818 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 6819 // Consume the MemLoc.The InVal has already been emitted, so nothing 6820 // more needs to be done. 6821 ++I; 6822 } 6823 6824 continue; 6825 } 6826 6827 if (VA.isRegLoc() && !VA.needsCustom()) { 6828 MVT::SimpleValueType SVT = ValVT.SimpleTy; 6829 unsigned VReg = 6830 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6831 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6832 if (ValVT.isScalarInteger() && 6833 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 6834 ArgValue = 6835 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6836 } 6837 InVals.push_back(ArgValue); 6838 continue; 6839 } 6840 if (VA.isMemLoc()) { 6841 HandleMemLoc(); 6842 continue; 6843 } 6844 } 6845 6846 // On AIX a minimum of 8 words is saved to the parameter save area. 6847 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6848 // Area that is at least reserved in the caller of this function. 6849 unsigned CallerReservedArea = 6850 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 6851 6852 // Set the size that is at least reserved in caller of this function. Tail 6853 // call optimized function's reserved stack space needs to be aligned so 6854 // that taking the difference between two stack areas will result in an 6855 // aligned stack. 6856 CallerReservedArea = 6857 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 6858 FuncInfo->setMinReservedArea(CallerReservedArea); 6859 6860 if (isVarArg) { 6861 FuncInfo->setVarArgsFrameIndex( 6862 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 6863 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 6864 6865 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6866 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6867 6868 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6869 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6870 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 6871 6872 // The fixed integer arguments of a variadic function are stored to the 6873 // VarArgsFrameIndex on the stack so that they may be loaded by 6874 // dereferencing the result of va_next. 6875 for (unsigned GPRIndex = 6876 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 6877 GPRIndex < NumGPArgRegs; ++GPRIndex) { 6878 6879 const unsigned VReg = 6880 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 6881 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 6882 6883 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 6884 SDValue Store = 6885 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 6886 MemOps.push_back(Store); 6887 // Increment the address for the next argument to store. 6888 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 6889 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 6890 } 6891 } 6892 6893 if (!MemOps.empty()) 6894 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 6895 6896 return Chain; 6897 } 6898 6899 SDValue PPCTargetLowering::LowerCall_AIX( 6900 SDValue Chain, SDValue Callee, CallFlags CFlags, 6901 const SmallVectorImpl<ISD::OutputArg> &Outs, 6902 const SmallVectorImpl<SDValue> &OutVals, 6903 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6904 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6905 const CallBase *CB) const { 6906 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 6907 // AIX ABI stack frame layout. 6908 6909 assert((CFlags.CallConv == CallingConv::C || 6910 CFlags.CallConv == CallingConv::Cold || 6911 CFlags.CallConv == CallingConv::Fast) && 6912 "Unexpected calling convention!"); 6913 6914 if (CFlags.IsPatchPoint) 6915 report_fatal_error("This call type is unimplemented on AIX."); 6916 6917 const PPCSubtarget& Subtarget = 6918 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 6919 6920 MachineFunction &MF = DAG.getMachineFunction(); 6921 SmallVector<CCValAssign, 16> ArgLocs; 6922 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 6923 *DAG.getContext()); 6924 6925 // Reserve space for the linkage save area (LSA) on the stack. 6926 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 6927 // [SP][CR][LR][2 x reserved][TOC]. 6928 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 6929 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6930 const bool IsPPC64 = Subtarget.isPPC64(); 6931 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6932 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6933 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6934 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 6935 6936 // The prolog code of the callee may store up to 8 GPR argument registers to 6937 // the stack, allowing va_start to index over them in memory if the callee 6938 // is variadic. 6939 // Because we cannot tell if this is needed on the caller side, we have to 6940 // conservatively assume that it is needed. As such, make sure we have at 6941 // least enough stack space for the caller to store the 8 GPRs. 6942 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 6943 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 6944 CCInfo.getNextStackOffset()); 6945 6946 // Adjust the stack pointer for the new arguments... 6947 // These operations are automatically eliminated by the prolog/epilog pass. 6948 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6949 SDValue CallSeqStart = Chain; 6950 6951 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6952 SmallVector<SDValue, 8> MemOpChains; 6953 6954 // Set up a copy of the stack pointer for loading and storing any 6955 // arguments that may not fit in the registers available for argument 6956 // passing. 6957 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 6958 : DAG.getRegister(PPC::R1, MVT::i32); 6959 6960 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 6961 const unsigned ValNo = ArgLocs[I].getValNo(); 6962 SDValue Arg = OutVals[ValNo]; 6963 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 6964 6965 if (Flags.isByVal()) { 6966 const unsigned ByValSize = Flags.getByValSize(); 6967 6968 // Nothing to do for zero-sized ByVals on the caller side. 6969 if (!ByValSize) { 6970 ++I; 6971 continue; 6972 } 6973 6974 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 6975 return DAG.getExtLoad( 6976 ISD::ZEXTLOAD, dl, PtrVT, Chain, 6977 (LoadOffset != 0) 6978 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 6979 : Arg, 6980 MachinePointerInfo(), VT); 6981 }; 6982 6983 unsigned LoadOffset = 0; 6984 6985 // Initialize registers, which are fully occupied by the by-val argument. 6986 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 6987 SDValue Load = GetLoad(PtrVT, LoadOffset); 6988 MemOpChains.push_back(Load.getValue(1)); 6989 LoadOffset += PtrByteSize; 6990 const CCValAssign &ByValVA = ArgLocs[I++]; 6991 assert(ByValVA.getValNo() == ValNo && 6992 "Unexpected location for pass-by-value argument."); 6993 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 6994 } 6995 6996 if (LoadOffset == ByValSize) 6997 continue; 6998 6999 // There must be one more loc to handle the remainder. 7000 assert(ArgLocs[I].getValNo() == ValNo && 7001 "Expected additional location for by-value argument."); 7002 7003 if (ArgLocs[I].isMemLoc()) { 7004 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7005 const CCValAssign &ByValVA = ArgLocs[I++]; 7006 ISD::ArgFlagsTy MemcpyFlags = Flags; 7007 // Only memcpy the bytes that don't pass in register. 7008 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7009 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7010 (LoadOffset != 0) 7011 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7012 : Arg, 7013 DAG.getObjectPtrOffset(dl, StackPtr, 7014 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7015 CallSeqStart, MemcpyFlags, DAG, dl); 7016 continue; 7017 } 7018 7019 // Initialize the final register residue. 7020 // Any residue that occupies the final by-val arg register must be 7021 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7022 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7023 // 2 and 1 byte loads. 7024 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7025 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7026 "Unexpected register residue for by-value argument."); 7027 SDValue ResidueVal; 7028 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7029 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7030 const MVT VT = 7031 N == 1 ? MVT::i8 7032 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7033 SDValue Load = GetLoad(VT, LoadOffset); 7034 MemOpChains.push_back(Load.getValue(1)); 7035 LoadOffset += N; 7036 Bytes += N; 7037 7038 // By-val arguments are passed left-justfied in register. 7039 // Every load here needs to be shifted, otherwise a full register load 7040 // should have been used. 7041 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7042 "Unexpected load emitted during handling of pass-by-value " 7043 "argument."); 7044 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7045 EVT ShiftAmountTy = 7046 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7047 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7048 SDValue ShiftedLoad = 7049 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7050 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7051 ShiftedLoad) 7052 : ShiftedLoad; 7053 } 7054 7055 const CCValAssign &ByValVA = ArgLocs[I++]; 7056 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7057 continue; 7058 } 7059 7060 CCValAssign &VA = ArgLocs[I++]; 7061 const MVT LocVT = VA.getLocVT(); 7062 const MVT ValVT = VA.getValVT(); 7063 7064 switch (VA.getLocInfo()) { 7065 default: 7066 report_fatal_error("Unexpected argument extension type."); 7067 case CCValAssign::Full: 7068 break; 7069 case CCValAssign::ZExt: 7070 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7071 break; 7072 case CCValAssign::SExt: 7073 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7074 break; 7075 } 7076 7077 if (VA.isRegLoc() && !VA.needsCustom()) { 7078 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7079 continue; 7080 } 7081 7082 // Vector arguments passed to VarArg functions need custom handling when 7083 // they are passed (at least partially) in GPRs. 7084 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7085 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7086 // Store value to its stack slot. 7087 SDValue PtrOff = 7088 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7089 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7090 SDValue Store = 7091 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7092 MemOpChains.push_back(Store); 7093 const unsigned OriginalValNo = VA.getValNo(); 7094 // Then load the GPRs from the stack 7095 unsigned LoadOffset = 0; 7096 auto HandleCustomVecRegLoc = [&]() { 7097 assert(I != E && "Unexpected end of CCvalAssigns."); 7098 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7099 "Expected custom RegLoc."); 7100 CCValAssign RegVA = ArgLocs[I++]; 7101 assert(RegVA.getValNo() == OriginalValNo && 7102 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7103 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7104 DAG.getConstant(LoadOffset, dl, PtrVT)); 7105 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7106 MemOpChains.push_back(Load.getValue(1)); 7107 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7108 LoadOffset += PtrByteSize; 7109 }; 7110 7111 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7112 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7113 // R10. 7114 HandleCustomVecRegLoc(); 7115 HandleCustomVecRegLoc(); 7116 7117 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7118 ArgLocs[I].getValNo() == OriginalValNo) { 7119 assert(!IsPPC64 && 7120 "Only 2 custom RegLocs expected for 64-bit codegen."); 7121 HandleCustomVecRegLoc(); 7122 HandleCustomVecRegLoc(); 7123 } 7124 7125 continue; 7126 } 7127 7128 if (VA.isMemLoc()) { 7129 SDValue PtrOff = 7130 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7131 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7132 MemOpChains.push_back( 7133 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7134 7135 continue; 7136 } 7137 7138 if (!ValVT.isFloatingPoint()) 7139 report_fatal_error( 7140 "Unexpected register handling for calling convention."); 7141 7142 // Custom handling is used for GPR initializations for vararg float 7143 // arguments. 7144 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7145 LocVT.isInteger() && 7146 "Custom register handling only expected for VarArg."); 7147 7148 SDValue ArgAsInt = 7149 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7150 7151 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7152 // f32 in 32-bit GPR 7153 // f64 in 64-bit GPR 7154 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7155 else if (Arg.getValueType().getFixedSizeInBits() < 7156 LocVT.getFixedSizeInBits()) 7157 // f32 in 64-bit GPR. 7158 RegsToPass.push_back(std::make_pair( 7159 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7160 else { 7161 // f64 in two 32-bit GPRs 7162 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7163 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7164 "Unexpected custom register for argument!"); 7165 CCValAssign &GPR1 = VA; 7166 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7167 DAG.getConstant(32, dl, MVT::i8)); 7168 RegsToPass.push_back(std::make_pair( 7169 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7170 7171 if (I != E) { 7172 // If only 1 GPR was available, there will only be one custom GPR and 7173 // the argument will also pass in memory. 7174 CCValAssign &PeekArg = ArgLocs[I]; 7175 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7176 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7177 CCValAssign &GPR2 = ArgLocs[I++]; 7178 RegsToPass.push_back(std::make_pair( 7179 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7180 } 7181 } 7182 } 7183 } 7184 7185 if (!MemOpChains.empty()) 7186 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7187 7188 // For indirect calls, we need to save the TOC base to the stack for 7189 // restoration after the call. 7190 if (CFlags.IsIndirect) { 7191 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7192 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7193 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7194 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7195 const unsigned TOCSaveOffset = 7196 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7197 7198 setUsesTOCBasePtr(DAG); 7199 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7200 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7201 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7202 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7203 Chain = DAG.getStore( 7204 Val.getValue(1), dl, Val, AddPtr, 7205 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7206 } 7207 7208 // Build a sequence of copy-to-reg nodes chained together with token chain 7209 // and flag operands which copy the outgoing args into the appropriate regs. 7210 SDValue InFlag; 7211 for (auto Reg : RegsToPass) { 7212 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7213 InFlag = Chain.getValue(1); 7214 } 7215 7216 const int SPDiff = 0; 7217 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7218 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7219 } 7220 7221 bool 7222 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7223 MachineFunction &MF, bool isVarArg, 7224 const SmallVectorImpl<ISD::OutputArg> &Outs, 7225 LLVMContext &Context) const { 7226 SmallVector<CCValAssign, 16> RVLocs; 7227 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7228 return CCInfo.CheckReturn( 7229 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7230 ? RetCC_PPC_Cold 7231 : RetCC_PPC); 7232 } 7233 7234 SDValue 7235 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7236 bool isVarArg, 7237 const SmallVectorImpl<ISD::OutputArg> &Outs, 7238 const SmallVectorImpl<SDValue> &OutVals, 7239 const SDLoc &dl, SelectionDAG &DAG) const { 7240 SmallVector<CCValAssign, 16> RVLocs; 7241 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7242 *DAG.getContext()); 7243 CCInfo.AnalyzeReturn(Outs, 7244 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7245 ? RetCC_PPC_Cold 7246 : RetCC_PPC); 7247 7248 SDValue Flag; 7249 SmallVector<SDValue, 4> RetOps(1, Chain); 7250 7251 // Copy the result values into the output registers. 7252 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7253 CCValAssign &VA = RVLocs[i]; 7254 assert(VA.isRegLoc() && "Can only return in registers!"); 7255 7256 SDValue Arg = OutVals[RealResIdx]; 7257 7258 switch (VA.getLocInfo()) { 7259 default: llvm_unreachable("Unknown loc info!"); 7260 case CCValAssign::Full: break; 7261 case CCValAssign::AExt: 7262 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7263 break; 7264 case CCValAssign::ZExt: 7265 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7266 break; 7267 case CCValAssign::SExt: 7268 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7269 break; 7270 } 7271 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7272 bool isLittleEndian = Subtarget.isLittleEndian(); 7273 // Legalize ret f64 -> ret 2 x i32. 7274 SDValue SVal = 7275 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7276 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7277 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7278 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7279 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7280 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7281 Flag = Chain.getValue(1); 7282 VA = RVLocs[++i]; // skip ahead to next loc 7283 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7284 } else 7285 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7286 Flag = Chain.getValue(1); 7287 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7288 } 7289 7290 RetOps[0] = Chain; // Update chain. 7291 7292 // Add the flag if we have it. 7293 if (Flag.getNode()) 7294 RetOps.push_back(Flag); 7295 7296 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7297 } 7298 7299 SDValue 7300 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7301 SelectionDAG &DAG) const { 7302 SDLoc dl(Op); 7303 7304 // Get the correct type for integers. 7305 EVT IntVT = Op.getValueType(); 7306 7307 // Get the inputs. 7308 SDValue Chain = Op.getOperand(0); 7309 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7310 // Build a DYNAREAOFFSET node. 7311 SDValue Ops[2] = {Chain, FPSIdx}; 7312 SDVTList VTs = DAG.getVTList(IntVT); 7313 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7314 } 7315 7316 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7317 SelectionDAG &DAG) const { 7318 // When we pop the dynamic allocation we need to restore the SP link. 7319 SDLoc dl(Op); 7320 7321 // Get the correct type for pointers. 7322 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7323 7324 // Construct the stack pointer operand. 7325 bool isPPC64 = Subtarget.isPPC64(); 7326 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7327 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7328 7329 // Get the operands for the STACKRESTORE. 7330 SDValue Chain = Op.getOperand(0); 7331 SDValue SaveSP = Op.getOperand(1); 7332 7333 // Load the old link SP. 7334 SDValue LoadLinkSP = 7335 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7336 7337 // Restore the stack pointer. 7338 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7339 7340 // Store the old link SP. 7341 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7342 } 7343 7344 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7345 MachineFunction &MF = DAG.getMachineFunction(); 7346 bool isPPC64 = Subtarget.isPPC64(); 7347 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7348 7349 // Get current frame pointer save index. The users of this index will be 7350 // primarily DYNALLOC instructions. 7351 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7352 int RASI = FI->getReturnAddrSaveIndex(); 7353 7354 // If the frame pointer save index hasn't been defined yet. 7355 if (!RASI) { 7356 // Find out what the fix offset of the frame pointer save area. 7357 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7358 // Allocate the frame index for frame pointer save area. 7359 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7360 // Save the result. 7361 FI->setReturnAddrSaveIndex(RASI); 7362 } 7363 return DAG.getFrameIndex(RASI, PtrVT); 7364 } 7365 7366 SDValue 7367 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7368 MachineFunction &MF = DAG.getMachineFunction(); 7369 bool isPPC64 = Subtarget.isPPC64(); 7370 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7371 7372 // Get current frame pointer save index. The users of this index will be 7373 // primarily DYNALLOC instructions. 7374 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7375 int FPSI = FI->getFramePointerSaveIndex(); 7376 7377 // If the frame pointer save index hasn't been defined yet. 7378 if (!FPSI) { 7379 // Find out what the fix offset of the frame pointer save area. 7380 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7381 // Allocate the frame index for frame pointer save area. 7382 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7383 // Save the result. 7384 FI->setFramePointerSaveIndex(FPSI); 7385 } 7386 return DAG.getFrameIndex(FPSI, PtrVT); 7387 } 7388 7389 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7390 SelectionDAG &DAG) const { 7391 MachineFunction &MF = DAG.getMachineFunction(); 7392 // Get the inputs. 7393 SDValue Chain = Op.getOperand(0); 7394 SDValue Size = Op.getOperand(1); 7395 SDLoc dl(Op); 7396 7397 // Get the correct type for pointers. 7398 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7399 // Negate the size. 7400 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7401 DAG.getConstant(0, dl, PtrVT), Size); 7402 // Construct a node for the frame pointer save index. 7403 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7404 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7405 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7406 if (hasInlineStackProbe(MF)) 7407 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7408 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7409 } 7410 7411 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7412 SelectionDAG &DAG) const { 7413 MachineFunction &MF = DAG.getMachineFunction(); 7414 7415 bool isPPC64 = Subtarget.isPPC64(); 7416 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7417 7418 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7419 return DAG.getFrameIndex(FI, PtrVT); 7420 } 7421 7422 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7423 SelectionDAG &DAG) const { 7424 SDLoc DL(Op); 7425 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7426 DAG.getVTList(MVT::i32, MVT::Other), 7427 Op.getOperand(0), Op.getOperand(1)); 7428 } 7429 7430 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7431 SelectionDAG &DAG) const { 7432 SDLoc DL(Op); 7433 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7434 Op.getOperand(0), Op.getOperand(1)); 7435 } 7436 7437 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7438 if (Op.getValueType().isVector()) 7439 return LowerVectorLoad(Op, DAG); 7440 7441 assert(Op.getValueType() == MVT::i1 && 7442 "Custom lowering only for i1 loads"); 7443 7444 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7445 7446 SDLoc dl(Op); 7447 LoadSDNode *LD = cast<LoadSDNode>(Op); 7448 7449 SDValue Chain = LD->getChain(); 7450 SDValue BasePtr = LD->getBasePtr(); 7451 MachineMemOperand *MMO = LD->getMemOperand(); 7452 7453 SDValue NewLD = 7454 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7455 BasePtr, MVT::i8, MMO); 7456 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7457 7458 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7459 return DAG.getMergeValues(Ops, dl); 7460 } 7461 7462 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7463 if (Op.getOperand(1).getValueType().isVector()) 7464 return LowerVectorStore(Op, DAG); 7465 7466 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7467 "Custom lowering only for i1 stores"); 7468 7469 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7470 7471 SDLoc dl(Op); 7472 StoreSDNode *ST = cast<StoreSDNode>(Op); 7473 7474 SDValue Chain = ST->getChain(); 7475 SDValue BasePtr = ST->getBasePtr(); 7476 SDValue Value = ST->getValue(); 7477 MachineMemOperand *MMO = ST->getMemOperand(); 7478 7479 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7480 Value); 7481 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7482 } 7483 7484 // FIXME: Remove this once the ANDI glue bug is fixed: 7485 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7486 assert(Op.getValueType() == MVT::i1 && 7487 "Custom lowering only for i1 results"); 7488 7489 SDLoc DL(Op); 7490 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7491 } 7492 7493 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7494 SelectionDAG &DAG) const { 7495 7496 // Implements a vector truncate that fits in a vector register as a shuffle. 7497 // We want to legalize vector truncates down to where the source fits in 7498 // a vector register (and target is therefore smaller than vector register 7499 // size). At that point legalization will try to custom lower the sub-legal 7500 // result and get here - where we can contain the truncate as a single target 7501 // operation. 7502 7503 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7504 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7505 // 7506 // We will implement it for big-endian ordering as this (where x denotes 7507 // undefined): 7508 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7509 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7510 // 7511 // The same operation in little-endian ordering will be: 7512 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7513 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7514 7515 EVT TrgVT = Op.getValueType(); 7516 assert(TrgVT.isVector() && "Vector type expected."); 7517 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7518 EVT EltVT = TrgVT.getVectorElementType(); 7519 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7520 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7521 !isPowerOf2_32(EltVT.getSizeInBits())) 7522 return SDValue(); 7523 7524 SDValue N1 = Op.getOperand(0); 7525 EVT SrcVT = N1.getValueType(); 7526 unsigned SrcSize = SrcVT.getSizeInBits(); 7527 if (SrcSize > 256 || 7528 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7529 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7530 return SDValue(); 7531 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7532 return SDValue(); 7533 7534 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7535 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7536 7537 SDLoc DL(Op); 7538 SDValue Op1, Op2; 7539 if (SrcSize == 256) { 7540 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7541 EVT SplitVT = 7542 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7543 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7544 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7545 DAG.getConstant(0, DL, VecIdxTy)); 7546 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7547 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7548 } 7549 else { 7550 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7551 Op2 = DAG.getUNDEF(WideVT); 7552 } 7553 7554 // First list the elements we want to keep. 7555 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7556 SmallVector<int, 16> ShuffV; 7557 if (Subtarget.isLittleEndian()) 7558 for (unsigned i = 0; i < TrgNumElts; ++i) 7559 ShuffV.push_back(i * SizeMult); 7560 else 7561 for (unsigned i = 1; i <= TrgNumElts; ++i) 7562 ShuffV.push_back(i * SizeMult - 1); 7563 7564 // Populate the remaining elements with undefs. 7565 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7566 // ShuffV.push_back(i + WideNumElts); 7567 ShuffV.push_back(WideNumElts + 1); 7568 7569 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7570 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7571 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7572 } 7573 7574 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7575 /// possible. 7576 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7577 // Not FP, or using SPE? Not a fsel. 7578 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7579 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7580 return Op; 7581 7582 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7583 7584 EVT ResVT = Op.getValueType(); 7585 EVT CmpVT = Op.getOperand(0).getValueType(); 7586 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7587 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7588 SDLoc dl(Op); 7589 SDNodeFlags Flags = Op.getNode()->getFlags(); 7590 7591 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7592 // presence of infinities. 7593 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7594 switch (CC) { 7595 default: 7596 break; 7597 case ISD::SETOGT: 7598 case ISD::SETGT: 7599 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7600 case ISD::SETOLT: 7601 case ISD::SETLT: 7602 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7603 } 7604 } 7605 7606 // We might be able to do better than this under some circumstances, but in 7607 // general, fsel-based lowering of select is a finite-math-only optimization. 7608 // For more information, see section F.3 of the 2.06 ISA specification. 7609 // With ISA 3.0 7610 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7611 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7612 return Op; 7613 7614 // If the RHS of the comparison is a 0.0, we don't need to do the 7615 // subtraction at all. 7616 SDValue Sel1; 7617 if (isFloatingPointZero(RHS)) 7618 switch (CC) { 7619 default: break; // SETUO etc aren't handled by fsel. 7620 case ISD::SETNE: 7621 std::swap(TV, FV); 7622 LLVM_FALLTHROUGH; 7623 case ISD::SETEQ: 7624 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7625 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7626 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7627 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7628 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7629 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7630 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7631 case ISD::SETULT: 7632 case ISD::SETLT: 7633 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7634 LLVM_FALLTHROUGH; 7635 case ISD::SETOGE: 7636 case ISD::SETGE: 7637 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7638 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7639 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7640 case ISD::SETUGT: 7641 case ISD::SETGT: 7642 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7643 LLVM_FALLTHROUGH; 7644 case ISD::SETOLE: 7645 case ISD::SETLE: 7646 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7647 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7648 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7649 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7650 } 7651 7652 SDValue Cmp; 7653 switch (CC) { 7654 default: break; // SETUO etc aren't handled by fsel. 7655 case ISD::SETNE: 7656 std::swap(TV, FV); 7657 LLVM_FALLTHROUGH; 7658 case ISD::SETEQ: 7659 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7660 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7661 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7662 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7663 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7664 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7665 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7666 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7667 case ISD::SETULT: 7668 case ISD::SETLT: 7669 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7670 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7671 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7672 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7673 case ISD::SETOGE: 7674 case ISD::SETGE: 7675 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7676 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7677 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7678 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7679 case ISD::SETUGT: 7680 case ISD::SETGT: 7681 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7682 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7683 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7684 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7685 case ISD::SETOLE: 7686 case ISD::SETLE: 7687 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7688 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7689 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7690 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7691 } 7692 return Op; 7693 } 7694 7695 static unsigned getPPCStrictOpcode(unsigned Opc) { 7696 switch (Opc) { 7697 default: 7698 llvm_unreachable("No strict version of this opcode!"); 7699 case PPCISD::FCTIDZ: 7700 return PPCISD::STRICT_FCTIDZ; 7701 case PPCISD::FCTIWZ: 7702 return PPCISD::STRICT_FCTIWZ; 7703 case PPCISD::FCTIDUZ: 7704 return PPCISD::STRICT_FCTIDUZ; 7705 case PPCISD::FCTIWUZ: 7706 return PPCISD::STRICT_FCTIWUZ; 7707 case PPCISD::FCFID: 7708 return PPCISD::STRICT_FCFID; 7709 case PPCISD::FCFIDU: 7710 return PPCISD::STRICT_FCFIDU; 7711 case PPCISD::FCFIDS: 7712 return PPCISD::STRICT_FCFIDS; 7713 case PPCISD::FCFIDUS: 7714 return PPCISD::STRICT_FCFIDUS; 7715 } 7716 } 7717 7718 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7719 const PPCSubtarget &Subtarget) { 7720 SDLoc dl(Op); 7721 bool IsStrict = Op->isStrictFPOpcode(); 7722 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7723 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7724 7725 // TODO: Any other flags to propagate? 7726 SDNodeFlags Flags; 7727 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7728 7729 // For strict nodes, source is the second operand. 7730 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7731 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 7732 assert(Src.getValueType().isFloatingPoint()); 7733 if (Src.getValueType() == MVT::f32) { 7734 if (IsStrict) { 7735 Src = 7736 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 7737 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 7738 Chain = Src.getValue(1); 7739 } else 7740 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7741 } 7742 SDValue Conv; 7743 unsigned Opc = ISD::DELETED_NODE; 7744 switch (Op.getSimpleValueType().SimpleTy) { 7745 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7746 case MVT::i32: 7747 Opc = IsSigned ? PPCISD::FCTIWZ 7748 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 7749 break; 7750 case MVT::i64: 7751 assert((IsSigned || Subtarget.hasFPCVT()) && 7752 "i64 FP_TO_UINT is supported only with FPCVT"); 7753 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 7754 } 7755 if (IsStrict) { 7756 Opc = getPPCStrictOpcode(Opc); 7757 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 7758 {Chain, Src}, Flags); 7759 } else { 7760 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 7761 } 7762 return Conv; 7763 } 7764 7765 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7766 SelectionDAG &DAG, 7767 const SDLoc &dl) const { 7768 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 7769 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7770 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7771 bool IsStrict = Op->isStrictFPOpcode(); 7772 7773 // Convert the FP value to an int value through memory. 7774 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7775 (IsSigned || Subtarget.hasFPCVT()); 7776 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7777 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7778 MachinePointerInfo MPI = 7779 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7780 7781 // Emit a store to the stack slot. 7782 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 7783 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 7784 if (i32Stack) { 7785 MachineFunction &MF = DAG.getMachineFunction(); 7786 Alignment = Align(4); 7787 MachineMemOperand *MMO = 7788 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 7789 SDValue Ops[] = { Chain, Tmp, FIPtr }; 7790 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7791 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7792 } else 7793 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 7794 7795 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7796 // add in a bias on big endian. 7797 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7798 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7799 DAG.getConstant(4, dl, FIPtr.getValueType())); 7800 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7801 } 7802 7803 RLI.Chain = Chain; 7804 RLI.Ptr = FIPtr; 7805 RLI.MPI = MPI; 7806 RLI.Alignment = Alignment; 7807 } 7808 7809 /// Custom lowers floating point to integer conversions to use 7810 /// the direct move instructions available in ISA 2.07 to avoid the 7811 /// need for load/store combinations. 7812 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7813 SelectionDAG &DAG, 7814 const SDLoc &dl) const { 7815 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 7816 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 7817 if (Op->isStrictFPOpcode()) 7818 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 7819 else 7820 return Mov; 7821 } 7822 7823 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7824 const SDLoc &dl) const { 7825 bool IsStrict = Op->isStrictFPOpcode(); 7826 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7827 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7828 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7829 EVT SrcVT = Src.getValueType(); 7830 EVT DstVT = Op.getValueType(); 7831 7832 // FP to INT conversions are legal for f128. 7833 if (SrcVT == MVT::f128) 7834 return Subtarget.hasP9Vector() ? Op : SDValue(); 7835 7836 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7837 // PPC (the libcall is not available). 7838 if (SrcVT == MVT::ppcf128) { 7839 if (DstVT == MVT::i32) { 7840 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 7841 // set other fast-math flags to FP operations in both strict and 7842 // non-strict cases. (FP_TO_SINT, FSUB) 7843 SDNodeFlags Flags; 7844 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7845 7846 if (IsSigned) { 7847 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 7848 DAG.getIntPtrConstant(0, dl)); 7849 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 7850 DAG.getIntPtrConstant(1, dl)); 7851 7852 // Add the two halves of the long double in round-to-zero mode, and use 7853 // a smaller FP_TO_SINT. 7854 if (IsStrict) { 7855 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 7856 DAG.getVTList(MVT::f64, MVT::Other), 7857 {Op.getOperand(0), Lo, Hi}, Flags); 7858 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 7859 DAG.getVTList(MVT::i32, MVT::Other), 7860 {Res.getValue(1), Res}, Flags); 7861 } else { 7862 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7863 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7864 } 7865 } else { 7866 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7867 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7868 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7869 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 7870 if (IsStrict) { 7871 // Sel = Src < 0x80000000 7872 // FltOfs = select Sel, 0.0, 0x80000000 7873 // IntOfs = select Sel, 0, 0x80000000 7874 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7875 SDValue Chain = Op.getOperand(0); 7876 EVT SetCCVT = 7877 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7878 EVT DstSetCCVT = 7879 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7880 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7881 Chain, true); 7882 Chain = Sel.getValue(1); 7883 7884 SDValue FltOfs = DAG.getSelect( 7885 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7886 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7887 7888 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 7889 DAG.getVTList(SrcVT, MVT::Other), 7890 {Chain, Src, FltOfs}, Flags); 7891 Chain = Val.getValue(1); 7892 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 7893 DAG.getVTList(DstVT, MVT::Other), 7894 {Chain, Val}, Flags); 7895 Chain = SInt.getValue(1); 7896 SDValue IntOfs = DAG.getSelect( 7897 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 7898 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7899 return DAG.getMergeValues({Result, Chain}, dl); 7900 } else { 7901 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7902 // FIXME: generated code sucks. 7903 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 7904 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7905 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 7906 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 7907 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 7908 } 7909 } 7910 } 7911 7912 return SDValue(); 7913 } 7914 7915 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7916 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7917 7918 ReuseLoadInfo RLI; 7919 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7920 7921 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7922 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7923 } 7924 7925 // We're trying to insert a regular store, S, and then a load, L. If the 7926 // incoming value, O, is a load, we might just be able to have our load use the 7927 // address used by O. However, we don't know if anything else will store to 7928 // that address before we can load from it. To prevent this situation, we need 7929 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7930 // the same chain operand as O, we create a token factor from the chain results 7931 // of O and L, and we replace all uses of O's chain result with that token 7932 // factor (see spliceIntoChain below for this last part). 7933 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7934 ReuseLoadInfo &RLI, 7935 SelectionDAG &DAG, 7936 ISD::LoadExtType ET) const { 7937 // Conservatively skip reusing for constrained FP nodes. 7938 if (Op->isStrictFPOpcode()) 7939 return false; 7940 7941 SDLoc dl(Op); 7942 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 7943 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 7944 if (ET == ISD::NON_EXTLOAD && 7945 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 7946 isOperationLegalOrCustom(Op.getOpcode(), 7947 Op.getOperand(0).getValueType())) { 7948 7949 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7950 return true; 7951 } 7952 7953 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7954 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7955 LD->isNonTemporal()) 7956 return false; 7957 if (LD->getMemoryVT() != MemVT) 7958 return false; 7959 7960 // If the result of the load is an illegal type, then we can't build a 7961 // valid chain for reuse since the legalised loads and token factor node that 7962 // ties the legalised loads together uses a different output chain then the 7963 // illegal load. 7964 if (!isTypeLegal(LD->getValueType(0))) 7965 return false; 7966 7967 RLI.Ptr = LD->getBasePtr(); 7968 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7969 assert(LD->getAddressingMode() == ISD::PRE_INC && 7970 "Non-pre-inc AM on PPC?"); 7971 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7972 LD->getOffset()); 7973 } 7974 7975 RLI.Chain = LD->getChain(); 7976 RLI.MPI = LD->getPointerInfo(); 7977 RLI.IsDereferenceable = LD->isDereferenceable(); 7978 RLI.IsInvariant = LD->isInvariant(); 7979 RLI.Alignment = LD->getAlign(); 7980 RLI.AAInfo = LD->getAAInfo(); 7981 RLI.Ranges = LD->getRanges(); 7982 7983 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7984 return true; 7985 } 7986 7987 // Given the head of the old chain, ResChain, insert a token factor containing 7988 // it and NewResChain, and make users of ResChain now be users of that token 7989 // factor. 7990 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7991 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7992 SDValue NewResChain, 7993 SelectionDAG &DAG) const { 7994 if (!ResChain) 7995 return; 7996 7997 SDLoc dl(NewResChain); 7998 7999 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8000 NewResChain, DAG.getUNDEF(MVT::Other)); 8001 assert(TF.getNode() != NewResChain.getNode() && 8002 "A new TF really is required here"); 8003 8004 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8005 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8006 } 8007 8008 /// Analyze profitability of direct move 8009 /// prefer float load to int load plus direct move 8010 /// when there is no integer use of int load 8011 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8012 SDNode *Origin = Op.getOperand(0).getNode(); 8013 if (Origin->getOpcode() != ISD::LOAD) 8014 return true; 8015 8016 // If there is no LXSIBZX/LXSIHZX, like Power8, 8017 // prefer direct move if the memory size is 1 or 2 bytes. 8018 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8019 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8020 return true; 8021 8022 for (SDNode::use_iterator UI = Origin->use_begin(), 8023 UE = Origin->use_end(); 8024 UI != UE; ++UI) { 8025 8026 // Only look at the users of the loaded value. 8027 if (UI.getUse().get().getResNo() != 0) 8028 continue; 8029 8030 if (UI->getOpcode() != ISD::SINT_TO_FP && 8031 UI->getOpcode() != ISD::UINT_TO_FP && 8032 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8033 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8034 return true; 8035 } 8036 8037 return false; 8038 } 8039 8040 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8041 const PPCSubtarget &Subtarget, 8042 SDValue Chain = SDValue()) { 8043 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8044 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8045 SDLoc dl(Op); 8046 8047 // TODO: Any other flags to propagate? 8048 SDNodeFlags Flags; 8049 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8050 8051 // If we have FCFIDS, then use it when converting to single-precision. 8052 // Otherwise, convert to double-precision and then round. 8053 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8054 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8055 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8056 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8057 if (Op->isStrictFPOpcode()) { 8058 if (!Chain) 8059 Chain = Op.getOperand(0); 8060 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8061 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8062 } else 8063 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8064 } 8065 8066 /// Custom lowers integer to floating point conversions to use 8067 /// the direct move instructions available in ISA 2.07 to avoid the 8068 /// need for load/store combinations. 8069 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8070 SelectionDAG &DAG, 8071 const SDLoc &dl) const { 8072 assert((Op.getValueType() == MVT::f32 || 8073 Op.getValueType() == MVT::f64) && 8074 "Invalid floating point type as target of conversion"); 8075 assert(Subtarget.hasFPCVT() && 8076 "Int to FP conversions with direct moves require FPCVT"); 8077 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8078 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8079 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8080 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8081 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8082 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8083 return convertIntToFP(Op, Mov, DAG, Subtarget); 8084 } 8085 8086 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8087 8088 EVT VecVT = Vec.getValueType(); 8089 assert(VecVT.isVector() && "Expected a vector type."); 8090 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8091 8092 EVT EltVT = VecVT.getVectorElementType(); 8093 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8094 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8095 8096 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8097 SmallVector<SDValue, 16> Ops(NumConcat); 8098 Ops[0] = Vec; 8099 SDValue UndefVec = DAG.getUNDEF(VecVT); 8100 for (unsigned i = 1; i < NumConcat; ++i) 8101 Ops[i] = UndefVec; 8102 8103 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8104 } 8105 8106 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8107 const SDLoc &dl) const { 8108 bool IsStrict = Op->isStrictFPOpcode(); 8109 unsigned Opc = Op.getOpcode(); 8110 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8111 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8112 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8113 "Unexpected conversion type"); 8114 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8115 "Supports conversions to v2f64/v4f32 only."); 8116 8117 // TODO: Any other flags to propagate? 8118 SDNodeFlags Flags; 8119 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8120 8121 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8122 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8123 8124 SDValue Wide = widenVec(DAG, Src, dl); 8125 EVT WideVT = Wide.getValueType(); 8126 unsigned WideNumElts = WideVT.getVectorNumElements(); 8127 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8128 8129 SmallVector<int, 16> ShuffV; 8130 for (unsigned i = 0; i < WideNumElts; ++i) 8131 ShuffV.push_back(i + WideNumElts); 8132 8133 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8134 int SaveElts = FourEltRes ? 4 : 2; 8135 if (Subtarget.isLittleEndian()) 8136 for (int i = 0; i < SaveElts; i++) 8137 ShuffV[i * Stride] = i; 8138 else 8139 for (int i = 1; i <= SaveElts; i++) 8140 ShuffV[i * Stride - 1] = i - 1; 8141 8142 SDValue ShuffleSrc2 = 8143 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8144 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8145 8146 SDValue Extend; 8147 if (SignedConv) { 8148 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8149 EVT ExtVT = Src.getValueType(); 8150 if (Subtarget.hasP9Altivec()) 8151 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8152 IntermediateVT.getVectorNumElements()); 8153 8154 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8155 DAG.getValueType(ExtVT)); 8156 } else 8157 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8158 8159 if (IsStrict) 8160 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8161 {Op.getOperand(0), Extend}, Flags); 8162 8163 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8164 } 8165 8166 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8167 SelectionDAG &DAG) const { 8168 SDLoc dl(Op); 8169 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8170 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8171 bool IsStrict = Op->isStrictFPOpcode(); 8172 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8173 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8174 8175 // TODO: Any other flags to propagate? 8176 SDNodeFlags Flags; 8177 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8178 8179 EVT InVT = Src.getValueType(); 8180 EVT OutVT = Op.getValueType(); 8181 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8182 isOperationCustom(Op.getOpcode(), InVT)) 8183 return LowerINT_TO_FPVector(Op, DAG, dl); 8184 8185 // Conversions to f128 are legal. 8186 if (Op.getValueType() == MVT::f128) 8187 return Subtarget.hasP9Vector() ? Op : SDValue(); 8188 8189 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8190 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8191 return SDValue(); 8192 8193 if (Src.getValueType() == MVT::i1) { 8194 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8195 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8196 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8197 if (IsStrict) 8198 return DAG.getMergeValues({Sel, Chain}, dl); 8199 else 8200 return Sel; 8201 } 8202 8203 // If we have direct moves, we can do all the conversion, skip the store/load 8204 // however, without FPCVT we can't do most conversions. 8205 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8206 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8207 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8208 8209 assert((IsSigned || Subtarget.hasFPCVT()) && 8210 "UINT_TO_FP is supported only with FPCVT"); 8211 8212 if (Src.getValueType() == MVT::i64) { 8213 SDValue SINT = Src; 8214 // When converting to single-precision, we actually need to convert 8215 // to double-precision first and then round to single-precision. 8216 // To avoid double-rounding effects during that operation, we have 8217 // to prepare the input operand. Bits that might be truncated when 8218 // converting to double-precision are replaced by a bit that won't 8219 // be lost at this stage, but is below the single-precision rounding 8220 // position. 8221 // 8222 // However, if -enable-unsafe-fp-math is in effect, accept double 8223 // rounding to avoid the extra overhead. 8224 if (Op.getValueType() == MVT::f32 && 8225 !Subtarget.hasFPCVT() && 8226 !DAG.getTarget().Options.UnsafeFPMath) { 8227 8228 // Twiddle input to make sure the low 11 bits are zero. (If this 8229 // is the case, we are guaranteed the value will fit into the 53 bit 8230 // mantissa of an IEEE double-precision value without rounding.) 8231 // If any of those low 11 bits were not zero originally, make sure 8232 // bit 12 (value 2048) is set instead, so that the final rounding 8233 // to single-precision gets the correct result. 8234 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8235 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8236 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8237 Round, DAG.getConstant(2047, dl, MVT::i64)); 8238 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8239 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8240 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8241 8242 // However, we cannot use that value unconditionally: if the magnitude 8243 // of the input value is small, the bit-twiddling we did above might 8244 // end up visibly changing the output. Fortunately, in that case, we 8245 // don't need to twiddle bits since the original input will convert 8246 // exactly to double-precision floating-point already. Therefore, 8247 // construct a conditional to use the original value if the top 11 8248 // bits are all sign-bit copies, and use the rounded value computed 8249 // above otherwise. 8250 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8251 SINT, DAG.getConstant(53, dl, MVT::i32)); 8252 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8253 Cond, DAG.getConstant(1, dl, MVT::i64)); 8254 Cond = DAG.getSetCC( 8255 dl, 8256 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8257 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8258 8259 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8260 } 8261 8262 ReuseLoadInfo RLI; 8263 SDValue Bits; 8264 8265 MachineFunction &MF = DAG.getMachineFunction(); 8266 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8267 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8268 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8269 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8270 } else if (Subtarget.hasLFIWAX() && 8271 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8272 MachineMemOperand *MMO = 8273 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8274 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8275 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8276 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8277 DAG.getVTList(MVT::f64, MVT::Other), 8278 Ops, MVT::i32, MMO); 8279 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8280 } else if (Subtarget.hasFPCVT() && 8281 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8282 MachineMemOperand *MMO = 8283 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8284 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8285 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8286 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8287 DAG.getVTList(MVT::f64, MVT::Other), 8288 Ops, MVT::i32, MMO); 8289 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8290 } else if (((Subtarget.hasLFIWAX() && 8291 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8292 (Subtarget.hasFPCVT() && 8293 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8294 SINT.getOperand(0).getValueType() == MVT::i32) { 8295 MachineFrameInfo &MFI = MF.getFrameInfo(); 8296 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8297 8298 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8299 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8300 8301 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8302 MachinePointerInfo::getFixedStack( 8303 DAG.getMachineFunction(), FrameIdx)); 8304 Chain = Store; 8305 8306 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8307 "Expected an i32 store"); 8308 8309 RLI.Ptr = FIdx; 8310 RLI.Chain = Chain; 8311 RLI.MPI = 8312 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8313 RLI.Alignment = Align(4); 8314 8315 MachineMemOperand *MMO = 8316 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8317 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8318 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8319 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8320 PPCISD::LFIWZX : PPCISD::LFIWAX, 8321 dl, DAG.getVTList(MVT::f64, MVT::Other), 8322 Ops, MVT::i32, MMO); 8323 Chain = Bits.getValue(1); 8324 } else 8325 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8326 8327 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8328 if (IsStrict) 8329 Chain = FP.getValue(1); 8330 8331 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8332 if (IsStrict) 8333 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8334 DAG.getVTList(MVT::f32, MVT::Other), 8335 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8336 else 8337 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8338 DAG.getIntPtrConstant(0, dl)); 8339 } 8340 return FP; 8341 } 8342 8343 assert(Src.getValueType() == MVT::i32 && 8344 "Unhandled INT_TO_FP type in custom expander!"); 8345 // Since we only generate this in 64-bit mode, we can take advantage of 8346 // 64-bit registers. In particular, sign extend the input value into the 8347 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8348 // then lfd it and fcfid it. 8349 MachineFunction &MF = DAG.getMachineFunction(); 8350 MachineFrameInfo &MFI = MF.getFrameInfo(); 8351 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8352 8353 SDValue Ld; 8354 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8355 ReuseLoadInfo RLI; 8356 bool ReusingLoad; 8357 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8358 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8359 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8360 8361 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8362 MachinePointerInfo::getFixedStack( 8363 DAG.getMachineFunction(), FrameIdx)); 8364 Chain = Store; 8365 8366 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8367 "Expected an i32 store"); 8368 8369 RLI.Ptr = FIdx; 8370 RLI.Chain = Chain; 8371 RLI.MPI = 8372 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8373 RLI.Alignment = Align(4); 8374 } 8375 8376 MachineMemOperand *MMO = 8377 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8378 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8379 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8380 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8381 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8382 MVT::i32, MMO); 8383 Chain = Ld.getValue(1); 8384 if (ReusingLoad) 8385 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8386 } else { 8387 assert(Subtarget.isPPC64() && 8388 "i32->FP without LFIWAX supported only on PPC64"); 8389 8390 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8391 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8392 8393 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8394 8395 // STD the extended value into the stack slot. 8396 SDValue Store = DAG.getStore( 8397 Chain, dl, Ext64, FIdx, 8398 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8399 Chain = Store; 8400 8401 // Load the value as a double. 8402 Ld = DAG.getLoad( 8403 MVT::f64, dl, Chain, FIdx, 8404 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8405 Chain = Ld.getValue(1); 8406 } 8407 8408 // FCFID it and return it. 8409 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8410 if (IsStrict) 8411 Chain = FP.getValue(1); 8412 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8413 if (IsStrict) 8414 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8415 DAG.getVTList(MVT::f32, MVT::Other), 8416 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8417 else 8418 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8419 DAG.getIntPtrConstant(0, dl)); 8420 } 8421 return FP; 8422 } 8423 8424 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8425 SelectionDAG &DAG) const { 8426 SDLoc dl(Op); 8427 /* 8428 The rounding mode is in bits 30:31 of FPSR, and has the following 8429 settings: 8430 00 Round to nearest 8431 01 Round to 0 8432 10 Round to +inf 8433 11 Round to -inf 8434 8435 FLT_ROUNDS, on the other hand, expects the following: 8436 -1 Undefined 8437 0 Round to 0 8438 1 Round to nearest 8439 2 Round to +inf 8440 3 Round to -inf 8441 8442 To perform the conversion, we do: 8443 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8444 */ 8445 8446 MachineFunction &MF = DAG.getMachineFunction(); 8447 EVT VT = Op.getValueType(); 8448 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8449 8450 // Save FP Control Word to register 8451 SDValue Chain = Op.getOperand(0); 8452 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8453 Chain = MFFS.getValue(1); 8454 8455 SDValue CWD; 8456 if (isTypeLegal(MVT::i64)) { 8457 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8458 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8459 } else { 8460 // Save FP register to stack slot 8461 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8462 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8463 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8464 8465 // Load FP Control Word from low 32 bits of stack slot. 8466 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8467 "Stack slot adjustment is valid only on big endian subtargets!"); 8468 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8469 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8470 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8471 Chain = CWD.getValue(1); 8472 } 8473 8474 // Transform as necessary 8475 SDValue CWD1 = 8476 DAG.getNode(ISD::AND, dl, MVT::i32, 8477 CWD, DAG.getConstant(3, dl, MVT::i32)); 8478 SDValue CWD2 = 8479 DAG.getNode(ISD::SRL, dl, MVT::i32, 8480 DAG.getNode(ISD::AND, dl, MVT::i32, 8481 DAG.getNode(ISD::XOR, dl, MVT::i32, 8482 CWD, DAG.getConstant(3, dl, MVT::i32)), 8483 DAG.getConstant(3, dl, MVT::i32)), 8484 DAG.getConstant(1, dl, MVT::i32)); 8485 8486 SDValue RetVal = 8487 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8488 8489 RetVal = 8490 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8491 dl, VT, RetVal); 8492 8493 return DAG.getMergeValues({RetVal, Chain}, dl); 8494 } 8495 8496 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8497 EVT VT = Op.getValueType(); 8498 unsigned BitWidth = VT.getSizeInBits(); 8499 SDLoc dl(Op); 8500 assert(Op.getNumOperands() == 3 && 8501 VT == Op.getOperand(1).getValueType() && 8502 "Unexpected SHL!"); 8503 8504 // Expand into a bunch of logical ops. Note that these ops 8505 // depend on the PPC behavior for oversized shift amounts. 8506 SDValue Lo = Op.getOperand(0); 8507 SDValue Hi = Op.getOperand(1); 8508 SDValue Amt = Op.getOperand(2); 8509 EVT AmtVT = Amt.getValueType(); 8510 8511 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8512 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8513 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8514 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8515 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8516 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8517 DAG.getConstant(-BitWidth, dl, AmtVT)); 8518 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8519 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8520 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8521 SDValue OutOps[] = { OutLo, OutHi }; 8522 return DAG.getMergeValues(OutOps, dl); 8523 } 8524 8525 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8526 EVT VT = Op.getValueType(); 8527 SDLoc dl(Op); 8528 unsigned BitWidth = VT.getSizeInBits(); 8529 assert(Op.getNumOperands() == 3 && 8530 VT == Op.getOperand(1).getValueType() && 8531 "Unexpected SRL!"); 8532 8533 // Expand into a bunch of logical ops. Note that these ops 8534 // depend on the PPC behavior for oversized shift amounts. 8535 SDValue Lo = Op.getOperand(0); 8536 SDValue Hi = Op.getOperand(1); 8537 SDValue Amt = Op.getOperand(2); 8538 EVT AmtVT = Amt.getValueType(); 8539 8540 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8541 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8542 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8543 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8544 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8545 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8546 DAG.getConstant(-BitWidth, dl, AmtVT)); 8547 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8548 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8549 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8550 SDValue OutOps[] = { OutLo, OutHi }; 8551 return DAG.getMergeValues(OutOps, dl); 8552 } 8553 8554 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8555 SDLoc dl(Op); 8556 EVT VT = Op.getValueType(); 8557 unsigned BitWidth = VT.getSizeInBits(); 8558 assert(Op.getNumOperands() == 3 && 8559 VT == Op.getOperand(1).getValueType() && 8560 "Unexpected SRA!"); 8561 8562 // Expand into a bunch of logical ops, followed by a select_cc. 8563 SDValue Lo = Op.getOperand(0); 8564 SDValue Hi = Op.getOperand(1); 8565 SDValue Amt = Op.getOperand(2); 8566 EVT AmtVT = Amt.getValueType(); 8567 8568 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8569 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8570 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8571 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8572 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8573 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8574 DAG.getConstant(-BitWidth, dl, AmtVT)); 8575 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8576 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8577 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8578 Tmp4, Tmp6, ISD::SETLE); 8579 SDValue OutOps[] = { OutLo, OutHi }; 8580 return DAG.getMergeValues(OutOps, dl); 8581 } 8582 8583 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8584 SelectionDAG &DAG) const { 8585 SDLoc dl(Op); 8586 EVT VT = Op.getValueType(); 8587 unsigned BitWidth = VT.getSizeInBits(); 8588 8589 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8590 SDValue X = Op.getOperand(0); 8591 SDValue Y = Op.getOperand(1); 8592 SDValue Z = Op.getOperand(2); 8593 EVT AmtVT = Z.getValueType(); 8594 8595 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8596 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8597 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8598 // on PowerPC shift by BW being well defined. 8599 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8600 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8601 SDValue SubZ = 8602 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8603 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8604 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8605 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8606 } 8607 8608 //===----------------------------------------------------------------------===// 8609 // Vector related lowering. 8610 // 8611 8612 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8613 /// element size of SplatSize. Cast the result to VT. 8614 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8615 SelectionDAG &DAG, const SDLoc &dl) { 8616 static const MVT VTys[] = { // canonical VT to use for each size. 8617 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8618 }; 8619 8620 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8621 8622 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8623 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8624 SplatSize = 1; 8625 Val = 0xFF; 8626 } 8627 8628 EVT CanonicalVT = VTys[SplatSize-1]; 8629 8630 // Build a canonical splat for this value. 8631 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8632 } 8633 8634 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8635 /// specified intrinsic ID. 8636 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8637 const SDLoc &dl, EVT DestVT = MVT::Other) { 8638 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8639 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8640 DAG.getConstant(IID, dl, MVT::i32), Op); 8641 } 8642 8643 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8644 /// specified intrinsic ID. 8645 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8646 SelectionDAG &DAG, const SDLoc &dl, 8647 EVT DestVT = MVT::Other) { 8648 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8649 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8650 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8651 } 8652 8653 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8654 /// specified intrinsic ID. 8655 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8656 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8657 EVT DestVT = MVT::Other) { 8658 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8659 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8660 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8661 } 8662 8663 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8664 /// amount. The result has the specified value type. 8665 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8666 SelectionDAG &DAG, const SDLoc &dl) { 8667 // Force LHS/RHS to be the right type. 8668 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8669 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8670 8671 int Ops[16]; 8672 for (unsigned i = 0; i != 16; ++i) 8673 Ops[i] = i + Amt; 8674 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8675 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8676 } 8677 8678 /// Do we have an efficient pattern in a .td file for this node? 8679 /// 8680 /// \param V - pointer to the BuildVectorSDNode being matched 8681 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8682 /// 8683 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8684 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8685 /// the opposite is true (expansion is beneficial) are: 8686 /// - The node builds a vector out of integers that are not 32 or 64-bits 8687 /// - The node builds a vector out of constants 8688 /// - The node is a "load-and-splat" 8689 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8690 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8691 bool HasDirectMove, 8692 bool HasP8Vector) { 8693 EVT VecVT = V->getValueType(0); 8694 bool RightType = VecVT == MVT::v2f64 || 8695 (HasP8Vector && VecVT == MVT::v4f32) || 8696 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8697 if (!RightType) 8698 return false; 8699 8700 bool IsSplat = true; 8701 bool IsLoad = false; 8702 SDValue Op0 = V->getOperand(0); 8703 8704 // This function is called in a block that confirms the node is not a constant 8705 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8706 // different constants. 8707 if (V->isConstant()) 8708 return false; 8709 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8710 if (V->getOperand(i).isUndef()) 8711 return false; 8712 // We want to expand nodes that represent load-and-splat even if the 8713 // loaded value is a floating point truncation or conversion to int. 8714 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8715 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8716 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8717 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8718 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8719 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8720 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8721 IsLoad = true; 8722 // If the operands are different or the input is not a load and has more 8723 // uses than just this BV node, then it isn't a splat. 8724 if (V->getOperand(i) != Op0 || 8725 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8726 IsSplat = false; 8727 } 8728 return !(IsSplat && IsLoad); 8729 } 8730 8731 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8732 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8733 8734 SDLoc dl(Op); 8735 SDValue Op0 = Op->getOperand(0); 8736 8737 if ((Op.getValueType() != MVT::f128) || 8738 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8739 (Op0.getOperand(0).getValueType() != MVT::i64) || 8740 (Op0.getOperand(1).getValueType() != MVT::i64)) 8741 return SDValue(); 8742 8743 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8744 Op0.getOperand(1)); 8745 } 8746 8747 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8748 const SDValue *InputLoad = &Op; 8749 if (InputLoad->getOpcode() == ISD::BITCAST) 8750 InputLoad = &InputLoad->getOperand(0); 8751 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8752 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8753 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8754 InputLoad = &InputLoad->getOperand(0); 8755 } 8756 if (InputLoad->getOpcode() != ISD::LOAD) 8757 return nullptr; 8758 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8759 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8760 } 8761 8762 // Convert the argument APFloat to a single precision APFloat if there is no 8763 // loss in information during the conversion to single precision APFloat and the 8764 // resulting number is not a denormal number. Return true if successful. 8765 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8766 APFloat APFloatToConvert = ArgAPFloat; 8767 bool LosesInfo = true; 8768 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8769 &LosesInfo); 8770 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8771 if (Success) 8772 ArgAPFloat = APFloatToConvert; 8773 return Success; 8774 } 8775 8776 // Bitcast the argument APInt to a double and convert it to a single precision 8777 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8778 // argument if there is no loss in information during the conversion from 8779 // double to single precision APFloat and the resulting number is not a denormal 8780 // number. Return true if successful. 8781 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8782 double DpValue = ArgAPInt.bitsToDouble(); 8783 APFloat APFloatDp(DpValue); 8784 bool Success = convertToNonDenormSingle(APFloatDp); 8785 if (Success) 8786 ArgAPInt = APFloatDp.bitcastToAPInt(); 8787 return Success; 8788 } 8789 8790 // If this is a case we can't handle, return null and let the default 8791 // expansion code take care of it. If we CAN select this case, and if it 8792 // selects to a single instruction, return Op. Otherwise, if we can codegen 8793 // this case more efficiently than a constant pool load, lower it to the 8794 // sequence of ops that should be used. 8795 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8796 SelectionDAG &DAG) const { 8797 SDLoc dl(Op); 8798 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8799 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8800 8801 // Check if this is a splat of a constant value. 8802 APInt APSplatBits, APSplatUndef; 8803 unsigned SplatBitSize; 8804 bool HasAnyUndefs; 8805 bool BVNIsConstantSplat = 8806 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8807 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 8808 8809 // If it is a splat of a double, check if we can shrink it to a 32 bit 8810 // non-denormal float which when converted back to double gives us the same 8811 // double. This is to exploit the XXSPLTIDP instruction. 8812 // If we lose precision, we use XXSPLTI32DX. 8813 if (BVNIsConstantSplat && (SplatBitSize == 64) && 8814 Subtarget.hasPrefixInstrs()) { 8815 // Check the type first to short-circuit so we don't modify APSplatBits if 8816 // this block isn't executed. 8817 if ((Op->getValueType(0) == MVT::v2f64) && 8818 convertToNonDenormSingle(APSplatBits)) { 8819 SDValue SplatNode = DAG.getNode( 8820 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 8821 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 8822 return DAG.getBitcast(Op.getValueType(), SplatNode); 8823 } else { 8824 // We may lose precision, so we have to use XXSPLTI32DX. 8825 8826 uint32_t Hi = 8827 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 8828 uint32_t Lo = 8829 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 8830 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 8831 8832 if (!Hi || !Lo) 8833 // If either load is 0, then we should generate XXLXOR to set to 0. 8834 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 8835 8836 if (Hi) 8837 SplatNode = DAG.getNode( 8838 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 8839 DAG.getTargetConstant(0, dl, MVT::i32), 8840 DAG.getTargetConstant(Hi, dl, MVT::i32)); 8841 8842 if (Lo) 8843 SplatNode = 8844 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 8845 DAG.getTargetConstant(1, dl, MVT::i32), 8846 DAG.getTargetConstant(Lo, dl, MVT::i32)); 8847 8848 return DAG.getBitcast(Op.getValueType(), SplatNode); 8849 } 8850 } 8851 8852 if (!BVNIsConstantSplat || SplatBitSize > 32) { 8853 8854 bool IsPermutedLoad = false; 8855 const SDValue *InputLoad = 8856 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 8857 // Handle load-and-splat patterns as we have instructions that will do this 8858 // in one go. 8859 if (InputLoad && DAG.isSplatValue(Op, true)) { 8860 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8861 8862 // We have handling for 4 and 8 byte elements. 8863 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8864 8865 // Checking for a single use of this load, we have to check for vector 8866 // width (128 bits) / ElementSize uses (since each operand of the 8867 // BUILD_VECTOR is a separate use of the value. 8868 unsigned NumUsesOfInputLD = 128 / ElementSize; 8869 for (SDValue BVInOp : Op->ops()) 8870 if (BVInOp.isUndef()) 8871 NumUsesOfInputLD--; 8872 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 8873 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 8874 ((Subtarget.hasVSX() && ElementSize == 64) || 8875 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8876 SDValue Ops[] = { 8877 LD->getChain(), // Chain 8878 LD->getBasePtr(), // Ptr 8879 DAG.getValueType(Op.getValueType()) // VT 8880 }; 8881 SDValue LdSplt = DAG.getMemIntrinsicNode( 8882 PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8883 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8884 // Replace all uses of the output chain of the original load with the 8885 // output chain of the new load. 8886 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 8887 LdSplt.getValue(1)); 8888 return LdSplt; 8889 } 8890 } 8891 8892 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 8893 // 32-bits can be lowered to VSX instructions under certain conditions. 8894 // Without VSX, there is no pattern more efficient than expanding the node. 8895 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 8896 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8897 Subtarget.hasP8Vector())) 8898 return Op; 8899 return SDValue(); 8900 } 8901 8902 uint64_t SplatBits = APSplatBits.getZExtValue(); 8903 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 8904 unsigned SplatSize = SplatBitSize / 8; 8905 8906 // First, handle single instruction cases. 8907 8908 // All zeros? 8909 if (SplatBits == 0) { 8910 // Canonicalize all zero vectors to be v4i32. 8911 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8912 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8913 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8914 } 8915 return Op; 8916 } 8917 8918 // We have XXSPLTIW for constant splats four bytes wide. 8919 // Given vector length is a multiple of 4, 2-byte splats can be replaced 8920 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 8921 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 8922 // turned into a 4-byte splat of 0xABABABAB. 8923 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 8924 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 8925 Op.getValueType(), DAG, dl); 8926 8927 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 8928 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8929 dl); 8930 8931 // We have XXSPLTIB for constant splats one byte wide. 8932 if (Subtarget.hasP9Vector() && SplatSize == 1) 8933 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8934 dl); 8935 8936 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8937 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8938 (32-SplatBitSize)); 8939 if (SextVal >= -16 && SextVal <= 15) 8940 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 8941 dl); 8942 8943 // Two instruction sequences. 8944 8945 // If this value is in the range [-32,30] and is even, use: 8946 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8947 // If this value is in the range [17,31] and is odd, use: 8948 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8949 // If this value is in the range [-31,-17] and is odd, use: 8950 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8951 // Note the last two are three-instruction sequences. 8952 if (SextVal >= -32 && SextVal <= 31) { 8953 // To avoid having these optimizations undone by constant folding, 8954 // we convert to a pseudo that will be expanded later into one of 8955 // the above forms. 8956 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8957 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8958 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8959 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8960 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8961 if (VT == Op.getValueType()) 8962 return RetVal; 8963 else 8964 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8965 } 8966 8967 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8968 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8969 // for fneg/fabs. 8970 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8971 // Make -1 and vspltisw -1: 8972 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 8973 8974 // Make the VSLW intrinsic, computing 0x8000_0000. 8975 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8976 OnesV, DAG, dl); 8977 8978 // xor by OnesV to invert it. 8979 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8980 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8981 } 8982 8983 // Check to see if this is a wide variety of vsplti*, binop self cases. 8984 static const signed char SplatCsts[] = { 8985 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8986 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8987 }; 8988 8989 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8990 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8991 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8992 int i = SplatCsts[idx]; 8993 8994 // Figure out what shift amount will be used by altivec if shifted by i in 8995 // this splat size. 8996 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8997 8998 // vsplti + shl self. 8999 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9000 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9001 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9002 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9003 Intrinsic::ppc_altivec_vslw 9004 }; 9005 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9006 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9007 } 9008 9009 // vsplti + srl self. 9010 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9011 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9012 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9013 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9014 Intrinsic::ppc_altivec_vsrw 9015 }; 9016 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9017 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9018 } 9019 9020 // vsplti + rol self. 9021 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9022 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9023 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9024 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9025 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9026 Intrinsic::ppc_altivec_vrlw 9027 }; 9028 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9029 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9030 } 9031 9032 // t = vsplti c, result = vsldoi t, t, 1 9033 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9034 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9035 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9036 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9037 } 9038 // t = vsplti c, result = vsldoi t, t, 2 9039 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9040 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9041 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9042 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9043 } 9044 // t = vsplti c, result = vsldoi t, t, 3 9045 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9046 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9047 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9048 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9049 } 9050 } 9051 9052 return SDValue(); 9053 } 9054 9055 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9056 /// the specified operations to build the shuffle. 9057 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9058 SDValue RHS, SelectionDAG &DAG, 9059 const SDLoc &dl) { 9060 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9061 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9062 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9063 9064 enum { 9065 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9066 OP_VMRGHW, 9067 OP_VMRGLW, 9068 OP_VSPLTISW0, 9069 OP_VSPLTISW1, 9070 OP_VSPLTISW2, 9071 OP_VSPLTISW3, 9072 OP_VSLDOI4, 9073 OP_VSLDOI8, 9074 OP_VSLDOI12 9075 }; 9076 9077 if (OpNum == OP_COPY) { 9078 if (LHSID == (1*9+2)*9+3) return LHS; 9079 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9080 return RHS; 9081 } 9082 9083 SDValue OpLHS, OpRHS; 9084 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9085 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9086 9087 int ShufIdxs[16]; 9088 switch (OpNum) { 9089 default: llvm_unreachable("Unknown i32 permute!"); 9090 case OP_VMRGHW: 9091 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9092 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9093 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9094 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9095 break; 9096 case OP_VMRGLW: 9097 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9098 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9099 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9100 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9101 break; 9102 case OP_VSPLTISW0: 9103 for (unsigned i = 0; i != 16; ++i) 9104 ShufIdxs[i] = (i&3)+0; 9105 break; 9106 case OP_VSPLTISW1: 9107 for (unsigned i = 0; i != 16; ++i) 9108 ShufIdxs[i] = (i&3)+4; 9109 break; 9110 case OP_VSPLTISW2: 9111 for (unsigned i = 0; i != 16; ++i) 9112 ShufIdxs[i] = (i&3)+8; 9113 break; 9114 case OP_VSPLTISW3: 9115 for (unsigned i = 0; i != 16; ++i) 9116 ShufIdxs[i] = (i&3)+12; 9117 break; 9118 case OP_VSLDOI4: 9119 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9120 case OP_VSLDOI8: 9121 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9122 case OP_VSLDOI12: 9123 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9124 } 9125 EVT VT = OpLHS.getValueType(); 9126 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9127 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9128 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9129 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9130 } 9131 9132 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9133 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9134 /// SDValue. 9135 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9136 SelectionDAG &DAG) const { 9137 const unsigned BytesInVector = 16; 9138 bool IsLE = Subtarget.isLittleEndian(); 9139 SDLoc dl(N); 9140 SDValue V1 = N->getOperand(0); 9141 SDValue V2 = N->getOperand(1); 9142 unsigned ShiftElts = 0, InsertAtByte = 0; 9143 bool Swap = false; 9144 9145 // Shifts required to get the byte we want at element 7. 9146 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9147 0, 15, 14, 13, 12, 11, 10, 9}; 9148 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9149 1, 2, 3, 4, 5, 6, 7, 8}; 9150 9151 ArrayRef<int> Mask = N->getMask(); 9152 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9153 9154 // For each mask element, find out if we're just inserting something 9155 // from V2 into V1 or vice versa. 9156 // Possible permutations inserting an element from V2 into V1: 9157 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9158 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9159 // ... 9160 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9161 // Inserting from V1 into V2 will be similar, except mask range will be 9162 // [16,31]. 9163 9164 bool FoundCandidate = false; 9165 // If both vector operands for the shuffle are the same vector, the mask 9166 // will contain only elements from the first one and the second one will be 9167 // undef. 9168 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9169 // Go through the mask of half-words to find an element that's being moved 9170 // from one vector to the other. 9171 for (unsigned i = 0; i < BytesInVector; ++i) { 9172 unsigned CurrentElement = Mask[i]; 9173 // If 2nd operand is undefined, we should only look for element 7 in the 9174 // Mask. 9175 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9176 continue; 9177 9178 bool OtherElementsInOrder = true; 9179 // Examine the other elements in the Mask to see if they're in original 9180 // order. 9181 for (unsigned j = 0; j < BytesInVector; ++j) { 9182 if (j == i) 9183 continue; 9184 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9185 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9186 // in which we always assume we're always picking from the 1st operand. 9187 int MaskOffset = 9188 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9189 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9190 OtherElementsInOrder = false; 9191 break; 9192 } 9193 } 9194 // If other elements are in original order, we record the number of shifts 9195 // we need to get the element we want into element 7. Also record which byte 9196 // in the vector we should insert into. 9197 if (OtherElementsInOrder) { 9198 // If 2nd operand is undefined, we assume no shifts and no swapping. 9199 if (V2.isUndef()) { 9200 ShiftElts = 0; 9201 Swap = false; 9202 } else { 9203 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9204 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9205 : BigEndianShifts[CurrentElement & 0xF]; 9206 Swap = CurrentElement < BytesInVector; 9207 } 9208 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9209 FoundCandidate = true; 9210 break; 9211 } 9212 } 9213 9214 if (!FoundCandidate) 9215 return SDValue(); 9216 9217 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9218 // optionally with VECSHL if shift is required. 9219 if (Swap) 9220 std::swap(V1, V2); 9221 if (V2.isUndef()) 9222 V2 = V1; 9223 if (ShiftElts) { 9224 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9225 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9226 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9227 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9228 } 9229 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9230 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9231 } 9232 9233 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9234 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9235 /// SDValue. 9236 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9237 SelectionDAG &DAG) const { 9238 const unsigned NumHalfWords = 8; 9239 const unsigned BytesInVector = NumHalfWords * 2; 9240 // Check that the shuffle is on half-words. 9241 if (!isNByteElemShuffleMask(N, 2, 1)) 9242 return SDValue(); 9243 9244 bool IsLE = Subtarget.isLittleEndian(); 9245 SDLoc dl(N); 9246 SDValue V1 = N->getOperand(0); 9247 SDValue V2 = N->getOperand(1); 9248 unsigned ShiftElts = 0, InsertAtByte = 0; 9249 bool Swap = false; 9250 9251 // Shifts required to get the half-word we want at element 3. 9252 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9253 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9254 9255 uint32_t Mask = 0; 9256 uint32_t OriginalOrderLow = 0x1234567; 9257 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9258 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9259 // 32-bit space, only need 4-bit nibbles per element. 9260 for (unsigned i = 0; i < NumHalfWords; ++i) { 9261 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9262 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9263 } 9264 9265 // For each mask element, find out if we're just inserting something 9266 // from V2 into V1 or vice versa. Possible permutations inserting an element 9267 // from V2 into V1: 9268 // X, 1, 2, 3, 4, 5, 6, 7 9269 // 0, X, 2, 3, 4, 5, 6, 7 9270 // 0, 1, X, 3, 4, 5, 6, 7 9271 // 0, 1, 2, X, 4, 5, 6, 7 9272 // 0, 1, 2, 3, X, 5, 6, 7 9273 // 0, 1, 2, 3, 4, X, 6, 7 9274 // 0, 1, 2, 3, 4, 5, X, 7 9275 // 0, 1, 2, 3, 4, 5, 6, X 9276 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9277 9278 bool FoundCandidate = false; 9279 // Go through the mask of half-words to find an element that's being moved 9280 // from one vector to the other. 9281 for (unsigned i = 0; i < NumHalfWords; ++i) { 9282 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9283 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9284 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9285 uint32_t TargetOrder = 0x0; 9286 9287 // If both vector operands for the shuffle are the same vector, the mask 9288 // will contain only elements from the first one and the second one will be 9289 // undef. 9290 if (V2.isUndef()) { 9291 ShiftElts = 0; 9292 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9293 TargetOrder = OriginalOrderLow; 9294 Swap = false; 9295 // Skip if not the correct element or mask of other elements don't equal 9296 // to our expected order. 9297 if (MaskOneElt == VINSERTHSrcElem && 9298 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9299 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9300 FoundCandidate = true; 9301 break; 9302 } 9303 } else { // If both operands are defined. 9304 // Target order is [8,15] if the current mask is between [0,7]. 9305 TargetOrder = 9306 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9307 // Skip if mask of other elements don't equal our expected order. 9308 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9309 // We only need the last 3 bits for the number of shifts. 9310 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9311 : BigEndianShifts[MaskOneElt & 0x7]; 9312 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9313 Swap = MaskOneElt < NumHalfWords; 9314 FoundCandidate = true; 9315 break; 9316 } 9317 } 9318 } 9319 9320 if (!FoundCandidate) 9321 return SDValue(); 9322 9323 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9324 // optionally with VECSHL if shift is required. 9325 if (Swap) 9326 std::swap(V1, V2); 9327 if (V2.isUndef()) 9328 V2 = V1; 9329 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9330 if (ShiftElts) { 9331 // Double ShiftElts because we're left shifting on v16i8 type. 9332 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9333 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9334 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9335 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9336 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9337 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9338 } 9339 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9340 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9341 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9342 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9343 } 9344 9345 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9346 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9347 /// return the default SDValue. 9348 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9349 SelectionDAG &DAG) const { 9350 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9351 // to v16i8. Peek through the bitcasts to get the actual operands. 9352 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9353 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9354 9355 auto ShuffleMask = SVN->getMask(); 9356 SDValue VecShuffle(SVN, 0); 9357 SDLoc DL(SVN); 9358 9359 // Check that we have a four byte shuffle. 9360 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9361 return SDValue(); 9362 9363 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9364 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9365 std::swap(LHS, RHS); 9366 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9367 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9368 } 9369 9370 // Ensure that the RHS is a vector of constants. 9371 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9372 if (!BVN) 9373 return SDValue(); 9374 9375 // Check if RHS is a splat of 4-bytes (or smaller). 9376 APInt APSplatValue, APSplatUndef; 9377 unsigned SplatBitSize; 9378 bool HasAnyUndefs; 9379 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9380 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9381 SplatBitSize > 32) 9382 return SDValue(); 9383 9384 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9385 // The instruction splats a constant C into two words of the source vector 9386 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9387 // Thus we check that the shuffle mask is the equivalent of 9388 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9389 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9390 // within each word are consecutive, so we only need to check the first byte. 9391 SDValue Index; 9392 bool IsLE = Subtarget.isLittleEndian(); 9393 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9394 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9395 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9396 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9397 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9398 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9399 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9400 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9401 else 9402 return SDValue(); 9403 9404 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9405 // for XXSPLTI32DX. 9406 unsigned SplatVal = APSplatValue.getZExtValue(); 9407 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9408 SplatVal |= (SplatVal << SplatBitSize); 9409 9410 SDValue SplatNode = DAG.getNode( 9411 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9412 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9413 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9414 } 9415 9416 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9417 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9418 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9419 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9420 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9421 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9422 assert(Op.getValueType() == MVT::v1i128 && 9423 "Only set v1i128 as custom, other type shouldn't reach here!"); 9424 SDLoc dl(Op); 9425 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9426 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9427 unsigned SHLAmt = N1.getConstantOperandVal(0); 9428 if (SHLAmt % 8 == 0) { 9429 SmallVector<int, 16> Mask(16, 0); 9430 std::iota(Mask.begin(), Mask.end(), 0); 9431 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9432 if (SDValue Shuffle = 9433 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9434 DAG.getUNDEF(MVT::v16i8), Mask)) 9435 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9436 } 9437 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9438 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9439 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9440 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9441 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9442 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9443 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9444 } 9445 9446 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9447 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9448 /// return the code it can be lowered into. Worst case, it can always be 9449 /// lowered into a vperm. 9450 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9451 SelectionDAG &DAG) const { 9452 SDLoc dl(Op); 9453 SDValue V1 = Op.getOperand(0); 9454 SDValue V2 = Op.getOperand(1); 9455 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9456 9457 // Any nodes that were combined in the target-independent combiner prior 9458 // to vector legalization will not be sent to the target combine. Try to 9459 // combine it here. 9460 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9461 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9462 return NewShuffle; 9463 Op = NewShuffle; 9464 SVOp = cast<ShuffleVectorSDNode>(Op); 9465 V1 = Op.getOperand(0); 9466 V2 = Op.getOperand(1); 9467 } 9468 EVT VT = Op.getValueType(); 9469 bool isLittleEndian = Subtarget.isLittleEndian(); 9470 9471 unsigned ShiftElts, InsertAtByte; 9472 bool Swap = false; 9473 9474 // If this is a load-and-splat, we can do that with a single instruction 9475 // in some cases. However if the load has multiple uses, we don't want to 9476 // combine it because that will just produce multiple loads. 9477 bool IsPermutedLoad = false; 9478 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9479 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9480 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9481 InputLoad->hasOneUse()) { 9482 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9483 int SplatIdx = 9484 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9485 9486 // The splat index for permuted loads will be in the left half of the vector 9487 // which is strictly wider than the loaded value by 8 bytes. So we need to 9488 // adjust the splat index to point to the correct address in memory. 9489 if (IsPermutedLoad) { 9490 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9491 SplatIdx += IsFourByte ? 2 : 1; 9492 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9493 "Splat of a value outside of the loaded memory"); 9494 } 9495 9496 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9497 // For 4-byte load-and-splat, we need Power9. 9498 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9499 uint64_t Offset = 0; 9500 if (IsFourByte) 9501 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9502 else 9503 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9504 9505 SDValue BasePtr = LD->getBasePtr(); 9506 if (Offset != 0) 9507 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9508 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9509 SDValue Ops[] = { 9510 LD->getChain(), // Chain 9511 BasePtr, // BasePtr 9512 DAG.getValueType(Op.getValueType()) // VT 9513 }; 9514 SDVTList VTL = 9515 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9516 SDValue LdSplt = 9517 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9518 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9519 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9520 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9521 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9522 return LdSplt; 9523 } 9524 } 9525 if (Subtarget.hasP9Vector() && 9526 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9527 isLittleEndian)) { 9528 if (Swap) 9529 std::swap(V1, V2); 9530 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9531 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9532 if (ShiftElts) { 9533 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9534 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9535 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9536 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9537 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9538 } 9539 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9540 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9541 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9542 } 9543 9544 if (Subtarget.hasPrefixInstrs()) { 9545 SDValue SplatInsertNode; 9546 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9547 return SplatInsertNode; 9548 } 9549 9550 if (Subtarget.hasP9Altivec()) { 9551 SDValue NewISDNode; 9552 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9553 return NewISDNode; 9554 9555 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9556 return NewISDNode; 9557 } 9558 9559 if (Subtarget.hasVSX() && 9560 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9561 if (Swap) 9562 std::swap(V1, V2); 9563 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9564 SDValue Conv2 = 9565 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9566 9567 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9568 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9569 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9570 } 9571 9572 if (Subtarget.hasVSX() && 9573 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9574 if (Swap) 9575 std::swap(V1, V2); 9576 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9577 SDValue Conv2 = 9578 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9579 9580 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9581 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9582 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9583 } 9584 9585 if (Subtarget.hasP9Vector()) { 9586 if (PPC::isXXBRHShuffleMask(SVOp)) { 9587 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9588 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9589 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9590 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9591 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9592 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9593 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9594 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9595 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9596 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9597 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9598 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9599 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9600 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9601 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9602 } 9603 } 9604 9605 if (Subtarget.hasVSX()) { 9606 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9607 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9608 9609 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9610 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9611 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9612 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9613 } 9614 9615 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9616 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9617 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9618 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9619 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9620 } 9621 } 9622 9623 // Cases that are handled by instructions that take permute immediates 9624 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9625 // selected by the instruction selector. 9626 if (V2.isUndef()) { 9627 if (PPC::isSplatShuffleMask(SVOp, 1) || 9628 PPC::isSplatShuffleMask(SVOp, 2) || 9629 PPC::isSplatShuffleMask(SVOp, 4) || 9630 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9631 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9632 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9633 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9634 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9635 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9636 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9637 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9638 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9639 (Subtarget.hasP8Altivec() && ( 9640 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9641 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9642 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9643 return Op; 9644 } 9645 } 9646 9647 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9648 // and produce a fixed permutation. If any of these match, do not lower to 9649 // VPERM. 9650 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9651 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9652 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9653 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9654 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9655 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9656 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9657 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9658 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9659 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9660 (Subtarget.hasP8Altivec() && ( 9661 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9662 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9663 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9664 return Op; 9665 9666 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9667 // perfect shuffle table to emit an optimal matching sequence. 9668 ArrayRef<int> PermMask = SVOp->getMask(); 9669 9670 unsigned PFIndexes[4]; 9671 bool isFourElementShuffle = true; 9672 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9673 unsigned EltNo = 8; // Start out undef. 9674 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9675 if (PermMask[i*4+j] < 0) 9676 continue; // Undef, ignore it. 9677 9678 unsigned ByteSource = PermMask[i*4+j]; 9679 if ((ByteSource & 3) != j) { 9680 isFourElementShuffle = false; 9681 break; 9682 } 9683 9684 if (EltNo == 8) { 9685 EltNo = ByteSource/4; 9686 } else if (EltNo != ByteSource/4) { 9687 isFourElementShuffle = false; 9688 break; 9689 } 9690 } 9691 PFIndexes[i] = EltNo; 9692 } 9693 9694 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9695 // perfect shuffle vector to determine if it is cost effective to do this as 9696 // discrete instructions, or whether we should use a vperm. 9697 // For now, we skip this for little endian until such time as we have a 9698 // little-endian perfect shuffle table. 9699 if (isFourElementShuffle && !isLittleEndian) { 9700 // Compute the index in the perfect shuffle table. 9701 unsigned PFTableIndex = 9702 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9703 9704 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9705 unsigned Cost = (PFEntry >> 30); 9706 9707 // Determining when to avoid vperm is tricky. Many things affect the cost 9708 // of vperm, particularly how many times the perm mask needs to be computed. 9709 // For example, if the perm mask can be hoisted out of a loop or is already 9710 // used (perhaps because there are multiple permutes with the same shuffle 9711 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9712 // the loop requires an extra register. 9713 // 9714 // As a compromise, we only emit discrete instructions if the shuffle can be 9715 // generated in 3 or fewer operations. When we have loop information 9716 // available, if this block is within a loop, we should avoid using vperm 9717 // for 3-operation perms and use a constant pool load instead. 9718 if (Cost < 3) 9719 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9720 } 9721 9722 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9723 // vector that will get spilled to the constant pool. 9724 if (V2.isUndef()) V2 = V1; 9725 9726 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9727 // that it is in input element units, not in bytes. Convert now. 9728 9729 // For little endian, the order of the input vectors is reversed, and 9730 // the permutation mask is complemented with respect to 31. This is 9731 // necessary to produce proper semantics with the big-endian-biased vperm 9732 // instruction. 9733 EVT EltVT = V1.getValueType().getVectorElementType(); 9734 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9735 9736 SmallVector<SDValue, 16> ResultMask; 9737 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9738 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9739 9740 for (unsigned j = 0; j != BytesPerElement; ++j) 9741 if (isLittleEndian) 9742 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9743 dl, MVT::i32)); 9744 else 9745 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9746 MVT::i32)); 9747 } 9748 9749 ShufflesHandledWithVPERM++; 9750 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9751 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9752 LLVM_DEBUG(SVOp->dump()); 9753 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9754 LLVM_DEBUG(VPermMask.dump()); 9755 9756 if (isLittleEndian) 9757 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9758 V2, V1, VPermMask); 9759 else 9760 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9761 V1, V2, VPermMask); 9762 } 9763 9764 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9765 /// vector comparison. If it is, return true and fill in Opc/isDot with 9766 /// information about the intrinsic. 9767 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9768 bool &isDot, const PPCSubtarget &Subtarget) { 9769 unsigned IntrinsicID = 9770 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9771 CompareOpc = -1; 9772 isDot = false; 9773 switch (IntrinsicID) { 9774 default: 9775 return false; 9776 // Comparison predicates. 9777 case Intrinsic::ppc_altivec_vcmpbfp_p: 9778 CompareOpc = 966; 9779 isDot = true; 9780 break; 9781 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9782 CompareOpc = 198; 9783 isDot = true; 9784 break; 9785 case Intrinsic::ppc_altivec_vcmpequb_p: 9786 CompareOpc = 6; 9787 isDot = true; 9788 break; 9789 case Intrinsic::ppc_altivec_vcmpequh_p: 9790 CompareOpc = 70; 9791 isDot = true; 9792 break; 9793 case Intrinsic::ppc_altivec_vcmpequw_p: 9794 CompareOpc = 134; 9795 isDot = true; 9796 break; 9797 case Intrinsic::ppc_altivec_vcmpequd_p: 9798 if (Subtarget.hasP8Altivec()) { 9799 CompareOpc = 199; 9800 isDot = true; 9801 } else 9802 return false; 9803 break; 9804 case Intrinsic::ppc_altivec_vcmpneb_p: 9805 case Intrinsic::ppc_altivec_vcmpneh_p: 9806 case Intrinsic::ppc_altivec_vcmpnew_p: 9807 case Intrinsic::ppc_altivec_vcmpnezb_p: 9808 case Intrinsic::ppc_altivec_vcmpnezh_p: 9809 case Intrinsic::ppc_altivec_vcmpnezw_p: 9810 if (Subtarget.hasP9Altivec()) { 9811 switch (IntrinsicID) { 9812 default: 9813 llvm_unreachable("Unknown comparison intrinsic."); 9814 case Intrinsic::ppc_altivec_vcmpneb_p: 9815 CompareOpc = 7; 9816 break; 9817 case Intrinsic::ppc_altivec_vcmpneh_p: 9818 CompareOpc = 71; 9819 break; 9820 case Intrinsic::ppc_altivec_vcmpnew_p: 9821 CompareOpc = 135; 9822 break; 9823 case Intrinsic::ppc_altivec_vcmpnezb_p: 9824 CompareOpc = 263; 9825 break; 9826 case Intrinsic::ppc_altivec_vcmpnezh_p: 9827 CompareOpc = 327; 9828 break; 9829 case Intrinsic::ppc_altivec_vcmpnezw_p: 9830 CompareOpc = 391; 9831 break; 9832 } 9833 isDot = true; 9834 } else 9835 return false; 9836 break; 9837 case Intrinsic::ppc_altivec_vcmpgefp_p: 9838 CompareOpc = 454; 9839 isDot = true; 9840 break; 9841 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9842 CompareOpc = 710; 9843 isDot = true; 9844 break; 9845 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9846 CompareOpc = 774; 9847 isDot = true; 9848 break; 9849 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9850 CompareOpc = 838; 9851 isDot = true; 9852 break; 9853 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9854 CompareOpc = 902; 9855 isDot = true; 9856 break; 9857 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9858 if (Subtarget.hasP8Altivec()) { 9859 CompareOpc = 967; 9860 isDot = true; 9861 } else 9862 return false; 9863 break; 9864 case Intrinsic::ppc_altivec_vcmpgtub_p: 9865 CompareOpc = 518; 9866 isDot = true; 9867 break; 9868 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9869 CompareOpc = 582; 9870 isDot = true; 9871 break; 9872 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9873 CompareOpc = 646; 9874 isDot = true; 9875 break; 9876 case Intrinsic::ppc_altivec_vcmpgtud_p: 9877 if (Subtarget.hasP8Altivec()) { 9878 CompareOpc = 711; 9879 isDot = true; 9880 } else 9881 return false; 9882 break; 9883 9884 case Intrinsic::ppc_altivec_vcmpequq: 9885 case Intrinsic::ppc_altivec_vcmpgtsq: 9886 case Intrinsic::ppc_altivec_vcmpgtuq: 9887 if (!Subtarget.isISA3_1()) 9888 return false; 9889 switch (IntrinsicID) { 9890 default: 9891 llvm_unreachable("Unknown comparison intrinsic."); 9892 case Intrinsic::ppc_altivec_vcmpequq: 9893 CompareOpc = 455; 9894 break; 9895 case Intrinsic::ppc_altivec_vcmpgtsq: 9896 CompareOpc = 903; 9897 break; 9898 case Intrinsic::ppc_altivec_vcmpgtuq: 9899 CompareOpc = 647; 9900 break; 9901 } 9902 break; 9903 9904 // VSX predicate comparisons use the same infrastructure 9905 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9906 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9907 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9908 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9909 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9910 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9911 if (Subtarget.hasVSX()) { 9912 switch (IntrinsicID) { 9913 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9914 CompareOpc = 99; 9915 break; 9916 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9917 CompareOpc = 115; 9918 break; 9919 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9920 CompareOpc = 107; 9921 break; 9922 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9923 CompareOpc = 67; 9924 break; 9925 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9926 CompareOpc = 83; 9927 break; 9928 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9929 CompareOpc = 75; 9930 break; 9931 } 9932 isDot = true; 9933 } else 9934 return false; 9935 break; 9936 9937 // Normal Comparisons. 9938 case Intrinsic::ppc_altivec_vcmpbfp: 9939 CompareOpc = 966; 9940 break; 9941 case Intrinsic::ppc_altivec_vcmpeqfp: 9942 CompareOpc = 198; 9943 break; 9944 case Intrinsic::ppc_altivec_vcmpequb: 9945 CompareOpc = 6; 9946 break; 9947 case Intrinsic::ppc_altivec_vcmpequh: 9948 CompareOpc = 70; 9949 break; 9950 case Intrinsic::ppc_altivec_vcmpequw: 9951 CompareOpc = 134; 9952 break; 9953 case Intrinsic::ppc_altivec_vcmpequd: 9954 if (Subtarget.hasP8Altivec()) 9955 CompareOpc = 199; 9956 else 9957 return false; 9958 break; 9959 case Intrinsic::ppc_altivec_vcmpneb: 9960 case Intrinsic::ppc_altivec_vcmpneh: 9961 case Intrinsic::ppc_altivec_vcmpnew: 9962 case Intrinsic::ppc_altivec_vcmpnezb: 9963 case Intrinsic::ppc_altivec_vcmpnezh: 9964 case Intrinsic::ppc_altivec_vcmpnezw: 9965 if (Subtarget.hasP9Altivec()) 9966 switch (IntrinsicID) { 9967 default: 9968 llvm_unreachable("Unknown comparison intrinsic."); 9969 case Intrinsic::ppc_altivec_vcmpneb: 9970 CompareOpc = 7; 9971 break; 9972 case Intrinsic::ppc_altivec_vcmpneh: 9973 CompareOpc = 71; 9974 break; 9975 case Intrinsic::ppc_altivec_vcmpnew: 9976 CompareOpc = 135; 9977 break; 9978 case Intrinsic::ppc_altivec_vcmpnezb: 9979 CompareOpc = 263; 9980 break; 9981 case Intrinsic::ppc_altivec_vcmpnezh: 9982 CompareOpc = 327; 9983 break; 9984 case Intrinsic::ppc_altivec_vcmpnezw: 9985 CompareOpc = 391; 9986 break; 9987 } 9988 else 9989 return false; 9990 break; 9991 case Intrinsic::ppc_altivec_vcmpgefp: 9992 CompareOpc = 454; 9993 break; 9994 case Intrinsic::ppc_altivec_vcmpgtfp: 9995 CompareOpc = 710; 9996 break; 9997 case Intrinsic::ppc_altivec_vcmpgtsb: 9998 CompareOpc = 774; 9999 break; 10000 case Intrinsic::ppc_altivec_vcmpgtsh: 10001 CompareOpc = 838; 10002 break; 10003 case Intrinsic::ppc_altivec_vcmpgtsw: 10004 CompareOpc = 902; 10005 break; 10006 case Intrinsic::ppc_altivec_vcmpgtsd: 10007 if (Subtarget.hasP8Altivec()) 10008 CompareOpc = 967; 10009 else 10010 return false; 10011 break; 10012 case Intrinsic::ppc_altivec_vcmpgtub: 10013 CompareOpc = 518; 10014 break; 10015 case Intrinsic::ppc_altivec_vcmpgtuh: 10016 CompareOpc = 582; 10017 break; 10018 case Intrinsic::ppc_altivec_vcmpgtuw: 10019 CompareOpc = 646; 10020 break; 10021 case Intrinsic::ppc_altivec_vcmpgtud: 10022 if (Subtarget.hasP8Altivec()) 10023 CompareOpc = 711; 10024 else 10025 return false; 10026 break; 10027 case Intrinsic::ppc_altivec_vcmpequq_p: 10028 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10029 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10030 if (!Subtarget.isISA3_1()) 10031 return false; 10032 switch (IntrinsicID) { 10033 default: 10034 llvm_unreachable("Unknown comparison intrinsic."); 10035 case Intrinsic::ppc_altivec_vcmpequq_p: 10036 CompareOpc = 455; 10037 break; 10038 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10039 CompareOpc = 903; 10040 break; 10041 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10042 CompareOpc = 647; 10043 break; 10044 } 10045 isDot = true; 10046 break; 10047 } 10048 return true; 10049 } 10050 10051 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10052 /// lower, do it, otherwise return null. 10053 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10054 SelectionDAG &DAG) const { 10055 unsigned IntrinsicID = 10056 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10057 10058 SDLoc dl(Op); 10059 10060 switch (IntrinsicID) { 10061 case Intrinsic::thread_pointer: 10062 // Reads the thread pointer register, used for __builtin_thread_pointer. 10063 if (Subtarget.isPPC64()) 10064 return DAG.getRegister(PPC::X13, MVT::i64); 10065 return DAG.getRegister(PPC::R2, MVT::i32); 10066 10067 case Intrinsic::ppc_mma_disassemble_acc: 10068 case Intrinsic::ppc_vsx_disassemble_pair: { 10069 int NumVecs = 2; 10070 SDValue WideVec = Op.getOperand(1); 10071 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10072 NumVecs = 4; 10073 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10074 } 10075 SmallVector<SDValue, 4> RetOps; 10076 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10077 SDValue Extract = DAG.getNode( 10078 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10079 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10080 : VecNo, 10081 dl, MVT::i64)); 10082 RetOps.push_back(Extract); 10083 } 10084 return DAG.getMergeValues(RetOps, dl); 10085 } 10086 } 10087 10088 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10089 // opcode number of the comparison. 10090 int CompareOpc; 10091 bool isDot; 10092 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10093 return SDValue(); // Don't custom lower most intrinsics. 10094 10095 // If this is a non-dot comparison, make the VCMP node and we are done. 10096 if (!isDot) { 10097 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10098 Op.getOperand(1), Op.getOperand(2), 10099 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10100 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10101 } 10102 10103 // Create the PPCISD altivec 'dot' comparison node. 10104 SDValue Ops[] = { 10105 Op.getOperand(2), // LHS 10106 Op.getOperand(3), // RHS 10107 DAG.getConstant(CompareOpc, dl, MVT::i32) 10108 }; 10109 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10110 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10111 10112 // Now that we have the comparison, emit a copy from the CR to a GPR. 10113 // This is flagged to the above dot comparison. 10114 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10115 DAG.getRegister(PPC::CR6, MVT::i32), 10116 CompNode.getValue(1)); 10117 10118 // Unpack the result based on how the target uses it. 10119 unsigned BitNo; // Bit # of CR6. 10120 bool InvertBit; // Invert result? 10121 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10122 default: // Can't happen, don't crash on invalid number though. 10123 case 0: // Return the value of the EQ bit of CR6. 10124 BitNo = 0; InvertBit = false; 10125 break; 10126 case 1: // Return the inverted value of the EQ bit of CR6. 10127 BitNo = 0; InvertBit = true; 10128 break; 10129 case 2: // Return the value of the LT bit of CR6. 10130 BitNo = 2; InvertBit = false; 10131 break; 10132 case 3: // Return the inverted value of the LT bit of CR6. 10133 BitNo = 2; InvertBit = true; 10134 break; 10135 } 10136 10137 // Shift the bit into the low position. 10138 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10139 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10140 // Isolate the bit. 10141 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10142 DAG.getConstant(1, dl, MVT::i32)); 10143 10144 // If we are supposed to, toggle the bit. 10145 if (InvertBit) 10146 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10147 DAG.getConstant(1, dl, MVT::i32)); 10148 return Flags; 10149 } 10150 10151 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10152 SelectionDAG &DAG) const { 10153 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10154 // the beginning of the argument list. 10155 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10156 SDLoc DL(Op); 10157 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10158 case Intrinsic::ppc_cfence: { 10159 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10160 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10161 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10162 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10163 Op.getOperand(ArgStart + 1)), 10164 Op.getOperand(0)), 10165 0); 10166 } 10167 default: 10168 break; 10169 } 10170 return SDValue(); 10171 } 10172 10173 // Lower scalar BSWAP64 to xxbrd. 10174 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10175 SDLoc dl(Op); 10176 // MTVSRDD 10177 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10178 Op.getOperand(0)); 10179 // XXBRD 10180 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10181 // MFVSRD 10182 int VectorIndex = 0; 10183 if (Subtarget.isLittleEndian()) 10184 VectorIndex = 1; 10185 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10186 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10187 return Op; 10188 } 10189 10190 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10191 // compared to a value that is atomically loaded (atomic loads zero-extend). 10192 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10193 SelectionDAG &DAG) const { 10194 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10195 "Expecting an atomic compare-and-swap here."); 10196 SDLoc dl(Op); 10197 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10198 EVT MemVT = AtomicNode->getMemoryVT(); 10199 if (MemVT.getSizeInBits() >= 32) 10200 return Op; 10201 10202 SDValue CmpOp = Op.getOperand(2); 10203 // If this is already correctly zero-extended, leave it alone. 10204 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10205 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10206 return Op; 10207 10208 // Clear the high bits of the compare operand. 10209 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10210 SDValue NewCmpOp = 10211 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10212 DAG.getConstant(MaskVal, dl, MVT::i32)); 10213 10214 // Replace the existing compare operand with the properly zero-extended one. 10215 SmallVector<SDValue, 4> Ops; 10216 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10217 Ops.push_back(AtomicNode->getOperand(i)); 10218 Ops[2] = NewCmpOp; 10219 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10220 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10221 auto NodeTy = 10222 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10223 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10224 } 10225 10226 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10227 SelectionDAG &DAG) const { 10228 SDLoc dl(Op); 10229 // Create a stack slot that is 16-byte aligned. 10230 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10231 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10232 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10233 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10234 10235 // Store the input value into Value#0 of the stack slot. 10236 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10237 MachinePointerInfo()); 10238 // Load it out. 10239 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10240 } 10241 10242 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10243 SelectionDAG &DAG) const { 10244 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10245 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10246 10247 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10248 10249 EVT VT = Op.getValueType(); 10250 SDLoc dl(Op); 10251 SDValue V1 = Op.getOperand(0); 10252 SDValue V2 = Op.getOperand(1); 10253 SDValue V3 = Op.getOperand(2); 10254 10255 if (Subtarget.isISA3_1()) { 10256 // On P10, we have legal lowering for constant and variable indices for 10257 // integer vectors. 10258 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10259 VT == MVT::v2i64) 10260 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10261 // For f32 and f64 vectors, we have legal lowering for variable indices. 10262 // For f32 we also have legal lowering when the element is loaded from 10263 // memory. 10264 if (VT == MVT::v4f32 || VT == MVT::v2f64) { 10265 if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2))) 10266 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10267 return SDValue(); 10268 } 10269 } 10270 10271 // Before P10, we have legal lowering for constant indices but not for 10272 // variable ones. 10273 if (!C) 10274 return SDValue(); 10275 10276 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10277 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10278 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10279 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10280 unsigned InsertAtElement = C->getZExtValue(); 10281 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10282 if (Subtarget.isLittleEndian()) { 10283 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10284 } 10285 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10286 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10287 } 10288 return Op; 10289 } 10290 10291 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10292 SelectionDAG &DAG) const { 10293 SDLoc dl(Op); 10294 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10295 SDValue LoadChain = LN->getChain(); 10296 SDValue BasePtr = LN->getBasePtr(); 10297 EVT VT = Op.getValueType(); 10298 10299 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10300 return Op; 10301 10302 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10303 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10304 // 2 or 4 vsx registers. 10305 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10306 "Type unsupported without MMA"); 10307 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10308 "Type unsupported without paired vector support"); 10309 Align Alignment = LN->getAlign(); 10310 SmallVector<SDValue, 4> Loads; 10311 SmallVector<SDValue, 4> LoadChains; 10312 unsigned NumVecs = VT.getSizeInBits() / 128; 10313 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10314 SDValue Load = 10315 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10316 LN->getPointerInfo().getWithOffset(Idx * 16), 10317 commonAlignment(Alignment, Idx * 16), 10318 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10319 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10320 DAG.getConstant(16, dl, BasePtr.getValueType())); 10321 Loads.push_back(Load); 10322 LoadChains.push_back(Load.getValue(1)); 10323 } 10324 if (Subtarget.isLittleEndian()) { 10325 std::reverse(Loads.begin(), Loads.end()); 10326 std::reverse(LoadChains.begin(), LoadChains.end()); 10327 } 10328 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10329 SDValue Value = 10330 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10331 dl, VT, Loads); 10332 SDValue RetOps[] = {Value, TF}; 10333 return DAG.getMergeValues(RetOps, dl); 10334 } 10335 10336 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10337 SelectionDAG &DAG) const { 10338 SDLoc dl(Op); 10339 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10340 SDValue StoreChain = SN->getChain(); 10341 SDValue BasePtr = SN->getBasePtr(); 10342 SDValue Value = SN->getValue(); 10343 EVT StoreVT = Value.getValueType(); 10344 10345 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10346 return Op; 10347 10348 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10349 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10350 // underlying registers individually. 10351 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10352 "Type unsupported without MMA"); 10353 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10354 "Type unsupported without paired vector support"); 10355 Align Alignment = SN->getAlign(); 10356 SmallVector<SDValue, 4> Stores; 10357 unsigned NumVecs = 2; 10358 if (StoreVT == MVT::v512i1) { 10359 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10360 NumVecs = 4; 10361 } 10362 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10363 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10364 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10365 DAG.getConstant(VecNum, dl, MVT::i64)); 10366 SDValue Store = 10367 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10368 SN->getPointerInfo().getWithOffset(Idx * 16), 10369 commonAlignment(Alignment, Idx * 16), 10370 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10371 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10372 DAG.getConstant(16, dl, BasePtr.getValueType())); 10373 Stores.push_back(Store); 10374 } 10375 SDValue TF = DAG.getTokenFactor(dl, Stores); 10376 return TF; 10377 } 10378 10379 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10380 SDLoc dl(Op); 10381 if (Op.getValueType() == MVT::v4i32) { 10382 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10383 10384 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10385 // +16 as shift amt. 10386 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10387 SDValue RHSSwap = // = vrlw RHS, 16 10388 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10389 10390 // Shrinkify inputs to v8i16. 10391 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10392 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10393 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10394 10395 // Low parts multiplied together, generating 32-bit results (we ignore the 10396 // top parts). 10397 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10398 LHS, RHS, DAG, dl, MVT::v4i32); 10399 10400 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10401 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10402 // Shift the high parts up 16 bits. 10403 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10404 Neg16, DAG, dl); 10405 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10406 } else if (Op.getValueType() == MVT::v16i8) { 10407 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10408 bool isLittleEndian = Subtarget.isLittleEndian(); 10409 10410 // Multiply the even 8-bit parts, producing 16-bit sums. 10411 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10412 LHS, RHS, DAG, dl, MVT::v8i16); 10413 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10414 10415 // Multiply the odd 8-bit parts, producing 16-bit sums. 10416 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10417 LHS, RHS, DAG, dl, MVT::v8i16); 10418 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10419 10420 // Merge the results together. Because vmuleub and vmuloub are 10421 // instructions with a big-endian bias, we must reverse the 10422 // element numbering and reverse the meaning of "odd" and "even" 10423 // when generating little endian code. 10424 int Ops[16]; 10425 for (unsigned i = 0; i != 8; ++i) { 10426 if (isLittleEndian) { 10427 Ops[i*2 ] = 2*i; 10428 Ops[i*2+1] = 2*i+16; 10429 } else { 10430 Ops[i*2 ] = 2*i+1; 10431 Ops[i*2+1] = 2*i+1+16; 10432 } 10433 } 10434 if (isLittleEndian) 10435 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10436 else 10437 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10438 } else { 10439 llvm_unreachable("Unknown mul to lower!"); 10440 } 10441 } 10442 10443 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10444 bool IsStrict = Op->isStrictFPOpcode(); 10445 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10446 !Subtarget.hasP9Vector()) 10447 return SDValue(); 10448 10449 return Op; 10450 } 10451 10452 // Custom lowering for fpext vf32 to v2f64 10453 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10454 10455 assert(Op.getOpcode() == ISD::FP_EXTEND && 10456 "Should only be called for ISD::FP_EXTEND"); 10457 10458 // FIXME: handle extends from half precision float vectors on P9. 10459 // We only want to custom lower an extend from v2f32 to v2f64. 10460 if (Op.getValueType() != MVT::v2f64 || 10461 Op.getOperand(0).getValueType() != MVT::v2f32) 10462 return SDValue(); 10463 10464 SDLoc dl(Op); 10465 SDValue Op0 = Op.getOperand(0); 10466 10467 switch (Op0.getOpcode()) { 10468 default: 10469 return SDValue(); 10470 case ISD::EXTRACT_SUBVECTOR: { 10471 assert(Op0.getNumOperands() == 2 && 10472 isa<ConstantSDNode>(Op0->getOperand(1)) && 10473 "Node should have 2 operands with second one being a constant!"); 10474 10475 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10476 return SDValue(); 10477 10478 // Custom lower is only done for high or low doubleword. 10479 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10480 if (Idx % 2 != 0) 10481 return SDValue(); 10482 10483 // Since input is v4f32, at this point Idx is either 0 or 2. 10484 // Shift to get the doubleword position we want. 10485 int DWord = Idx >> 1; 10486 10487 // High and low word positions are different on little endian. 10488 if (Subtarget.isLittleEndian()) 10489 DWord ^= 0x1; 10490 10491 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10492 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10493 } 10494 case ISD::FADD: 10495 case ISD::FMUL: 10496 case ISD::FSUB: { 10497 SDValue NewLoad[2]; 10498 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10499 // Ensure both input are loads. 10500 SDValue LdOp = Op0.getOperand(i); 10501 if (LdOp.getOpcode() != ISD::LOAD) 10502 return SDValue(); 10503 // Generate new load node. 10504 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10505 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10506 NewLoad[i] = DAG.getMemIntrinsicNode( 10507 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10508 LD->getMemoryVT(), LD->getMemOperand()); 10509 } 10510 SDValue NewOp = 10511 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10512 NewLoad[1], Op0.getNode()->getFlags()); 10513 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10514 DAG.getConstant(0, dl, MVT::i32)); 10515 } 10516 case ISD::LOAD: { 10517 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10518 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10519 SDValue NewLd = DAG.getMemIntrinsicNode( 10520 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10521 LD->getMemoryVT(), LD->getMemOperand()); 10522 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10523 DAG.getConstant(0, dl, MVT::i32)); 10524 } 10525 } 10526 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10527 } 10528 10529 /// LowerOperation - Provide custom lowering hooks for some operations. 10530 /// 10531 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10532 switch (Op.getOpcode()) { 10533 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10534 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10535 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10536 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10537 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10538 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10539 case ISD::SETCC: return LowerSETCC(Op, DAG); 10540 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10541 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10542 10543 // Variable argument lowering. 10544 case ISD::VASTART: return LowerVASTART(Op, DAG); 10545 case ISD::VAARG: return LowerVAARG(Op, DAG); 10546 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10547 10548 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10549 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10550 case ISD::GET_DYNAMIC_AREA_OFFSET: 10551 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10552 10553 // Exception handling lowering. 10554 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10555 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10556 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10557 10558 case ISD::LOAD: return LowerLOAD(Op, DAG); 10559 case ISD::STORE: return LowerSTORE(Op, DAG); 10560 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10561 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10562 case ISD::STRICT_FP_TO_UINT: 10563 case ISD::STRICT_FP_TO_SINT: 10564 case ISD::FP_TO_UINT: 10565 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10566 case ISD::STRICT_UINT_TO_FP: 10567 case ISD::STRICT_SINT_TO_FP: 10568 case ISD::UINT_TO_FP: 10569 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10570 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10571 10572 // Lower 64-bit shifts. 10573 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10574 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10575 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10576 10577 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10578 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10579 10580 // Vector-related lowering. 10581 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10582 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10583 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10584 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10585 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10586 case ISD::MUL: return LowerMUL(Op, DAG); 10587 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10588 case ISD::STRICT_FP_ROUND: 10589 case ISD::FP_ROUND: 10590 return LowerFP_ROUND(Op, DAG); 10591 case ISD::ROTL: return LowerROTL(Op, DAG); 10592 10593 // For counter-based loop handling. 10594 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10595 10596 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10597 10598 // Frame & Return address. 10599 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10600 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10601 10602 case ISD::INTRINSIC_VOID: 10603 return LowerINTRINSIC_VOID(Op, DAG); 10604 case ISD::BSWAP: 10605 return LowerBSWAP(Op, DAG); 10606 case ISD::ATOMIC_CMP_SWAP: 10607 return LowerATOMIC_CMP_SWAP(Op, DAG); 10608 } 10609 } 10610 10611 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10612 SmallVectorImpl<SDValue>&Results, 10613 SelectionDAG &DAG) const { 10614 SDLoc dl(N); 10615 switch (N->getOpcode()) { 10616 default: 10617 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10618 case ISD::READCYCLECOUNTER: { 10619 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10620 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10621 10622 Results.push_back( 10623 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10624 Results.push_back(RTB.getValue(2)); 10625 break; 10626 } 10627 case ISD::INTRINSIC_W_CHAIN: { 10628 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10629 Intrinsic::loop_decrement) 10630 break; 10631 10632 assert(N->getValueType(0) == MVT::i1 && 10633 "Unexpected result type for CTR decrement intrinsic"); 10634 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10635 N->getValueType(0)); 10636 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10637 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10638 N->getOperand(1)); 10639 10640 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10641 Results.push_back(NewInt.getValue(1)); 10642 break; 10643 } 10644 case ISD::VAARG: { 10645 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10646 return; 10647 10648 EVT VT = N->getValueType(0); 10649 10650 if (VT == MVT::i64) { 10651 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10652 10653 Results.push_back(NewNode); 10654 Results.push_back(NewNode.getValue(1)); 10655 } 10656 return; 10657 } 10658 case ISD::STRICT_FP_TO_SINT: 10659 case ISD::STRICT_FP_TO_UINT: 10660 case ISD::FP_TO_SINT: 10661 case ISD::FP_TO_UINT: 10662 // LowerFP_TO_INT() can only handle f32 and f64. 10663 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10664 MVT::ppcf128) 10665 return; 10666 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10667 return; 10668 case ISD::TRUNCATE: { 10669 if (!N->getValueType(0).isVector()) 10670 return; 10671 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10672 if (Lowered) 10673 Results.push_back(Lowered); 10674 return; 10675 } 10676 case ISD::FSHL: 10677 case ISD::FSHR: 10678 // Don't handle funnel shifts here. 10679 return; 10680 case ISD::BITCAST: 10681 // Don't handle bitcast here. 10682 return; 10683 case ISD::FP_EXTEND: 10684 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10685 if (Lowered) 10686 Results.push_back(Lowered); 10687 return; 10688 } 10689 } 10690 10691 //===----------------------------------------------------------------------===// 10692 // Other Lowering Code 10693 //===----------------------------------------------------------------------===// 10694 10695 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10696 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10697 Function *Func = Intrinsic::getDeclaration(M, Id); 10698 return Builder.CreateCall(Func, {}); 10699 } 10700 10701 // The mappings for emitLeading/TrailingFence is taken from 10702 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10703 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10704 Instruction *Inst, 10705 AtomicOrdering Ord) const { 10706 if (Ord == AtomicOrdering::SequentiallyConsistent) 10707 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10708 if (isReleaseOrStronger(Ord)) 10709 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10710 return nullptr; 10711 } 10712 10713 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10714 Instruction *Inst, 10715 AtomicOrdering Ord) const { 10716 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10717 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10718 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10719 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10720 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10721 return Builder.CreateCall( 10722 Intrinsic::getDeclaration( 10723 Builder.GetInsertBlock()->getParent()->getParent(), 10724 Intrinsic::ppc_cfence, {Inst->getType()}), 10725 {Inst}); 10726 // FIXME: Can use isync for rmw operation. 10727 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10728 } 10729 return nullptr; 10730 } 10731 10732 MachineBasicBlock * 10733 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10734 unsigned AtomicSize, 10735 unsigned BinOpcode, 10736 unsigned CmpOpcode, 10737 unsigned CmpPred) const { 10738 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10739 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10740 10741 auto LoadMnemonic = PPC::LDARX; 10742 auto StoreMnemonic = PPC::STDCX; 10743 switch (AtomicSize) { 10744 default: 10745 llvm_unreachable("Unexpected size of atomic entity"); 10746 case 1: 10747 LoadMnemonic = PPC::LBARX; 10748 StoreMnemonic = PPC::STBCX; 10749 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10750 break; 10751 case 2: 10752 LoadMnemonic = PPC::LHARX; 10753 StoreMnemonic = PPC::STHCX; 10754 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10755 break; 10756 case 4: 10757 LoadMnemonic = PPC::LWARX; 10758 StoreMnemonic = PPC::STWCX; 10759 break; 10760 case 8: 10761 LoadMnemonic = PPC::LDARX; 10762 StoreMnemonic = PPC::STDCX; 10763 break; 10764 } 10765 10766 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10767 MachineFunction *F = BB->getParent(); 10768 MachineFunction::iterator It = ++BB->getIterator(); 10769 10770 Register dest = MI.getOperand(0).getReg(); 10771 Register ptrA = MI.getOperand(1).getReg(); 10772 Register ptrB = MI.getOperand(2).getReg(); 10773 Register incr = MI.getOperand(3).getReg(); 10774 DebugLoc dl = MI.getDebugLoc(); 10775 10776 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10777 MachineBasicBlock *loop2MBB = 10778 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10779 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10780 F->insert(It, loopMBB); 10781 if (CmpOpcode) 10782 F->insert(It, loop2MBB); 10783 F->insert(It, exitMBB); 10784 exitMBB->splice(exitMBB->begin(), BB, 10785 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10786 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10787 10788 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10789 Register TmpReg = (!BinOpcode) ? incr : 10790 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10791 : &PPC::GPRCRegClass); 10792 10793 // thisMBB: 10794 // ... 10795 // fallthrough --> loopMBB 10796 BB->addSuccessor(loopMBB); 10797 10798 // loopMBB: 10799 // l[wd]arx dest, ptr 10800 // add r0, dest, incr 10801 // st[wd]cx. r0, ptr 10802 // bne- loopMBB 10803 // fallthrough --> exitMBB 10804 10805 // For max/min... 10806 // loopMBB: 10807 // l[wd]arx dest, ptr 10808 // cmpl?[wd] incr, dest 10809 // bgt exitMBB 10810 // loop2MBB: 10811 // st[wd]cx. dest, ptr 10812 // bne- loopMBB 10813 // fallthrough --> exitMBB 10814 10815 BB = loopMBB; 10816 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10817 .addReg(ptrA).addReg(ptrB); 10818 if (BinOpcode) 10819 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10820 if (CmpOpcode) { 10821 // Signed comparisons of byte or halfword values must be sign-extended. 10822 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10823 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10824 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10825 ExtReg).addReg(dest); 10826 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10827 .addReg(incr).addReg(ExtReg); 10828 } else 10829 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10830 .addReg(incr).addReg(dest); 10831 10832 BuildMI(BB, dl, TII->get(PPC::BCC)) 10833 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10834 BB->addSuccessor(loop2MBB); 10835 BB->addSuccessor(exitMBB); 10836 BB = loop2MBB; 10837 } 10838 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10839 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10840 BuildMI(BB, dl, TII->get(PPC::BCC)) 10841 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10842 BB->addSuccessor(loopMBB); 10843 BB->addSuccessor(exitMBB); 10844 10845 // exitMBB: 10846 // ... 10847 BB = exitMBB; 10848 return BB; 10849 } 10850 10851 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 10852 switch(MI.getOpcode()) { 10853 default: 10854 return false; 10855 case PPC::COPY: 10856 return TII->isSignExtended(MI); 10857 case PPC::LHA: 10858 case PPC::LHA8: 10859 case PPC::LHAU: 10860 case PPC::LHAU8: 10861 case PPC::LHAUX: 10862 case PPC::LHAUX8: 10863 case PPC::LHAX: 10864 case PPC::LHAX8: 10865 case PPC::LWA: 10866 case PPC::LWAUX: 10867 case PPC::LWAX: 10868 case PPC::LWAX_32: 10869 case PPC::LWA_32: 10870 case PPC::PLHA: 10871 case PPC::PLHA8: 10872 case PPC::PLHA8pc: 10873 case PPC::PLHApc: 10874 case PPC::PLWA: 10875 case PPC::PLWA8: 10876 case PPC::PLWA8pc: 10877 case PPC::PLWApc: 10878 case PPC::EXTSB: 10879 case PPC::EXTSB8: 10880 case PPC::EXTSB8_32_64: 10881 case PPC::EXTSB8_rec: 10882 case PPC::EXTSB_rec: 10883 case PPC::EXTSH: 10884 case PPC::EXTSH8: 10885 case PPC::EXTSH8_32_64: 10886 case PPC::EXTSH8_rec: 10887 case PPC::EXTSH_rec: 10888 case PPC::EXTSW: 10889 case PPC::EXTSWSLI: 10890 case PPC::EXTSWSLI_32_64: 10891 case PPC::EXTSWSLI_32_64_rec: 10892 case PPC::EXTSWSLI_rec: 10893 case PPC::EXTSW_32: 10894 case PPC::EXTSW_32_64: 10895 case PPC::EXTSW_32_64_rec: 10896 case PPC::EXTSW_rec: 10897 case PPC::SRAW: 10898 case PPC::SRAWI: 10899 case PPC::SRAWI_rec: 10900 case PPC::SRAW_rec: 10901 return true; 10902 } 10903 return false; 10904 } 10905 10906 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10907 MachineInstr &MI, MachineBasicBlock *BB, 10908 bool is8bit, // operation 10909 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10910 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10911 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 10912 10913 // If this is a signed comparison and the value being compared is not known 10914 // to be sign extended, sign extend it here. 10915 DebugLoc dl = MI.getDebugLoc(); 10916 MachineFunction *F = BB->getParent(); 10917 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10918 Register incr = MI.getOperand(3).getReg(); 10919 bool IsSignExtended = Register::isVirtualRegister(incr) && 10920 isSignExtended(*RegInfo.getVRegDef(incr), TII); 10921 10922 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 10923 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10924 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 10925 .addReg(MI.getOperand(3).getReg()); 10926 MI.getOperand(3).setReg(ValueReg); 10927 } 10928 // If we support part-word atomic mnemonics, just use them 10929 if (Subtarget.hasPartwordAtomics()) 10930 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10931 CmpPred); 10932 10933 // In 64 bit mode we have to use 64 bits for addresses, even though the 10934 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10935 // registers without caring whether they're 32 or 64, but here we're 10936 // doing actual arithmetic on the addresses. 10937 bool is64bit = Subtarget.isPPC64(); 10938 bool isLittleEndian = Subtarget.isLittleEndian(); 10939 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10940 10941 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10942 MachineFunction::iterator It = ++BB->getIterator(); 10943 10944 Register dest = MI.getOperand(0).getReg(); 10945 Register ptrA = MI.getOperand(1).getReg(); 10946 Register ptrB = MI.getOperand(2).getReg(); 10947 10948 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10949 MachineBasicBlock *loop2MBB = 10950 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10951 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10952 F->insert(It, loopMBB); 10953 if (CmpOpcode) 10954 F->insert(It, loop2MBB); 10955 F->insert(It, exitMBB); 10956 exitMBB->splice(exitMBB->begin(), BB, 10957 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10958 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10959 10960 const TargetRegisterClass *RC = 10961 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10962 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10963 10964 Register PtrReg = RegInfo.createVirtualRegister(RC); 10965 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10966 Register ShiftReg = 10967 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10968 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10969 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10970 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10971 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10972 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10973 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10974 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10975 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10976 Register Ptr1Reg; 10977 Register TmpReg = 10978 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10979 10980 // thisMBB: 10981 // ... 10982 // fallthrough --> loopMBB 10983 BB->addSuccessor(loopMBB); 10984 10985 // The 4-byte load must be aligned, while a char or short may be 10986 // anywhere in the word. Hence all this nasty bookkeeping code. 10987 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10988 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10989 // xori shift, shift1, 24 [16] 10990 // rlwinm ptr, ptr1, 0, 0, 29 10991 // slw incr2, incr, shift 10992 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10993 // slw mask, mask2, shift 10994 // loopMBB: 10995 // lwarx tmpDest, ptr 10996 // add tmp, tmpDest, incr2 10997 // andc tmp2, tmpDest, mask 10998 // and tmp3, tmp, mask 10999 // or tmp4, tmp3, tmp2 11000 // stwcx. tmp4, ptr 11001 // bne- loopMBB 11002 // fallthrough --> exitMBB 11003 // srw dest, tmpDest, shift 11004 if (ptrA != ZeroReg) { 11005 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11006 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11007 .addReg(ptrA) 11008 .addReg(ptrB); 11009 } else { 11010 Ptr1Reg = ptrB; 11011 } 11012 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11013 // mode. 11014 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11015 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11016 .addImm(3) 11017 .addImm(27) 11018 .addImm(is8bit ? 28 : 27); 11019 if (!isLittleEndian) 11020 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11021 .addReg(Shift1Reg) 11022 .addImm(is8bit ? 24 : 16); 11023 if (is64bit) 11024 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11025 .addReg(Ptr1Reg) 11026 .addImm(0) 11027 .addImm(61); 11028 else 11029 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11030 .addReg(Ptr1Reg) 11031 .addImm(0) 11032 .addImm(0) 11033 .addImm(29); 11034 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11035 if (is8bit) 11036 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11037 else { 11038 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11039 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11040 .addReg(Mask3Reg) 11041 .addImm(65535); 11042 } 11043 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11044 .addReg(Mask2Reg) 11045 .addReg(ShiftReg); 11046 11047 BB = loopMBB; 11048 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11049 .addReg(ZeroReg) 11050 .addReg(PtrReg); 11051 if (BinOpcode) 11052 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11053 .addReg(Incr2Reg) 11054 .addReg(TmpDestReg); 11055 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11056 .addReg(TmpDestReg) 11057 .addReg(MaskReg); 11058 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11059 if (CmpOpcode) { 11060 // For unsigned comparisons, we can directly compare the shifted values. 11061 // For signed comparisons we shift and sign extend. 11062 Register SReg = RegInfo.createVirtualRegister(GPRC); 11063 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11064 .addReg(TmpDestReg) 11065 .addReg(MaskReg); 11066 unsigned ValueReg = SReg; 11067 unsigned CmpReg = Incr2Reg; 11068 if (CmpOpcode == PPC::CMPW) { 11069 ValueReg = RegInfo.createVirtualRegister(GPRC); 11070 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11071 .addReg(SReg) 11072 .addReg(ShiftReg); 11073 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11074 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11075 .addReg(ValueReg); 11076 ValueReg = ValueSReg; 11077 CmpReg = incr; 11078 } 11079 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11080 .addReg(CmpReg) 11081 .addReg(ValueReg); 11082 BuildMI(BB, dl, TII->get(PPC::BCC)) 11083 .addImm(CmpPred) 11084 .addReg(PPC::CR0) 11085 .addMBB(exitMBB); 11086 BB->addSuccessor(loop2MBB); 11087 BB->addSuccessor(exitMBB); 11088 BB = loop2MBB; 11089 } 11090 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11091 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11092 .addReg(Tmp4Reg) 11093 .addReg(ZeroReg) 11094 .addReg(PtrReg); 11095 BuildMI(BB, dl, TII->get(PPC::BCC)) 11096 .addImm(PPC::PRED_NE) 11097 .addReg(PPC::CR0) 11098 .addMBB(loopMBB); 11099 BB->addSuccessor(loopMBB); 11100 BB->addSuccessor(exitMBB); 11101 11102 // exitMBB: 11103 // ... 11104 BB = exitMBB; 11105 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11106 .addReg(TmpDestReg) 11107 .addReg(ShiftReg); 11108 return BB; 11109 } 11110 11111 llvm::MachineBasicBlock * 11112 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11113 MachineBasicBlock *MBB) const { 11114 DebugLoc DL = MI.getDebugLoc(); 11115 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11116 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11117 11118 MachineFunction *MF = MBB->getParent(); 11119 MachineRegisterInfo &MRI = MF->getRegInfo(); 11120 11121 const BasicBlock *BB = MBB->getBasicBlock(); 11122 MachineFunction::iterator I = ++MBB->getIterator(); 11123 11124 Register DstReg = MI.getOperand(0).getReg(); 11125 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11126 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11127 Register mainDstReg = MRI.createVirtualRegister(RC); 11128 Register restoreDstReg = MRI.createVirtualRegister(RC); 11129 11130 MVT PVT = getPointerTy(MF->getDataLayout()); 11131 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11132 "Invalid Pointer Size!"); 11133 // For v = setjmp(buf), we generate 11134 // 11135 // thisMBB: 11136 // SjLjSetup mainMBB 11137 // bl mainMBB 11138 // v_restore = 1 11139 // b sinkMBB 11140 // 11141 // mainMBB: 11142 // buf[LabelOffset] = LR 11143 // v_main = 0 11144 // 11145 // sinkMBB: 11146 // v = phi(main, restore) 11147 // 11148 11149 MachineBasicBlock *thisMBB = MBB; 11150 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11151 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11152 MF->insert(I, mainMBB); 11153 MF->insert(I, sinkMBB); 11154 11155 MachineInstrBuilder MIB; 11156 11157 // Transfer the remainder of BB and its successor edges to sinkMBB. 11158 sinkMBB->splice(sinkMBB->begin(), MBB, 11159 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11160 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11161 11162 // Note that the structure of the jmp_buf used here is not compatible 11163 // with that used by libc, and is not designed to be. Specifically, it 11164 // stores only those 'reserved' registers that LLVM does not otherwise 11165 // understand how to spill. Also, by convention, by the time this 11166 // intrinsic is called, Clang has already stored the frame address in the 11167 // first slot of the buffer and stack address in the third. Following the 11168 // X86 target code, we'll store the jump address in the second slot. We also 11169 // need to save the TOC pointer (R2) to handle jumps between shared 11170 // libraries, and that will be stored in the fourth slot. The thread 11171 // identifier (R13) is not affected. 11172 11173 // thisMBB: 11174 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11175 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11176 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11177 11178 // Prepare IP either in reg. 11179 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11180 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11181 Register BufReg = MI.getOperand(1).getReg(); 11182 11183 if (Subtarget.is64BitELFABI()) { 11184 setUsesTOCBasePtr(*MBB->getParent()); 11185 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11186 .addReg(PPC::X2) 11187 .addImm(TOCOffset) 11188 .addReg(BufReg) 11189 .cloneMemRefs(MI); 11190 } 11191 11192 // Naked functions never have a base pointer, and so we use r1. For all 11193 // other functions, this decision must be delayed until during PEI. 11194 unsigned BaseReg; 11195 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11196 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11197 else 11198 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11199 11200 MIB = BuildMI(*thisMBB, MI, DL, 11201 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11202 .addReg(BaseReg) 11203 .addImm(BPOffset) 11204 .addReg(BufReg) 11205 .cloneMemRefs(MI); 11206 11207 // Setup 11208 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11209 MIB.addRegMask(TRI->getNoPreservedMask()); 11210 11211 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11212 11213 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11214 .addMBB(mainMBB); 11215 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11216 11217 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11218 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11219 11220 // mainMBB: 11221 // mainDstReg = 0 11222 MIB = 11223 BuildMI(mainMBB, DL, 11224 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11225 11226 // Store IP 11227 if (Subtarget.isPPC64()) { 11228 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11229 .addReg(LabelReg) 11230 .addImm(LabelOffset) 11231 .addReg(BufReg); 11232 } else { 11233 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11234 .addReg(LabelReg) 11235 .addImm(LabelOffset) 11236 .addReg(BufReg); 11237 } 11238 MIB.cloneMemRefs(MI); 11239 11240 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11241 mainMBB->addSuccessor(sinkMBB); 11242 11243 // sinkMBB: 11244 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11245 TII->get(PPC::PHI), DstReg) 11246 .addReg(mainDstReg).addMBB(mainMBB) 11247 .addReg(restoreDstReg).addMBB(thisMBB); 11248 11249 MI.eraseFromParent(); 11250 return sinkMBB; 11251 } 11252 11253 MachineBasicBlock * 11254 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11255 MachineBasicBlock *MBB) const { 11256 DebugLoc DL = MI.getDebugLoc(); 11257 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11258 11259 MachineFunction *MF = MBB->getParent(); 11260 MachineRegisterInfo &MRI = MF->getRegInfo(); 11261 11262 MVT PVT = getPointerTy(MF->getDataLayout()); 11263 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11264 "Invalid Pointer Size!"); 11265 11266 const TargetRegisterClass *RC = 11267 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11268 Register Tmp = MRI.createVirtualRegister(RC); 11269 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11270 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11271 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11272 unsigned BP = 11273 (PVT == MVT::i64) 11274 ? PPC::X30 11275 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11276 : PPC::R30); 11277 11278 MachineInstrBuilder MIB; 11279 11280 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11281 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11282 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11283 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11284 11285 Register BufReg = MI.getOperand(0).getReg(); 11286 11287 // Reload FP (the jumped-to function may not have had a 11288 // frame pointer, and if so, then its r31 will be restored 11289 // as necessary). 11290 if (PVT == MVT::i64) { 11291 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11292 .addImm(0) 11293 .addReg(BufReg); 11294 } else { 11295 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11296 .addImm(0) 11297 .addReg(BufReg); 11298 } 11299 MIB.cloneMemRefs(MI); 11300 11301 // Reload IP 11302 if (PVT == MVT::i64) { 11303 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11304 .addImm(LabelOffset) 11305 .addReg(BufReg); 11306 } else { 11307 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11308 .addImm(LabelOffset) 11309 .addReg(BufReg); 11310 } 11311 MIB.cloneMemRefs(MI); 11312 11313 // Reload SP 11314 if (PVT == MVT::i64) { 11315 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11316 .addImm(SPOffset) 11317 .addReg(BufReg); 11318 } else { 11319 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11320 .addImm(SPOffset) 11321 .addReg(BufReg); 11322 } 11323 MIB.cloneMemRefs(MI); 11324 11325 // Reload BP 11326 if (PVT == MVT::i64) { 11327 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11328 .addImm(BPOffset) 11329 .addReg(BufReg); 11330 } else { 11331 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11332 .addImm(BPOffset) 11333 .addReg(BufReg); 11334 } 11335 MIB.cloneMemRefs(MI); 11336 11337 // Reload TOC 11338 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11339 setUsesTOCBasePtr(*MBB->getParent()); 11340 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11341 .addImm(TOCOffset) 11342 .addReg(BufReg) 11343 .cloneMemRefs(MI); 11344 } 11345 11346 // Jump 11347 BuildMI(*MBB, MI, DL, 11348 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11349 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11350 11351 MI.eraseFromParent(); 11352 return MBB; 11353 } 11354 11355 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11356 // If the function specifically requests inline stack probes, emit them. 11357 if (MF.getFunction().hasFnAttribute("probe-stack")) 11358 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11359 "inline-asm"; 11360 return false; 11361 } 11362 11363 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11364 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11365 unsigned StackAlign = TFI->getStackAlignment(); 11366 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11367 "Unexpected stack alignment"); 11368 // The default stack probe size is 4096 if the function has no 11369 // stack-probe-size attribute. 11370 unsigned StackProbeSize = 4096; 11371 const Function &Fn = MF.getFunction(); 11372 if (Fn.hasFnAttribute("stack-probe-size")) 11373 Fn.getFnAttribute("stack-probe-size") 11374 .getValueAsString() 11375 .getAsInteger(0, StackProbeSize); 11376 // Round down to the stack alignment. 11377 StackProbeSize &= ~(StackAlign - 1); 11378 return StackProbeSize ? StackProbeSize : StackAlign; 11379 } 11380 11381 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11382 // into three phases. In the first phase, it uses pseudo instruction 11383 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11384 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11385 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11386 // MaxCallFrameSize so that it can calculate correct data area pointer. 11387 MachineBasicBlock * 11388 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11389 MachineBasicBlock *MBB) const { 11390 const bool isPPC64 = Subtarget.isPPC64(); 11391 MachineFunction *MF = MBB->getParent(); 11392 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11393 DebugLoc DL = MI.getDebugLoc(); 11394 const unsigned ProbeSize = getStackProbeSize(*MF); 11395 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11396 MachineRegisterInfo &MRI = MF->getRegInfo(); 11397 // The CFG of probing stack looks as 11398 // +-----+ 11399 // | MBB | 11400 // +--+--+ 11401 // | 11402 // +----v----+ 11403 // +--->+ TestMBB +---+ 11404 // | +----+----+ | 11405 // | | | 11406 // | +-----v----+ | 11407 // +---+ BlockMBB | | 11408 // +----------+ | 11409 // | 11410 // +---------+ | 11411 // | TailMBB +<--+ 11412 // +---------+ 11413 // In MBB, calculate previous frame pointer and final stack pointer. 11414 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11415 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11416 // TailMBB is spliced via \p MI. 11417 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11418 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11419 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11420 11421 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11422 MF->insert(MBBIter, TestMBB); 11423 MF->insert(MBBIter, BlockMBB); 11424 MF->insert(MBBIter, TailMBB); 11425 11426 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11427 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11428 11429 Register DstReg = MI.getOperand(0).getReg(); 11430 Register NegSizeReg = MI.getOperand(1).getReg(); 11431 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11432 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11433 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11434 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11435 11436 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11437 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11438 // NegSize. 11439 unsigned ProbeOpc; 11440 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11441 ProbeOpc = 11442 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11443 else 11444 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11445 // and NegSizeReg will be allocated in the same phyreg to avoid 11446 // redundant copy when NegSizeReg has only one use which is current MI and 11447 // will be replaced by PREPARE_PROBED_ALLOCA then. 11448 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11449 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11450 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11451 .addDef(ActualNegSizeReg) 11452 .addReg(NegSizeReg) 11453 .add(MI.getOperand(2)) 11454 .add(MI.getOperand(3)); 11455 11456 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11457 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11458 FinalStackPtr) 11459 .addReg(SPReg) 11460 .addReg(ActualNegSizeReg); 11461 11462 // Materialize a scratch register for update. 11463 int64_t NegProbeSize = -(int64_t)ProbeSize; 11464 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11465 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11466 if (!isInt<16>(NegProbeSize)) { 11467 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11468 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11469 .addImm(NegProbeSize >> 16); 11470 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11471 ScratchReg) 11472 .addReg(TempReg) 11473 .addImm(NegProbeSize & 0xFFFF); 11474 } else 11475 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11476 .addImm(NegProbeSize); 11477 11478 { 11479 // Probing leading residual part. 11480 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11481 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11482 .addReg(ActualNegSizeReg) 11483 .addReg(ScratchReg); 11484 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11485 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11486 .addReg(Div) 11487 .addReg(ScratchReg); 11488 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11489 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11490 .addReg(Mul) 11491 .addReg(ActualNegSizeReg); 11492 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11493 .addReg(FramePointer) 11494 .addReg(SPReg) 11495 .addReg(NegMod); 11496 } 11497 11498 { 11499 // Remaining part should be multiple of ProbeSize. 11500 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11501 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11502 .addReg(SPReg) 11503 .addReg(FinalStackPtr); 11504 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11505 .addImm(PPC::PRED_EQ) 11506 .addReg(CmpResult) 11507 .addMBB(TailMBB); 11508 TestMBB->addSuccessor(BlockMBB); 11509 TestMBB->addSuccessor(TailMBB); 11510 } 11511 11512 { 11513 // Touch the block. 11514 // |P...|P...|P... 11515 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11516 .addReg(FramePointer) 11517 .addReg(SPReg) 11518 .addReg(ScratchReg); 11519 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11520 BlockMBB->addSuccessor(TestMBB); 11521 } 11522 11523 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11524 // DYNAREAOFFSET pseudo instruction to get the future result. 11525 Register MaxCallFrameSizeReg = 11526 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11527 BuildMI(TailMBB, DL, 11528 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11529 MaxCallFrameSizeReg) 11530 .add(MI.getOperand(2)) 11531 .add(MI.getOperand(3)); 11532 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11533 .addReg(SPReg) 11534 .addReg(MaxCallFrameSizeReg); 11535 11536 // Splice instructions after MI to TailMBB. 11537 TailMBB->splice(TailMBB->end(), MBB, 11538 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11539 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11540 MBB->addSuccessor(TestMBB); 11541 11542 // Delete the pseudo instruction. 11543 MI.eraseFromParent(); 11544 11545 ++NumDynamicAllocaProbed; 11546 return TailMBB; 11547 } 11548 11549 MachineBasicBlock * 11550 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11551 MachineBasicBlock *BB) const { 11552 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11553 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11554 if (Subtarget.is64BitELFABI() && 11555 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11556 !Subtarget.isUsingPCRelativeCalls()) { 11557 // Call lowering should have added an r2 operand to indicate a dependence 11558 // on the TOC base pointer value. It can't however, because there is no 11559 // way to mark the dependence as implicit there, and so the stackmap code 11560 // will confuse it with a regular operand. Instead, add the dependence 11561 // here. 11562 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11563 } 11564 11565 return emitPatchPoint(MI, BB); 11566 } 11567 11568 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11569 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11570 return emitEHSjLjSetJmp(MI, BB); 11571 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11572 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11573 return emitEHSjLjLongJmp(MI, BB); 11574 } 11575 11576 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11577 11578 // To "insert" these instructions we actually have to insert their 11579 // control-flow patterns. 11580 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11581 MachineFunction::iterator It = ++BB->getIterator(); 11582 11583 MachineFunction *F = BB->getParent(); 11584 11585 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11586 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11587 MI.getOpcode() == PPC::SELECT_I8) { 11588 SmallVector<MachineOperand, 2> Cond; 11589 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11590 MI.getOpcode() == PPC::SELECT_CC_I8) 11591 Cond.push_back(MI.getOperand(4)); 11592 else 11593 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11594 Cond.push_back(MI.getOperand(1)); 11595 11596 DebugLoc dl = MI.getDebugLoc(); 11597 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11598 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11599 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11600 MI.getOpcode() == PPC::SELECT_CC_F8 || 11601 MI.getOpcode() == PPC::SELECT_CC_F16 || 11602 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11603 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11604 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11605 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11606 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11607 MI.getOpcode() == PPC::SELECT_CC_SPE || 11608 MI.getOpcode() == PPC::SELECT_F4 || 11609 MI.getOpcode() == PPC::SELECT_F8 || 11610 MI.getOpcode() == PPC::SELECT_F16 || 11611 MI.getOpcode() == PPC::SELECT_SPE || 11612 MI.getOpcode() == PPC::SELECT_SPE4 || 11613 MI.getOpcode() == PPC::SELECT_VRRC || 11614 MI.getOpcode() == PPC::SELECT_VSFRC || 11615 MI.getOpcode() == PPC::SELECT_VSSRC || 11616 MI.getOpcode() == PPC::SELECT_VSRC) { 11617 // The incoming instruction knows the destination vreg to set, the 11618 // condition code register to branch on, the true/false values to 11619 // select between, and a branch opcode to use. 11620 11621 // thisMBB: 11622 // ... 11623 // TrueVal = ... 11624 // cmpTY ccX, r1, r2 11625 // bCC copy1MBB 11626 // fallthrough --> copy0MBB 11627 MachineBasicBlock *thisMBB = BB; 11628 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11629 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11630 DebugLoc dl = MI.getDebugLoc(); 11631 F->insert(It, copy0MBB); 11632 F->insert(It, sinkMBB); 11633 11634 // Transfer the remainder of BB and its successor edges to sinkMBB. 11635 sinkMBB->splice(sinkMBB->begin(), BB, 11636 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11637 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11638 11639 // Next, add the true and fallthrough blocks as its successors. 11640 BB->addSuccessor(copy0MBB); 11641 BB->addSuccessor(sinkMBB); 11642 11643 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11644 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11645 MI.getOpcode() == PPC::SELECT_F16 || 11646 MI.getOpcode() == PPC::SELECT_SPE4 || 11647 MI.getOpcode() == PPC::SELECT_SPE || 11648 MI.getOpcode() == PPC::SELECT_VRRC || 11649 MI.getOpcode() == PPC::SELECT_VSFRC || 11650 MI.getOpcode() == PPC::SELECT_VSSRC || 11651 MI.getOpcode() == PPC::SELECT_VSRC) { 11652 BuildMI(BB, dl, TII->get(PPC::BC)) 11653 .addReg(MI.getOperand(1).getReg()) 11654 .addMBB(sinkMBB); 11655 } else { 11656 unsigned SelectPred = MI.getOperand(4).getImm(); 11657 BuildMI(BB, dl, TII->get(PPC::BCC)) 11658 .addImm(SelectPred) 11659 .addReg(MI.getOperand(1).getReg()) 11660 .addMBB(sinkMBB); 11661 } 11662 11663 // copy0MBB: 11664 // %FalseValue = ... 11665 // # fallthrough to sinkMBB 11666 BB = copy0MBB; 11667 11668 // Update machine-CFG edges 11669 BB->addSuccessor(sinkMBB); 11670 11671 // sinkMBB: 11672 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11673 // ... 11674 BB = sinkMBB; 11675 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11676 .addReg(MI.getOperand(3).getReg()) 11677 .addMBB(copy0MBB) 11678 .addReg(MI.getOperand(2).getReg()) 11679 .addMBB(thisMBB); 11680 } else if (MI.getOpcode() == PPC::ReadTB) { 11681 // To read the 64-bit time-base register on a 32-bit target, we read the 11682 // two halves. Should the counter have wrapped while it was being read, we 11683 // need to try again. 11684 // ... 11685 // readLoop: 11686 // mfspr Rx,TBU # load from TBU 11687 // mfspr Ry,TB # load from TB 11688 // mfspr Rz,TBU # load from TBU 11689 // cmpw crX,Rx,Rz # check if 'old'='new' 11690 // bne readLoop # branch if they're not equal 11691 // ... 11692 11693 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11694 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11695 DebugLoc dl = MI.getDebugLoc(); 11696 F->insert(It, readMBB); 11697 F->insert(It, sinkMBB); 11698 11699 // Transfer the remainder of BB and its successor edges to sinkMBB. 11700 sinkMBB->splice(sinkMBB->begin(), BB, 11701 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11702 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11703 11704 BB->addSuccessor(readMBB); 11705 BB = readMBB; 11706 11707 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11708 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11709 Register LoReg = MI.getOperand(0).getReg(); 11710 Register HiReg = MI.getOperand(1).getReg(); 11711 11712 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11713 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11714 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11715 11716 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11717 11718 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11719 .addReg(HiReg) 11720 .addReg(ReadAgainReg); 11721 BuildMI(BB, dl, TII->get(PPC::BCC)) 11722 .addImm(PPC::PRED_NE) 11723 .addReg(CmpReg) 11724 .addMBB(readMBB); 11725 11726 BB->addSuccessor(readMBB); 11727 BB->addSuccessor(sinkMBB); 11728 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11729 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11730 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11731 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11732 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11733 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11734 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11735 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11736 11737 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11738 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11739 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11740 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11741 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11742 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11743 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11744 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11745 11746 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11747 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11748 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11749 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11750 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11751 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11752 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11753 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11754 11755 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11756 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11757 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11758 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11759 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11760 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11761 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11762 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11763 11764 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11765 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11766 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11767 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11768 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11769 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11770 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11771 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11772 11773 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11774 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11775 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11776 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11777 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11778 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11779 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11780 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11781 11782 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11783 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11784 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11785 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11787 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11789 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11790 11791 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11792 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11793 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11794 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11796 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11798 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11799 11800 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11801 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11802 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11803 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11805 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11807 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11808 11809 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11810 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11811 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11812 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11814 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11816 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11817 11818 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11819 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11820 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11821 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11822 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11823 BB = EmitAtomicBinary(MI, BB, 4, 0); 11824 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11825 BB = EmitAtomicBinary(MI, BB, 8, 0); 11826 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11827 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11828 (Subtarget.hasPartwordAtomics() && 11829 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11830 (Subtarget.hasPartwordAtomics() && 11831 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11832 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11833 11834 auto LoadMnemonic = PPC::LDARX; 11835 auto StoreMnemonic = PPC::STDCX; 11836 switch (MI.getOpcode()) { 11837 default: 11838 llvm_unreachable("Compare and swap of unknown size"); 11839 case PPC::ATOMIC_CMP_SWAP_I8: 11840 LoadMnemonic = PPC::LBARX; 11841 StoreMnemonic = PPC::STBCX; 11842 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11843 break; 11844 case PPC::ATOMIC_CMP_SWAP_I16: 11845 LoadMnemonic = PPC::LHARX; 11846 StoreMnemonic = PPC::STHCX; 11847 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11848 break; 11849 case PPC::ATOMIC_CMP_SWAP_I32: 11850 LoadMnemonic = PPC::LWARX; 11851 StoreMnemonic = PPC::STWCX; 11852 break; 11853 case PPC::ATOMIC_CMP_SWAP_I64: 11854 LoadMnemonic = PPC::LDARX; 11855 StoreMnemonic = PPC::STDCX; 11856 break; 11857 } 11858 Register dest = MI.getOperand(0).getReg(); 11859 Register ptrA = MI.getOperand(1).getReg(); 11860 Register ptrB = MI.getOperand(2).getReg(); 11861 Register oldval = MI.getOperand(3).getReg(); 11862 Register newval = MI.getOperand(4).getReg(); 11863 DebugLoc dl = MI.getDebugLoc(); 11864 11865 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11866 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11867 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11868 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11869 F->insert(It, loop1MBB); 11870 F->insert(It, loop2MBB); 11871 F->insert(It, midMBB); 11872 F->insert(It, exitMBB); 11873 exitMBB->splice(exitMBB->begin(), BB, 11874 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11875 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11876 11877 // thisMBB: 11878 // ... 11879 // fallthrough --> loopMBB 11880 BB->addSuccessor(loop1MBB); 11881 11882 // loop1MBB: 11883 // l[bhwd]arx dest, ptr 11884 // cmp[wd] dest, oldval 11885 // bne- midMBB 11886 // loop2MBB: 11887 // st[bhwd]cx. newval, ptr 11888 // bne- loopMBB 11889 // b exitBB 11890 // midMBB: 11891 // st[bhwd]cx. dest, ptr 11892 // exitBB: 11893 BB = loop1MBB; 11894 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11895 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11896 .addReg(oldval) 11897 .addReg(dest); 11898 BuildMI(BB, dl, TII->get(PPC::BCC)) 11899 .addImm(PPC::PRED_NE) 11900 .addReg(PPC::CR0) 11901 .addMBB(midMBB); 11902 BB->addSuccessor(loop2MBB); 11903 BB->addSuccessor(midMBB); 11904 11905 BB = loop2MBB; 11906 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11907 .addReg(newval) 11908 .addReg(ptrA) 11909 .addReg(ptrB); 11910 BuildMI(BB, dl, TII->get(PPC::BCC)) 11911 .addImm(PPC::PRED_NE) 11912 .addReg(PPC::CR0) 11913 .addMBB(loop1MBB); 11914 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11915 BB->addSuccessor(loop1MBB); 11916 BB->addSuccessor(exitMBB); 11917 11918 BB = midMBB; 11919 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11920 .addReg(dest) 11921 .addReg(ptrA) 11922 .addReg(ptrB); 11923 BB->addSuccessor(exitMBB); 11924 11925 // exitMBB: 11926 // ... 11927 BB = exitMBB; 11928 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11929 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11930 // We must use 64-bit registers for addresses when targeting 64-bit, 11931 // since we're actually doing arithmetic on them. Other registers 11932 // can be 32-bit. 11933 bool is64bit = Subtarget.isPPC64(); 11934 bool isLittleEndian = Subtarget.isLittleEndian(); 11935 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11936 11937 Register dest = MI.getOperand(0).getReg(); 11938 Register ptrA = MI.getOperand(1).getReg(); 11939 Register ptrB = MI.getOperand(2).getReg(); 11940 Register oldval = MI.getOperand(3).getReg(); 11941 Register newval = MI.getOperand(4).getReg(); 11942 DebugLoc dl = MI.getDebugLoc(); 11943 11944 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11945 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11946 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11947 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11948 F->insert(It, loop1MBB); 11949 F->insert(It, loop2MBB); 11950 F->insert(It, midMBB); 11951 F->insert(It, exitMBB); 11952 exitMBB->splice(exitMBB->begin(), BB, 11953 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11954 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11955 11956 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11957 const TargetRegisterClass *RC = 11958 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11959 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11960 11961 Register PtrReg = RegInfo.createVirtualRegister(RC); 11962 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11963 Register ShiftReg = 11964 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11965 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11966 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11967 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11968 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11969 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11970 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11971 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11972 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11973 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11974 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11975 Register Ptr1Reg; 11976 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11977 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11978 // thisMBB: 11979 // ... 11980 // fallthrough --> loopMBB 11981 BB->addSuccessor(loop1MBB); 11982 11983 // The 4-byte load must be aligned, while a char or short may be 11984 // anywhere in the word. Hence all this nasty bookkeeping code. 11985 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11986 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11987 // xori shift, shift1, 24 [16] 11988 // rlwinm ptr, ptr1, 0, 0, 29 11989 // slw newval2, newval, shift 11990 // slw oldval2, oldval,shift 11991 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11992 // slw mask, mask2, shift 11993 // and newval3, newval2, mask 11994 // and oldval3, oldval2, mask 11995 // loop1MBB: 11996 // lwarx tmpDest, ptr 11997 // and tmp, tmpDest, mask 11998 // cmpw tmp, oldval3 11999 // bne- midMBB 12000 // loop2MBB: 12001 // andc tmp2, tmpDest, mask 12002 // or tmp4, tmp2, newval3 12003 // stwcx. tmp4, ptr 12004 // bne- loop1MBB 12005 // b exitBB 12006 // midMBB: 12007 // stwcx. tmpDest, ptr 12008 // exitBB: 12009 // srw dest, tmpDest, shift 12010 if (ptrA != ZeroReg) { 12011 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12012 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12013 .addReg(ptrA) 12014 .addReg(ptrB); 12015 } else { 12016 Ptr1Reg = ptrB; 12017 } 12018 12019 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12020 // mode. 12021 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12022 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12023 .addImm(3) 12024 .addImm(27) 12025 .addImm(is8bit ? 28 : 27); 12026 if (!isLittleEndian) 12027 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12028 .addReg(Shift1Reg) 12029 .addImm(is8bit ? 24 : 16); 12030 if (is64bit) 12031 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12032 .addReg(Ptr1Reg) 12033 .addImm(0) 12034 .addImm(61); 12035 else 12036 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12037 .addReg(Ptr1Reg) 12038 .addImm(0) 12039 .addImm(0) 12040 .addImm(29); 12041 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12042 .addReg(newval) 12043 .addReg(ShiftReg); 12044 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12045 .addReg(oldval) 12046 .addReg(ShiftReg); 12047 if (is8bit) 12048 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12049 else { 12050 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12051 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12052 .addReg(Mask3Reg) 12053 .addImm(65535); 12054 } 12055 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12056 .addReg(Mask2Reg) 12057 .addReg(ShiftReg); 12058 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12059 .addReg(NewVal2Reg) 12060 .addReg(MaskReg); 12061 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12062 .addReg(OldVal2Reg) 12063 .addReg(MaskReg); 12064 12065 BB = loop1MBB; 12066 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12067 .addReg(ZeroReg) 12068 .addReg(PtrReg); 12069 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12070 .addReg(TmpDestReg) 12071 .addReg(MaskReg); 12072 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12073 .addReg(TmpReg) 12074 .addReg(OldVal3Reg); 12075 BuildMI(BB, dl, TII->get(PPC::BCC)) 12076 .addImm(PPC::PRED_NE) 12077 .addReg(PPC::CR0) 12078 .addMBB(midMBB); 12079 BB->addSuccessor(loop2MBB); 12080 BB->addSuccessor(midMBB); 12081 12082 BB = loop2MBB; 12083 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12084 .addReg(TmpDestReg) 12085 .addReg(MaskReg); 12086 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12087 .addReg(Tmp2Reg) 12088 .addReg(NewVal3Reg); 12089 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12090 .addReg(Tmp4Reg) 12091 .addReg(ZeroReg) 12092 .addReg(PtrReg); 12093 BuildMI(BB, dl, TII->get(PPC::BCC)) 12094 .addImm(PPC::PRED_NE) 12095 .addReg(PPC::CR0) 12096 .addMBB(loop1MBB); 12097 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12098 BB->addSuccessor(loop1MBB); 12099 BB->addSuccessor(exitMBB); 12100 12101 BB = midMBB; 12102 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12103 .addReg(TmpDestReg) 12104 .addReg(ZeroReg) 12105 .addReg(PtrReg); 12106 BB->addSuccessor(exitMBB); 12107 12108 // exitMBB: 12109 // ... 12110 BB = exitMBB; 12111 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12112 .addReg(TmpReg) 12113 .addReg(ShiftReg); 12114 } else if (MI.getOpcode() == PPC::FADDrtz) { 12115 // This pseudo performs an FADD with rounding mode temporarily forced 12116 // to round-to-zero. We emit this via custom inserter since the FPSCR 12117 // is not modeled at the SelectionDAG level. 12118 Register Dest = MI.getOperand(0).getReg(); 12119 Register Src1 = MI.getOperand(1).getReg(); 12120 Register Src2 = MI.getOperand(2).getReg(); 12121 DebugLoc dl = MI.getDebugLoc(); 12122 12123 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12124 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12125 12126 // Save FPSCR value. 12127 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12128 12129 // Set rounding mode to round-to-zero. 12130 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12131 .addImm(31) 12132 .addReg(PPC::RM, RegState::ImplicitDefine); 12133 12134 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12135 .addImm(30) 12136 .addReg(PPC::RM, RegState::ImplicitDefine); 12137 12138 // Perform addition. 12139 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12140 .addReg(Src1) 12141 .addReg(Src2); 12142 if (MI.getFlag(MachineInstr::NoFPExcept)) 12143 MIB.setMIFlag(MachineInstr::NoFPExcept); 12144 12145 // Restore FPSCR value. 12146 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12147 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12148 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12149 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12150 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12151 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12152 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12153 ? PPC::ANDI8_rec 12154 : PPC::ANDI_rec; 12155 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12156 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12157 12158 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12159 Register Dest = RegInfo.createVirtualRegister( 12160 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12161 12162 DebugLoc Dl = MI.getDebugLoc(); 12163 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12164 .addReg(MI.getOperand(1).getReg()) 12165 .addImm(1); 12166 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12167 MI.getOperand(0).getReg()) 12168 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12169 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12170 DebugLoc Dl = MI.getDebugLoc(); 12171 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12172 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12173 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12174 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12175 MI.getOperand(0).getReg()) 12176 .addReg(CRReg); 12177 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12178 DebugLoc Dl = MI.getDebugLoc(); 12179 unsigned Imm = MI.getOperand(1).getImm(); 12180 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12181 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12182 MI.getOperand(0).getReg()) 12183 .addReg(PPC::CR0EQ); 12184 } else if (MI.getOpcode() == PPC::SETRNDi) { 12185 DebugLoc dl = MI.getDebugLoc(); 12186 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12187 12188 // Save FPSCR value. 12189 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12190 12191 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12192 // the following settings: 12193 // 00 Round to nearest 12194 // 01 Round to 0 12195 // 10 Round to +inf 12196 // 11 Round to -inf 12197 12198 // When the operand is immediate, using the two least significant bits of 12199 // the immediate to set the bits 62:63 of FPSCR. 12200 unsigned Mode = MI.getOperand(1).getImm(); 12201 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12202 .addImm(31) 12203 .addReg(PPC::RM, RegState::ImplicitDefine); 12204 12205 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12206 .addImm(30) 12207 .addReg(PPC::RM, RegState::ImplicitDefine); 12208 } else if (MI.getOpcode() == PPC::SETRND) { 12209 DebugLoc dl = MI.getDebugLoc(); 12210 12211 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12212 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12213 // If the target doesn't have DirectMove, we should use stack to do the 12214 // conversion, because the target doesn't have the instructions like mtvsrd 12215 // or mfvsrd to do this conversion directly. 12216 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12217 if (Subtarget.hasDirectMove()) { 12218 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12219 .addReg(SrcReg); 12220 } else { 12221 // Use stack to do the register copy. 12222 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12223 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12224 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12225 if (RC == &PPC::F8RCRegClass) { 12226 // Copy register from F8RCRegClass to G8RCRegclass. 12227 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12228 "Unsupported RegClass."); 12229 12230 StoreOp = PPC::STFD; 12231 LoadOp = PPC::LD; 12232 } else { 12233 // Copy register from G8RCRegClass to F8RCRegclass. 12234 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12235 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12236 "Unsupported RegClass."); 12237 } 12238 12239 MachineFrameInfo &MFI = F->getFrameInfo(); 12240 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12241 12242 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12243 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12244 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12245 MFI.getObjectAlign(FrameIdx)); 12246 12247 // Store the SrcReg into the stack. 12248 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12249 .addReg(SrcReg) 12250 .addImm(0) 12251 .addFrameIndex(FrameIdx) 12252 .addMemOperand(MMOStore); 12253 12254 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12255 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12256 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12257 MFI.getObjectAlign(FrameIdx)); 12258 12259 // Load from the stack where SrcReg is stored, and save to DestReg, 12260 // so we have done the RegClass conversion from RegClass::SrcReg to 12261 // RegClass::DestReg. 12262 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12263 .addImm(0) 12264 .addFrameIndex(FrameIdx) 12265 .addMemOperand(MMOLoad); 12266 } 12267 }; 12268 12269 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12270 12271 // Save FPSCR value. 12272 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12273 12274 // When the operand is gprc register, use two least significant bits of the 12275 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12276 // 12277 // copy OldFPSCRTmpReg, OldFPSCRReg 12278 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12279 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12280 // copy NewFPSCRReg, NewFPSCRTmpReg 12281 // mtfsf 255, NewFPSCRReg 12282 MachineOperand SrcOp = MI.getOperand(1); 12283 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12284 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12285 12286 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12287 12288 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12289 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12290 12291 // The first operand of INSERT_SUBREG should be a register which has 12292 // subregisters, we only care about its RegClass, so we should use an 12293 // IMPLICIT_DEF register. 12294 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12295 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12296 .addReg(ImDefReg) 12297 .add(SrcOp) 12298 .addImm(1); 12299 12300 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12301 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12302 .addReg(OldFPSCRTmpReg) 12303 .addReg(ExtSrcReg) 12304 .addImm(0) 12305 .addImm(62); 12306 12307 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12308 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12309 12310 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12311 // bits of FPSCR. 12312 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12313 .addImm(255) 12314 .addReg(NewFPSCRReg) 12315 .addImm(0) 12316 .addImm(0); 12317 } else if (MI.getOpcode() == PPC::SETFLM) { 12318 DebugLoc Dl = MI.getDebugLoc(); 12319 12320 // Result of setflm is previous FPSCR content, so we need to save it first. 12321 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12322 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12323 12324 // Put bits in 32:63 to FPSCR. 12325 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12326 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12327 .addImm(255) 12328 .addReg(NewFPSCRReg) 12329 .addImm(0) 12330 .addImm(0); 12331 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12332 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12333 return emitProbedAlloca(MI, BB); 12334 } else { 12335 llvm_unreachable("Unexpected instr type to insert"); 12336 } 12337 12338 MI.eraseFromParent(); // The pseudo instruction is gone now. 12339 return BB; 12340 } 12341 12342 //===----------------------------------------------------------------------===// 12343 // Target Optimization Hooks 12344 //===----------------------------------------------------------------------===// 12345 12346 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12347 // For the estimates, convergence is quadratic, so we essentially double the 12348 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12349 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12350 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12351 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12352 if (VT.getScalarType() == MVT::f64) 12353 RefinementSteps++; 12354 return RefinementSteps; 12355 } 12356 12357 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12358 const DenormalMode &Mode) const { 12359 // We only have VSX Vector Test for software Square Root. 12360 EVT VT = Op.getValueType(); 12361 if (!isTypeLegal(MVT::i1) || 12362 (VT != MVT::f64 && 12363 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12364 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12365 12366 SDLoc DL(Op); 12367 // The output register of FTSQRT is CR field. 12368 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12369 // ftsqrt BF,FRB 12370 // Let e_b be the unbiased exponent of the double-precision 12371 // floating-point operand in register FRB. 12372 // fe_flag is set to 1 if either of the following conditions occurs. 12373 // - The double-precision floating-point operand in register FRB is a zero, 12374 // a NaN, or an infinity, or a negative value. 12375 // - e_b is less than or equal to -970. 12376 // Otherwise fe_flag is set to 0. 12377 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12378 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12379 // exponent is less than -970) 12380 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12381 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12382 FTSQRT, SRIdxVal), 12383 0); 12384 } 12385 12386 SDValue 12387 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12388 SelectionDAG &DAG) const { 12389 // We only have VSX Vector Square Root. 12390 EVT VT = Op.getValueType(); 12391 if (VT != MVT::f64 && 12392 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12393 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12394 12395 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12396 } 12397 12398 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12399 int Enabled, int &RefinementSteps, 12400 bool &UseOneConstNR, 12401 bool Reciprocal) const { 12402 EVT VT = Operand.getValueType(); 12403 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12404 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12405 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12406 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12407 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12408 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12409 12410 // The Newton-Raphson computation with a single constant does not provide 12411 // enough accuracy on some CPUs. 12412 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12413 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12414 } 12415 return SDValue(); 12416 } 12417 12418 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12419 int Enabled, 12420 int &RefinementSteps) const { 12421 EVT VT = Operand.getValueType(); 12422 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12423 (VT == MVT::f64 && Subtarget.hasFRE()) || 12424 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12425 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12426 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12427 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12428 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12429 } 12430 return SDValue(); 12431 } 12432 12433 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12434 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12435 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12436 // enabled for division), this functionality is redundant with the default 12437 // combiner logic (once the division -> reciprocal/multiply transformation 12438 // has taken place). As a result, this matters more for older cores than for 12439 // newer ones. 12440 12441 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12442 // reciprocal if there are two or more FDIVs (for embedded cores with only 12443 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12444 switch (Subtarget.getCPUDirective()) { 12445 default: 12446 return 3; 12447 case PPC::DIR_440: 12448 case PPC::DIR_A2: 12449 case PPC::DIR_E500: 12450 case PPC::DIR_E500mc: 12451 case PPC::DIR_E5500: 12452 return 2; 12453 } 12454 } 12455 12456 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12457 // collapsed, and so we need to look through chains of them. 12458 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12459 int64_t& Offset, SelectionDAG &DAG) { 12460 if (DAG.isBaseWithConstantOffset(Loc)) { 12461 Base = Loc.getOperand(0); 12462 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12463 12464 // The base might itself be a base plus an offset, and if so, accumulate 12465 // that as well. 12466 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12467 } 12468 } 12469 12470 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12471 unsigned Bytes, int Dist, 12472 SelectionDAG &DAG) { 12473 if (VT.getSizeInBits() / 8 != Bytes) 12474 return false; 12475 12476 SDValue BaseLoc = Base->getBasePtr(); 12477 if (Loc.getOpcode() == ISD::FrameIndex) { 12478 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12479 return false; 12480 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12481 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12482 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12483 int FS = MFI.getObjectSize(FI); 12484 int BFS = MFI.getObjectSize(BFI); 12485 if (FS != BFS || FS != (int)Bytes) return false; 12486 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12487 } 12488 12489 SDValue Base1 = Loc, Base2 = BaseLoc; 12490 int64_t Offset1 = 0, Offset2 = 0; 12491 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12492 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12493 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12494 return true; 12495 12496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12497 const GlobalValue *GV1 = nullptr; 12498 const GlobalValue *GV2 = nullptr; 12499 Offset1 = 0; 12500 Offset2 = 0; 12501 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12502 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12503 if (isGA1 && isGA2 && GV1 == GV2) 12504 return Offset1 == (Offset2 + Dist*Bytes); 12505 return false; 12506 } 12507 12508 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12509 // not enforce equality of the chain operands. 12510 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12511 unsigned Bytes, int Dist, 12512 SelectionDAG &DAG) { 12513 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12514 EVT VT = LS->getMemoryVT(); 12515 SDValue Loc = LS->getBasePtr(); 12516 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12517 } 12518 12519 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12520 EVT VT; 12521 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12522 default: return false; 12523 case Intrinsic::ppc_altivec_lvx: 12524 case Intrinsic::ppc_altivec_lvxl: 12525 case Intrinsic::ppc_vsx_lxvw4x: 12526 case Intrinsic::ppc_vsx_lxvw4x_be: 12527 VT = MVT::v4i32; 12528 break; 12529 case Intrinsic::ppc_vsx_lxvd2x: 12530 case Intrinsic::ppc_vsx_lxvd2x_be: 12531 VT = MVT::v2f64; 12532 break; 12533 case Intrinsic::ppc_altivec_lvebx: 12534 VT = MVT::i8; 12535 break; 12536 case Intrinsic::ppc_altivec_lvehx: 12537 VT = MVT::i16; 12538 break; 12539 case Intrinsic::ppc_altivec_lvewx: 12540 VT = MVT::i32; 12541 break; 12542 } 12543 12544 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12545 } 12546 12547 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12548 EVT VT; 12549 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12550 default: return false; 12551 case Intrinsic::ppc_altivec_stvx: 12552 case Intrinsic::ppc_altivec_stvxl: 12553 case Intrinsic::ppc_vsx_stxvw4x: 12554 VT = MVT::v4i32; 12555 break; 12556 case Intrinsic::ppc_vsx_stxvd2x: 12557 VT = MVT::v2f64; 12558 break; 12559 case Intrinsic::ppc_vsx_stxvw4x_be: 12560 VT = MVT::v4i32; 12561 break; 12562 case Intrinsic::ppc_vsx_stxvd2x_be: 12563 VT = MVT::v2f64; 12564 break; 12565 case Intrinsic::ppc_altivec_stvebx: 12566 VT = MVT::i8; 12567 break; 12568 case Intrinsic::ppc_altivec_stvehx: 12569 VT = MVT::i16; 12570 break; 12571 case Intrinsic::ppc_altivec_stvewx: 12572 VT = MVT::i32; 12573 break; 12574 } 12575 12576 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12577 } 12578 12579 return false; 12580 } 12581 12582 // Return true is there is a nearyby consecutive load to the one provided 12583 // (regardless of alignment). We search up and down the chain, looking though 12584 // token factors and other loads (but nothing else). As a result, a true result 12585 // indicates that it is safe to create a new consecutive load adjacent to the 12586 // load provided. 12587 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12588 SDValue Chain = LD->getChain(); 12589 EVT VT = LD->getMemoryVT(); 12590 12591 SmallSet<SDNode *, 16> LoadRoots; 12592 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12593 SmallSet<SDNode *, 16> Visited; 12594 12595 // First, search up the chain, branching to follow all token-factor operands. 12596 // If we find a consecutive load, then we're done, otherwise, record all 12597 // nodes just above the top-level loads and token factors. 12598 while (!Queue.empty()) { 12599 SDNode *ChainNext = Queue.pop_back_val(); 12600 if (!Visited.insert(ChainNext).second) 12601 continue; 12602 12603 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12604 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12605 return true; 12606 12607 if (!Visited.count(ChainLD->getChain().getNode())) 12608 Queue.push_back(ChainLD->getChain().getNode()); 12609 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12610 for (const SDUse &O : ChainNext->ops()) 12611 if (!Visited.count(O.getNode())) 12612 Queue.push_back(O.getNode()); 12613 } else 12614 LoadRoots.insert(ChainNext); 12615 } 12616 12617 // Second, search down the chain, starting from the top-level nodes recorded 12618 // in the first phase. These top-level nodes are the nodes just above all 12619 // loads and token factors. Starting with their uses, recursively look though 12620 // all loads (just the chain uses) and token factors to find a consecutive 12621 // load. 12622 Visited.clear(); 12623 Queue.clear(); 12624 12625 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12626 IE = LoadRoots.end(); I != IE; ++I) { 12627 Queue.push_back(*I); 12628 12629 while (!Queue.empty()) { 12630 SDNode *LoadRoot = Queue.pop_back_val(); 12631 if (!Visited.insert(LoadRoot).second) 12632 continue; 12633 12634 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12635 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12636 return true; 12637 12638 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12639 UE = LoadRoot->use_end(); UI != UE; ++UI) 12640 if (((isa<MemSDNode>(*UI) && 12641 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12642 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12643 Queue.push_back(*UI); 12644 } 12645 } 12646 12647 return false; 12648 } 12649 12650 /// This function is called when we have proved that a SETCC node can be replaced 12651 /// by subtraction (and other supporting instructions) so that the result of 12652 /// comparison is kept in a GPR instead of CR. This function is purely for 12653 /// codegen purposes and has some flags to guide the codegen process. 12654 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12655 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12656 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12657 12658 // Zero extend the operands to the largest legal integer. Originally, they 12659 // must be of a strictly smaller size. 12660 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12661 DAG.getConstant(Size, DL, MVT::i32)); 12662 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12663 DAG.getConstant(Size, DL, MVT::i32)); 12664 12665 // Swap if needed. Depends on the condition code. 12666 if (Swap) 12667 std::swap(Op0, Op1); 12668 12669 // Subtract extended integers. 12670 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12671 12672 // Move the sign bit to the least significant position and zero out the rest. 12673 // Now the least significant bit carries the result of original comparison. 12674 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12675 DAG.getConstant(Size - 1, DL, MVT::i32)); 12676 auto Final = Shifted; 12677 12678 // Complement the result if needed. Based on the condition code. 12679 if (Complement) 12680 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12681 DAG.getConstant(1, DL, MVT::i64)); 12682 12683 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12684 } 12685 12686 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12687 DAGCombinerInfo &DCI) const { 12688 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12689 12690 SelectionDAG &DAG = DCI.DAG; 12691 SDLoc DL(N); 12692 12693 // Size of integers being compared has a critical role in the following 12694 // analysis, so we prefer to do this when all types are legal. 12695 if (!DCI.isAfterLegalizeDAG()) 12696 return SDValue(); 12697 12698 // If all users of SETCC extend its value to a legal integer type 12699 // then we replace SETCC with a subtraction 12700 for (SDNode::use_iterator UI = N->use_begin(), 12701 UE = N->use_end(); UI != UE; ++UI) { 12702 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12703 return SDValue(); 12704 } 12705 12706 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12707 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12708 12709 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12710 12711 if (OpSize < Size) { 12712 switch (CC) { 12713 default: break; 12714 case ISD::SETULT: 12715 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12716 case ISD::SETULE: 12717 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12718 case ISD::SETUGT: 12719 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12720 case ISD::SETUGE: 12721 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12722 } 12723 } 12724 12725 return SDValue(); 12726 } 12727 12728 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12729 DAGCombinerInfo &DCI) const { 12730 SelectionDAG &DAG = DCI.DAG; 12731 SDLoc dl(N); 12732 12733 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12734 // If we're tracking CR bits, we need to be careful that we don't have: 12735 // trunc(binary-ops(zext(x), zext(y))) 12736 // or 12737 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12738 // such that we're unnecessarily moving things into GPRs when it would be 12739 // better to keep them in CR bits. 12740 12741 // Note that trunc here can be an actual i1 trunc, or can be the effective 12742 // truncation that comes from a setcc or select_cc. 12743 if (N->getOpcode() == ISD::TRUNCATE && 12744 N->getValueType(0) != MVT::i1) 12745 return SDValue(); 12746 12747 if (N->getOperand(0).getValueType() != MVT::i32 && 12748 N->getOperand(0).getValueType() != MVT::i64) 12749 return SDValue(); 12750 12751 if (N->getOpcode() == ISD::SETCC || 12752 N->getOpcode() == ISD::SELECT_CC) { 12753 // If we're looking at a comparison, then we need to make sure that the 12754 // high bits (all except for the first) don't matter the result. 12755 ISD::CondCode CC = 12756 cast<CondCodeSDNode>(N->getOperand( 12757 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12758 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12759 12760 if (ISD::isSignedIntSetCC(CC)) { 12761 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12762 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12763 return SDValue(); 12764 } else if (ISD::isUnsignedIntSetCC(CC)) { 12765 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12766 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12767 !DAG.MaskedValueIsZero(N->getOperand(1), 12768 APInt::getHighBitsSet(OpBits, OpBits-1))) 12769 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12770 : SDValue()); 12771 } else { 12772 // This is neither a signed nor an unsigned comparison, just make sure 12773 // that the high bits are equal. 12774 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12775 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12776 12777 // We don't really care about what is known about the first bit (if 12778 // anything), so pretend that it is known zero for both to ensure they can 12779 // be compared as constants. 12780 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 12781 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 12782 12783 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 12784 Op1Known.getConstant() != Op2Known.getConstant()) 12785 return SDValue(); 12786 } 12787 } 12788 12789 // We now know that the higher-order bits are irrelevant, we just need to 12790 // make sure that all of the intermediate operations are bit operations, and 12791 // all inputs are extensions. 12792 if (N->getOperand(0).getOpcode() != ISD::AND && 12793 N->getOperand(0).getOpcode() != ISD::OR && 12794 N->getOperand(0).getOpcode() != ISD::XOR && 12795 N->getOperand(0).getOpcode() != ISD::SELECT && 12796 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12797 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12798 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12799 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12800 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12801 return SDValue(); 12802 12803 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12804 N->getOperand(1).getOpcode() != ISD::AND && 12805 N->getOperand(1).getOpcode() != ISD::OR && 12806 N->getOperand(1).getOpcode() != ISD::XOR && 12807 N->getOperand(1).getOpcode() != ISD::SELECT && 12808 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12809 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12810 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12811 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12812 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12813 return SDValue(); 12814 12815 SmallVector<SDValue, 4> Inputs; 12816 SmallVector<SDValue, 8> BinOps, PromOps; 12817 SmallPtrSet<SDNode *, 16> Visited; 12818 12819 for (unsigned i = 0; i < 2; ++i) { 12820 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12821 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12822 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12823 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12824 isa<ConstantSDNode>(N->getOperand(i))) 12825 Inputs.push_back(N->getOperand(i)); 12826 else 12827 BinOps.push_back(N->getOperand(i)); 12828 12829 if (N->getOpcode() == ISD::TRUNCATE) 12830 break; 12831 } 12832 12833 // Visit all inputs, collect all binary operations (and, or, xor and 12834 // select) that are all fed by extensions. 12835 while (!BinOps.empty()) { 12836 SDValue BinOp = BinOps.pop_back_val(); 12837 12838 if (!Visited.insert(BinOp.getNode()).second) 12839 continue; 12840 12841 PromOps.push_back(BinOp); 12842 12843 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12844 // The condition of the select is not promoted. 12845 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12846 continue; 12847 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12848 continue; 12849 12850 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12851 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12852 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12853 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12854 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12855 Inputs.push_back(BinOp.getOperand(i)); 12856 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12857 BinOp.getOperand(i).getOpcode() == ISD::OR || 12858 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12859 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12860 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12861 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12862 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12863 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12864 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12865 BinOps.push_back(BinOp.getOperand(i)); 12866 } else { 12867 // We have an input that is not an extension or another binary 12868 // operation; we'll abort this transformation. 12869 return SDValue(); 12870 } 12871 } 12872 } 12873 12874 // Make sure that this is a self-contained cluster of operations (which 12875 // is not quite the same thing as saying that everything has only one 12876 // use). 12877 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12878 if (isa<ConstantSDNode>(Inputs[i])) 12879 continue; 12880 12881 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12882 UE = Inputs[i].getNode()->use_end(); 12883 UI != UE; ++UI) { 12884 SDNode *User = *UI; 12885 if (User != N && !Visited.count(User)) 12886 return SDValue(); 12887 12888 // Make sure that we're not going to promote the non-output-value 12889 // operand(s) or SELECT or SELECT_CC. 12890 // FIXME: Although we could sometimes handle this, and it does occur in 12891 // practice that one of the condition inputs to the select is also one of 12892 // the outputs, we currently can't deal with this. 12893 if (User->getOpcode() == ISD::SELECT) { 12894 if (User->getOperand(0) == Inputs[i]) 12895 return SDValue(); 12896 } else if (User->getOpcode() == ISD::SELECT_CC) { 12897 if (User->getOperand(0) == Inputs[i] || 12898 User->getOperand(1) == Inputs[i]) 12899 return SDValue(); 12900 } 12901 } 12902 } 12903 12904 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12905 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12906 UE = PromOps[i].getNode()->use_end(); 12907 UI != UE; ++UI) { 12908 SDNode *User = *UI; 12909 if (User != N && !Visited.count(User)) 12910 return SDValue(); 12911 12912 // Make sure that we're not going to promote the non-output-value 12913 // operand(s) or SELECT or SELECT_CC. 12914 // FIXME: Although we could sometimes handle this, and it does occur in 12915 // practice that one of the condition inputs to the select is also one of 12916 // the outputs, we currently can't deal with this. 12917 if (User->getOpcode() == ISD::SELECT) { 12918 if (User->getOperand(0) == PromOps[i]) 12919 return SDValue(); 12920 } else if (User->getOpcode() == ISD::SELECT_CC) { 12921 if (User->getOperand(0) == PromOps[i] || 12922 User->getOperand(1) == PromOps[i]) 12923 return SDValue(); 12924 } 12925 } 12926 } 12927 12928 // Replace all inputs with the extension operand. 12929 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12930 // Constants may have users outside the cluster of to-be-promoted nodes, 12931 // and so we need to replace those as we do the promotions. 12932 if (isa<ConstantSDNode>(Inputs[i])) 12933 continue; 12934 else 12935 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12936 } 12937 12938 std::list<HandleSDNode> PromOpHandles; 12939 for (auto &PromOp : PromOps) 12940 PromOpHandles.emplace_back(PromOp); 12941 12942 // Replace all operations (these are all the same, but have a different 12943 // (i1) return type). DAG.getNode will validate that the types of 12944 // a binary operator match, so go through the list in reverse so that 12945 // we've likely promoted both operands first. Any intermediate truncations or 12946 // extensions disappear. 12947 while (!PromOpHandles.empty()) { 12948 SDValue PromOp = PromOpHandles.back().getValue(); 12949 PromOpHandles.pop_back(); 12950 12951 if (PromOp.getOpcode() == ISD::TRUNCATE || 12952 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12953 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12954 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12955 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12956 PromOp.getOperand(0).getValueType() != MVT::i1) { 12957 // The operand is not yet ready (see comment below). 12958 PromOpHandles.emplace_front(PromOp); 12959 continue; 12960 } 12961 12962 SDValue RepValue = PromOp.getOperand(0); 12963 if (isa<ConstantSDNode>(RepValue)) 12964 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12965 12966 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12967 continue; 12968 } 12969 12970 unsigned C; 12971 switch (PromOp.getOpcode()) { 12972 default: C = 0; break; 12973 case ISD::SELECT: C = 1; break; 12974 case ISD::SELECT_CC: C = 2; break; 12975 } 12976 12977 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12978 PromOp.getOperand(C).getValueType() != MVT::i1) || 12979 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12980 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12981 // The to-be-promoted operands of this node have not yet been 12982 // promoted (this should be rare because we're going through the 12983 // list backward, but if one of the operands has several users in 12984 // this cluster of to-be-promoted nodes, it is possible). 12985 PromOpHandles.emplace_front(PromOp); 12986 continue; 12987 } 12988 12989 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12990 PromOp.getNode()->op_end()); 12991 12992 // If there are any constant inputs, make sure they're replaced now. 12993 for (unsigned i = 0; i < 2; ++i) 12994 if (isa<ConstantSDNode>(Ops[C+i])) 12995 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12996 12997 DAG.ReplaceAllUsesOfValueWith(PromOp, 12998 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12999 } 13000 13001 // Now we're left with the initial truncation itself. 13002 if (N->getOpcode() == ISD::TRUNCATE) 13003 return N->getOperand(0); 13004 13005 // Otherwise, this is a comparison. The operands to be compared have just 13006 // changed type (to i1), but everything else is the same. 13007 return SDValue(N, 0); 13008 } 13009 13010 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13011 DAGCombinerInfo &DCI) const { 13012 SelectionDAG &DAG = DCI.DAG; 13013 SDLoc dl(N); 13014 13015 // If we're tracking CR bits, we need to be careful that we don't have: 13016 // zext(binary-ops(trunc(x), trunc(y))) 13017 // or 13018 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13019 // such that we're unnecessarily moving things into CR bits that can more 13020 // efficiently stay in GPRs. Note that if we're not certain that the high 13021 // bits are set as required by the final extension, we still may need to do 13022 // some masking to get the proper behavior. 13023 13024 // This same functionality is important on PPC64 when dealing with 13025 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13026 // the return values of functions. Because it is so similar, it is handled 13027 // here as well. 13028 13029 if (N->getValueType(0) != MVT::i32 && 13030 N->getValueType(0) != MVT::i64) 13031 return SDValue(); 13032 13033 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13034 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13035 return SDValue(); 13036 13037 if (N->getOperand(0).getOpcode() != ISD::AND && 13038 N->getOperand(0).getOpcode() != ISD::OR && 13039 N->getOperand(0).getOpcode() != ISD::XOR && 13040 N->getOperand(0).getOpcode() != ISD::SELECT && 13041 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13042 return SDValue(); 13043 13044 SmallVector<SDValue, 4> Inputs; 13045 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13046 SmallPtrSet<SDNode *, 16> Visited; 13047 13048 // Visit all inputs, collect all binary operations (and, or, xor and 13049 // select) that are all fed by truncations. 13050 while (!BinOps.empty()) { 13051 SDValue BinOp = BinOps.pop_back_val(); 13052 13053 if (!Visited.insert(BinOp.getNode()).second) 13054 continue; 13055 13056 PromOps.push_back(BinOp); 13057 13058 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13059 // The condition of the select is not promoted. 13060 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13061 continue; 13062 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13063 continue; 13064 13065 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13066 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13067 Inputs.push_back(BinOp.getOperand(i)); 13068 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13069 BinOp.getOperand(i).getOpcode() == ISD::OR || 13070 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13071 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13072 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13073 BinOps.push_back(BinOp.getOperand(i)); 13074 } else { 13075 // We have an input that is not a truncation or another binary 13076 // operation; we'll abort this transformation. 13077 return SDValue(); 13078 } 13079 } 13080 } 13081 13082 // The operands of a select that must be truncated when the select is 13083 // promoted because the operand is actually part of the to-be-promoted set. 13084 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13085 13086 // Make sure that this is a self-contained cluster of operations (which 13087 // is not quite the same thing as saying that everything has only one 13088 // use). 13089 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13090 if (isa<ConstantSDNode>(Inputs[i])) 13091 continue; 13092 13093 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13094 UE = Inputs[i].getNode()->use_end(); 13095 UI != UE; ++UI) { 13096 SDNode *User = *UI; 13097 if (User != N && !Visited.count(User)) 13098 return SDValue(); 13099 13100 // If we're going to promote the non-output-value operand(s) or SELECT or 13101 // SELECT_CC, record them for truncation. 13102 if (User->getOpcode() == ISD::SELECT) { 13103 if (User->getOperand(0) == Inputs[i]) 13104 SelectTruncOp[0].insert(std::make_pair(User, 13105 User->getOperand(0).getValueType())); 13106 } else if (User->getOpcode() == ISD::SELECT_CC) { 13107 if (User->getOperand(0) == Inputs[i]) 13108 SelectTruncOp[0].insert(std::make_pair(User, 13109 User->getOperand(0).getValueType())); 13110 if (User->getOperand(1) == Inputs[i]) 13111 SelectTruncOp[1].insert(std::make_pair(User, 13112 User->getOperand(1).getValueType())); 13113 } 13114 } 13115 } 13116 13117 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13118 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13119 UE = PromOps[i].getNode()->use_end(); 13120 UI != UE; ++UI) { 13121 SDNode *User = *UI; 13122 if (User != N && !Visited.count(User)) 13123 return SDValue(); 13124 13125 // If we're going to promote the non-output-value operand(s) or SELECT or 13126 // SELECT_CC, record them for truncation. 13127 if (User->getOpcode() == ISD::SELECT) { 13128 if (User->getOperand(0) == PromOps[i]) 13129 SelectTruncOp[0].insert(std::make_pair(User, 13130 User->getOperand(0).getValueType())); 13131 } else if (User->getOpcode() == ISD::SELECT_CC) { 13132 if (User->getOperand(0) == PromOps[i]) 13133 SelectTruncOp[0].insert(std::make_pair(User, 13134 User->getOperand(0).getValueType())); 13135 if (User->getOperand(1) == PromOps[i]) 13136 SelectTruncOp[1].insert(std::make_pair(User, 13137 User->getOperand(1).getValueType())); 13138 } 13139 } 13140 } 13141 13142 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13143 bool ReallyNeedsExt = false; 13144 if (N->getOpcode() != ISD::ANY_EXTEND) { 13145 // If all of the inputs are not already sign/zero extended, then 13146 // we'll still need to do that at the end. 13147 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13148 if (isa<ConstantSDNode>(Inputs[i])) 13149 continue; 13150 13151 unsigned OpBits = 13152 Inputs[i].getOperand(0).getValueSizeInBits(); 13153 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13154 13155 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13156 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13157 APInt::getHighBitsSet(OpBits, 13158 OpBits-PromBits))) || 13159 (N->getOpcode() == ISD::SIGN_EXTEND && 13160 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13161 (OpBits-(PromBits-1)))) { 13162 ReallyNeedsExt = true; 13163 break; 13164 } 13165 } 13166 } 13167 13168 // Replace all inputs, either with the truncation operand, or a 13169 // truncation or extension to the final output type. 13170 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13171 // Constant inputs need to be replaced with the to-be-promoted nodes that 13172 // use them because they might have users outside of the cluster of 13173 // promoted nodes. 13174 if (isa<ConstantSDNode>(Inputs[i])) 13175 continue; 13176 13177 SDValue InSrc = Inputs[i].getOperand(0); 13178 if (Inputs[i].getValueType() == N->getValueType(0)) 13179 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13180 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13181 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13182 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13183 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13184 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13185 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13186 else 13187 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13188 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13189 } 13190 13191 std::list<HandleSDNode> PromOpHandles; 13192 for (auto &PromOp : PromOps) 13193 PromOpHandles.emplace_back(PromOp); 13194 13195 // Replace all operations (these are all the same, but have a different 13196 // (promoted) return type). DAG.getNode will validate that the types of 13197 // a binary operator match, so go through the list in reverse so that 13198 // we've likely promoted both operands first. 13199 while (!PromOpHandles.empty()) { 13200 SDValue PromOp = PromOpHandles.back().getValue(); 13201 PromOpHandles.pop_back(); 13202 13203 unsigned C; 13204 switch (PromOp.getOpcode()) { 13205 default: C = 0; break; 13206 case ISD::SELECT: C = 1; break; 13207 case ISD::SELECT_CC: C = 2; break; 13208 } 13209 13210 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13211 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13212 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13213 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13214 // The to-be-promoted operands of this node have not yet been 13215 // promoted (this should be rare because we're going through the 13216 // list backward, but if one of the operands has several users in 13217 // this cluster of to-be-promoted nodes, it is possible). 13218 PromOpHandles.emplace_front(PromOp); 13219 continue; 13220 } 13221 13222 // For SELECT and SELECT_CC nodes, we do a similar check for any 13223 // to-be-promoted comparison inputs. 13224 if (PromOp.getOpcode() == ISD::SELECT || 13225 PromOp.getOpcode() == ISD::SELECT_CC) { 13226 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13227 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13228 (SelectTruncOp[1].count(PromOp.getNode()) && 13229 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13230 PromOpHandles.emplace_front(PromOp); 13231 continue; 13232 } 13233 } 13234 13235 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13236 PromOp.getNode()->op_end()); 13237 13238 // If this node has constant inputs, then they'll need to be promoted here. 13239 for (unsigned i = 0; i < 2; ++i) { 13240 if (!isa<ConstantSDNode>(Ops[C+i])) 13241 continue; 13242 if (Ops[C+i].getValueType() == N->getValueType(0)) 13243 continue; 13244 13245 if (N->getOpcode() == ISD::SIGN_EXTEND) 13246 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13247 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13248 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13249 else 13250 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13251 } 13252 13253 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13254 // truncate them again to the original value type. 13255 if (PromOp.getOpcode() == ISD::SELECT || 13256 PromOp.getOpcode() == ISD::SELECT_CC) { 13257 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13258 if (SI0 != SelectTruncOp[0].end()) 13259 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13260 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13261 if (SI1 != SelectTruncOp[1].end()) 13262 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13263 } 13264 13265 DAG.ReplaceAllUsesOfValueWith(PromOp, 13266 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13267 } 13268 13269 // Now we're left with the initial extension itself. 13270 if (!ReallyNeedsExt) 13271 return N->getOperand(0); 13272 13273 // To zero extend, just mask off everything except for the first bit (in the 13274 // i1 case). 13275 if (N->getOpcode() == ISD::ZERO_EXTEND) 13276 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13277 DAG.getConstant(APInt::getLowBitsSet( 13278 N->getValueSizeInBits(0), PromBits), 13279 dl, N->getValueType(0))); 13280 13281 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13282 "Invalid extension type"); 13283 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13284 SDValue ShiftCst = 13285 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13286 return DAG.getNode( 13287 ISD::SRA, dl, N->getValueType(0), 13288 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13289 ShiftCst); 13290 } 13291 13292 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13293 DAGCombinerInfo &DCI) const { 13294 assert(N->getOpcode() == ISD::SETCC && 13295 "Should be called with a SETCC node"); 13296 13297 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13298 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13299 SDValue LHS = N->getOperand(0); 13300 SDValue RHS = N->getOperand(1); 13301 13302 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13303 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13304 LHS.hasOneUse()) 13305 std::swap(LHS, RHS); 13306 13307 // x == 0-y --> x+y == 0 13308 // x != 0-y --> x+y != 0 13309 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13310 RHS.hasOneUse()) { 13311 SDLoc DL(N); 13312 SelectionDAG &DAG = DCI.DAG; 13313 EVT VT = N->getValueType(0); 13314 EVT OpVT = LHS.getValueType(); 13315 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13316 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13317 } 13318 } 13319 13320 return DAGCombineTruncBoolExt(N, DCI); 13321 } 13322 13323 // Is this an extending load from an f32 to an f64? 13324 static bool isFPExtLoad(SDValue Op) { 13325 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13326 return LD->getExtensionType() == ISD::EXTLOAD && 13327 Op.getValueType() == MVT::f64; 13328 return false; 13329 } 13330 13331 /// Reduces the number of fp-to-int conversion when building a vector. 13332 /// 13333 /// If this vector is built out of floating to integer conversions, 13334 /// transform it to a vector built out of floating point values followed by a 13335 /// single floating to integer conversion of the vector. 13336 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13337 /// becomes (fptosi (build_vector ($A, $B, ...))) 13338 SDValue PPCTargetLowering:: 13339 combineElementTruncationToVectorTruncation(SDNode *N, 13340 DAGCombinerInfo &DCI) const { 13341 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13342 "Should be called with a BUILD_VECTOR node"); 13343 13344 SelectionDAG &DAG = DCI.DAG; 13345 SDLoc dl(N); 13346 13347 SDValue FirstInput = N->getOperand(0); 13348 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13349 "The input operand must be an fp-to-int conversion."); 13350 13351 // This combine happens after legalization so the fp_to_[su]i nodes are 13352 // already converted to PPCSISD nodes. 13353 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13354 if (FirstConversion == PPCISD::FCTIDZ || 13355 FirstConversion == PPCISD::FCTIDUZ || 13356 FirstConversion == PPCISD::FCTIWZ || 13357 FirstConversion == PPCISD::FCTIWUZ) { 13358 bool IsSplat = true; 13359 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13360 FirstConversion == PPCISD::FCTIWUZ; 13361 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13362 SmallVector<SDValue, 4> Ops; 13363 EVT TargetVT = N->getValueType(0); 13364 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13365 SDValue NextOp = N->getOperand(i); 13366 if (NextOp.getOpcode() != PPCISD::MFVSR) 13367 return SDValue(); 13368 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13369 if (NextConversion != FirstConversion) 13370 return SDValue(); 13371 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13372 // This is not valid if the input was originally double precision. It is 13373 // also not profitable to do unless this is an extending load in which 13374 // case doing this combine will allow us to combine consecutive loads. 13375 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13376 return SDValue(); 13377 if (N->getOperand(i) != FirstInput) 13378 IsSplat = false; 13379 } 13380 13381 // If this is a splat, we leave it as-is since there will be only a single 13382 // fp-to-int conversion followed by a splat of the integer. This is better 13383 // for 32-bit and smaller ints and neutral for 64-bit ints. 13384 if (IsSplat) 13385 return SDValue(); 13386 13387 // Now that we know we have the right type of node, get its operands 13388 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13389 SDValue In = N->getOperand(i).getOperand(0); 13390 if (Is32Bit) { 13391 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13392 // here, we know that all inputs are extending loads so this is safe). 13393 if (In.isUndef()) 13394 Ops.push_back(DAG.getUNDEF(SrcVT)); 13395 else { 13396 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13397 MVT::f32, In.getOperand(0), 13398 DAG.getIntPtrConstant(1, dl)); 13399 Ops.push_back(Trunc); 13400 } 13401 } else 13402 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13403 } 13404 13405 unsigned Opcode; 13406 if (FirstConversion == PPCISD::FCTIDZ || 13407 FirstConversion == PPCISD::FCTIWZ) 13408 Opcode = ISD::FP_TO_SINT; 13409 else 13410 Opcode = ISD::FP_TO_UINT; 13411 13412 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13413 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13414 return DAG.getNode(Opcode, dl, TargetVT, BV); 13415 } 13416 return SDValue(); 13417 } 13418 13419 /// Reduce the number of loads when building a vector. 13420 /// 13421 /// Building a vector out of multiple loads can be converted to a load 13422 /// of the vector type if the loads are consecutive. If the loads are 13423 /// consecutive but in descending order, a shuffle is added at the end 13424 /// to reorder the vector. 13425 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13426 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13427 "Should be called with a BUILD_VECTOR node"); 13428 13429 SDLoc dl(N); 13430 13431 // Return early for non byte-sized type, as they can't be consecutive. 13432 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13433 return SDValue(); 13434 13435 bool InputsAreConsecutiveLoads = true; 13436 bool InputsAreReverseConsecutive = true; 13437 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13438 SDValue FirstInput = N->getOperand(0); 13439 bool IsRoundOfExtLoad = false; 13440 13441 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13442 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13443 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13444 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13445 } 13446 // Not a build vector of (possibly fp_rounded) loads. 13447 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13448 N->getNumOperands() == 1) 13449 return SDValue(); 13450 13451 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13452 // If any inputs are fp_round(extload), they all must be. 13453 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13454 return SDValue(); 13455 13456 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13457 N->getOperand(i); 13458 if (NextInput.getOpcode() != ISD::LOAD) 13459 return SDValue(); 13460 13461 SDValue PreviousInput = 13462 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13463 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13464 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13465 13466 // If any inputs are fp_round(extload), they all must be. 13467 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13468 return SDValue(); 13469 13470 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13471 InputsAreConsecutiveLoads = false; 13472 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13473 InputsAreReverseConsecutive = false; 13474 13475 // Exit early if the loads are neither consecutive nor reverse consecutive. 13476 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13477 return SDValue(); 13478 } 13479 13480 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13481 "The loads cannot be both consecutive and reverse consecutive."); 13482 13483 SDValue FirstLoadOp = 13484 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13485 SDValue LastLoadOp = 13486 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13487 N->getOperand(N->getNumOperands()-1); 13488 13489 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13490 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13491 if (InputsAreConsecutiveLoads) { 13492 assert(LD1 && "Input needs to be a LoadSDNode."); 13493 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13494 LD1->getBasePtr(), LD1->getPointerInfo(), 13495 LD1->getAlignment()); 13496 } 13497 if (InputsAreReverseConsecutive) { 13498 assert(LDL && "Input needs to be a LoadSDNode."); 13499 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13500 LDL->getBasePtr(), LDL->getPointerInfo(), 13501 LDL->getAlignment()); 13502 SmallVector<int, 16> Ops; 13503 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13504 Ops.push_back(i); 13505 13506 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13507 DAG.getUNDEF(N->getValueType(0)), Ops); 13508 } 13509 return SDValue(); 13510 } 13511 13512 // This function adds the required vector_shuffle needed to get 13513 // the elements of the vector extract in the correct position 13514 // as specified by the CorrectElems encoding. 13515 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13516 SDValue Input, uint64_t Elems, 13517 uint64_t CorrectElems) { 13518 SDLoc dl(N); 13519 13520 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13521 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13522 13523 // Knowing the element indices being extracted from the original 13524 // vector and the order in which they're being inserted, just put 13525 // them at element indices required for the instruction. 13526 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13527 if (DAG.getDataLayout().isLittleEndian()) 13528 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13529 else 13530 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13531 CorrectElems = CorrectElems >> 8; 13532 Elems = Elems >> 8; 13533 } 13534 13535 SDValue Shuffle = 13536 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13537 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13538 13539 EVT VT = N->getValueType(0); 13540 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13541 13542 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13543 Input.getValueType().getVectorElementType(), 13544 VT.getVectorNumElements()); 13545 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13546 DAG.getValueType(ExtVT)); 13547 } 13548 13549 // Look for build vector patterns where input operands come from sign 13550 // extended vector_extract elements of specific indices. If the correct indices 13551 // aren't used, add a vector shuffle to fix up the indices and create 13552 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13553 // during instruction selection. 13554 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13555 // This array encodes the indices that the vector sign extend instructions 13556 // extract from when extending from one type to another for both BE and LE. 13557 // The right nibble of each byte corresponds to the LE incides. 13558 // and the left nibble of each byte corresponds to the BE incides. 13559 // For example: 0x3074B8FC byte->word 13560 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13561 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13562 // For example: 0x000070F8 byte->double word 13563 // For LE: the allowed indices are: 0x0,0x8 13564 // For BE: the allowed indices are: 0x7,0xF 13565 uint64_t TargetElems[] = { 13566 0x3074B8FC, // b->w 13567 0x000070F8, // b->d 13568 0x10325476, // h->w 13569 0x00003074, // h->d 13570 0x00001032, // w->d 13571 }; 13572 13573 uint64_t Elems = 0; 13574 int Index; 13575 SDValue Input; 13576 13577 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13578 if (!Op) 13579 return false; 13580 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13581 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13582 return false; 13583 13584 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13585 // of the right width. 13586 SDValue Extract = Op.getOperand(0); 13587 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13588 Extract = Extract.getOperand(0); 13589 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13590 return false; 13591 13592 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13593 if (!ExtOp) 13594 return false; 13595 13596 Index = ExtOp->getZExtValue(); 13597 if (Input && Input != Extract.getOperand(0)) 13598 return false; 13599 13600 if (!Input) 13601 Input = Extract.getOperand(0); 13602 13603 Elems = Elems << 8; 13604 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13605 Elems |= Index; 13606 13607 return true; 13608 }; 13609 13610 // If the build vector operands aren't sign extended vector extracts, 13611 // of the same input vector, then return. 13612 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13613 if (!isSExtOfVecExtract(N->getOperand(i))) { 13614 return SDValue(); 13615 } 13616 } 13617 13618 // If the vector extract indicies are not correct, add the appropriate 13619 // vector_shuffle. 13620 int TgtElemArrayIdx; 13621 int InputSize = Input.getValueType().getScalarSizeInBits(); 13622 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13623 if (InputSize + OutputSize == 40) 13624 TgtElemArrayIdx = 0; 13625 else if (InputSize + OutputSize == 72) 13626 TgtElemArrayIdx = 1; 13627 else if (InputSize + OutputSize == 48) 13628 TgtElemArrayIdx = 2; 13629 else if (InputSize + OutputSize == 80) 13630 TgtElemArrayIdx = 3; 13631 else if (InputSize + OutputSize == 96) 13632 TgtElemArrayIdx = 4; 13633 else 13634 return SDValue(); 13635 13636 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13637 CorrectElems = DAG.getDataLayout().isLittleEndian() 13638 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13639 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13640 if (Elems != CorrectElems) { 13641 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13642 } 13643 13644 // Regular lowering will catch cases where a shuffle is not needed. 13645 return SDValue(); 13646 } 13647 13648 // Look for the pattern of a load from a narrow width to i128, feeding 13649 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13650 // (LXVRZX). This node represents a zero extending load that will be matched 13651 // to the Load VSX Vector Rightmost instructions. 13652 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13653 SDLoc DL(N); 13654 13655 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13656 if (N->getValueType(0) != MVT::v1i128) 13657 return SDValue(); 13658 13659 SDValue Operand = N->getOperand(0); 13660 // Proceed with the transformation if the operand to the BUILD_VECTOR 13661 // is a load instruction. 13662 if (Operand.getOpcode() != ISD::LOAD) 13663 return SDValue(); 13664 13665 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13666 EVT MemoryType = LD->getMemoryVT(); 13667 13668 // This transformation is only valid if the we are loading either a byte, 13669 // halfword, word, or doubleword. 13670 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13671 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13672 13673 // Ensure that the load from the narrow width is being zero extended to i128. 13674 if (!ValidLDType || 13675 (LD->getExtensionType() != ISD::ZEXTLOAD && 13676 LD->getExtensionType() != ISD::EXTLOAD)) 13677 return SDValue(); 13678 13679 SDValue LoadOps[] = { 13680 LD->getChain(), LD->getBasePtr(), 13681 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13682 13683 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13684 DAG.getVTList(MVT::v1i128, MVT::Other), 13685 LoadOps, MemoryType, LD->getMemOperand()); 13686 } 13687 13688 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13689 DAGCombinerInfo &DCI) const { 13690 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13691 "Should be called with a BUILD_VECTOR node"); 13692 13693 SelectionDAG &DAG = DCI.DAG; 13694 SDLoc dl(N); 13695 13696 if (!Subtarget.hasVSX()) 13697 return SDValue(); 13698 13699 // The target independent DAG combiner will leave a build_vector of 13700 // float-to-int conversions intact. We can generate MUCH better code for 13701 // a float-to-int conversion of a vector of floats. 13702 SDValue FirstInput = N->getOperand(0); 13703 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13704 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13705 if (Reduced) 13706 return Reduced; 13707 } 13708 13709 // If we're building a vector out of consecutive loads, just load that 13710 // vector type. 13711 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13712 if (Reduced) 13713 return Reduced; 13714 13715 // If we're building a vector out of extended elements from another vector 13716 // we have P9 vector integer extend instructions. The code assumes legal 13717 // input types (i.e. it can't handle things like v4i16) so do not run before 13718 // legalization. 13719 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13720 Reduced = combineBVOfVecSExt(N, DAG); 13721 if (Reduced) 13722 return Reduced; 13723 } 13724 13725 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13726 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13727 // is a load from <valid narrow width> to i128. 13728 if (Subtarget.isISA3_1()) { 13729 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13730 if (BVOfZLoad) 13731 return BVOfZLoad; 13732 } 13733 13734 if (N->getValueType(0) != MVT::v2f64) 13735 return SDValue(); 13736 13737 // Looking for: 13738 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13739 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13740 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13741 return SDValue(); 13742 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13743 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13744 return SDValue(); 13745 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13746 return SDValue(); 13747 13748 SDValue Ext1 = FirstInput.getOperand(0); 13749 SDValue Ext2 = N->getOperand(1).getOperand(0); 13750 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13751 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13752 return SDValue(); 13753 13754 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13755 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13756 if (!Ext1Op || !Ext2Op) 13757 return SDValue(); 13758 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13759 Ext1.getOperand(0) != Ext2.getOperand(0)) 13760 return SDValue(); 13761 13762 int FirstElem = Ext1Op->getZExtValue(); 13763 int SecondElem = Ext2Op->getZExtValue(); 13764 int SubvecIdx; 13765 if (FirstElem == 0 && SecondElem == 1) 13766 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13767 else if (FirstElem == 2 && SecondElem == 3) 13768 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13769 else 13770 return SDValue(); 13771 13772 SDValue SrcVec = Ext1.getOperand(0); 13773 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13774 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13775 return DAG.getNode(NodeType, dl, MVT::v2f64, 13776 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13777 } 13778 13779 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13780 DAGCombinerInfo &DCI) const { 13781 assert((N->getOpcode() == ISD::SINT_TO_FP || 13782 N->getOpcode() == ISD::UINT_TO_FP) && 13783 "Need an int -> FP conversion node here"); 13784 13785 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13786 return SDValue(); 13787 13788 SelectionDAG &DAG = DCI.DAG; 13789 SDLoc dl(N); 13790 SDValue Op(N, 0); 13791 13792 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13793 // from the hardware. 13794 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13795 return SDValue(); 13796 if (!Op.getOperand(0).getValueType().isSimple()) 13797 return SDValue(); 13798 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13799 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13800 return SDValue(); 13801 13802 SDValue FirstOperand(Op.getOperand(0)); 13803 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13804 (FirstOperand.getValueType() == MVT::i8 || 13805 FirstOperand.getValueType() == MVT::i16); 13806 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13807 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13808 bool DstDouble = Op.getValueType() == MVT::f64; 13809 unsigned ConvOp = Signed ? 13810 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13811 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13812 SDValue WidthConst = 13813 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13814 dl, false); 13815 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13816 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13817 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13818 DAG.getVTList(MVT::f64, MVT::Other), 13819 Ops, MVT::i8, LDN->getMemOperand()); 13820 13821 // For signed conversion, we need to sign-extend the value in the VSR 13822 if (Signed) { 13823 SDValue ExtOps[] = { Ld, WidthConst }; 13824 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13825 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13826 } else 13827 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13828 } 13829 13830 13831 // For i32 intermediate values, unfortunately, the conversion functions 13832 // leave the upper 32 bits of the value are undefined. Within the set of 13833 // scalar instructions, we have no method for zero- or sign-extending the 13834 // value. Thus, we cannot handle i32 intermediate values here. 13835 if (Op.getOperand(0).getValueType() == MVT::i32) 13836 return SDValue(); 13837 13838 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13839 "UINT_TO_FP is supported only with FPCVT"); 13840 13841 // If we have FCFIDS, then use it when converting to single-precision. 13842 // Otherwise, convert to double-precision and then round. 13843 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13844 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13845 : PPCISD::FCFIDS) 13846 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13847 : PPCISD::FCFID); 13848 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13849 ? MVT::f32 13850 : MVT::f64; 13851 13852 // If we're converting from a float, to an int, and back to a float again, 13853 // then we don't need the store/load pair at all. 13854 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13855 Subtarget.hasFPCVT()) || 13856 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13857 SDValue Src = Op.getOperand(0).getOperand(0); 13858 if (Src.getValueType() == MVT::f32) { 13859 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13860 DCI.AddToWorklist(Src.getNode()); 13861 } else if (Src.getValueType() != MVT::f64) { 13862 // Make sure that we don't pick up a ppc_fp128 source value. 13863 return SDValue(); 13864 } 13865 13866 unsigned FCTOp = 13867 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13868 PPCISD::FCTIDUZ; 13869 13870 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13871 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13872 13873 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13874 FP = DAG.getNode(ISD::FP_ROUND, dl, 13875 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13876 DCI.AddToWorklist(FP.getNode()); 13877 } 13878 13879 return FP; 13880 } 13881 13882 return SDValue(); 13883 } 13884 13885 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13886 // builtins) into loads with swaps. 13887 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13888 DAGCombinerInfo &DCI) const { 13889 SelectionDAG &DAG = DCI.DAG; 13890 SDLoc dl(N); 13891 SDValue Chain; 13892 SDValue Base; 13893 MachineMemOperand *MMO; 13894 13895 switch (N->getOpcode()) { 13896 default: 13897 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13898 case ISD::LOAD: { 13899 LoadSDNode *LD = cast<LoadSDNode>(N); 13900 Chain = LD->getChain(); 13901 Base = LD->getBasePtr(); 13902 MMO = LD->getMemOperand(); 13903 // If the MMO suggests this isn't a load of a full vector, leave 13904 // things alone. For a built-in, we have to make the change for 13905 // correctness, so if there is a size problem that will be a bug. 13906 if (MMO->getSize() < 16) 13907 return SDValue(); 13908 break; 13909 } 13910 case ISD::INTRINSIC_W_CHAIN: { 13911 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13912 Chain = Intrin->getChain(); 13913 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13914 // us what we want. Get operand 2 instead. 13915 Base = Intrin->getOperand(2); 13916 MMO = Intrin->getMemOperand(); 13917 break; 13918 } 13919 } 13920 13921 MVT VecTy = N->getValueType(0).getSimpleVT(); 13922 13923 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13924 // aligned and the type is a vector with elements up to 4 bytes 13925 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13926 VecTy.getScalarSizeInBits() <= 32) { 13927 return SDValue(); 13928 } 13929 13930 SDValue LoadOps[] = { Chain, Base }; 13931 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13932 DAG.getVTList(MVT::v2f64, MVT::Other), 13933 LoadOps, MVT::v2f64, MMO); 13934 13935 DCI.AddToWorklist(Load.getNode()); 13936 Chain = Load.getValue(1); 13937 SDValue Swap = DAG.getNode( 13938 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13939 DCI.AddToWorklist(Swap.getNode()); 13940 13941 // Add a bitcast if the resulting load type doesn't match v2f64. 13942 if (VecTy != MVT::v2f64) { 13943 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13944 DCI.AddToWorklist(N.getNode()); 13945 // Package {bitcast value, swap's chain} to match Load's shape. 13946 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13947 N, Swap.getValue(1)); 13948 } 13949 13950 return Swap; 13951 } 13952 13953 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13954 // builtins) into stores with swaps. 13955 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13956 DAGCombinerInfo &DCI) const { 13957 SelectionDAG &DAG = DCI.DAG; 13958 SDLoc dl(N); 13959 SDValue Chain; 13960 SDValue Base; 13961 unsigned SrcOpnd; 13962 MachineMemOperand *MMO; 13963 13964 switch (N->getOpcode()) { 13965 default: 13966 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13967 case ISD::STORE: { 13968 StoreSDNode *ST = cast<StoreSDNode>(N); 13969 Chain = ST->getChain(); 13970 Base = ST->getBasePtr(); 13971 MMO = ST->getMemOperand(); 13972 SrcOpnd = 1; 13973 // If the MMO suggests this isn't a store of a full vector, leave 13974 // things alone. For a built-in, we have to make the change for 13975 // correctness, so if there is a size problem that will be a bug. 13976 if (MMO->getSize() < 16) 13977 return SDValue(); 13978 break; 13979 } 13980 case ISD::INTRINSIC_VOID: { 13981 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13982 Chain = Intrin->getChain(); 13983 // Intrin->getBasePtr() oddly does not get what we want. 13984 Base = Intrin->getOperand(3); 13985 MMO = Intrin->getMemOperand(); 13986 SrcOpnd = 2; 13987 break; 13988 } 13989 } 13990 13991 SDValue Src = N->getOperand(SrcOpnd); 13992 MVT VecTy = Src.getValueType().getSimpleVT(); 13993 13994 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13995 // aligned and the type is a vector with elements up to 4 bytes 13996 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13997 VecTy.getScalarSizeInBits() <= 32) { 13998 return SDValue(); 13999 } 14000 14001 // All stores are done as v2f64 and possible bit cast. 14002 if (VecTy != MVT::v2f64) { 14003 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14004 DCI.AddToWorklist(Src.getNode()); 14005 } 14006 14007 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14008 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14009 DCI.AddToWorklist(Swap.getNode()); 14010 Chain = Swap.getValue(1); 14011 SDValue StoreOps[] = { Chain, Swap, Base }; 14012 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14013 DAG.getVTList(MVT::Other), 14014 StoreOps, VecTy, MMO); 14015 DCI.AddToWorklist(Store.getNode()); 14016 return Store; 14017 } 14018 14019 // Handle DAG combine for STORE (FP_TO_INT F). 14020 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14021 DAGCombinerInfo &DCI) const { 14022 14023 SelectionDAG &DAG = DCI.DAG; 14024 SDLoc dl(N); 14025 unsigned Opcode = N->getOperand(1).getOpcode(); 14026 14027 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14028 && "Not a FP_TO_INT Instruction!"); 14029 14030 SDValue Val = N->getOperand(1).getOperand(0); 14031 EVT Op1VT = N->getOperand(1).getValueType(); 14032 EVT ResVT = Val.getValueType(); 14033 14034 if (!isTypeLegal(ResVT)) 14035 return SDValue(); 14036 14037 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14038 bool ValidTypeForStoreFltAsInt = 14039 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14040 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14041 14042 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14043 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14044 return SDValue(); 14045 14046 // Extend f32 values to f64 14047 if (ResVT.getScalarSizeInBits() == 32) { 14048 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14049 DCI.AddToWorklist(Val.getNode()); 14050 } 14051 14052 // Set signed or unsigned conversion opcode. 14053 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14054 PPCISD::FP_TO_SINT_IN_VSR : 14055 PPCISD::FP_TO_UINT_IN_VSR; 14056 14057 Val = DAG.getNode(ConvOpcode, 14058 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14059 DCI.AddToWorklist(Val.getNode()); 14060 14061 // Set number of bytes being converted. 14062 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14063 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14064 DAG.getIntPtrConstant(ByteSize, dl, false), 14065 DAG.getValueType(Op1VT) }; 14066 14067 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14068 DAG.getVTList(MVT::Other), Ops, 14069 cast<StoreSDNode>(N)->getMemoryVT(), 14070 cast<StoreSDNode>(N)->getMemOperand()); 14071 14072 DCI.AddToWorklist(Val.getNode()); 14073 return Val; 14074 } 14075 14076 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14077 // Check that the source of the element keeps flipping 14078 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14079 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14080 for (int i = 1, e = Mask.size(); i < e; i++) { 14081 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14082 return false; 14083 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14084 return false; 14085 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14086 } 14087 return true; 14088 } 14089 14090 static bool isSplatBV(SDValue Op) { 14091 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14092 return false; 14093 SDValue FirstOp; 14094 14095 // Find first non-undef input. 14096 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14097 FirstOp = Op.getOperand(i); 14098 if (!FirstOp.isUndef()) 14099 break; 14100 } 14101 14102 // All inputs are undef or the same as the first non-undef input. 14103 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14104 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14105 return false; 14106 return true; 14107 } 14108 14109 static SDValue isScalarToVec(SDValue Op) { 14110 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14111 return Op; 14112 if (Op.getOpcode() != ISD::BITCAST) 14113 return SDValue(); 14114 Op = Op.getOperand(0); 14115 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14116 return Op; 14117 return SDValue(); 14118 } 14119 14120 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14121 int LHSMaxIdx, int RHSMinIdx, 14122 int RHSMaxIdx, int HalfVec) { 14123 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14124 int Idx = ShuffV[i]; 14125 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14126 ShuffV[i] += HalfVec; 14127 } 14128 } 14129 14130 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14131 // the original is: 14132 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14133 // In such a case, just change the shuffle mask to extract the element 14134 // from the permuted index. 14135 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14136 SDLoc dl(OrigSToV); 14137 EVT VT = OrigSToV.getValueType(); 14138 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14139 "Expecting a SCALAR_TO_VECTOR here"); 14140 SDValue Input = OrigSToV.getOperand(0); 14141 14142 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14143 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14144 SDValue OrigVector = Input.getOperand(0); 14145 14146 // Can't handle non-const element indices or different vector types 14147 // for the input to the extract and the output of the scalar_to_vector. 14148 if (Idx && VT == OrigVector.getValueType()) { 14149 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14150 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14151 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14152 } 14153 } 14154 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14155 OrigSToV.getOperand(0)); 14156 } 14157 14158 // On little endian subtargets, combine shuffles such as: 14159 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14160 // into: 14161 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14162 // because the latter can be matched to a single instruction merge. 14163 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14164 // to put the value into element zero. Adjust the shuffle mask so that the 14165 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14166 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14167 SelectionDAG &DAG) const { 14168 SDValue LHS = SVN->getOperand(0); 14169 SDValue RHS = SVN->getOperand(1); 14170 auto Mask = SVN->getMask(); 14171 int NumElts = LHS.getValueType().getVectorNumElements(); 14172 SDValue Res(SVN, 0); 14173 SDLoc dl(SVN); 14174 14175 // None of these combines are useful on big endian systems since the ISA 14176 // already has a big endian bias. 14177 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14178 return Res; 14179 14180 // If this is not a shuffle of a shuffle and the first element comes from 14181 // the second vector, canonicalize to the commuted form. This will make it 14182 // more likely to match one of the single instruction patterns. 14183 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14184 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14185 std::swap(LHS, RHS); 14186 Res = DAG.getCommutedVectorShuffle(*SVN); 14187 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14188 } 14189 14190 // Adjust the shuffle mask if either input vector comes from a 14191 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14192 // form (to prevent the need for a swap). 14193 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14194 SDValue SToVLHS = isScalarToVec(LHS); 14195 SDValue SToVRHS = isScalarToVec(RHS); 14196 if (SToVLHS || SToVRHS) { 14197 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14198 : SToVRHS.getValueType().getVectorNumElements(); 14199 int NumEltsOut = ShuffV.size(); 14200 14201 // Initially assume that neither input is permuted. These will be adjusted 14202 // accordingly if either input is. 14203 int LHSMaxIdx = -1; 14204 int RHSMinIdx = -1; 14205 int RHSMaxIdx = -1; 14206 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14207 14208 // Get the permuted scalar to vector nodes for the source(s) that come from 14209 // ISD::SCALAR_TO_VECTOR. 14210 if (SToVLHS) { 14211 // Set up the values for the shuffle vector fixup. 14212 LHSMaxIdx = NumEltsOut / NumEltsIn; 14213 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14214 if (SToVLHS.getValueType() != LHS.getValueType()) 14215 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14216 LHS = SToVLHS; 14217 } 14218 if (SToVRHS) { 14219 RHSMinIdx = NumEltsOut; 14220 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14221 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14222 if (SToVRHS.getValueType() != RHS.getValueType()) 14223 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14224 RHS = SToVRHS; 14225 } 14226 14227 // Fix up the shuffle mask to reflect where the desired element actually is. 14228 // The minimum and maximum indices that correspond to element zero for both 14229 // the LHS and RHS are computed and will control which shuffle mask entries 14230 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14231 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14232 // HalfVec to refer to the corresponding element in the permuted vector. 14233 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14234 HalfVec); 14235 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14236 14237 // We may have simplified away the shuffle. We won't be able to do anything 14238 // further with it here. 14239 if (!isa<ShuffleVectorSDNode>(Res)) 14240 return Res; 14241 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14242 } 14243 14244 // The common case after we commuted the shuffle is that the RHS is a splat 14245 // and we have elements coming in from the splat at indices that are not 14246 // conducive to using a merge. 14247 // Example: 14248 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14249 if (!isSplatBV(RHS)) 14250 return Res; 14251 14252 // We are looking for a mask such that all even elements are from 14253 // one vector and all odd elements from the other. 14254 if (!isAlternatingShuffMask(Mask, NumElts)) 14255 return Res; 14256 14257 // Adjust the mask so we are pulling in the same index from the splat 14258 // as the index from the interesting vector in consecutive elements. 14259 // Example (even elements from first vector): 14260 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14261 if (Mask[0] < NumElts) 14262 for (int i = 1, e = Mask.size(); i < e; i += 2) 14263 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14264 // Example (odd elements from first vector): 14265 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14266 else 14267 for (int i = 0, e = Mask.size(); i < e; i += 2) 14268 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14269 14270 // If the RHS has undefs, we need to remove them since we may have created 14271 // a shuffle that adds those instead of the splat value. 14272 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14273 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14274 14275 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14276 return Res; 14277 } 14278 14279 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14280 LSBaseSDNode *LSBase, 14281 DAGCombinerInfo &DCI) const { 14282 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14283 "Not a reverse memop pattern!"); 14284 14285 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14286 auto Mask = SVN->getMask(); 14287 int i = 0; 14288 auto I = Mask.rbegin(); 14289 auto E = Mask.rend(); 14290 14291 for (; I != E; ++I) { 14292 if (*I != i) 14293 return false; 14294 i++; 14295 } 14296 return true; 14297 }; 14298 14299 SelectionDAG &DAG = DCI.DAG; 14300 EVT VT = SVN->getValueType(0); 14301 14302 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14303 return SDValue(); 14304 14305 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14306 // See comment in PPCVSXSwapRemoval.cpp. 14307 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14308 if (!Subtarget.hasP9Vector()) 14309 return SDValue(); 14310 14311 if(!IsElementReverse(SVN)) 14312 return SDValue(); 14313 14314 if (LSBase->getOpcode() == ISD::LOAD) { 14315 SDLoc dl(SVN); 14316 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14317 return DAG.getMemIntrinsicNode( 14318 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14319 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14320 } 14321 14322 if (LSBase->getOpcode() == ISD::STORE) { 14323 SDLoc dl(LSBase); 14324 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14325 LSBase->getBasePtr()}; 14326 return DAG.getMemIntrinsicNode( 14327 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14328 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14329 } 14330 14331 llvm_unreachable("Expected a load or store node here"); 14332 } 14333 14334 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14335 DAGCombinerInfo &DCI) const { 14336 SelectionDAG &DAG = DCI.DAG; 14337 SDLoc dl(N); 14338 switch (N->getOpcode()) { 14339 default: break; 14340 case ISD::ADD: 14341 return combineADD(N, DCI); 14342 case ISD::SHL: 14343 return combineSHL(N, DCI); 14344 case ISD::SRA: 14345 return combineSRA(N, DCI); 14346 case ISD::SRL: 14347 return combineSRL(N, DCI); 14348 case ISD::MUL: 14349 return combineMUL(N, DCI); 14350 case ISD::FMA: 14351 case PPCISD::FNMSUB: 14352 return combineFMALike(N, DCI); 14353 case PPCISD::SHL: 14354 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14355 return N->getOperand(0); 14356 break; 14357 case PPCISD::SRL: 14358 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14359 return N->getOperand(0); 14360 break; 14361 case PPCISD::SRA: 14362 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14363 if (C->isNullValue() || // 0 >>s V -> 0. 14364 C->isAllOnesValue()) // -1 >>s V -> -1. 14365 return N->getOperand(0); 14366 } 14367 break; 14368 case ISD::SIGN_EXTEND: 14369 case ISD::ZERO_EXTEND: 14370 case ISD::ANY_EXTEND: 14371 return DAGCombineExtBoolTrunc(N, DCI); 14372 case ISD::TRUNCATE: 14373 return combineTRUNCATE(N, DCI); 14374 case ISD::SETCC: 14375 if (SDValue CSCC = combineSetCC(N, DCI)) 14376 return CSCC; 14377 LLVM_FALLTHROUGH; 14378 case ISD::SELECT_CC: 14379 return DAGCombineTruncBoolExt(N, DCI); 14380 case ISD::SINT_TO_FP: 14381 case ISD::UINT_TO_FP: 14382 return combineFPToIntToFP(N, DCI); 14383 case ISD::VECTOR_SHUFFLE: 14384 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14385 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14386 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14387 } 14388 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14389 case ISD::STORE: { 14390 14391 EVT Op1VT = N->getOperand(1).getValueType(); 14392 unsigned Opcode = N->getOperand(1).getOpcode(); 14393 14394 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14395 SDValue Val= combineStoreFPToInt(N, DCI); 14396 if (Val) 14397 return Val; 14398 } 14399 14400 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14401 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14402 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14403 if (Val) 14404 return Val; 14405 } 14406 14407 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14408 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14409 N->getOperand(1).getNode()->hasOneUse() && 14410 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14411 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14412 14413 // STBRX can only handle simple types and it makes no sense to store less 14414 // two bytes in byte-reversed order. 14415 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14416 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14417 break; 14418 14419 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14420 // Do an any-extend to 32-bits if this is a half-word input. 14421 if (BSwapOp.getValueType() == MVT::i16) 14422 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14423 14424 // If the type of BSWAP operand is wider than stored memory width 14425 // it need to be shifted to the right side before STBRX. 14426 if (Op1VT.bitsGT(mVT)) { 14427 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14428 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14429 DAG.getConstant(Shift, dl, MVT::i32)); 14430 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14431 if (Op1VT == MVT::i64) 14432 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14433 } 14434 14435 SDValue Ops[] = { 14436 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14437 }; 14438 return 14439 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14440 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14441 cast<StoreSDNode>(N)->getMemOperand()); 14442 } 14443 14444 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14445 // So it can increase the chance of CSE constant construction. 14446 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14447 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14448 // Need to sign-extended to 64-bits to handle negative values. 14449 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14450 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14451 MemVT.getSizeInBits()); 14452 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14453 14454 // DAG.getTruncStore() can't be used here because it doesn't accept 14455 // the general (base + offset) addressing mode. 14456 // So we use UpdateNodeOperands and setTruncatingStore instead. 14457 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14458 N->getOperand(3)); 14459 cast<StoreSDNode>(N)->setTruncatingStore(true); 14460 return SDValue(N, 0); 14461 } 14462 14463 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14464 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14465 if (Op1VT.isSimple()) { 14466 MVT StoreVT = Op1VT.getSimpleVT(); 14467 if (Subtarget.needsSwapsForVSXMemOps() && 14468 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14469 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14470 return expandVSXStoreForLE(N, DCI); 14471 } 14472 break; 14473 } 14474 case ISD::LOAD: { 14475 LoadSDNode *LD = cast<LoadSDNode>(N); 14476 EVT VT = LD->getValueType(0); 14477 14478 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14479 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14480 if (VT.isSimple()) { 14481 MVT LoadVT = VT.getSimpleVT(); 14482 if (Subtarget.needsSwapsForVSXMemOps() && 14483 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14484 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14485 return expandVSXLoadForLE(N, DCI); 14486 } 14487 14488 // We sometimes end up with a 64-bit integer load, from which we extract 14489 // two single-precision floating-point numbers. This happens with 14490 // std::complex<float>, and other similar structures, because of the way we 14491 // canonicalize structure copies. However, if we lack direct moves, 14492 // then the final bitcasts from the extracted integer values to the 14493 // floating-point numbers turn into store/load pairs. Even with direct moves, 14494 // just loading the two floating-point numbers is likely better. 14495 auto ReplaceTwoFloatLoad = [&]() { 14496 if (VT != MVT::i64) 14497 return false; 14498 14499 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14500 LD->isVolatile()) 14501 return false; 14502 14503 // We're looking for a sequence like this: 14504 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14505 // t16: i64 = srl t13, Constant:i32<32> 14506 // t17: i32 = truncate t16 14507 // t18: f32 = bitcast t17 14508 // t19: i32 = truncate t13 14509 // t20: f32 = bitcast t19 14510 14511 if (!LD->hasNUsesOfValue(2, 0)) 14512 return false; 14513 14514 auto UI = LD->use_begin(); 14515 while (UI.getUse().getResNo() != 0) ++UI; 14516 SDNode *Trunc = *UI++; 14517 while (UI.getUse().getResNo() != 0) ++UI; 14518 SDNode *RightShift = *UI; 14519 if (Trunc->getOpcode() != ISD::TRUNCATE) 14520 std::swap(Trunc, RightShift); 14521 14522 if (Trunc->getOpcode() != ISD::TRUNCATE || 14523 Trunc->getValueType(0) != MVT::i32 || 14524 !Trunc->hasOneUse()) 14525 return false; 14526 if (RightShift->getOpcode() != ISD::SRL || 14527 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14528 RightShift->getConstantOperandVal(1) != 32 || 14529 !RightShift->hasOneUse()) 14530 return false; 14531 14532 SDNode *Trunc2 = *RightShift->use_begin(); 14533 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14534 Trunc2->getValueType(0) != MVT::i32 || 14535 !Trunc2->hasOneUse()) 14536 return false; 14537 14538 SDNode *Bitcast = *Trunc->use_begin(); 14539 SDNode *Bitcast2 = *Trunc2->use_begin(); 14540 14541 if (Bitcast->getOpcode() != ISD::BITCAST || 14542 Bitcast->getValueType(0) != MVT::f32) 14543 return false; 14544 if (Bitcast2->getOpcode() != ISD::BITCAST || 14545 Bitcast2->getValueType(0) != MVT::f32) 14546 return false; 14547 14548 if (Subtarget.isLittleEndian()) 14549 std::swap(Bitcast, Bitcast2); 14550 14551 // Bitcast has the second float (in memory-layout order) and Bitcast2 14552 // has the first one. 14553 14554 SDValue BasePtr = LD->getBasePtr(); 14555 if (LD->isIndexed()) { 14556 assert(LD->getAddressingMode() == ISD::PRE_INC && 14557 "Non-pre-inc AM on PPC?"); 14558 BasePtr = 14559 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14560 LD->getOffset()); 14561 } 14562 14563 auto MMOFlags = 14564 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14565 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14566 LD->getPointerInfo(), LD->getAlignment(), 14567 MMOFlags, LD->getAAInfo()); 14568 SDValue AddPtr = 14569 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14570 BasePtr, DAG.getIntPtrConstant(4, dl)); 14571 SDValue FloatLoad2 = DAG.getLoad( 14572 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14573 LD->getPointerInfo().getWithOffset(4), 14574 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14575 14576 if (LD->isIndexed()) { 14577 // Note that DAGCombine should re-form any pre-increment load(s) from 14578 // what is produced here if that makes sense. 14579 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14580 } 14581 14582 DCI.CombineTo(Bitcast2, FloatLoad); 14583 DCI.CombineTo(Bitcast, FloatLoad2); 14584 14585 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14586 SDValue(FloatLoad2.getNode(), 1)); 14587 return true; 14588 }; 14589 14590 if (ReplaceTwoFloatLoad()) 14591 return SDValue(N, 0); 14592 14593 EVT MemVT = LD->getMemoryVT(); 14594 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14595 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14596 if (LD->isUnindexed() && VT.isVector() && 14597 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14598 // P8 and later hardware should just use LOAD. 14599 !Subtarget.hasP8Vector() && 14600 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14601 VT == MVT::v4f32))) && 14602 LD->getAlign() < ABIAlignment) { 14603 // This is a type-legal unaligned Altivec load. 14604 SDValue Chain = LD->getChain(); 14605 SDValue Ptr = LD->getBasePtr(); 14606 bool isLittleEndian = Subtarget.isLittleEndian(); 14607 14608 // This implements the loading of unaligned vectors as described in 14609 // the venerable Apple Velocity Engine overview. Specifically: 14610 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14611 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14612 // 14613 // The general idea is to expand a sequence of one or more unaligned 14614 // loads into an alignment-based permutation-control instruction (lvsl 14615 // or lvsr), a series of regular vector loads (which always truncate 14616 // their input address to an aligned address), and a series of 14617 // permutations. The results of these permutations are the requested 14618 // loaded values. The trick is that the last "extra" load is not taken 14619 // from the address you might suspect (sizeof(vector) bytes after the 14620 // last requested load), but rather sizeof(vector) - 1 bytes after the 14621 // last requested vector. The point of this is to avoid a page fault if 14622 // the base address happened to be aligned. This works because if the 14623 // base address is aligned, then adding less than a full vector length 14624 // will cause the last vector in the sequence to be (re)loaded. 14625 // Otherwise, the next vector will be fetched as you might suspect was 14626 // necessary. 14627 14628 // We might be able to reuse the permutation generation from 14629 // a different base address offset from this one by an aligned amount. 14630 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14631 // optimization later. 14632 Intrinsic::ID Intr, IntrLD, IntrPerm; 14633 MVT PermCntlTy, PermTy, LDTy; 14634 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14635 : Intrinsic::ppc_altivec_lvsl; 14636 IntrLD = Intrinsic::ppc_altivec_lvx; 14637 IntrPerm = Intrinsic::ppc_altivec_vperm; 14638 PermCntlTy = MVT::v16i8; 14639 PermTy = MVT::v4i32; 14640 LDTy = MVT::v4i32; 14641 14642 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14643 14644 // Create the new MMO for the new base load. It is like the original MMO, 14645 // but represents an area in memory almost twice the vector size centered 14646 // on the original address. If the address is unaligned, we might start 14647 // reading up to (sizeof(vector)-1) bytes below the address of the 14648 // original unaligned load. 14649 MachineFunction &MF = DAG.getMachineFunction(); 14650 MachineMemOperand *BaseMMO = 14651 MF.getMachineMemOperand(LD->getMemOperand(), 14652 -(long)MemVT.getStoreSize()+1, 14653 2*MemVT.getStoreSize()-1); 14654 14655 // Create the new base load. 14656 SDValue LDXIntID = 14657 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14658 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14659 SDValue BaseLoad = 14660 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14661 DAG.getVTList(PermTy, MVT::Other), 14662 BaseLoadOps, LDTy, BaseMMO); 14663 14664 // Note that the value of IncOffset (which is provided to the next 14665 // load's pointer info offset value, and thus used to calculate the 14666 // alignment), and the value of IncValue (which is actually used to 14667 // increment the pointer value) are different! This is because we 14668 // require the next load to appear to be aligned, even though it 14669 // is actually offset from the base pointer by a lesser amount. 14670 int IncOffset = VT.getSizeInBits() / 8; 14671 int IncValue = IncOffset; 14672 14673 // Walk (both up and down) the chain looking for another load at the real 14674 // (aligned) offset (the alignment of the other load does not matter in 14675 // this case). If found, then do not use the offset reduction trick, as 14676 // that will prevent the loads from being later combined (as they would 14677 // otherwise be duplicates). 14678 if (!findConsecutiveLoad(LD, DAG)) 14679 --IncValue; 14680 14681 SDValue Increment = 14682 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14683 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14684 14685 MachineMemOperand *ExtraMMO = 14686 MF.getMachineMemOperand(LD->getMemOperand(), 14687 1, 2*MemVT.getStoreSize()-1); 14688 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14689 SDValue ExtraLoad = 14690 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14691 DAG.getVTList(PermTy, MVT::Other), 14692 ExtraLoadOps, LDTy, ExtraMMO); 14693 14694 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14695 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14696 14697 // Because vperm has a big-endian bias, we must reverse the order 14698 // of the input vectors and complement the permute control vector 14699 // when generating little endian code. We have already handled the 14700 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14701 // and ExtraLoad here. 14702 SDValue Perm; 14703 if (isLittleEndian) 14704 Perm = BuildIntrinsicOp(IntrPerm, 14705 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14706 else 14707 Perm = BuildIntrinsicOp(IntrPerm, 14708 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14709 14710 if (VT != PermTy) 14711 Perm = Subtarget.hasAltivec() 14712 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14713 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14714 DAG.getTargetConstant(1, dl, MVT::i64)); 14715 // second argument is 1 because this rounding 14716 // is always exact. 14717 14718 // The output of the permutation is our loaded result, the TokenFactor is 14719 // our new chain. 14720 DCI.CombineTo(N, Perm, TF); 14721 return SDValue(N, 0); 14722 } 14723 } 14724 break; 14725 case ISD::INTRINSIC_WO_CHAIN: { 14726 bool isLittleEndian = Subtarget.isLittleEndian(); 14727 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14728 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14729 : Intrinsic::ppc_altivec_lvsl); 14730 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14731 SDValue Add = N->getOperand(1); 14732 14733 int Bits = 4 /* 16 byte alignment */; 14734 14735 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14736 APInt::getAllOnesValue(Bits /* alignment */) 14737 .zext(Add.getScalarValueSizeInBits()))) { 14738 SDNode *BasePtr = Add->getOperand(0).getNode(); 14739 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14740 UE = BasePtr->use_end(); 14741 UI != UE; ++UI) { 14742 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14743 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14744 IID) { 14745 // We've found another LVSL/LVSR, and this address is an aligned 14746 // multiple of that one. The results will be the same, so use the 14747 // one we've just found instead. 14748 14749 return SDValue(*UI, 0); 14750 } 14751 } 14752 } 14753 14754 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14755 SDNode *BasePtr = Add->getOperand(0).getNode(); 14756 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14757 UE = BasePtr->use_end(); UI != UE; ++UI) { 14758 if (UI->getOpcode() == ISD::ADD && 14759 isa<ConstantSDNode>(UI->getOperand(1)) && 14760 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14761 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14762 (1ULL << Bits) == 0) { 14763 SDNode *OtherAdd = *UI; 14764 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14765 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14766 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14767 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14768 return SDValue(*VI, 0); 14769 } 14770 } 14771 } 14772 } 14773 } 14774 } 14775 14776 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14777 // Expose the vabsduw/h/b opportunity for down stream 14778 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14779 (IID == Intrinsic::ppc_altivec_vmaxsw || 14780 IID == Intrinsic::ppc_altivec_vmaxsh || 14781 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14782 SDValue V1 = N->getOperand(1); 14783 SDValue V2 = N->getOperand(2); 14784 if ((V1.getSimpleValueType() == MVT::v4i32 || 14785 V1.getSimpleValueType() == MVT::v8i16 || 14786 V1.getSimpleValueType() == MVT::v16i8) && 14787 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14788 // (0-a, a) 14789 if (V1.getOpcode() == ISD::SUB && 14790 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14791 V1.getOperand(1) == V2) { 14792 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14793 } 14794 // (a, 0-a) 14795 if (V2.getOpcode() == ISD::SUB && 14796 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14797 V2.getOperand(1) == V1) { 14798 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14799 } 14800 // (x-y, y-x) 14801 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14802 V1.getOperand(0) == V2.getOperand(1) && 14803 V1.getOperand(1) == V2.getOperand(0)) { 14804 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14805 } 14806 } 14807 } 14808 } 14809 14810 break; 14811 case ISD::INTRINSIC_W_CHAIN: 14812 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14813 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14814 if (Subtarget.needsSwapsForVSXMemOps()) { 14815 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14816 default: 14817 break; 14818 case Intrinsic::ppc_vsx_lxvw4x: 14819 case Intrinsic::ppc_vsx_lxvd2x: 14820 return expandVSXLoadForLE(N, DCI); 14821 } 14822 } 14823 break; 14824 case ISD::INTRINSIC_VOID: 14825 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14826 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14827 if (Subtarget.needsSwapsForVSXMemOps()) { 14828 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14829 default: 14830 break; 14831 case Intrinsic::ppc_vsx_stxvw4x: 14832 case Intrinsic::ppc_vsx_stxvd2x: 14833 return expandVSXStoreForLE(N, DCI); 14834 } 14835 } 14836 break; 14837 case ISD::BSWAP: 14838 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14839 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14840 N->getOperand(0).hasOneUse() && 14841 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14842 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14843 N->getValueType(0) == MVT::i64))) { 14844 SDValue Load = N->getOperand(0); 14845 LoadSDNode *LD = cast<LoadSDNode>(Load); 14846 // Create the byte-swapping load. 14847 SDValue Ops[] = { 14848 LD->getChain(), // Chain 14849 LD->getBasePtr(), // Ptr 14850 DAG.getValueType(N->getValueType(0)) // VT 14851 }; 14852 SDValue BSLoad = 14853 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14854 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14855 MVT::i64 : MVT::i32, MVT::Other), 14856 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14857 14858 // If this is an i16 load, insert the truncate. 14859 SDValue ResVal = BSLoad; 14860 if (N->getValueType(0) == MVT::i16) 14861 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14862 14863 // First, combine the bswap away. This makes the value produced by the 14864 // load dead. 14865 DCI.CombineTo(N, ResVal); 14866 14867 // Next, combine the load away, we give it a bogus result value but a real 14868 // chain result. The result value is dead because the bswap is dead. 14869 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14870 14871 // Return N so it doesn't get rechecked! 14872 return SDValue(N, 0); 14873 } 14874 break; 14875 case PPCISD::VCMP: 14876 // If a VCMP_rec node already exists with exactly the same operands as this 14877 // node, use its result instead of this node (VCMP_rec computes both a CR6 14878 // and a normal output). 14879 // 14880 if (!N->getOperand(0).hasOneUse() && 14881 !N->getOperand(1).hasOneUse() && 14882 !N->getOperand(2).hasOneUse()) { 14883 14884 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 14885 SDNode *VCMPrecNode = nullptr; 14886 14887 SDNode *LHSN = N->getOperand(0).getNode(); 14888 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14889 UI != E; ++UI) 14890 if (UI->getOpcode() == PPCISD::VCMP_rec && 14891 UI->getOperand(1) == N->getOperand(1) && 14892 UI->getOperand(2) == N->getOperand(2) && 14893 UI->getOperand(0) == N->getOperand(0)) { 14894 VCMPrecNode = *UI; 14895 break; 14896 } 14897 14898 // If there is no VCMP_rec node, or if the flag value has a single use, 14899 // don't transform this. 14900 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 14901 break; 14902 14903 // Look at the (necessarily single) use of the flag value. If it has a 14904 // chain, this transformation is more complex. Note that multiple things 14905 // could use the value result, which we should ignore. 14906 SDNode *FlagUser = nullptr; 14907 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 14908 FlagUser == nullptr; ++UI) { 14909 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 14910 SDNode *User = *UI; 14911 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14912 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 14913 FlagUser = User; 14914 break; 14915 } 14916 } 14917 } 14918 14919 // If the user is a MFOCRF instruction, we know this is safe. 14920 // Otherwise we give up for right now. 14921 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14922 return SDValue(VCMPrecNode, 0); 14923 } 14924 break; 14925 case ISD::BRCOND: { 14926 SDValue Cond = N->getOperand(1); 14927 SDValue Target = N->getOperand(2); 14928 14929 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14930 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14931 Intrinsic::loop_decrement) { 14932 14933 // We now need to make the intrinsic dead (it cannot be instruction 14934 // selected). 14935 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14936 assert(Cond.getNode()->hasOneUse() && 14937 "Counter decrement has more than one use"); 14938 14939 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14940 N->getOperand(0), Target); 14941 } 14942 } 14943 break; 14944 case ISD::BR_CC: { 14945 // If this is a branch on an altivec predicate comparison, lower this so 14946 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14947 // lowering is done pre-legalize, because the legalizer lowers the predicate 14948 // compare down to code that is difficult to reassemble. 14949 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14950 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14951 14952 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14953 // value. If so, pass-through the AND to get to the intrinsic. 14954 if (LHS.getOpcode() == ISD::AND && 14955 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14956 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14957 Intrinsic::loop_decrement && 14958 isa<ConstantSDNode>(LHS.getOperand(1)) && 14959 !isNullConstant(LHS.getOperand(1))) 14960 LHS = LHS.getOperand(0); 14961 14962 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14963 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14964 Intrinsic::loop_decrement && 14965 isa<ConstantSDNode>(RHS)) { 14966 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14967 "Counter decrement comparison is not EQ or NE"); 14968 14969 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14970 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14971 (CC == ISD::SETNE && !Val); 14972 14973 // We now need to make the intrinsic dead (it cannot be instruction 14974 // selected). 14975 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14976 assert(LHS.getNode()->hasOneUse() && 14977 "Counter decrement has more than one use"); 14978 14979 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14980 N->getOperand(0), N->getOperand(4)); 14981 } 14982 14983 int CompareOpc; 14984 bool isDot; 14985 14986 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14987 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14988 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14989 assert(isDot && "Can't compare against a vector result!"); 14990 14991 // If this is a comparison against something other than 0/1, then we know 14992 // that the condition is never/always true. 14993 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14994 if (Val != 0 && Val != 1) { 14995 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14996 return N->getOperand(0); 14997 // Always !=, turn it into an unconditional branch. 14998 return DAG.getNode(ISD::BR, dl, MVT::Other, 14999 N->getOperand(0), N->getOperand(4)); 15000 } 15001 15002 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15003 15004 // Create the PPCISD altivec 'dot' comparison node. 15005 SDValue Ops[] = { 15006 LHS.getOperand(2), // LHS of compare 15007 LHS.getOperand(3), // RHS of compare 15008 DAG.getConstant(CompareOpc, dl, MVT::i32) 15009 }; 15010 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15011 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15012 15013 // Unpack the result based on how the target uses it. 15014 PPC::Predicate CompOpc; 15015 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15016 default: // Can't happen, don't crash on invalid number though. 15017 case 0: // Branch on the value of the EQ bit of CR6. 15018 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15019 break; 15020 case 1: // Branch on the inverted value of the EQ bit of CR6. 15021 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15022 break; 15023 case 2: // Branch on the value of the LT bit of CR6. 15024 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15025 break; 15026 case 3: // Branch on the inverted value of the LT bit of CR6. 15027 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15028 break; 15029 } 15030 15031 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15032 DAG.getConstant(CompOpc, dl, MVT::i32), 15033 DAG.getRegister(PPC::CR6, MVT::i32), 15034 N->getOperand(4), CompNode.getValue(1)); 15035 } 15036 break; 15037 } 15038 case ISD::BUILD_VECTOR: 15039 return DAGCombineBuildVector(N, DCI); 15040 case ISD::ABS: 15041 return combineABS(N, DCI); 15042 case ISD::VSELECT: 15043 return combineVSelect(N, DCI); 15044 } 15045 15046 return SDValue(); 15047 } 15048 15049 SDValue 15050 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15051 SelectionDAG &DAG, 15052 SmallVectorImpl<SDNode *> &Created) const { 15053 // fold (sdiv X, pow2) 15054 EVT VT = N->getValueType(0); 15055 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15056 return SDValue(); 15057 if ((VT != MVT::i32 && VT != MVT::i64) || 15058 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15059 return SDValue(); 15060 15061 SDLoc DL(N); 15062 SDValue N0 = N->getOperand(0); 15063 15064 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15065 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15066 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15067 15068 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15069 Created.push_back(Op.getNode()); 15070 15071 if (IsNegPow2) { 15072 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15073 Created.push_back(Op.getNode()); 15074 } 15075 15076 return Op; 15077 } 15078 15079 //===----------------------------------------------------------------------===// 15080 // Inline Assembly Support 15081 //===----------------------------------------------------------------------===// 15082 15083 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15084 KnownBits &Known, 15085 const APInt &DemandedElts, 15086 const SelectionDAG &DAG, 15087 unsigned Depth) const { 15088 Known.resetAll(); 15089 switch (Op.getOpcode()) { 15090 default: break; 15091 case PPCISD::LBRX: { 15092 // lhbrx is known to have the top bits cleared out. 15093 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15094 Known.Zero = 0xFFFF0000; 15095 break; 15096 } 15097 case ISD::INTRINSIC_WO_CHAIN: { 15098 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15099 default: break; 15100 case Intrinsic::ppc_altivec_vcmpbfp_p: 15101 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15102 case Intrinsic::ppc_altivec_vcmpequb_p: 15103 case Intrinsic::ppc_altivec_vcmpequh_p: 15104 case Intrinsic::ppc_altivec_vcmpequw_p: 15105 case Intrinsic::ppc_altivec_vcmpequd_p: 15106 case Intrinsic::ppc_altivec_vcmpequq_p: 15107 case Intrinsic::ppc_altivec_vcmpgefp_p: 15108 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15109 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15110 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15111 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15112 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15113 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15114 case Intrinsic::ppc_altivec_vcmpgtub_p: 15115 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15116 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15117 case Intrinsic::ppc_altivec_vcmpgtud_p: 15118 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15119 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15120 break; 15121 } 15122 } 15123 } 15124 } 15125 15126 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15127 switch (Subtarget.getCPUDirective()) { 15128 default: break; 15129 case PPC::DIR_970: 15130 case PPC::DIR_PWR4: 15131 case PPC::DIR_PWR5: 15132 case PPC::DIR_PWR5X: 15133 case PPC::DIR_PWR6: 15134 case PPC::DIR_PWR6X: 15135 case PPC::DIR_PWR7: 15136 case PPC::DIR_PWR8: 15137 case PPC::DIR_PWR9: 15138 case PPC::DIR_PWR10: 15139 case PPC::DIR_PWR_FUTURE: { 15140 if (!ML) 15141 break; 15142 15143 if (!DisableInnermostLoopAlign32) { 15144 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15145 // so that we can decrease cache misses and branch-prediction misses. 15146 // Actual alignment of the loop will depend on the hotness check and other 15147 // logic in alignBlocks. 15148 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15149 return Align(32); 15150 } 15151 15152 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15153 15154 // For small loops (between 5 and 8 instructions), align to a 32-byte 15155 // boundary so that the entire loop fits in one instruction-cache line. 15156 uint64_t LoopSize = 0; 15157 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15158 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15159 LoopSize += TII->getInstSizeInBytes(*J); 15160 if (LoopSize > 32) 15161 break; 15162 } 15163 15164 if (LoopSize > 16 && LoopSize <= 32) 15165 return Align(32); 15166 15167 break; 15168 } 15169 } 15170 15171 return TargetLowering::getPrefLoopAlignment(ML); 15172 } 15173 15174 /// getConstraintType - Given a constraint, return the type of 15175 /// constraint it is for this target. 15176 PPCTargetLowering::ConstraintType 15177 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15178 if (Constraint.size() == 1) { 15179 switch (Constraint[0]) { 15180 default: break; 15181 case 'b': 15182 case 'r': 15183 case 'f': 15184 case 'd': 15185 case 'v': 15186 case 'y': 15187 return C_RegisterClass; 15188 case 'Z': 15189 // FIXME: While Z does indicate a memory constraint, it specifically 15190 // indicates an r+r address (used in conjunction with the 'y' modifier 15191 // in the replacement string). Currently, we're forcing the base 15192 // register to be r0 in the asm printer (which is interpreted as zero) 15193 // and forming the complete address in the second register. This is 15194 // suboptimal. 15195 return C_Memory; 15196 } 15197 } else if (Constraint == "wc") { // individual CR bits. 15198 return C_RegisterClass; 15199 } else if (Constraint == "wa" || Constraint == "wd" || 15200 Constraint == "wf" || Constraint == "ws" || 15201 Constraint == "wi" || Constraint == "ww") { 15202 return C_RegisterClass; // VSX registers. 15203 } 15204 return TargetLowering::getConstraintType(Constraint); 15205 } 15206 15207 /// Examine constraint type and operand type and determine a weight value. 15208 /// This object must already have been set up with the operand type 15209 /// and the current alternative constraint selected. 15210 TargetLowering::ConstraintWeight 15211 PPCTargetLowering::getSingleConstraintMatchWeight( 15212 AsmOperandInfo &info, const char *constraint) const { 15213 ConstraintWeight weight = CW_Invalid; 15214 Value *CallOperandVal = info.CallOperandVal; 15215 // If we don't have a value, we can't do a match, 15216 // but allow it at the lowest weight. 15217 if (!CallOperandVal) 15218 return CW_Default; 15219 Type *type = CallOperandVal->getType(); 15220 15221 // Look at the constraint type. 15222 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15223 return CW_Register; // an individual CR bit. 15224 else if ((StringRef(constraint) == "wa" || 15225 StringRef(constraint) == "wd" || 15226 StringRef(constraint) == "wf") && 15227 type->isVectorTy()) 15228 return CW_Register; 15229 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15230 return CW_Register; // just hold 64-bit integers data. 15231 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15232 return CW_Register; 15233 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15234 return CW_Register; 15235 15236 switch (*constraint) { 15237 default: 15238 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15239 break; 15240 case 'b': 15241 if (type->isIntegerTy()) 15242 weight = CW_Register; 15243 break; 15244 case 'f': 15245 if (type->isFloatTy()) 15246 weight = CW_Register; 15247 break; 15248 case 'd': 15249 if (type->isDoubleTy()) 15250 weight = CW_Register; 15251 break; 15252 case 'v': 15253 if (type->isVectorTy()) 15254 weight = CW_Register; 15255 break; 15256 case 'y': 15257 weight = CW_Register; 15258 break; 15259 case 'Z': 15260 weight = CW_Memory; 15261 break; 15262 } 15263 return weight; 15264 } 15265 15266 std::pair<unsigned, const TargetRegisterClass *> 15267 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15268 StringRef Constraint, 15269 MVT VT) const { 15270 if (Constraint.size() == 1) { 15271 // GCC RS6000 Constraint Letters 15272 switch (Constraint[0]) { 15273 case 'b': // R1-R31 15274 if (VT == MVT::i64 && Subtarget.isPPC64()) 15275 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15276 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15277 case 'r': // R0-R31 15278 if (VT == MVT::i64 && Subtarget.isPPC64()) 15279 return std::make_pair(0U, &PPC::G8RCRegClass); 15280 return std::make_pair(0U, &PPC::GPRCRegClass); 15281 // 'd' and 'f' constraints are both defined to be "the floating point 15282 // registers", where one is for 32-bit and the other for 64-bit. We don't 15283 // really care overly much here so just give them all the same reg classes. 15284 case 'd': 15285 case 'f': 15286 if (Subtarget.hasSPE()) { 15287 if (VT == MVT::f32 || VT == MVT::i32) 15288 return std::make_pair(0U, &PPC::GPRCRegClass); 15289 if (VT == MVT::f64 || VT == MVT::i64) 15290 return std::make_pair(0U, &PPC::SPERCRegClass); 15291 } else { 15292 if (VT == MVT::f32 || VT == MVT::i32) 15293 return std::make_pair(0U, &PPC::F4RCRegClass); 15294 if (VT == MVT::f64 || VT == MVT::i64) 15295 return std::make_pair(0U, &PPC::F8RCRegClass); 15296 } 15297 break; 15298 case 'v': 15299 if (Subtarget.hasAltivec()) 15300 return std::make_pair(0U, &PPC::VRRCRegClass); 15301 break; 15302 case 'y': // crrc 15303 return std::make_pair(0U, &PPC::CRRCRegClass); 15304 } 15305 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15306 // An individual CR bit. 15307 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15308 } else if ((Constraint == "wa" || Constraint == "wd" || 15309 Constraint == "wf" || Constraint == "wi") && 15310 Subtarget.hasVSX()) { 15311 return std::make_pair(0U, &PPC::VSRCRegClass); 15312 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15313 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15314 return std::make_pair(0U, &PPC::VSSRCRegClass); 15315 else 15316 return std::make_pair(0U, &PPC::VSFRCRegClass); 15317 } 15318 15319 // Handle special cases of physical registers that are not properly handled 15320 // by the base class. 15321 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 15322 // If we name a VSX register, we can't defer to the base class because it 15323 // will not recognize the correct register (their names will be VSL{0-31} 15324 // and V{0-31} so they won't match). So we match them here. 15325 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15326 int VSNum = atoi(Constraint.data() + 3); 15327 assert(VSNum >= 0 && VSNum <= 63 && 15328 "Attempted to access a vsr out of range"); 15329 if (VSNum < 32) 15330 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15331 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15332 } 15333 15334 // For float registers, we can't defer to the base class as it will match 15335 // the SPILLTOVSRRC class. 15336 if (Constraint.size() > 3 && Constraint[1] == 'f') { 15337 int RegNum = atoi(Constraint.data() + 2); 15338 if (RegNum > 31 || RegNum < 0) 15339 report_fatal_error("Invalid floating point register number"); 15340 if (VT == MVT::f32 || VT == MVT::i32) 15341 return Subtarget.hasSPE() 15342 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 15343 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 15344 if (VT == MVT::f64 || VT == MVT::i64) 15345 return Subtarget.hasSPE() 15346 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 15347 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 15348 } 15349 } 15350 15351 std::pair<unsigned, const TargetRegisterClass *> R = 15352 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15353 15354 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15355 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15356 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15357 // register. 15358 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15359 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15360 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15361 PPC::GPRCRegClass.contains(R.first)) 15362 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15363 PPC::sub_32, &PPC::G8RCRegClass), 15364 &PPC::G8RCRegClass); 15365 15366 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15367 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15368 R.first = PPC::CR0; 15369 R.second = &PPC::CRRCRegClass; 15370 } 15371 // FIXME: This warning should ideally be emitted in the front end. 15372 const auto &TM = getTargetMachine(); 15373 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 15374 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 15375 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 15376 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 15377 errs() << "warning: vector registers 20 to 32 are reserved in the " 15378 "default AIX AltiVec ABI and cannot be used\n"; 15379 } 15380 15381 return R; 15382 } 15383 15384 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15385 /// vector. If it is invalid, don't add anything to Ops. 15386 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15387 std::string &Constraint, 15388 std::vector<SDValue>&Ops, 15389 SelectionDAG &DAG) const { 15390 SDValue Result; 15391 15392 // Only support length 1 constraints. 15393 if (Constraint.length() > 1) return; 15394 15395 char Letter = Constraint[0]; 15396 switch (Letter) { 15397 default: break; 15398 case 'I': 15399 case 'J': 15400 case 'K': 15401 case 'L': 15402 case 'M': 15403 case 'N': 15404 case 'O': 15405 case 'P': { 15406 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15407 if (!CST) return; // Must be an immediate to match. 15408 SDLoc dl(Op); 15409 int64_t Value = CST->getSExtValue(); 15410 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15411 // numbers are printed as such. 15412 switch (Letter) { 15413 default: llvm_unreachable("Unknown constraint letter!"); 15414 case 'I': // "I" is a signed 16-bit constant. 15415 if (isInt<16>(Value)) 15416 Result = DAG.getTargetConstant(Value, dl, TCVT); 15417 break; 15418 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15419 if (isShiftedUInt<16, 16>(Value)) 15420 Result = DAG.getTargetConstant(Value, dl, TCVT); 15421 break; 15422 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15423 if (isShiftedInt<16, 16>(Value)) 15424 Result = DAG.getTargetConstant(Value, dl, TCVT); 15425 break; 15426 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15427 if (isUInt<16>(Value)) 15428 Result = DAG.getTargetConstant(Value, dl, TCVT); 15429 break; 15430 case 'M': // "M" is a constant that is greater than 31. 15431 if (Value > 31) 15432 Result = DAG.getTargetConstant(Value, dl, TCVT); 15433 break; 15434 case 'N': // "N" is a positive constant that is an exact power of two. 15435 if (Value > 0 && isPowerOf2_64(Value)) 15436 Result = DAG.getTargetConstant(Value, dl, TCVT); 15437 break; 15438 case 'O': // "O" is the constant zero. 15439 if (Value == 0) 15440 Result = DAG.getTargetConstant(Value, dl, TCVT); 15441 break; 15442 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15443 if (isInt<16>(-Value)) 15444 Result = DAG.getTargetConstant(Value, dl, TCVT); 15445 break; 15446 } 15447 break; 15448 } 15449 } 15450 15451 if (Result.getNode()) { 15452 Ops.push_back(Result); 15453 return; 15454 } 15455 15456 // Handle standard constraint letters. 15457 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15458 } 15459 15460 // isLegalAddressingMode - Return true if the addressing mode represented 15461 // by AM is legal for this target, for a load/store of the specified type. 15462 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15463 const AddrMode &AM, Type *Ty, 15464 unsigned AS, 15465 Instruction *I) const { 15466 // Vector type r+i form is supported since power9 as DQ form. We don't check 15467 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15468 // imm form is preferred and the offset can be adjusted to use imm form later 15469 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15470 // max offset to check legal addressing mode, we should be a little aggressive 15471 // to contain other offsets for that LSRUse. 15472 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15473 return false; 15474 15475 // PPC allows a sign-extended 16-bit immediate field. 15476 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15477 return false; 15478 15479 // No global is ever allowed as a base. 15480 if (AM.BaseGV) 15481 return false; 15482 15483 // PPC only support r+r, 15484 switch (AM.Scale) { 15485 case 0: // "r+i" or just "i", depending on HasBaseReg. 15486 break; 15487 case 1: 15488 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15489 return false; 15490 // Otherwise we have r+r or r+i. 15491 break; 15492 case 2: 15493 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15494 return false; 15495 // Allow 2*r as r+r. 15496 break; 15497 default: 15498 // No other scales are supported. 15499 return false; 15500 } 15501 15502 return true; 15503 } 15504 15505 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15506 SelectionDAG &DAG) const { 15507 MachineFunction &MF = DAG.getMachineFunction(); 15508 MachineFrameInfo &MFI = MF.getFrameInfo(); 15509 MFI.setReturnAddressIsTaken(true); 15510 15511 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15512 return SDValue(); 15513 15514 SDLoc dl(Op); 15515 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15516 15517 // Make sure the function does not optimize away the store of the RA to 15518 // the stack. 15519 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15520 FuncInfo->setLRStoreRequired(); 15521 bool isPPC64 = Subtarget.isPPC64(); 15522 auto PtrVT = getPointerTy(MF.getDataLayout()); 15523 15524 if (Depth > 0) { 15525 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15526 SDValue Offset = 15527 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15528 isPPC64 ? MVT::i64 : MVT::i32); 15529 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15530 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15531 MachinePointerInfo()); 15532 } 15533 15534 // Just load the return address off the stack. 15535 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15536 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15537 MachinePointerInfo()); 15538 } 15539 15540 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15541 SelectionDAG &DAG) const { 15542 SDLoc dl(Op); 15543 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15544 15545 MachineFunction &MF = DAG.getMachineFunction(); 15546 MachineFrameInfo &MFI = MF.getFrameInfo(); 15547 MFI.setFrameAddressIsTaken(true); 15548 15549 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15550 bool isPPC64 = PtrVT == MVT::i64; 15551 15552 // Naked functions never have a frame pointer, and so we use r1. For all 15553 // other functions, this decision must be delayed until during PEI. 15554 unsigned FrameReg; 15555 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15556 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15557 else 15558 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15559 15560 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15561 PtrVT); 15562 while (Depth--) 15563 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15564 FrameAddr, MachinePointerInfo()); 15565 return FrameAddr; 15566 } 15567 15568 // FIXME? Maybe this could be a TableGen attribute on some registers and 15569 // this table could be generated automatically from RegInfo. 15570 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15571 const MachineFunction &MF) const { 15572 bool isPPC64 = Subtarget.isPPC64(); 15573 15574 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15575 if (!is64Bit && VT != LLT::scalar(32)) 15576 report_fatal_error("Invalid register global variable type"); 15577 15578 Register Reg = StringSwitch<Register>(RegName) 15579 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15580 .Case("r2", isPPC64 ? Register() : PPC::R2) 15581 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15582 .Default(Register()); 15583 15584 if (Reg) 15585 return Reg; 15586 report_fatal_error("Invalid register name global variable"); 15587 } 15588 15589 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15590 // 32-bit SVR4 ABI access everything as got-indirect. 15591 if (Subtarget.is32BitELFABI()) 15592 return true; 15593 15594 // AIX accesses everything indirectly through the TOC, which is similar to 15595 // the GOT. 15596 if (Subtarget.isAIXABI()) 15597 return true; 15598 15599 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15600 // If it is small or large code model, module locals are accessed 15601 // indirectly by loading their address from .toc/.got. 15602 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15603 return true; 15604 15605 // JumpTable and BlockAddress are accessed as got-indirect. 15606 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15607 return true; 15608 15609 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15610 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15611 15612 return false; 15613 } 15614 15615 bool 15616 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15617 // The PowerPC target isn't yet aware of offsets. 15618 return false; 15619 } 15620 15621 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15622 const CallInst &I, 15623 MachineFunction &MF, 15624 unsigned Intrinsic) const { 15625 switch (Intrinsic) { 15626 case Intrinsic::ppc_altivec_lvx: 15627 case Intrinsic::ppc_altivec_lvxl: 15628 case Intrinsic::ppc_altivec_lvebx: 15629 case Intrinsic::ppc_altivec_lvehx: 15630 case Intrinsic::ppc_altivec_lvewx: 15631 case Intrinsic::ppc_vsx_lxvd2x: 15632 case Intrinsic::ppc_vsx_lxvw4x: 15633 case Intrinsic::ppc_vsx_lxvd2x_be: 15634 case Intrinsic::ppc_vsx_lxvw4x_be: 15635 case Intrinsic::ppc_vsx_lxvl: 15636 case Intrinsic::ppc_vsx_lxvll: { 15637 EVT VT; 15638 switch (Intrinsic) { 15639 case Intrinsic::ppc_altivec_lvebx: 15640 VT = MVT::i8; 15641 break; 15642 case Intrinsic::ppc_altivec_lvehx: 15643 VT = MVT::i16; 15644 break; 15645 case Intrinsic::ppc_altivec_lvewx: 15646 VT = MVT::i32; 15647 break; 15648 case Intrinsic::ppc_vsx_lxvd2x: 15649 case Intrinsic::ppc_vsx_lxvd2x_be: 15650 VT = MVT::v2f64; 15651 break; 15652 default: 15653 VT = MVT::v4i32; 15654 break; 15655 } 15656 15657 Info.opc = ISD::INTRINSIC_W_CHAIN; 15658 Info.memVT = VT; 15659 Info.ptrVal = I.getArgOperand(0); 15660 Info.offset = -VT.getStoreSize()+1; 15661 Info.size = 2*VT.getStoreSize()-1; 15662 Info.align = Align(1); 15663 Info.flags = MachineMemOperand::MOLoad; 15664 return true; 15665 } 15666 case Intrinsic::ppc_altivec_stvx: 15667 case Intrinsic::ppc_altivec_stvxl: 15668 case Intrinsic::ppc_altivec_stvebx: 15669 case Intrinsic::ppc_altivec_stvehx: 15670 case Intrinsic::ppc_altivec_stvewx: 15671 case Intrinsic::ppc_vsx_stxvd2x: 15672 case Intrinsic::ppc_vsx_stxvw4x: 15673 case Intrinsic::ppc_vsx_stxvd2x_be: 15674 case Intrinsic::ppc_vsx_stxvw4x_be: 15675 case Intrinsic::ppc_vsx_stxvl: 15676 case Intrinsic::ppc_vsx_stxvll: { 15677 EVT VT; 15678 switch (Intrinsic) { 15679 case Intrinsic::ppc_altivec_stvebx: 15680 VT = MVT::i8; 15681 break; 15682 case Intrinsic::ppc_altivec_stvehx: 15683 VT = MVT::i16; 15684 break; 15685 case Intrinsic::ppc_altivec_stvewx: 15686 VT = MVT::i32; 15687 break; 15688 case Intrinsic::ppc_vsx_stxvd2x: 15689 case Intrinsic::ppc_vsx_stxvd2x_be: 15690 VT = MVT::v2f64; 15691 break; 15692 default: 15693 VT = MVT::v4i32; 15694 break; 15695 } 15696 15697 Info.opc = ISD::INTRINSIC_VOID; 15698 Info.memVT = VT; 15699 Info.ptrVal = I.getArgOperand(1); 15700 Info.offset = -VT.getStoreSize()+1; 15701 Info.size = 2*VT.getStoreSize()-1; 15702 Info.align = Align(1); 15703 Info.flags = MachineMemOperand::MOStore; 15704 return true; 15705 } 15706 default: 15707 break; 15708 } 15709 15710 return false; 15711 } 15712 15713 /// It returns EVT::Other if the type should be determined using generic 15714 /// target-independent logic. 15715 EVT PPCTargetLowering::getOptimalMemOpType( 15716 const MemOp &Op, const AttributeList &FuncAttributes) const { 15717 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15718 // We should use Altivec/VSX loads and stores when available. For unaligned 15719 // addresses, unaligned VSX loads are only fast starting with the P8. 15720 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15721 (Op.isAligned(Align(16)) || 15722 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15723 return MVT::v4i32; 15724 } 15725 15726 if (Subtarget.isPPC64()) { 15727 return MVT::i64; 15728 } 15729 15730 return MVT::i32; 15731 } 15732 15733 /// Returns true if it is beneficial to convert a load of a constant 15734 /// to just the constant itself. 15735 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15736 Type *Ty) const { 15737 assert(Ty->isIntegerTy()); 15738 15739 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15740 return !(BitSize == 0 || BitSize > 64); 15741 } 15742 15743 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15744 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15745 return false; 15746 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15747 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15748 return NumBits1 == 64 && NumBits2 == 32; 15749 } 15750 15751 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15752 if (!VT1.isInteger() || !VT2.isInteger()) 15753 return false; 15754 unsigned NumBits1 = VT1.getSizeInBits(); 15755 unsigned NumBits2 = VT2.getSizeInBits(); 15756 return NumBits1 == 64 && NumBits2 == 32; 15757 } 15758 15759 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15760 // Generally speaking, zexts are not free, but they are free when they can be 15761 // folded with other operations. 15762 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15763 EVT MemVT = LD->getMemoryVT(); 15764 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15765 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15766 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15767 LD->getExtensionType() == ISD::ZEXTLOAD)) 15768 return true; 15769 } 15770 15771 // FIXME: Add other cases... 15772 // - 32-bit shifts with a zext to i64 15773 // - zext after ctlz, bswap, etc. 15774 // - zext after and by a constant mask 15775 15776 return TargetLowering::isZExtFree(Val, VT2); 15777 } 15778 15779 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15780 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15781 "invalid fpext types"); 15782 // Extending to float128 is not free. 15783 if (DestVT == MVT::f128) 15784 return false; 15785 return true; 15786 } 15787 15788 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15789 return isInt<16>(Imm) || isUInt<16>(Imm); 15790 } 15791 15792 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15793 return isInt<16>(Imm) || isUInt<16>(Imm); 15794 } 15795 15796 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 15797 MachineMemOperand::Flags, 15798 bool *Fast) const { 15799 if (DisablePPCUnaligned) 15800 return false; 15801 15802 // PowerPC supports unaligned memory access for simple non-vector types. 15803 // Although accessing unaligned addresses is not as efficient as accessing 15804 // aligned addresses, it is generally more efficient than manual expansion, 15805 // and generally only traps for software emulation when crossing page 15806 // boundaries. 15807 15808 if (!VT.isSimple()) 15809 return false; 15810 15811 if (VT.isFloatingPoint() && !VT.isVector() && 15812 !Subtarget.allowsUnalignedFPAccess()) 15813 return false; 15814 15815 if (VT.getSimpleVT().isVector()) { 15816 if (Subtarget.hasVSX()) { 15817 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15818 VT != MVT::v4f32 && VT != MVT::v4i32) 15819 return false; 15820 } else { 15821 return false; 15822 } 15823 } 15824 15825 if (VT == MVT::ppcf128) 15826 return false; 15827 15828 if (Fast) 15829 *Fast = true; 15830 15831 return true; 15832 } 15833 15834 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 15835 SDValue C) const { 15836 // Check integral scalar types. 15837 if (!VT.isScalarInteger()) 15838 return false; 15839 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 15840 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 15841 return false; 15842 // This transformation will generate >= 2 operations. But the following 15843 // cases will generate <= 2 instructions during ISEL. So exclude them. 15844 // 1. If the constant multiplier fits 16 bits, it can be handled by one 15845 // HW instruction, ie. MULLI 15846 // 2. If the multiplier after shifted fits 16 bits, an extra shift 15847 // instruction is needed than case 1, ie. MULLI and RLDICR 15848 int64_t Imm = ConstNode->getSExtValue(); 15849 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 15850 Imm >>= Shift; 15851 if (isInt<16>(Imm)) 15852 return false; 15853 uint64_t UImm = static_cast<uint64_t>(Imm); 15854 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 15855 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 15856 return true; 15857 } 15858 return false; 15859 } 15860 15861 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15862 EVT VT) const { 15863 return isFMAFasterThanFMulAndFAdd( 15864 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15865 } 15866 15867 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15868 Type *Ty) const { 15869 switch (Ty->getScalarType()->getTypeID()) { 15870 case Type::FloatTyID: 15871 case Type::DoubleTyID: 15872 return true; 15873 case Type::FP128TyID: 15874 return Subtarget.hasP9Vector(); 15875 default: 15876 return false; 15877 } 15878 } 15879 15880 // FIXME: add more patterns which are not profitable to hoist. 15881 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15882 if (!I->hasOneUse()) 15883 return true; 15884 15885 Instruction *User = I->user_back(); 15886 assert(User && "A single use instruction with no uses."); 15887 15888 switch (I->getOpcode()) { 15889 case Instruction::FMul: { 15890 // Don't break FMA, PowerPC prefers FMA. 15891 if (User->getOpcode() != Instruction::FSub && 15892 User->getOpcode() != Instruction::FAdd) 15893 return true; 15894 15895 const TargetOptions &Options = getTargetMachine().Options; 15896 const Function *F = I->getFunction(); 15897 const DataLayout &DL = F->getParent()->getDataLayout(); 15898 Type *Ty = User->getOperand(0)->getType(); 15899 15900 return !( 15901 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15902 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15903 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15904 } 15905 case Instruction::Load: { 15906 // Don't break "store (load float*)" pattern, this pattern will be combined 15907 // to "store (load int32)" in later InstCombine pass. See function 15908 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15909 // cycles than loading a 32 bit integer. 15910 LoadInst *LI = cast<LoadInst>(I); 15911 // For the loads that combineLoadToOperationType does nothing, like 15912 // ordered load, it should be profitable to hoist them. 15913 // For swifterror load, it can only be used for pointer to pointer type, so 15914 // later type check should get rid of this case. 15915 if (!LI->isUnordered()) 15916 return true; 15917 15918 if (User->getOpcode() != Instruction::Store) 15919 return true; 15920 15921 if (I->getType()->getTypeID() != Type::FloatTyID) 15922 return true; 15923 15924 return false; 15925 } 15926 default: 15927 return true; 15928 } 15929 return true; 15930 } 15931 15932 const MCPhysReg * 15933 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15934 // LR is a callee-save register, but we must treat it as clobbered by any call 15935 // site. Hence we include LR in the scratch registers, which are in turn added 15936 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15937 // to CTR, which is used by any indirect call. 15938 static const MCPhysReg ScratchRegs[] = { 15939 PPC::X12, PPC::LR8, PPC::CTR8, 0 15940 }; 15941 15942 return ScratchRegs; 15943 } 15944 15945 Register PPCTargetLowering::getExceptionPointerRegister( 15946 const Constant *PersonalityFn) const { 15947 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15948 } 15949 15950 Register PPCTargetLowering::getExceptionSelectorRegister( 15951 const Constant *PersonalityFn) const { 15952 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15953 } 15954 15955 bool 15956 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15957 EVT VT , unsigned DefinedValues) const { 15958 if (VT == MVT::v2i64) 15959 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15960 15961 if (Subtarget.hasVSX()) 15962 return true; 15963 15964 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15965 } 15966 15967 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15968 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15969 return TargetLowering::getSchedulingPreference(N); 15970 15971 return Sched::ILP; 15972 } 15973 15974 // Create a fast isel object. 15975 FastISel * 15976 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15977 const TargetLibraryInfo *LibInfo) const { 15978 return PPC::createFastISel(FuncInfo, LibInfo); 15979 } 15980 15981 // 'Inverted' means the FMA opcode after negating one multiplicand. 15982 // For example, (fma -a b c) = (fnmsub a b c) 15983 static unsigned invertFMAOpcode(unsigned Opc) { 15984 switch (Opc) { 15985 default: 15986 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15987 case ISD::FMA: 15988 return PPCISD::FNMSUB; 15989 case PPCISD::FNMSUB: 15990 return ISD::FMA; 15991 } 15992 } 15993 15994 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15995 bool LegalOps, bool OptForSize, 15996 NegatibleCost &Cost, 15997 unsigned Depth) const { 15998 if (Depth > SelectionDAG::MaxRecursionDepth) 15999 return SDValue(); 16000 16001 unsigned Opc = Op.getOpcode(); 16002 EVT VT = Op.getValueType(); 16003 SDNodeFlags Flags = Op.getNode()->getFlags(); 16004 16005 switch (Opc) { 16006 case PPCISD::FNMSUB: 16007 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16008 break; 16009 16010 const TargetOptions &Options = getTargetMachine().Options; 16011 SDValue N0 = Op.getOperand(0); 16012 SDValue N1 = Op.getOperand(1); 16013 SDValue N2 = Op.getOperand(2); 16014 SDLoc Loc(Op); 16015 16016 NegatibleCost N2Cost = NegatibleCost::Expensive; 16017 SDValue NegN2 = 16018 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16019 16020 if (!NegN2) 16021 return SDValue(); 16022 16023 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16024 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16025 // These transformations may change sign of zeroes. For example, 16026 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16027 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16028 // Try and choose the cheaper one to negate. 16029 NegatibleCost N0Cost = NegatibleCost::Expensive; 16030 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16031 N0Cost, Depth + 1); 16032 16033 NegatibleCost N1Cost = NegatibleCost::Expensive; 16034 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16035 N1Cost, Depth + 1); 16036 16037 if (NegN0 && N0Cost <= N1Cost) { 16038 Cost = std::min(N0Cost, N2Cost); 16039 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16040 } else if (NegN1) { 16041 Cost = std::min(N1Cost, N2Cost); 16042 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16043 } 16044 } 16045 16046 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16047 if (isOperationLegal(ISD::FMA, VT)) { 16048 Cost = N2Cost; 16049 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16050 } 16051 16052 break; 16053 } 16054 16055 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16056 Cost, Depth); 16057 } 16058 16059 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16060 bool PPCTargetLowering::useLoadStackGuardNode() const { 16061 if (!Subtarget.isTargetLinux()) 16062 return TargetLowering::useLoadStackGuardNode(); 16063 return true; 16064 } 16065 16066 // Override to disable global variable loading on Linux. 16067 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16068 if (!Subtarget.isTargetLinux()) 16069 return TargetLowering::insertSSPDeclarations(M); 16070 } 16071 16072 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16073 bool ForCodeSize) const { 16074 if (!VT.isSimple() || !Subtarget.hasVSX()) 16075 return false; 16076 16077 switch(VT.getSimpleVT().SimpleTy) { 16078 default: 16079 // For FP types that are currently not supported by PPC backend, return 16080 // false. Examples: f16, f80. 16081 return false; 16082 case MVT::f32: 16083 case MVT::f64: 16084 if (Subtarget.hasPrefixInstrs()) { 16085 // With prefixed instructions, we can materialize anything that can be 16086 // represented with a 32-bit immediate, not just positive zero. 16087 APFloat APFloatOfImm = Imm; 16088 return convertToNonDenormSingle(APFloatOfImm); 16089 } 16090 LLVM_FALLTHROUGH; 16091 case MVT::ppcf128: 16092 return Imm.isPosZero(); 16093 } 16094 } 16095 16096 // For vector shift operation op, fold 16097 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16098 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16099 SelectionDAG &DAG) { 16100 SDValue N0 = N->getOperand(0); 16101 SDValue N1 = N->getOperand(1); 16102 EVT VT = N0.getValueType(); 16103 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16104 unsigned Opcode = N->getOpcode(); 16105 unsigned TargetOpcode; 16106 16107 switch (Opcode) { 16108 default: 16109 llvm_unreachable("Unexpected shift operation"); 16110 case ISD::SHL: 16111 TargetOpcode = PPCISD::SHL; 16112 break; 16113 case ISD::SRL: 16114 TargetOpcode = PPCISD::SRL; 16115 break; 16116 case ISD::SRA: 16117 TargetOpcode = PPCISD::SRA; 16118 break; 16119 } 16120 16121 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16122 N1->getOpcode() == ISD::AND) 16123 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16124 if (Mask->getZExtValue() == OpSizeInBits - 1) 16125 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16126 16127 return SDValue(); 16128 } 16129 16130 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16131 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16132 return Value; 16133 16134 SDValue N0 = N->getOperand(0); 16135 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16136 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16137 N0.getOpcode() != ISD::SIGN_EXTEND || 16138 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16139 N->getValueType(0) != MVT::i64) 16140 return SDValue(); 16141 16142 // We can't save an operation here if the value is already extended, and 16143 // the existing shift is easier to combine. 16144 SDValue ExtsSrc = N0.getOperand(0); 16145 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16146 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16147 return SDValue(); 16148 16149 SDLoc DL(N0); 16150 SDValue ShiftBy = SDValue(CN1, 0); 16151 // We want the shift amount to be i32 on the extswli, but the shift could 16152 // have an i64. 16153 if (ShiftBy.getValueType() == MVT::i64) 16154 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16155 16156 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16157 ShiftBy); 16158 } 16159 16160 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16161 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16162 return Value; 16163 16164 return SDValue(); 16165 } 16166 16167 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16168 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16169 return Value; 16170 16171 return SDValue(); 16172 } 16173 16174 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16175 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16176 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16177 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16178 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16179 const PPCSubtarget &Subtarget) { 16180 if (!Subtarget.isPPC64()) 16181 return SDValue(); 16182 16183 SDValue LHS = N->getOperand(0); 16184 SDValue RHS = N->getOperand(1); 16185 16186 auto isZextOfCompareWithConstant = [](SDValue Op) { 16187 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16188 Op.getValueType() != MVT::i64) 16189 return false; 16190 16191 SDValue Cmp = Op.getOperand(0); 16192 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16193 Cmp.getOperand(0).getValueType() != MVT::i64) 16194 return false; 16195 16196 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16197 int64_t NegConstant = 0 - Constant->getSExtValue(); 16198 // Due to the limitations of the addi instruction, 16199 // -C is required to be [-32768, 32767]. 16200 return isInt<16>(NegConstant); 16201 } 16202 16203 return false; 16204 }; 16205 16206 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16207 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16208 16209 // If there is a pattern, canonicalize a zext operand to the RHS. 16210 if (LHSHasPattern && !RHSHasPattern) 16211 std::swap(LHS, RHS); 16212 else if (!LHSHasPattern && !RHSHasPattern) 16213 return SDValue(); 16214 16215 SDLoc DL(N); 16216 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16217 SDValue Cmp = RHS.getOperand(0); 16218 SDValue Z = Cmp.getOperand(0); 16219 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16220 16221 assert(Constant && "Constant Should not be a null pointer."); 16222 int64_t NegConstant = 0 - Constant->getSExtValue(); 16223 16224 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16225 default: break; 16226 case ISD::SETNE: { 16227 // when C == 0 16228 // --> addze X, (addic Z, -1).carry 16229 // / 16230 // add X, (zext(setne Z, C))-- 16231 // \ when -32768 <= -C <= 32767 && C != 0 16232 // --> addze X, (addic (addi Z, -C), -1).carry 16233 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16234 DAG.getConstant(NegConstant, DL, MVT::i64)); 16235 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16236 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16237 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16238 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16239 SDValue(Addc.getNode(), 1)); 16240 } 16241 case ISD::SETEQ: { 16242 // when C == 0 16243 // --> addze X, (subfic Z, 0).carry 16244 // / 16245 // add X, (zext(sete Z, C))-- 16246 // \ when -32768 <= -C <= 32767 && C != 0 16247 // --> addze X, (subfic (addi Z, -C), 0).carry 16248 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16249 DAG.getConstant(NegConstant, DL, MVT::i64)); 16250 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16251 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16252 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16253 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16254 SDValue(Subc.getNode(), 1)); 16255 } 16256 } 16257 16258 return SDValue(); 16259 } 16260 16261 // Transform 16262 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16263 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16264 // In this case both C1 and C2 must be known constants. 16265 // C1+C2 must fit into a 34 bit signed integer. 16266 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16267 const PPCSubtarget &Subtarget) { 16268 if (!Subtarget.isUsingPCRelativeCalls()) 16269 return SDValue(); 16270 16271 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16272 // If we find that node try to cast the Global Address and the Constant. 16273 SDValue LHS = N->getOperand(0); 16274 SDValue RHS = N->getOperand(1); 16275 16276 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16277 std::swap(LHS, RHS); 16278 16279 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16280 return SDValue(); 16281 16282 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16283 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16284 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16285 16286 // Check that both casts succeeded. 16287 if (!GSDN || !ConstNode) 16288 return SDValue(); 16289 16290 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16291 SDLoc DL(GSDN); 16292 16293 // The signed int offset needs to fit in 34 bits. 16294 if (!isInt<34>(NewOffset)) 16295 return SDValue(); 16296 16297 // The new global address is a copy of the old global address except 16298 // that it has the updated Offset. 16299 SDValue GA = 16300 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16301 NewOffset, GSDN->getTargetFlags()); 16302 SDValue MatPCRel = 16303 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16304 return MatPCRel; 16305 } 16306 16307 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16308 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16309 return Value; 16310 16311 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16312 return Value; 16313 16314 return SDValue(); 16315 } 16316 16317 // Detect TRUNCATE operations on bitcasts of float128 values. 16318 // What we are looking for here is the situtation where we extract a subset 16319 // of bits from a 128 bit float. 16320 // This can be of two forms: 16321 // 1) BITCAST of f128 feeding TRUNCATE 16322 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16323 // The reason this is required is because we do not have a legal i128 type 16324 // and so we want to prevent having to store the f128 and then reload part 16325 // of it. 16326 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16327 DAGCombinerInfo &DCI) const { 16328 // If we are using CRBits then try that first. 16329 if (Subtarget.useCRBits()) { 16330 // Check if CRBits did anything and return that if it did. 16331 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16332 return CRTruncValue; 16333 } 16334 16335 SDLoc dl(N); 16336 SDValue Op0 = N->getOperand(0); 16337 16338 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16339 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16340 EVT VT = N->getValueType(0); 16341 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16342 return SDValue(); 16343 SDValue Sub = Op0.getOperand(0); 16344 if (Sub.getOpcode() == ISD::SUB) { 16345 SDValue SubOp0 = Sub.getOperand(0); 16346 SDValue SubOp1 = Sub.getOperand(1); 16347 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16348 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16349 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16350 SubOp1.getOperand(0), 16351 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16352 } 16353 } 16354 } 16355 16356 // Looking for a truncate of i128 to i64. 16357 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16358 return SDValue(); 16359 16360 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16361 16362 // SRL feeding TRUNCATE. 16363 if (Op0.getOpcode() == ISD::SRL) { 16364 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16365 // The right shift has to be by 64 bits. 16366 if (!ConstNode || ConstNode->getZExtValue() != 64) 16367 return SDValue(); 16368 16369 // Switch the element number to extract. 16370 EltToExtract = EltToExtract ? 0 : 1; 16371 // Update Op0 past the SRL. 16372 Op0 = Op0.getOperand(0); 16373 } 16374 16375 // BITCAST feeding a TRUNCATE possibly via SRL. 16376 if (Op0.getOpcode() == ISD::BITCAST && 16377 Op0.getValueType() == MVT::i128 && 16378 Op0.getOperand(0).getValueType() == MVT::f128) { 16379 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16380 return DCI.DAG.getNode( 16381 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16382 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16383 } 16384 return SDValue(); 16385 } 16386 16387 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16388 SelectionDAG &DAG = DCI.DAG; 16389 16390 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16391 if (!ConstOpOrElement) 16392 return SDValue(); 16393 16394 // An imul is usually smaller than the alternative sequence for legal type. 16395 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16396 isOperationLegal(ISD::MUL, N->getValueType(0))) 16397 return SDValue(); 16398 16399 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16400 switch (this->Subtarget.getCPUDirective()) { 16401 default: 16402 // TODO: enhance the condition for subtarget before pwr8 16403 return false; 16404 case PPC::DIR_PWR8: 16405 // type mul add shl 16406 // scalar 4 1 1 16407 // vector 7 2 2 16408 return true; 16409 case PPC::DIR_PWR9: 16410 case PPC::DIR_PWR10: 16411 case PPC::DIR_PWR_FUTURE: 16412 // type mul add shl 16413 // scalar 5 2 2 16414 // vector 7 2 2 16415 16416 // The cycle RATIO of related operations are showed as a table above. 16417 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16418 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16419 // are 4, it is always profitable; but for 3 instrs patterns 16420 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16421 // So we should only do it for vector type. 16422 return IsAddOne && IsNeg ? VT.isVector() : true; 16423 } 16424 }; 16425 16426 EVT VT = N->getValueType(0); 16427 SDLoc DL(N); 16428 16429 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16430 bool IsNeg = MulAmt.isNegative(); 16431 APInt MulAmtAbs = MulAmt.abs(); 16432 16433 if ((MulAmtAbs - 1).isPowerOf2()) { 16434 // (mul x, 2^N + 1) => (add (shl x, N), x) 16435 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16436 16437 if (!IsProfitable(IsNeg, true, VT)) 16438 return SDValue(); 16439 16440 SDValue Op0 = N->getOperand(0); 16441 SDValue Op1 = 16442 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16443 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16444 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16445 16446 if (!IsNeg) 16447 return Res; 16448 16449 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16450 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16451 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16452 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16453 16454 if (!IsProfitable(IsNeg, false, VT)) 16455 return SDValue(); 16456 16457 SDValue Op0 = N->getOperand(0); 16458 SDValue Op1 = 16459 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16460 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16461 16462 if (!IsNeg) 16463 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16464 else 16465 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16466 16467 } else { 16468 return SDValue(); 16469 } 16470 } 16471 16472 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16473 // in combiner since we need to check SD flags and other subtarget features. 16474 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16475 DAGCombinerInfo &DCI) const { 16476 SDValue N0 = N->getOperand(0); 16477 SDValue N1 = N->getOperand(1); 16478 SDValue N2 = N->getOperand(2); 16479 SDNodeFlags Flags = N->getFlags(); 16480 EVT VT = N->getValueType(0); 16481 SelectionDAG &DAG = DCI.DAG; 16482 const TargetOptions &Options = getTargetMachine().Options; 16483 unsigned Opc = N->getOpcode(); 16484 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16485 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16486 SDLoc Loc(N); 16487 16488 if (!isOperationLegal(ISD::FMA, VT)) 16489 return SDValue(); 16490 16491 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16492 // since (fnmsub a b c)=-0 while c-ab=+0. 16493 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16494 return SDValue(); 16495 16496 // (fma (fneg a) b c) => (fnmsub a b c) 16497 // (fnmsub (fneg a) b c) => (fma a b c) 16498 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16499 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16500 16501 // (fma a (fneg b) c) => (fnmsub a b c) 16502 // (fnmsub a (fneg b) c) => (fma a b c) 16503 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16504 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16505 16506 return SDValue(); 16507 } 16508 16509 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16510 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16511 if (!Subtarget.is64BitELFABI()) 16512 return false; 16513 16514 // If not a tail call then no need to proceed. 16515 if (!CI->isTailCall()) 16516 return false; 16517 16518 // If sibling calls have been disabled and tail-calls aren't guaranteed 16519 // there is no reason to duplicate. 16520 auto &TM = getTargetMachine(); 16521 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16522 return false; 16523 16524 // Can't tail call a function called indirectly, or if it has variadic args. 16525 const Function *Callee = CI->getCalledFunction(); 16526 if (!Callee || Callee->isVarArg()) 16527 return false; 16528 16529 // Make sure the callee and caller calling conventions are eligible for tco. 16530 const Function *Caller = CI->getParent()->getParent(); 16531 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16532 CI->getCallingConv())) 16533 return false; 16534 16535 // If the function is local then we have a good chance at tail-calling it 16536 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16537 } 16538 16539 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16540 if (!Subtarget.hasVSX()) 16541 return false; 16542 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16543 return true; 16544 return VT == MVT::f32 || VT == MVT::f64 || 16545 VT == MVT::v4f32 || VT == MVT::v2f64; 16546 } 16547 16548 bool PPCTargetLowering:: 16549 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16550 const Value *Mask = AndI.getOperand(1); 16551 // If the mask is suitable for andi. or andis. we should sink the and. 16552 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16553 // Can't handle constants wider than 64-bits. 16554 if (CI->getBitWidth() > 64) 16555 return false; 16556 int64_t ConstVal = CI->getZExtValue(); 16557 return isUInt<16>(ConstVal) || 16558 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16559 } 16560 16561 // For non-constant masks, we can always use the record-form and. 16562 return true; 16563 } 16564 16565 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16566 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16567 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16568 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16569 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16570 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16571 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16572 assert(Subtarget.hasP9Altivec() && 16573 "Only combine this when P9 altivec supported!"); 16574 EVT VT = N->getValueType(0); 16575 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16576 return SDValue(); 16577 16578 SelectionDAG &DAG = DCI.DAG; 16579 SDLoc dl(N); 16580 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16581 // Even for signed integers, if it's known to be positive (as signed 16582 // integer) due to zero-extended inputs. 16583 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16584 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16585 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16586 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16587 (SubOpcd1 == ISD::ZERO_EXTEND || 16588 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16589 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16590 N->getOperand(0)->getOperand(0), 16591 N->getOperand(0)->getOperand(1), 16592 DAG.getTargetConstant(0, dl, MVT::i32)); 16593 } 16594 16595 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16596 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16597 N->getOperand(0).hasOneUse()) { 16598 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16599 N->getOperand(0)->getOperand(0), 16600 N->getOperand(0)->getOperand(1), 16601 DAG.getTargetConstant(1, dl, MVT::i32)); 16602 } 16603 } 16604 16605 return SDValue(); 16606 } 16607 16608 // For type v4i32/v8ii16/v16i8, transform 16609 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16610 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16611 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16612 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16613 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16614 DAGCombinerInfo &DCI) const { 16615 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16616 assert(Subtarget.hasP9Altivec() && 16617 "Only combine this when P9 altivec supported!"); 16618 16619 SelectionDAG &DAG = DCI.DAG; 16620 SDLoc dl(N); 16621 SDValue Cond = N->getOperand(0); 16622 SDValue TrueOpnd = N->getOperand(1); 16623 SDValue FalseOpnd = N->getOperand(2); 16624 EVT VT = N->getOperand(1).getValueType(); 16625 16626 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16627 FalseOpnd.getOpcode() != ISD::SUB) 16628 return SDValue(); 16629 16630 // ABSD only available for type v4i32/v8i16/v16i8 16631 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16632 return SDValue(); 16633 16634 // At least to save one more dependent computation 16635 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16636 return SDValue(); 16637 16638 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16639 16640 // Can only handle unsigned comparison here 16641 switch (CC) { 16642 default: 16643 return SDValue(); 16644 case ISD::SETUGT: 16645 case ISD::SETUGE: 16646 break; 16647 case ISD::SETULT: 16648 case ISD::SETULE: 16649 std::swap(TrueOpnd, FalseOpnd); 16650 break; 16651 } 16652 16653 SDValue CmpOpnd1 = Cond.getOperand(0); 16654 SDValue CmpOpnd2 = Cond.getOperand(1); 16655 16656 // SETCC CmpOpnd1 CmpOpnd2 cond 16657 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16658 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16659 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16660 TrueOpnd.getOperand(1) == CmpOpnd2 && 16661 FalseOpnd.getOperand(0) == CmpOpnd2 && 16662 FalseOpnd.getOperand(1) == CmpOpnd1) { 16663 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16664 CmpOpnd1, CmpOpnd2, 16665 DAG.getTargetConstant(0, dl, MVT::i32)); 16666 } 16667 16668 return SDValue(); 16669 } 16670