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 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 if (Subtarget.isISA3_0()) { 175 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 177 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 178 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 179 } else { 180 // No extending loads from f16 or HW conversions back and forth. 181 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 184 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 185 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 186 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 187 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 188 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 189 } 190 191 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 192 193 // PowerPC has pre-inc load and store's. 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 204 if (!Subtarget.hasSPE()) { 205 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 206 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 209 } 210 211 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 212 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 213 for (MVT VT : ScalarIntVTs) { 214 setOperationAction(ISD::ADDC, VT, Legal); 215 setOperationAction(ISD::ADDE, VT, Legal); 216 setOperationAction(ISD::SUBC, VT, Legal); 217 setOperationAction(ISD::SUBE, VT, Legal); 218 } 219 220 if (Subtarget.useCRBits()) { 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 222 223 if (isPPC64 || Subtarget.hasFPCVT()) { 224 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 235 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 236 isPPC64 ? MVT::i64 : MVT::i32); 237 238 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 239 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 240 isPPC64 ? MVT::i64 : MVT::i32); 241 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 242 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 243 isPPC64 ? MVT::i64 : MVT::i32); 244 245 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 246 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 247 isPPC64 ? MVT::i64 : MVT::i32); 248 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 249 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 250 isPPC64 ? MVT::i64 : MVT::i32); 251 } else { 252 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 253 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 254 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 255 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 256 } 257 258 // PowerPC does not support direct load/store of condition registers. 259 setOperationAction(ISD::LOAD, MVT::i1, Custom); 260 setOperationAction(ISD::STORE, MVT::i1, Custom); 261 262 // FIXME: Remove this once the ANDI glue bug is fixed: 263 if (ANDIGlueBug) 264 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 265 266 for (MVT VT : MVT::integer_valuetypes()) { 267 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 268 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 269 setTruncStoreAction(VT, MVT::i1, Expand); 270 } 271 272 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 273 } 274 275 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 276 // PPC (the libcall is not available). 277 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 278 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 279 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 280 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 281 282 // We do not currently implement these libm ops for PowerPC. 283 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 284 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 285 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 286 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 287 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 288 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 289 290 // PowerPC has no SREM/UREM instructions unless we are on P9 291 // On P9 we may use a hardware instruction to compute the remainder. 292 // When the result of both the remainder and the division is required it is 293 // more efficient to compute the remainder from the result of the division 294 // rather than use the remainder instruction. The instructions are legalized 295 // directly because the DivRemPairsPass performs the transformation at the IR 296 // level. 297 if (Subtarget.isISA3_0()) { 298 setOperationAction(ISD::SREM, MVT::i32, Legal); 299 setOperationAction(ISD::UREM, MVT::i32, Legal); 300 setOperationAction(ISD::SREM, MVT::i64, Legal); 301 setOperationAction(ISD::UREM, MVT::i64, Legal); 302 } else { 303 setOperationAction(ISD::SREM, MVT::i32, Expand); 304 setOperationAction(ISD::UREM, MVT::i32, Expand); 305 setOperationAction(ISD::SREM, MVT::i64, Expand); 306 setOperationAction(ISD::UREM, MVT::i64, Expand); 307 } 308 309 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 310 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 311 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 312 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 313 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 314 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 315 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 316 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 317 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 318 319 // Handle constrained floating-point operations of scalar. 320 // TODO: Handle SPE specific operation. 321 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 322 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 323 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 324 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 325 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 326 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 327 328 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 329 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 330 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 331 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 332 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 333 if (Subtarget.hasVSX()) { 334 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 335 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 336 } 337 338 if (Subtarget.hasFSQRT()) { 339 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 340 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 341 } 342 343 if (Subtarget.hasFPRND()) { 344 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 345 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 346 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 347 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 348 349 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 350 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 351 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 352 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 353 } 354 355 // We don't support sin/cos/sqrt/fmod/pow 356 setOperationAction(ISD::FSIN , MVT::f64, Expand); 357 setOperationAction(ISD::FCOS , MVT::f64, Expand); 358 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 359 setOperationAction(ISD::FREM , MVT::f64, Expand); 360 setOperationAction(ISD::FPOW , MVT::f64, Expand); 361 setOperationAction(ISD::FSIN , MVT::f32, Expand); 362 setOperationAction(ISD::FCOS , MVT::f32, Expand); 363 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 364 setOperationAction(ISD::FREM , MVT::f32, Expand); 365 setOperationAction(ISD::FPOW , MVT::f32, Expand); 366 if (Subtarget.hasSPE()) { 367 setOperationAction(ISD::FMA , MVT::f64, Expand); 368 setOperationAction(ISD::FMA , MVT::f32, Expand); 369 } else { 370 setOperationAction(ISD::FMA , MVT::f64, Legal); 371 setOperationAction(ISD::FMA , MVT::f32, Legal); 372 } 373 374 if (Subtarget.hasSPE()) 375 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 376 377 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 378 379 // If we're enabling GP optimizations, use hardware square root 380 if (!Subtarget.hasFSQRT() && 381 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 382 Subtarget.hasFRE())) 383 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 384 385 if (!Subtarget.hasFSQRT() && 386 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 387 Subtarget.hasFRES())) 388 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 389 390 if (Subtarget.hasFCPSGN()) { 391 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 393 } else { 394 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 395 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 396 } 397 398 if (Subtarget.hasFPRND()) { 399 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 400 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 401 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 402 setOperationAction(ISD::FROUND, MVT::f64, Legal); 403 404 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 405 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 406 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 407 setOperationAction(ISD::FROUND, MVT::f32, Legal); 408 } 409 410 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 411 // to speed up scalar BSWAP64. 412 // CTPOP or CTTZ were introduced in P8/P9 respectively 413 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 414 if (Subtarget.hasP9Vector()) 415 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 416 else 417 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 418 if (Subtarget.isISA3_0()) { 419 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 420 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 421 } else { 422 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 423 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 424 } 425 426 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 427 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 428 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 429 } else { 430 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 431 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 432 } 433 434 // PowerPC does not have ROTR 435 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 436 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 437 438 if (!Subtarget.useCRBits()) { 439 // PowerPC does not have Select 440 setOperationAction(ISD::SELECT, MVT::i32, Expand); 441 setOperationAction(ISD::SELECT, MVT::i64, Expand); 442 setOperationAction(ISD::SELECT, MVT::f32, Expand); 443 setOperationAction(ISD::SELECT, MVT::f64, Expand); 444 } 445 446 // PowerPC wants to turn select_cc of FP into fsel when possible. 447 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 448 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 449 450 // PowerPC wants to optimize integer setcc a bit 451 if (!Subtarget.useCRBits()) 452 setOperationAction(ISD::SETCC, MVT::i32, Custom); 453 454 if (Subtarget.hasFPU()) { 455 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 456 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 457 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 458 459 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 460 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 461 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 462 } 463 464 // PowerPC does not have BRCOND which requires SetCC 465 if (!Subtarget.useCRBits()) 466 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 467 468 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 469 470 if (Subtarget.hasSPE()) { 471 // SPE has built-in conversions 472 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 473 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 474 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 475 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 476 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 477 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 478 } else { 479 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 480 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 481 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 482 483 // PowerPC does not have [U|S]INT_TO_FP 484 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 485 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 486 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 487 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 488 } 489 490 if (Subtarget.hasDirectMove() && isPPC64) { 491 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 492 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 493 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 494 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 495 if (TM.Options.UnsafeFPMath) { 496 setOperationAction(ISD::LRINT, MVT::f64, Legal); 497 setOperationAction(ISD::LRINT, MVT::f32, Legal); 498 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 499 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 500 setOperationAction(ISD::LROUND, MVT::f64, Legal); 501 setOperationAction(ISD::LROUND, MVT::f32, Legal); 502 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 503 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 504 } 505 } else { 506 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 507 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 508 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 509 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 510 } 511 512 // We cannot sextinreg(i1). Expand to shifts. 513 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 514 515 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 516 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 517 // support continuation, user-level threading, and etc.. As a result, no 518 // other SjLj exception interfaces are implemented and please don't build 519 // your own exception handling based on them. 520 // LLVM/Clang supports zero-cost DWARF exception handling. 521 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 522 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 523 524 // We want to legalize GlobalAddress and ConstantPool nodes into the 525 // appropriate instructions to materialize the address. 526 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 527 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 528 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 529 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 530 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 531 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 532 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 533 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 534 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 535 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 536 537 // TRAP is legal. 538 setOperationAction(ISD::TRAP, MVT::Other, Legal); 539 540 // TRAMPOLINE is custom lowered. 541 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 542 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 543 544 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 545 setOperationAction(ISD::VASTART , MVT::Other, Custom); 546 547 if (Subtarget.is64BitELFABI()) { 548 // VAARG always uses double-word chunks, so promote anything smaller. 549 setOperationAction(ISD::VAARG, MVT::i1, Promote); 550 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 551 setOperationAction(ISD::VAARG, MVT::i8, Promote); 552 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 553 setOperationAction(ISD::VAARG, MVT::i16, Promote); 554 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 555 setOperationAction(ISD::VAARG, MVT::i32, Promote); 556 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 557 setOperationAction(ISD::VAARG, MVT::Other, Expand); 558 } else if (Subtarget.is32BitELFABI()) { 559 // VAARG is custom lowered with the 32-bit SVR4 ABI. 560 setOperationAction(ISD::VAARG, MVT::Other, Custom); 561 setOperationAction(ISD::VAARG, MVT::i64, Custom); 562 } else 563 setOperationAction(ISD::VAARG, MVT::Other, Expand); 564 565 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 566 if (Subtarget.is32BitELFABI()) 567 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 568 else 569 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 570 571 // Use the default implementation. 572 setOperationAction(ISD::VAEND , MVT::Other, Expand); 573 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 574 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 575 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 576 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 577 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 578 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 579 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 580 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 581 582 // We want to custom lower some of our intrinsics. 583 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 584 585 // To handle counter-based loop conditions. 586 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 587 588 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 589 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 590 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 591 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 592 593 // Comparisons that require checking two conditions. 594 if (Subtarget.hasSPE()) { 595 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 596 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 597 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 598 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 599 } 600 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 601 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 602 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 603 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 604 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 605 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 606 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 607 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 608 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 609 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 610 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 611 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 612 613 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 614 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 615 616 if (Subtarget.has64BitSupport()) { 617 // They also have instructions for converting between i64 and fp. 618 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 619 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 620 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 621 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 622 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 623 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 624 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 625 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 626 // This is just the low 32 bits of a (signed) fp->i64 conversion. 627 // We cannot do this with Promote because i64 is not a legal type. 628 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 629 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 630 631 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 632 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 633 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 634 } 635 } else { 636 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 637 if (Subtarget.hasSPE()) { 638 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 639 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 640 } else { 641 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 642 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 643 } 644 } 645 646 // With the instructions enabled under FPCVT, we can do everything. 647 if (Subtarget.hasFPCVT()) { 648 if (Subtarget.has64BitSupport()) { 649 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 650 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 651 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 652 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 653 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 654 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 655 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 656 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 657 } 658 659 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 660 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 661 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 662 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 663 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 664 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 665 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 666 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 667 } 668 669 if (Subtarget.use64BitRegs()) { 670 // 64-bit PowerPC implementations can support i64 types directly 671 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 672 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 673 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 674 // 64-bit PowerPC wants to expand i128 shifts itself. 675 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 676 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 677 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 678 } else { 679 // 32-bit PowerPC wants to expand i64 shifts itself. 680 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 681 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 682 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 683 } 684 685 // PowerPC has better expansions for funnel shifts than the generic 686 // TargetLowering::expandFunnelShift. 687 if (Subtarget.has64BitSupport()) { 688 setOperationAction(ISD::FSHL, MVT::i64, Custom); 689 setOperationAction(ISD::FSHR, MVT::i64, Custom); 690 } 691 setOperationAction(ISD::FSHL, MVT::i32, Custom); 692 setOperationAction(ISD::FSHR, MVT::i32, Custom); 693 694 if (Subtarget.hasVSX()) { 695 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 696 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 697 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 698 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 699 } 700 701 if (Subtarget.hasAltivec()) { 702 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 703 setOperationAction(ISD::SADDSAT, VT, Legal); 704 setOperationAction(ISD::SSUBSAT, VT, Legal); 705 setOperationAction(ISD::UADDSAT, VT, Legal); 706 setOperationAction(ISD::USUBSAT, VT, Legal); 707 } 708 // First set operation action for all vector types to expand. Then we 709 // will selectively turn on ones that can be effectively codegen'd. 710 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 711 // add/sub are legal for all supported vector VT's. 712 setOperationAction(ISD::ADD, VT, Legal); 713 setOperationAction(ISD::SUB, VT, Legal); 714 715 // For v2i64, these are only valid with P8Vector. This is corrected after 716 // the loop. 717 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 718 setOperationAction(ISD::SMAX, VT, Legal); 719 setOperationAction(ISD::SMIN, VT, Legal); 720 setOperationAction(ISD::UMAX, VT, Legal); 721 setOperationAction(ISD::UMIN, VT, Legal); 722 } 723 else { 724 setOperationAction(ISD::SMAX, VT, Expand); 725 setOperationAction(ISD::SMIN, VT, Expand); 726 setOperationAction(ISD::UMAX, VT, Expand); 727 setOperationAction(ISD::UMIN, VT, Expand); 728 } 729 730 if (Subtarget.hasVSX()) { 731 setOperationAction(ISD::FMAXNUM, VT, Legal); 732 setOperationAction(ISD::FMINNUM, VT, Legal); 733 } 734 735 // Vector instructions introduced in P8 736 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 737 setOperationAction(ISD::CTPOP, VT, Legal); 738 setOperationAction(ISD::CTLZ, VT, Legal); 739 } 740 else { 741 setOperationAction(ISD::CTPOP, VT, Expand); 742 setOperationAction(ISD::CTLZ, VT, Expand); 743 } 744 745 // Vector instructions introduced in P9 746 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 747 setOperationAction(ISD::CTTZ, VT, Legal); 748 else 749 setOperationAction(ISD::CTTZ, VT, Expand); 750 751 // We promote all shuffles to v16i8. 752 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 753 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 754 755 // We promote all non-typed operations to v4i32. 756 setOperationAction(ISD::AND , VT, Promote); 757 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 758 setOperationAction(ISD::OR , VT, Promote); 759 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 760 setOperationAction(ISD::XOR , VT, Promote); 761 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 762 setOperationAction(ISD::LOAD , VT, Promote); 763 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 764 setOperationAction(ISD::SELECT, VT, Promote); 765 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 766 setOperationAction(ISD::VSELECT, VT, Legal); 767 setOperationAction(ISD::SELECT_CC, VT, Promote); 768 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 769 setOperationAction(ISD::STORE, VT, Promote); 770 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 771 772 // No other operations are legal. 773 setOperationAction(ISD::MUL , VT, Expand); 774 setOperationAction(ISD::SDIV, VT, Expand); 775 setOperationAction(ISD::SREM, VT, Expand); 776 setOperationAction(ISD::UDIV, VT, Expand); 777 setOperationAction(ISD::UREM, VT, Expand); 778 setOperationAction(ISD::FDIV, VT, Expand); 779 setOperationAction(ISD::FREM, VT, Expand); 780 setOperationAction(ISD::FNEG, VT, Expand); 781 setOperationAction(ISD::FSQRT, VT, Expand); 782 setOperationAction(ISD::FLOG, VT, Expand); 783 setOperationAction(ISD::FLOG10, VT, Expand); 784 setOperationAction(ISD::FLOG2, VT, Expand); 785 setOperationAction(ISD::FEXP, VT, Expand); 786 setOperationAction(ISD::FEXP2, VT, Expand); 787 setOperationAction(ISD::FSIN, VT, Expand); 788 setOperationAction(ISD::FCOS, VT, Expand); 789 setOperationAction(ISD::FABS, VT, Expand); 790 setOperationAction(ISD::FFLOOR, VT, Expand); 791 setOperationAction(ISD::FCEIL, VT, Expand); 792 setOperationAction(ISD::FTRUNC, VT, Expand); 793 setOperationAction(ISD::FRINT, VT, Expand); 794 setOperationAction(ISD::FNEARBYINT, VT, Expand); 795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 796 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 797 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 798 setOperationAction(ISD::MULHU, VT, Expand); 799 setOperationAction(ISD::MULHS, VT, Expand); 800 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 801 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 802 setOperationAction(ISD::UDIVREM, VT, Expand); 803 setOperationAction(ISD::SDIVREM, VT, Expand); 804 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 805 setOperationAction(ISD::FPOW, VT, Expand); 806 setOperationAction(ISD::BSWAP, VT, Expand); 807 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 808 setOperationAction(ISD::ROTL, VT, Expand); 809 setOperationAction(ISD::ROTR, VT, Expand); 810 811 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 812 setTruncStoreAction(VT, InnerVT, Expand); 813 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 814 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 815 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 816 } 817 } 818 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 819 if (!Subtarget.hasP8Vector()) { 820 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 821 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 822 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 823 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 824 } 825 826 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 827 // with merges, splats, etc. 828 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 829 830 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 831 // are cheap, so handle them before they get expanded to scalar. 832 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 833 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 834 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 835 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 836 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 837 838 setOperationAction(ISD::AND , MVT::v4i32, Legal); 839 setOperationAction(ISD::OR , MVT::v4i32, Legal); 840 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 841 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 842 setOperationAction(ISD::SELECT, MVT::v4i32, 843 Subtarget.useCRBits() ? Legal : Expand); 844 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 845 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 846 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 847 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 848 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 849 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 850 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 851 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 852 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 853 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 854 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 855 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 856 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 857 858 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 859 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 860 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 861 if (Subtarget.hasAltivec()) 862 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 863 setOperationAction(ISD::ROTL, VT, Legal); 864 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 865 if (Subtarget.hasP8Altivec()) 866 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 867 868 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 869 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 870 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 871 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 872 873 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 874 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 875 876 if (Subtarget.hasVSX()) { 877 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 878 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 879 } 880 881 if (Subtarget.hasP8Altivec()) 882 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 883 else 884 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 885 886 if (Subtarget.isISA3_1()) { 887 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 888 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 889 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 890 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 891 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 892 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 893 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 894 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 895 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 896 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 897 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 898 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 899 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 900 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 901 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 902 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 903 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 904 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 905 } 906 907 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 908 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 909 910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 912 913 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 914 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 915 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 916 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 917 918 // Altivec does not contain unordered floating-point compare instructions 919 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 920 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 921 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 922 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 923 924 if (Subtarget.hasVSX()) { 925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 926 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 927 if (Subtarget.hasP8Vector()) { 928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 929 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 930 } 931 if (Subtarget.hasDirectMove() && isPPC64) { 932 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 933 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 934 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 935 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 940 } 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 942 943 // The nearbyint variants are not allowed to raise the inexact exception 944 // so we can only code-gen them with unsafe math. 945 if (TM.Options.UnsafeFPMath) { 946 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 947 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 948 } 949 950 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 951 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 952 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 953 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 954 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 955 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 956 setOperationAction(ISD::FROUND, MVT::f64, Legal); 957 setOperationAction(ISD::FRINT, MVT::f64, Legal); 958 959 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 960 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 961 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 962 setOperationAction(ISD::FROUND, MVT::f32, Legal); 963 setOperationAction(ISD::FRINT, MVT::f32, Legal); 964 965 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 966 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 967 968 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 969 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 970 971 // Share the Altivec comparison restrictions. 972 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 973 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 974 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 975 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 976 977 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 978 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 979 980 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 981 982 if (Subtarget.hasP8Vector()) 983 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 984 985 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 986 987 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 988 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 989 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 990 991 if (Subtarget.hasP8Altivec()) { 992 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 993 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 994 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 995 996 // 128 bit shifts can be accomplished via 3 instructions for SHL and 997 // SRL, but not for SRA because of the instructions available: 998 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 999 // doing 1000 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1001 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1002 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1003 1004 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1005 } 1006 else { 1007 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1008 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1009 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1010 1011 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1012 1013 // VSX v2i64 only supports non-arithmetic operations. 1014 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1015 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1016 } 1017 1018 if (Subtarget.isISA3_1()) 1019 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1020 else 1021 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1022 1023 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1024 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1025 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1026 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1027 1028 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1029 1030 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1031 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1032 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1033 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1034 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1036 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1037 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1038 1039 // Custom handling for partial vectors of integers converted to 1040 // floating point. We already have optimal handling for v2i32 through 1041 // the DAG combine, so those aren't necessary. 1042 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1043 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1044 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1045 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1046 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1047 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1048 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1049 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1050 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1051 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1052 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1053 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1054 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1055 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1056 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1057 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1058 1059 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1060 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1061 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1062 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1063 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1064 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1065 1066 if (Subtarget.hasDirectMove()) 1067 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1068 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1069 1070 // Handle constrained floating-point operations of vector. 1071 // The predictor is `hasVSX` because altivec instruction has 1072 // no exception but VSX vector instruction has. 1073 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1074 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1075 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1076 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1077 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1078 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1079 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1080 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1081 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1082 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1083 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1084 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1085 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1086 1087 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1088 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1089 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1090 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1091 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1092 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1093 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1094 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1095 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1096 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1097 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1098 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1099 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1100 1101 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1102 } 1103 1104 if (Subtarget.hasP8Altivec()) { 1105 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1106 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1107 } 1108 1109 if (Subtarget.hasP9Vector()) { 1110 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1111 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1112 1113 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1114 // SRL, but not for SRA because of the instructions available: 1115 // VS{RL} and VS{RL}O. 1116 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1117 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1118 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1119 1120 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1121 setOperationAction(ISD::FADD, MVT::f128, Legal); 1122 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1123 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1124 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1125 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1126 // No extending loads to f128 on PPC. 1127 for (MVT FPT : MVT::fp_valuetypes()) 1128 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1129 setOperationAction(ISD::FMA, MVT::f128, Legal); 1130 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1131 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1132 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1133 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1134 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1135 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1136 1137 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1138 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1139 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1140 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1141 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1142 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1143 1144 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1145 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1146 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1147 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1148 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1149 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1150 // No implementation for these ops for PowerPC. 1151 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1152 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1153 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1154 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1155 setOperationAction(ISD::FREM, MVT::f128, Expand); 1156 1157 // Handle constrained floating-point operations of fp128 1158 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1159 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1160 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1161 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1162 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1163 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1164 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1165 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1166 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1167 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1168 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1169 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1170 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1171 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1172 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1173 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1174 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1175 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1176 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1177 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1178 } else if (Subtarget.hasAltivec() && EnableSoftFP128) { 1179 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1180 1181 for (MVT FPT : MVT::fp_valuetypes()) 1182 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1183 1184 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1185 setOperationAction(ISD::STORE, MVT::f128, Promote); 1186 1187 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1188 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1189 1190 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1191 // fp_to_uint and int_to_fp. 1192 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1193 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1194 1195 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1196 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1197 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1198 setOperationAction(ISD::FABS, MVT::f128, Expand); 1199 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1200 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1201 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1202 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1203 setOperationAction(ISD::FREM, MVT::f128, Expand); 1204 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1205 setOperationAction(ISD::FMA, MVT::f128, Expand); 1206 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1207 1208 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1209 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1210 1211 // Expand the fp_extend if the target type is fp128. 1212 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1213 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1214 1215 // Expand the fp_round if the source type is fp128. 1216 for (MVT VT : {MVT::f32, MVT::f64}) { 1217 setOperationAction(ISD::FP_ROUND, VT, Custom); 1218 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1219 } 1220 } 1221 1222 if (Subtarget.hasP9Altivec()) { 1223 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1224 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1225 1226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1227 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1233 } 1234 } 1235 1236 if (Subtarget.pairedVectorMemops()) { 1237 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1238 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1239 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1240 } 1241 if (Subtarget.hasMMA()) { 1242 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1243 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1244 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1245 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1246 } 1247 1248 if (Subtarget.has64BitSupport()) 1249 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1250 1251 if (Subtarget.isISA3_1()) 1252 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1253 1254 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1255 1256 if (!isPPC64) { 1257 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1258 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1259 } 1260 1261 setBooleanContents(ZeroOrOneBooleanContent); 1262 1263 if (Subtarget.hasAltivec()) { 1264 // Altivec instructions set fields to all zeros or all ones. 1265 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1266 } 1267 1268 if (!isPPC64) { 1269 // These libcalls are not available in 32-bit. 1270 setLibcallName(RTLIB::SHL_I128, nullptr); 1271 setLibcallName(RTLIB::SRL_I128, nullptr); 1272 setLibcallName(RTLIB::SRA_I128, nullptr); 1273 } 1274 1275 if (!isPPC64) 1276 setMaxAtomicSizeInBitsSupported(32); 1277 1278 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1279 1280 // We have target-specific dag combine patterns for the following nodes: 1281 setTargetDAGCombine(ISD::ADD); 1282 setTargetDAGCombine(ISD::SHL); 1283 setTargetDAGCombine(ISD::SRA); 1284 setTargetDAGCombine(ISD::SRL); 1285 setTargetDAGCombine(ISD::MUL); 1286 setTargetDAGCombine(ISD::FMA); 1287 setTargetDAGCombine(ISD::SINT_TO_FP); 1288 setTargetDAGCombine(ISD::BUILD_VECTOR); 1289 if (Subtarget.hasFPCVT()) 1290 setTargetDAGCombine(ISD::UINT_TO_FP); 1291 setTargetDAGCombine(ISD::LOAD); 1292 setTargetDAGCombine(ISD::STORE); 1293 setTargetDAGCombine(ISD::BR_CC); 1294 if (Subtarget.useCRBits()) 1295 setTargetDAGCombine(ISD::BRCOND); 1296 setTargetDAGCombine(ISD::BSWAP); 1297 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1298 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1299 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1300 1301 setTargetDAGCombine(ISD::SIGN_EXTEND); 1302 setTargetDAGCombine(ISD::ZERO_EXTEND); 1303 setTargetDAGCombine(ISD::ANY_EXTEND); 1304 1305 setTargetDAGCombine(ISD::TRUNCATE); 1306 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1307 1308 1309 if (Subtarget.useCRBits()) { 1310 setTargetDAGCombine(ISD::TRUNCATE); 1311 setTargetDAGCombine(ISD::SETCC); 1312 setTargetDAGCombine(ISD::SELECT_CC); 1313 } 1314 1315 if (Subtarget.hasP9Altivec()) { 1316 setTargetDAGCombine(ISD::ABS); 1317 setTargetDAGCombine(ISD::VSELECT); 1318 } 1319 1320 setLibcallName(RTLIB::LOG_F128, "logf128"); 1321 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1322 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1323 setLibcallName(RTLIB::EXP_F128, "expf128"); 1324 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1325 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1326 setLibcallName(RTLIB::COS_F128, "cosf128"); 1327 setLibcallName(RTLIB::POW_F128, "powf128"); 1328 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1329 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1330 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1331 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1332 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1333 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1334 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1335 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1336 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1337 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1338 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1339 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1340 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1341 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1342 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1343 1344 // With 32 condition bits, we don't need to sink (and duplicate) compares 1345 // aggressively in CodeGenPrep. 1346 if (Subtarget.useCRBits()) { 1347 setHasMultipleConditionRegisters(); 1348 setJumpIsExpensive(); 1349 } 1350 1351 setMinFunctionAlignment(Align(4)); 1352 1353 switch (Subtarget.getCPUDirective()) { 1354 default: break; 1355 case PPC::DIR_970: 1356 case PPC::DIR_A2: 1357 case PPC::DIR_E500: 1358 case PPC::DIR_E500mc: 1359 case PPC::DIR_E5500: 1360 case PPC::DIR_PWR4: 1361 case PPC::DIR_PWR5: 1362 case PPC::DIR_PWR5X: 1363 case PPC::DIR_PWR6: 1364 case PPC::DIR_PWR6X: 1365 case PPC::DIR_PWR7: 1366 case PPC::DIR_PWR8: 1367 case PPC::DIR_PWR9: 1368 case PPC::DIR_PWR10: 1369 case PPC::DIR_PWR_FUTURE: 1370 setPrefLoopAlignment(Align(16)); 1371 setPrefFunctionAlignment(Align(16)); 1372 break; 1373 } 1374 1375 if (Subtarget.enableMachineScheduler()) 1376 setSchedulingPreference(Sched::Source); 1377 else 1378 setSchedulingPreference(Sched::Hybrid); 1379 1380 computeRegisterProperties(STI.getRegisterInfo()); 1381 1382 // The Freescale cores do better with aggressive inlining of memcpy and 1383 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1384 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1385 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1386 MaxStoresPerMemset = 32; 1387 MaxStoresPerMemsetOptSize = 16; 1388 MaxStoresPerMemcpy = 32; 1389 MaxStoresPerMemcpyOptSize = 8; 1390 MaxStoresPerMemmove = 32; 1391 MaxStoresPerMemmoveOptSize = 8; 1392 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1393 // The A2 also benefits from (very) aggressive inlining of memcpy and 1394 // friends. The overhead of a the function call, even when warm, can be 1395 // over one hundred cycles. 1396 MaxStoresPerMemset = 128; 1397 MaxStoresPerMemcpy = 128; 1398 MaxStoresPerMemmove = 128; 1399 MaxLoadsPerMemcmp = 128; 1400 } else { 1401 MaxLoadsPerMemcmp = 8; 1402 MaxLoadsPerMemcmpOptSize = 4; 1403 } 1404 1405 IsStrictFPEnabled = true; 1406 1407 // Let the subtarget (CPU) decide if a predictable select is more expensive 1408 // than the corresponding branch. This information is used in CGP to decide 1409 // when to convert selects into branches. 1410 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1411 } 1412 1413 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1414 /// the desired ByVal argument alignment. 1415 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1416 if (MaxAlign == MaxMaxAlign) 1417 return; 1418 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1419 if (MaxMaxAlign >= 32 && 1420 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1421 MaxAlign = Align(32); 1422 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1423 MaxAlign < 16) 1424 MaxAlign = Align(16); 1425 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1426 Align EltAlign; 1427 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1428 if (EltAlign > MaxAlign) 1429 MaxAlign = EltAlign; 1430 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1431 for (auto *EltTy : STy->elements()) { 1432 Align EltAlign; 1433 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1434 if (EltAlign > MaxAlign) 1435 MaxAlign = EltAlign; 1436 if (MaxAlign == MaxMaxAlign) 1437 break; 1438 } 1439 } 1440 } 1441 1442 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1443 /// function arguments in the caller parameter area. 1444 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1445 const DataLayout &DL) const { 1446 // 16byte and wider vectors are passed on 16byte boundary. 1447 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1448 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1449 if (Subtarget.hasAltivec()) 1450 getMaxByValAlign(Ty, Alignment, Align(16)); 1451 return Alignment.value(); 1452 } 1453 1454 bool PPCTargetLowering::useSoftFloat() const { 1455 return Subtarget.useSoftFloat(); 1456 } 1457 1458 bool PPCTargetLowering::hasSPE() const { 1459 return Subtarget.hasSPE(); 1460 } 1461 1462 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1463 return VT.isScalarInteger(); 1464 } 1465 1466 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1467 switch ((PPCISD::NodeType)Opcode) { 1468 case PPCISD::FIRST_NUMBER: break; 1469 case PPCISD::FSEL: return "PPCISD::FSEL"; 1470 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1471 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1472 case PPCISD::FCFID: return "PPCISD::FCFID"; 1473 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1474 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1475 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1476 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1477 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1478 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1479 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1480 case PPCISD::FP_TO_UINT_IN_VSR: 1481 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1482 case PPCISD::FP_TO_SINT_IN_VSR: 1483 return "PPCISD::FP_TO_SINT_IN_VSR"; 1484 case PPCISD::FRE: return "PPCISD::FRE"; 1485 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1486 case PPCISD::FTSQRT: 1487 return "PPCISD::FTSQRT"; 1488 case PPCISD::FSQRT: 1489 return "PPCISD::FSQRT"; 1490 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1491 case PPCISD::VPERM: return "PPCISD::VPERM"; 1492 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1493 case PPCISD::XXSPLTI_SP_TO_DP: 1494 return "PPCISD::XXSPLTI_SP_TO_DP"; 1495 case PPCISD::XXSPLTI32DX: 1496 return "PPCISD::XXSPLTI32DX"; 1497 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1498 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1499 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1500 case PPCISD::CMPB: return "PPCISD::CMPB"; 1501 case PPCISD::Hi: return "PPCISD::Hi"; 1502 case PPCISD::Lo: return "PPCISD::Lo"; 1503 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1504 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1505 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1506 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1507 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1508 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1509 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1510 case PPCISD::SRL: return "PPCISD::SRL"; 1511 case PPCISD::SRA: return "PPCISD::SRA"; 1512 case PPCISD::SHL: return "PPCISD::SHL"; 1513 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1514 case PPCISD::CALL: return "PPCISD::CALL"; 1515 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1516 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1517 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1518 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1519 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1520 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1521 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1522 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1523 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1524 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1525 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1526 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1527 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1528 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1529 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1530 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1531 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1532 case PPCISD::ANDI_rec_1_EQ_BIT: 1533 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1534 case PPCISD::ANDI_rec_1_GT_BIT: 1535 return "PPCISD::ANDI_rec_1_GT_BIT"; 1536 case PPCISD::VCMP: return "PPCISD::VCMP"; 1537 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1538 case PPCISD::LBRX: return "PPCISD::LBRX"; 1539 case PPCISD::STBRX: return "PPCISD::STBRX"; 1540 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1541 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1542 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1543 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1544 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1545 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1546 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1547 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1548 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1549 case PPCISD::ST_VSR_SCAL_INT: 1550 return "PPCISD::ST_VSR_SCAL_INT"; 1551 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1552 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1553 case PPCISD::BDZ: return "PPCISD::BDZ"; 1554 case PPCISD::MFFS: return "PPCISD::MFFS"; 1555 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1556 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1557 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1558 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1559 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1560 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1561 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1562 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1563 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1564 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1565 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1566 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1567 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1568 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1569 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1570 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1571 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1572 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1573 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1574 case PPCISD::PADDI_DTPREL: 1575 return "PPCISD::PADDI_DTPREL"; 1576 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1577 case PPCISD::SC: return "PPCISD::SC"; 1578 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1579 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1580 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1581 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1582 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1583 case PPCISD::VABSD: return "PPCISD::VABSD"; 1584 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1585 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1586 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1587 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1588 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1589 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1590 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1591 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1592 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1593 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1594 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1595 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1596 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1597 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1598 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1599 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1600 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1601 case PPCISD::STRICT_FADDRTZ: 1602 return "PPCISD::STRICT_FADDRTZ"; 1603 case PPCISD::STRICT_FCTIDZ: 1604 return "PPCISD::STRICT_FCTIDZ"; 1605 case PPCISD::STRICT_FCTIWZ: 1606 return "PPCISD::STRICT_FCTIWZ"; 1607 case PPCISD::STRICT_FCTIDUZ: 1608 return "PPCISD::STRICT_FCTIDUZ"; 1609 case PPCISD::STRICT_FCTIWUZ: 1610 return "PPCISD::STRICT_FCTIWUZ"; 1611 case PPCISD::STRICT_FCFID: 1612 return "PPCISD::STRICT_FCFID"; 1613 case PPCISD::STRICT_FCFIDU: 1614 return "PPCISD::STRICT_FCFIDU"; 1615 case PPCISD::STRICT_FCFIDS: 1616 return "PPCISD::STRICT_FCFIDS"; 1617 case PPCISD::STRICT_FCFIDUS: 1618 return "PPCISD::STRICT_FCFIDUS"; 1619 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1620 } 1621 return nullptr; 1622 } 1623 1624 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1625 EVT VT) const { 1626 if (!VT.isVector()) 1627 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1628 1629 return VT.changeVectorElementTypeToInteger(); 1630 } 1631 1632 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1633 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1634 return true; 1635 } 1636 1637 //===----------------------------------------------------------------------===// 1638 // Node matching predicates, for use by the tblgen matching code. 1639 //===----------------------------------------------------------------------===// 1640 1641 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1642 static bool isFloatingPointZero(SDValue Op) { 1643 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1644 return CFP->getValueAPF().isZero(); 1645 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1646 // Maybe this has already been legalized into the constant pool? 1647 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1648 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1649 return CFP->getValueAPF().isZero(); 1650 } 1651 return false; 1652 } 1653 1654 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1655 /// true if Op is undef or if it matches the specified value. 1656 static bool isConstantOrUndef(int Op, int Val) { 1657 return Op < 0 || Op == Val; 1658 } 1659 1660 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1661 /// VPKUHUM instruction. 1662 /// The ShuffleKind distinguishes between big-endian operations with 1663 /// two different inputs (0), either-endian operations with two identical 1664 /// inputs (1), and little-endian operations with two different inputs (2). 1665 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1666 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1667 SelectionDAG &DAG) { 1668 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1669 if (ShuffleKind == 0) { 1670 if (IsLE) 1671 return false; 1672 for (unsigned i = 0; i != 16; ++i) 1673 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1674 return false; 1675 } else if (ShuffleKind == 2) { 1676 if (!IsLE) 1677 return false; 1678 for (unsigned i = 0; i != 16; ++i) 1679 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1680 return false; 1681 } else if (ShuffleKind == 1) { 1682 unsigned j = IsLE ? 0 : 1; 1683 for (unsigned i = 0; i != 8; ++i) 1684 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1685 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1686 return false; 1687 } 1688 return true; 1689 } 1690 1691 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1692 /// VPKUWUM instruction. 1693 /// The ShuffleKind distinguishes between big-endian operations with 1694 /// two different inputs (0), either-endian operations with two identical 1695 /// inputs (1), and little-endian operations with two different inputs (2). 1696 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1697 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1698 SelectionDAG &DAG) { 1699 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1700 if (ShuffleKind == 0) { 1701 if (IsLE) 1702 return false; 1703 for (unsigned i = 0; i != 16; i += 2) 1704 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1705 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1706 return false; 1707 } else if (ShuffleKind == 2) { 1708 if (!IsLE) 1709 return false; 1710 for (unsigned i = 0; i != 16; i += 2) 1711 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1712 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1713 return false; 1714 } else if (ShuffleKind == 1) { 1715 unsigned j = IsLE ? 0 : 2; 1716 for (unsigned i = 0; i != 8; i += 2) 1717 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1718 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1719 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1720 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1721 return false; 1722 } 1723 return true; 1724 } 1725 1726 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1727 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1728 /// current subtarget. 1729 /// 1730 /// The ShuffleKind distinguishes between big-endian operations with 1731 /// two different inputs (0), either-endian operations with two identical 1732 /// inputs (1), and little-endian operations with two different inputs (2). 1733 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1734 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1735 SelectionDAG &DAG) { 1736 const PPCSubtarget& Subtarget = 1737 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1738 if (!Subtarget.hasP8Vector()) 1739 return false; 1740 1741 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1742 if (ShuffleKind == 0) { 1743 if (IsLE) 1744 return false; 1745 for (unsigned i = 0; i != 16; i += 4) 1746 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1747 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1748 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1749 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1750 return false; 1751 } else if (ShuffleKind == 2) { 1752 if (!IsLE) 1753 return false; 1754 for (unsigned i = 0; i != 16; i += 4) 1755 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1756 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1757 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1758 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1759 return false; 1760 } else if (ShuffleKind == 1) { 1761 unsigned j = IsLE ? 0 : 4; 1762 for (unsigned i = 0; i != 8; i += 4) 1763 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1764 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1765 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1766 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1767 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1768 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1769 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1770 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1771 return false; 1772 } 1773 return true; 1774 } 1775 1776 /// isVMerge - Common function, used to match vmrg* shuffles. 1777 /// 1778 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1779 unsigned LHSStart, unsigned RHSStart) { 1780 if (N->getValueType(0) != MVT::v16i8) 1781 return false; 1782 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1783 "Unsupported merge size!"); 1784 1785 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1786 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1787 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1788 LHSStart+j+i*UnitSize) || 1789 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1790 RHSStart+j+i*UnitSize)) 1791 return false; 1792 } 1793 return true; 1794 } 1795 1796 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1797 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1798 /// The ShuffleKind distinguishes between big-endian merges with two 1799 /// different inputs (0), either-endian merges with two identical inputs (1), 1800 /// and little-endian merges with two different inputs (2). For the latter, 1801 /// the input operands are swapped (see PPCInstrAltivec.td). 1802 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1803 unsigned ShuffleKind, SelectionDAG &DAG) { 1804 if (DAG.getDataLayout().isLittleEndian()) { 1805 if (ShuffleKind == 1) // unary 1806 return isVMerge(N, UnitSize, 0, 0); 1807 else if (ShuffleKind == 2) // swapped 1808 return isVMerge(N, UnitSize, 0, 16); 1809 else 1810 return false; 1811 } else { 1812 if (ShuffleKind == 1) // unary 1813 return isVMerge(N, UnitSize, 8, 8); 1814 else if (ShuffleKind == 0) // normal 1815 return isVMerge(N, UnitSize, 8, 24); 1816 else 1817 return false; 1818 } 1819 } 1820 1821 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1822 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1823 /// The ShuffleKind distinguishes between big-endian merges with two 1824 /// different inputs (0), either-endian merges with two identical inputs (1), 1825 /// and little-endian merges with two different inputs (2). For the latter, 1826 /// the input operands are swapped (see PPCInstrAltivec.td). 1827 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1828 unsigned ShuffleKind, SelectionDAG &DAG) { 1829 if (DAG.getDataLayout().isLittleEndian()) { 1830 if (ShuffleKind == 1) // unary 1831 return isVMerge(N, UnitSize, 8, 8); 1832 else if (ShuffleKind == 2) // swapped 1833 return isVMerge(N, UnitSize, 8, 24); 1834 else 1835 return false; 1836 } else { 1837 if (ShuffleKind == 1) // unary 1838 return isVMerge(N, UnitSize, 0, 0); 1839 else if (ShuffleKind == 0) // normal 1840 return isVMerge(N, UnitSize, 0, 16); 1841 else 1842 return false; 1843 } 1844 } 1845 1846 /** 1847 * Common function used to match vmrgew and vmrgow shuffles 1848 * 1849 * The indexOffset determines whether to look for even or odd words in 1850 * the shuffle mask. This is based on the of the endianness of the target 1851 * machine. 1852 * - Little Endian: 1853 * - Use offset of 0 to check for odd elements 1854 * - Use offset of 4 to check for even elements 1855 * - Big Endian: 1856 * - Use offset of 0 to check for even elements 1857 * - Use offset of 4 to check for odd elements 1858 * A detailed description of the vector element ordering for little endian and 1859 * big endian can be found at 1860 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1861 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1862 * compiler differences mean to you 1863 * 1864 * The mask to the shuffle vector instruction specifies the indices of the 1865 * elements from the two input vectors to place in the result. The elements are 1866 * numbered in array-access order, starting with the first vector. These vectors 1867 * are always of type v16i8, thus each vector will contain 16 elements of size 1868 * 8. More info on the shuffle vector can be found in the 1869 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1870 * Language Reference. 1871 * 1872 * The RHSStartValue indicates whether the same input vectors are used (unary) 1873 * or two different input vectors are used, based on the following: 1874 * - If the instruction uses the same vector for both inputs, the range of the 1875 * indices will be 0 to 15. In this case, the RHSStart value passed should 1876 * be 0. 1877 * - If the instruction has two different vectors then the range of the 1878 * indices will be 0 to 31. In this case, the RHSStart value passed should 1879 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1880 * to 31 specify elements in the second vector). 1881 * 1882 * \param[in] N The shuffle vector SD Node to analyze 1883 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1884 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1885 * vector to the shuffle_vector instruction 1886 * \return true iff this shuffle vector represents an even or odd word merge 1887 */ 1888 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1889 unsigned RHSStartValue) { 1890 if (N->getValueType(0) != MVT::v16i8) 1891 return false; 1892 1893 for (unsigned i = 0; i < 2; ++i) 1894 for (unsigned j = 0; j < 4; ++j) 1895 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1896 i*RHSStartValue+j+IndexOffset) || 1897 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1898 i*RHSStartValue+j+IndexOffset+8)) 1899 return false; 1900 return true; 1901 } 1902 1903 /** 1904 * Determine if the specified shuffle mask is suitable for the vmrgew or 1905 * vmrgow instructions. 1906 * 1907 * \param[in] N The shuffle vector SD Node to analyze 1908 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1909 * \param[in] ShuffleKind Identify the type of merge: 1910 * - 0 = big-endian merge with two different inputs; 1911 * - 1 = either-endian merge with two identical inputs; 1912 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1913 * little-endian merges). 1914 * \param[in] DAG The current SelectionDAG 1915 * \return true iff this shuffle mask 1916 */ 1917 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1918 unsigned ShuffleKind, SelectionDAG &DAG) { 1919 if (DAG.getDataLayout().isLittleEndian()) { 1920 unsigned indexOffset = CheckEven ? 4 : 0; 1921 if (ShuffleKind == 1) // Unary 1922 return isVMerge(N, indexOffset, 0); 1923 else if (ShuffleKind == 2) // swapped 1924 return isVMerge(N, indexOffset, 16); 1925 else 1926 return false; 1927 } 1928 else { 1929 unsigned indexOffset = CheckEven ? 0 : 4; 1930 if (ShuffleKind == 1) // Unary 1931 return isVMerge(N, indexOffset, 0); 1932 else if (ShuffleKind == 0) // Normal 1933 return isVMerge(N, indexOffset, 16); 1934 else 1935 return false; 1936 } 1937 return false; 1938 } 1939 1940 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1941 /// amount, otherwise return -1. 1942 /// The ShuffleKind distinguishes between big-endian operations with two 1943 /// different inputs (0), either-endian operations with two identical inputs 1944 /// (1), and little-endian operations with two different inputs (2). For the 1945 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1946 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1947 SelectionDAG &DAG) { 1948 if (N->getValueType(0) != MVT::v16i8) 1949 return -1; 1950 1951 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1952 1953 // Find the first non-undef value in the shuffle mask. 1954 unsigned i; 1955 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1956 /*search*/; 1957 1958 if (i == 16) return -1; // all undef. 1959 1960 // Otherwise, check to see if the rest of the elements are consecutively 1961 // numbered from this value. 1962 unsigned ShiftAmt = SVOp->getMaskElt(i); 1963 if (ShiftAmt < i) return -1; 1964 1965 ShiftAmt -= i; 1966 bool isLE = DAG.getDataLayout().isLittleEndian(); 1967 1968 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1969 // Check the rest of the elements to see if they are consecutive. 1970 for (++i; i != 16; ++i) 1971 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1972 return -1; 1973 } else if (ShuffleKind == 1) { 1974 // Check the rest of the elements to see if they are consecutive. 1975 for (++i; i != 16; ++i) 1976 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1977 return -1; 1978 } else 1979 return -1; 1980 1981 if (isLE) 1982 ShiftAmt = 16 - ShiftAmt; 1983 1984 return ShiftAmt; 1985 } 1986 1987 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1988 /// specifies a splat of a single element that is suitable for input to 1989 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1990 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1991 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1992 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1993 1994 // The consecutive indices need to specify an element, not part of two 1995 // different elements. So abandon ship early if this isn't the case. 1996 if (N->getMaskElt(0) % EltSize != 0) 1997 return false; 1998 1999 // This is a splat operation if each element of the permute is the same, and 2000 // if the value doesn't reference the second vector. 2001 unsigned ElementBase = N->getMaskElt(0); 2002 2003 // FIXME: Handle UNDEF elements too! 2004 if (ElementBase >= 16) 2005 return false; 2006 2007 // Check that the indices are consecutive, in the case of a multi-byte element 2008 // splatted with a v16i8 mask. 2009 for (unsigned i = 1; i != EltSize; ++i) 2010 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2011 return false; 2012 2013 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2014 if (N->getMaskElt(i) < 0) continue; 2015 for (unsigned j = 0; j != EltSize; ++j) 2016 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2017 return false; 2018 } 2019 return true; 2020 } 2021 2022 /// Check that the mask is shuffling N byte elements. Within each N byte 2023 /// element of the mask, the indices could be either in increasing or 2024 /// decreasing order as long as they are consecutive. 2025 /// \param[in] N the shuffle vector SD Node to analyze 2026 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2027 /// Word/DoubleWord/QuadWord). 2028 /// \param[in] StepLen the delta indices number among the N byte element, if 2029 /// the mask is in increasing/decreasing order then it is 1/-1. 2030 /// \return true iff the mask is shuffling N byte elements. 2031 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2032 int StepLen) { 2033 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2034 "Unexpected element width."); 2035 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2036 2037 unsigned NumOfElem = 16 / Width; 2038 unsigned MaskVal[16]; // Width is never greater than 16 2039 for (unsigned i = 0; i < NumOfElem; ++i) { 2040 MaskVal[0] = N->getMaskElt(i * Width); 2041 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2042 return false; 2043 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2044 return false; 2045 } 2046 2047 for (unsigned int j = 1; j < Width; ++j) { 2048 MaskVal[j] = N->getMaskElt(i * Width + j); 2049 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2050 return false; 2051 } 2052 } 2053 } 2054 2055 return true; 2056 } 2057 2058 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2059 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2060 if (!isNByteElemShuffleMask(N, 4, 1)) 2061 return false; 2062 2063 // Now we look at mask elements 0,4,8,12 2064 unsigned M0 = N->getMaskElt(0) / 4; 2065 unsigned M1 = N->getMaskElt(4) / 4; 2066 unsigned M2 = N->getMaskElt(8) / 4; 2067 unsigned M3 = N->getMaskElt(12) / 4; 2068 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2069 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2070 2071 // Below, let H and L be arbitrary elements of the shuffle mask 2072 // where H is in the range [4,7] and L is in the range [0,3]. 2073 // H, 1, 2, 3 or L, 5, 6, 7 2074 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2075 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2076 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2077 InsertAtByte = IsLE ? 12 : 0; 2078 Swap = M0 < 4; 2079 return true; 2080 } 2081 // 0, H, 2, 3 or 4, L, 6, 7 2082 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2083 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2084 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2085 InsertAtByte = IsLE ? 8 : 4; 2086 Swap = M1 < 4; 2087 return true; 2088 } 2089 // 0, 1, H, 3 or 4, 5, L, 7 2090 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2091 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2092 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2093 InsertAtByte = IsLE ? 4 : 8; 2094 Swap = M2 < 4; 2095 return true; 2096 } 2097 // 0, 1, 2, H or 4, 5, 6, L 2098 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2099 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2100 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2101 InsertAtByte = IsLE ? 0 : 12; 2102 Swap = M3 < 4; 2103 return true; 2104 } 2105 2106 // If both vector operands for the shuffle are the same vector, the mask will 2107 // contain only elements from the first one and the second one will be undef. 2108 if (N->getOperand(1).isUndef()) { 2109 ShiftElts = 0; 2110 Swap = true; 2111 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2112 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2113 InsertAtByte = IsLE ? 12 : 0; 2114 return true; 2115 } 2116 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2117 InsertAtByte = IsLE ? 8 : 4; 2118 return true; 2119 } 2120 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2121 InsertAtByte = IsLE ? 4 : 8; 2122 return true; 2123 } 2124 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2125 InsertAtByte = IsLE ? 0 : 12; 2126 return true; 2127 } 2128 } 2129 2130 return false; 2131 } 2132 2133 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2134 bool &Swap, bool IsLE) { 2135 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2136 // Ensure each byte index of the word is consecutive. 2137 if (!isNByteElemShuffleMask(N, 4, 1)) 2138 return false; 2139 2140 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2141 unsigned M0 = N->getMaskElt(0) / 4; 2142 unsigned M1 = N->getMaskElt(4) / 4; 2143 unsigned M2 = N->getMaskElt(8) / 4; 2144 unsigned M3 = N->getMaskElt(12) / 4; 2145 2146 // If both vector operands for the shuffle are the same vector, the mask will 2147 // contain only elements from the first one and the second one will be undef. 2148 if (N->getOperand(1).isUndef()) { 2149 assert(M0 < 4 && "Indexing into an undef vector?"); 2150 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2151 return false; 2152 2153 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2154 Swap = false; 2155 return true; 2156 } 2157 2158 // Ensure each word index of the ShuffleVector Mask is consecutive. 2159 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2160 return false; 2161 2162 if (IsLE) { 2163 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2164 // Input vectors don't need to be swapped if the leading element 2165 // of the result is one of the 3 left elements of the second vector 2166 // (or if there is no shift to be done at all). 2167 Swap = false; 2168 ShiftElts = (8 - M0) % 8; 2169 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2170 // Input vectors need to be swapped if the leading element 2171 // of the result is one of the 3 left elements of the first vector 2172 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2173 Swap = true; 2174 ShiftElts = (4 - M0) % 4; 2175 } 2176 2177 return true; 2178 } else { // BE 2179 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2180 // Input vectors don't need to be swapped if the leading element 2181 // of the result is one of the 4 elements of the first vector. 2182 Swap = false; 2183 ShiftElts = M0; 2184 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2185 // Input vectors need to be swapped if the leading element 2186 // of the result is one of the 4 elements of the right vector. 2187 Swap = true; 2188 ShiftElts = M0 - 4; 2189 } 2190 2191 return true; 2192 } 2193 } 2194 2195 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2196 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2197 2198 if (!isNByteElemShuffleMask(N, Width, -1)) 2199 return false; 2200 2201 for (int i = 0; i < 16; i += Width) 2202 if (N->getMaskElt(i) != i + Width - 1) 2203 return false; 2204 2205 return true; 2206 } 2207 2208 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2209 return isXXBRShuffleMaskHelper(N, 2); 2210 } 2211 2212 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2213 return isXXBRShuffleMaskHelper(N, 4); 2214 } 2215 2216 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2217 return isXXBRShuffleMaskHelper(N, 8); 2218 } 2219 2220 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2221 return isXXBRShuffleMaskHelper(N, 16); 2222 } 2223 2224 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2225 /// if the inputs to the instruction should be swapped and set \p DM to the 2226 /// value for the immediate. 2227 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2228 /// AND element 0 of the result comes from the first input (LE) or second input 2229 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2230 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2231 /// mask. 2232 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2233 bool &Swap, bool IsLE) { 2234 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2235 2236 // Ensure each byte index of the double word is consecutive. 2237 if (!isNByteElemShuffleMask(N, 8, 1)) 2238 return false; 2239 2240 unsigned M0 = N->getMaskElt(0) / 8; 2241 unsigned M1 = N->getMaskElt(8) / 8; 2242 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2243 2244 // If both vector operands for the shuffle are the same vector, the mask will 2245 // contain only elements from the first one and the second one will be undef. 2246 if (N->getOperand(1).isUndef()) { 2247 if ((M0 | M1) < 2) { 2248 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2249 Swap = false; 2250 return true; 2251 } else 2252 return false; 2253 } 2254 2255 if (IsLE) { 2256 if (M0 > 1 && M1 < 2) { 2257 Swap = false; 2258 } else if (M0 < 2 && M1 > 1) { 2259 M0 = (M0 + 2) % 4; 2260 M1 = (M1 + 2) % 4; 2261 Swap = true; 2262 } else 2263 return false; 2264 2265 // Note: if control flow comes here that means Swap is already set above 2266 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2267 return true; 2268 } else { // BE 2269 if (M0 < 2 && M1 > 1) { 2270 Swap = false; 2271 } else if (M0 > 1 && M1 < 2) { 2272 M0 = (M0 + 2) % 4; 2273 M1 = (M1 + 2) % 4; 2274 Swap = true; 2275 } else 2276 return false; 2277 2278 // Note: if control flow comes here that means Swap is already set above 2279 DM = (M0 << 1) + (M1 & 1); 2280 return true; 2281 } 2282 } 2283 2284 2285 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2286 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2287 /// elements are counted from the left of the vector register). 2288 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2289 SelectionDAG &DAG) { 2290 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2291 assert(isSplatShuffleMask(SVOp, EltSize)); 2292 if (DAG.getDataLayout().isLittleEndian()) 2293 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2294 else 2295 return SVOp->getMaskElt(0) / EltSize; 2296 } 2297 2298 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2299 /// by using a vspltis[bhw] instruction of the specified element size, return 2300 /// the constant being splatted. The ByteSize field indicates the number of 2301 /// bytes of each element [124] -> [bhw]. 2302 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2303 SDValue OpVal(nullptr, 0); 2304 2305 // If ByteSize of the splat is bigger than the element size of the 2306 // build_vector, then we have a case where we are checking for a splat where 2307 // multiple elements of the buildvector are folded together into a single 2308 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2309 unsigned EltSize = 16/N->getNumOperands(); 2310 if (EltSize < ByteSize) { 2311 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2312 SDValue UniquedVals[4]; 2313 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2314 2315 // See if all of the elements in the buildvector agree across. 2316 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2317 if (N->getOperand(i).isUndef()) continue; 2318 // If the element isn't a constant, bail fully out. 2319 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2320 2321 if (!UniquedVals[i&(Multiple-1)].getNode()) 2322 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2323 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2324 return SDValue(); // no match. 2325 } 2326 2327 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2328 // either constant or undef values that are identical for each chunk. See 2329 // if these chunks can form into a larger vspltis*. 2330 2331 // Check to see if all of the leading entries are either 0 or -1. If 2332 // neither, then this won't fit into the immediate field. 2333 bool LeadingZero = true; 2334 bool LeadingOnes = true; 2335 for (unsigned i = 0; i != Multiple-1; ++i) { 2336 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2337 2338 LeadingZero &= isNullConstant(UniquedVals[i]); 2339 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2340 } 2341 // Finally, check the least significant entry. 2342 if (LeadingZero) { 2343 if (!UniquedVals[Multiple-1].getNode()) 2344 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2345 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2346 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2347 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2348 } 2349 if (LeadingOnes) { 2350 if (!UniquedVals[Multiple-1].getNode()) 2351 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2352 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2353 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2354 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2355 } 2356 2357 return SDValue(); 2358 } 2359 2360 // Check to see if this buildvec has a single non-undef value in its elements. 2361 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2362 if (N->getOperand(i).isUndef()) continue; 2363 if (!OpVal.getNode()) 2364 OpVal = N->getOperand(i); 2365 else if (OpVal != N->getOperand(i)) 2366 return SDValue(); 2367 } 2368 2369 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2370 2371 unsigned ValSizeInBytes = EltSize; 2372 uint64_t Value = 0; 2373 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2374 Value = CN->getZExtValue(); 2375 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2376 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2377 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2378 } 2379 2380 // If the splat value is larger than the element value, then we can never do 2381 // this splat. The only case that we could fit the replicated bits into our 2382 // immediate field for would be zero, and we prefer to use vxor for it. 2383 if (ValSizeInBytes < ByteSize) return SDValue(); 2384 2385 // If the element value is larger than the splat value, check if it consists 2386 // of a repeated bit pattern of size ByteSize. 2387 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2388 return SDValue(); 2389 2390 // Properly sign extend the value. 2391 int MaskVal = SignExtend32(Value, ByteSize * 8); 2392 2393 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2394 if (MaskVal == 0) return SDValue(); 2395 2396 // Finally, if this value fits in a 5 bit sext field, return it 2397 if (SignExtend32<5>(MaskVal) == MaskVal) 2398 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2399 return SDValue(); 2400 } 2401 2402 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2403 /// amount, otherwise return -1. 2404 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2405 EVT VT = N->getValueType(0); 2406 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2407 return -1; 2408 2409 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2410 2411 // Find the first non-undef value in the shuffle mask. 2412 unsigned i; 2413 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2414 /*search*/; 2415 2416 if (i == 4) return -1; // all undef. 2417 2418 // Otherwise, check to see if the rest of the elements are consecutively 2419 // numbered from this value. 2420 unsigned ShiftAmt = SVOp->getMaskElt(i); 2421 if (ShiftAmt < i) return -1; 2422 ShiftAmt -= i; 2423 2424 // Check the rest of the elements to see if they are consecutive. 2425 for (++i; i != 4; ++i) 2426 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2427 return -1; 2428 2429 return ShiftAmt; 2430 } 2431 2432 //===----------------------------------------------------------------------===// 2433 // Addressing Mode Selection 2434 //===----------------------------------------------------------------------===// 2435 2436 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2437 /// or 64-bit immediate, and if the value can be accurately represented as a 2438 /// sign extension from a 16-bit value. If so, this returns true and the 2439 /// immediate. 2440 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2441 if (!isa<ConstantSDNode>(N)) 2442 return false; 2443 2444 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2445 if (N->getValueType(0) == MVT::i32) 2446 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2447 else 2448 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2449 } 2450 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2451 return isIntS16Immediate(Op.getNode(), Imm); 2452 } 2453 2454 2455 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2456 /// be represented as an indexed [r+r] operation. 2457 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2458 SDValue &Index, 2459 SelectionDAG &DAG) const { 2460 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2461 UI != E; ++UI) { 2462 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2463 if (Memop->getMemoryVT() == MVT::f64) { 2464 Base = N.getOperand(0); 2465 Index = N.getOperand(1); 2466 return true; 2467 } 2468 } 2469 } 2470 return false; 2471 } 2472 2473 /// isIntS34Immediate - This method tests if value of node given can be 2474 /// accurately represented as a sign extension from a 34-bit value. If so, 2475 /// this returns true and the immediate. 2476 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2477 if (!isa<ConstantSDNode>(N)) 2478 return false; 2479 2480 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2481 return isInt<34>(Imm); 2482 } 2483 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2484 return isIntS34Immediate(Op.getNode(), Imm); 2485 } 2486 2487 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2488 /// can be represented as an indexed [r+r] operation. Returns false if it 2489 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2490 /// non-zero and N can be represented by a base register plus a signed 16-bit 2491 /// displacement, make a more precise judgement by checking (displacement % \p 2492 /// EncodingAlignment). 2493 bool PPCTargetLowering::SelectAddressRegReg( 2494 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2495 MaybeAlign EncodingAlignment) const { 2496 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2497 // a [pc+imm]. 2498 if (SelectAddressPCRel(N, Base)) 2499 return false; 2500 2501 int16_t Imm = 0; 2502 if (N.getOpcode() == ISD::ADD) { 2503 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2504 // SPE load/store can only handle 8-bit offsets. 2505 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2506 return true; 2507 if (isIntS16Immediate(N.getOperand(1), Imm) && 2508 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2509 return false; // r+i 2510 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2511 return false; // r+i 2512 2513 Base = N.getOperand(0); 2514 Index = N.getOperand(1); 2515 return true; 2516 } else if (N.getOpcode() == ISD::OR) { 2517 if (isIntS16Immediate(N.getOperand(1), Imm) && 2518 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2519 return false; // r+i can fold it if we can. 2520 2521 // If this is an or of disjoint bitfields, we can codegen this as an add 2522 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2523 // disjoint. 2524 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2525 2526 if (LHSKnown.Zero.getBoolValue()) { 2527 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2528 // If all of the bits are known zero on the LHS or RHS, the add won't 2529 // carry. 2530 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2531 Base = N.getOperand(0); 2532 Index = N.getOperand(1); 2533 return true; 2534 } 2535 } 2536 } 2537 2538 return false; 2539 } 2540 2541 // If we happen to be doing an i64 load or store into a stack slot that has 2542 // less than a 4-byte alignment, then the frame-index elimination may need to 2543 // use an indexed load or store instruction (because the offset may not be a 2544 // multiple of 4). The extra register needed to hold the offset comes from the 2545 // register scavenger, and it is possible that the scavenger will need to use 2546 // an emergency spill slot. As a result, we need to make sure that a spill slot 2547 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2548 // stack slot. 2549 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2550 // FIXME: This does not handle the LWA case. 2551 if (VT != MVT::i64) 2552 return; 2553 2554 // NOTE: We'll exclude negative FIs here, which come from argument 2555 // lowering, because there are no known test cases triggering this problem 2556 // using packed structures (or similar). We can remove this exclusion if 2557 // we find such a test case. The reason why this is so test-case driven is 2558 // because this entire 'fixup' is only to prevent crashes (from the 2559 // register scavenger) on not-really-valid inputs. For example, if we have: 2560 // %a = alloca i1 2561 // %b = bitcast i1* %a to i64* 2562 // store i64* a, i64 b 2563 // then the store should really be marked as 'align 1', but is not. If it 2564 // were marked as 'align 1' then the indexed form would have been 2565 // instruction-selected initially, and the problem this 'fixup' is preventing 2566 // won't happen regardless. 2567 if (FrameIdx < 0) 2568 return; 2569 2570 MachineFunction &MF = DAG.getMachineFunction(); 2571 MachineFrameInfo &MFI = MF.getFrameInfo(); 2572 2573 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2574 return; 2575 2576 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2577 FuncInfo->setHasNonRISpills(); 2578 } 2579 2580 /// Returns true if the address N can be represented by a base register plus 2581 /// a signed 16-bit displacement [r+imm], and if it is not better 2582 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2583 /// displacements that are multiples of that value. 2584 bool PPCTargetLowering::SelectAddressRegImm( 2585 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2586 MaybeAlign EncodingAlignment) const { 2587 // FIXME dl should come from parent load or store, not from address 2588 SDLoc dl(N); 2589 2590 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2591 // a [pc+imm]. 2592 if (SelectAddressPCRel(N, Base)) 2593 return false; 2594 2595 // If this can be more profitably realized as r+r, fail. 2596 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2597 return false; 2598 2599 if (N.getOpcode() == ISD::ADD) { 2600 int16_t imm = 0; 2601 if (isIntS16Immediate(N.getOperand(1), imm) && 2602 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2603 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2604 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2605 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2606 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2607 } else { 2608 Base = N.getOperand(0); 2609 } 2610 return true; // [r+i] 2611 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2612 // Match LOAD (ADD (X, Lo(G))). 2613 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2614 && "Cannot handle constant offsets yet!"); 2615 Disp = N.getOperand(1).getOperand(0); // The global address. 2616 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2617 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2618 Disp.getOpcode() == ISD::TargetConstantPool || 2619 Disp.getOpcode() == ISD::TargetJumpTable); 2620 Base = N.getOperand(0); 2621 return true; // [&g+r] 2622 } 2623 } else if (N.getOpcode() == ISD::OR) { 2624 int16_t imm = 0; 2625 if (isIntS16Immediate(N.getOperand(1), imm) && 2626 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2627 // If this is an or of disjoint bitfields, we can codegen this as an add 2628 // (for better address arithmetic) if the LHS and RHS of the OR are 2629 // provably disjoint. 2630 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2631 2632 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2633 // If all of the bits are known zero on the LHS or RHS, the add won't 2634 // carry. 2635 if (FrameIndexSDNode *FI = 2636 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2637 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2638 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2639 } else { 2640 Base = N.getOperand(0); 2641 } 2642 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2643 return true; 2644 } 2645 } 2646 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2647 // Loading from a constant address. 2648 2649 // If this address fits entirely in a 16-bit sext immediate field, codegen 2650 // this as "d, 0" 2651 int16_t Imm; 2652 if (isIntS16Immediate(CN, Imm) && 2653 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2654 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2655 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2656 CN->getValueType(0)); 2657 return true; 2658 } 2659 2660 // Handle 32-bit sext immediates with LIS + addr mode. 2661 if ((CN->getValueType(0) == MVT::i32 || 2662 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2663 (!EncodingAlignment || 2664 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2665 int Addr = (int)CN->getZExtValue(); 2666 2667 // Otherwise, break this down into an LIS + disp. 2668 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2669 2670 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2671 MVT::i32); 2672 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2673 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2674 return true; 2675 } 2676 } 2677 2678 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2679 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2680 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2681 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2682 } else 2683 Base = N; 2684 return true; // [r+0] 2685 } 2686 2687 /// Similar to the 16-bit case but for instructions that take a 34-bit 2688 /// displacement field (prefixed loads/stores). 2689 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2690 SDValue &Base, 2691 SelectionDAG &DAG) const { 2692 // Only on 64-bit targets. 2693 if (N.getValueType() != MVT::i64) 2694 return false; 2695 2696 SDLoc dl(N); 2697 int64_t Imm = 0; 2698 2699 if (N.getOpcode() == ISD::ADD) { 2700 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2701 return false; 2702 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2703 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2704 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2705 else 2706 Base = N.getOperand(0); 2707 return true; 2708 } 2709 2710 if (N.getOpcode() == ISD::OR) { 2711 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2712 return false; 2713 // If this is an or of disjoint bitfields, we can codegen this as an add 2714 // (for better address arithmetic) if the LHS and RHS of the OR are 2715 // provably disjoint. 2716 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2717 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2718 return false; 2719 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2720 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2721 else 2722 Base = N.getOperand(0); 2723 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2724 return true; 2725 } 2726 2727 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2728 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2729 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2730 return true; 2731 } 2732 2733 return false; 2734 } 2735 2736 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2737 /// represented as an indexed [r+r] operation. 2738 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2739 SDValue &Index, 2740 SelectionDAG &DAG) const { 2741 // Check to see if we can easily represent this as an [r+r] address. This 2742 // will fail if it thinks that the address is more profitably represented as 2743 // reg+imm, e.g. where imm = 0. 2744 if (SelectAddressRegReg(N, Base, Index, DAG)) 2745 return true; 2746 2747 // If the address is the result of an add, we will utilize the fact that the 2748 // address calculation includes an implicit add. However, we can reduce 2749 // register pressure if we do not materialize a constant just for use as the 2750 // index register. We only get rid of the add if it is not an add of a 2751 // value and a 16-bit signed constant and both have a single use. 2752 int16_t imm = 0; 2753 if (N.getOpcode() == ISD::ADD && 2754 (!isIntS16Immediate(N.getOperand(1), imm) || 2755 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2756 Base = N.getOperand(0); 2757 Index = N.getOperand(1); 2758 return true; 2759 } 2760 2761 // Otherwise, do it the hard way, using R0 as the base register. 2762 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2763 N.getValueType()); 2764 Index = N; 2765 return true; 2766 } 2767 2768 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2769 Ty *PCRelCand = dyn_cast<Ty>(N); 2770 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2771 } 2772 2773 /// Returns true if this address is a PC Relative address. 2774 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2775 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2776 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2777 // This is a materialize PC Relative node. Always select this as PC Relative. 2778 Base = N; 2779 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2780 return true; 2781 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2782 isValidPCRelNode<GlobalAddressSDNode>(N) || 2783 isValidPCRelNode<JumpTableSDNode>(N) || 2784 isValidPCRelNode<BlockAddressSDNode>(N)) 2785 return true; 2786 return false; 2787 } 2788 2789 /// Returns true if we should use a direct load into vector instruction 2790 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2791 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2792 2793 // If there are any other uses other than scalar to vector, then we should 2794 // keep it as a scalar load -> direct move pattern to prevent multiple 2795 // loads. 2796 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2797 if (!LD) 2798 return false; 2799 2800 EVT MemVT = LD->getMemoryVT(); 2801 if (!MemVT.isSimple()) 2802 return false; 2803 switch(MemVT.getSimpleVT().SimpleTy) { 2804 case MVT::i64: 2805 break; 2806 case MVT::i32: 2807 if (!ST.hasP8Vector()) 2808 return false; 2809 break; 2810 case MVT::i16: 2811 case MVT::i8: 2812 if (!ST.hasP9Vector()) 2813 return false; 2814 break; 2815 default: 2816 return false; 2817 } 2818 2819 SDValue LoadedVal(N, 0); 2820 if (!LoadedVal.hasOneUse()) 2821 return false; 2822 2823 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2824 UI != UE; ++UI) 2825 if (UI.getUse().get().getResNo() == 0 && 2826 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2827 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2828 return false; 2829 2830 return true; 2831 } 2832 2833 /// getPreIndexedAddressParts - returns true by value, base pointer and 2834 /// offset pointer and addressing mode by reference if the node's address 2835 /// can be legally represented as pre-indexed load / store address. 2836 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2837 SDValue &Offset, 2838 ISD::MemIndexedMode &AM, 2839 SelectionDAG &DAG) const { 2840 if (DisablePPCPreinc) return false; 2841 2842 bool isLoad = true; 2843 SDValue Ptr; 2844 EVT VT; 2845 unsigned Alignment; 2846 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2847 Ptr = LD->getBasePtr(); 2848 VT = LD->getMemoryVT(); 2849 Alignment = LD->getAlignment(); 2850 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2851 Ptr = ST->getBasePtr(); 2852 VT = ST->getMemoryVT(); 2853 Alignment = ST->getAlignment(); 2854 isLoad = false; 2855 } else 2856 return false; 2857 2858 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2859 // instructions because we can fold these into a more efficient instruction 2860 // instead, (such as LXSD). 2861 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2862 return false; 2863 } 2864 2865 // PowerPC doesn't have preinc load/store instructions for vectors 2866 if (VT.isVector()) 2867 return false; 2868 2869 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2870 // Common code will reject creating a pre-inc form if the base pointer 2871 // is a frame index, or if N is a store and the base pointer is either 2872 // the same as or a predecessor of the value being stored. Check for 2873 // those situations here, and try with swapped Base/Offset instead. 2874 bool Swap = false; 2875 2876 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2877 Swap = true; 2878 else if (!isLoad) { 2879 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2880 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2881 Swap = true; 2882 } 2883 2884 if (Swap) 2885 std::swap(Base, Offset); 2886 2887 AM = ISD::PRE_INC; 2888 return true; 2889 } 2890 2891 // LDU/STU can only handle immediates that are a multiple of 4. 2892 if (VT != MVT::i64) { 2893 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2894 return false; 2895 } else { 2896 // LDU/STU need an address with at least 4-byte alignment. 2897 if (Alignment < 4) 2898 return false; 2899 2900 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2901 return false; 2902 } 2903 2904 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2905 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2906 // sext i32 to i64 when addr mode is r+i. 2907 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2908 LD->getExtensionType() == ISD::SEXTLOAD && 2909 isa<ConstantSDNode>(Offset)) 2910 return false; 2911 } 2912 2913 AM = ISD::PRE_INC; 2914 return true; 2915 } 2916 2917 //===----------------------------------------------------------------------===// 2918 // LowerOperation implementation 2919 //===----------------------------------------------------------------------===// 2920 2921 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2922 /// and LoOpFlags to the target MO flags. 2923 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2924 unsigned &HiOpFlags, unsigned &LoOpFlags, 2925 const GlobalValue *GV = nullptr) { 2926 HiOpFlags = PPCII::MO_HA; 2927 LoOpFlags = PPCII::MO_LO; 2928 2929 // Don't use the pic base if not in PIC relocation model. 2930 if (IsPIC) { 2931 HiOpFlags |= PPCII::MO_PIC_FLAG; 2932 LoOpFlags |= PPCII::MO_PIC_FLAG; 2933 } 2934 } 2935 2936 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2937 SelectionDAG &DAG) { 2938 SDLoc DL(HiPart); 2939 EVT PtrVT = HiPart.getValueType(); 2940 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2941 2942 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2943 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2944 2945 // With PIC, the first instruction is actually "GR+hi(&G)". 2946 if (isPIC) 2947 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2948 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2949 2950 // Generate non-pic code that has direct accesses to the constant pool. 2951 // The address of the global is just (hi(&g)+lo(&g)). 2952 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2953 } 2954 2955 static void setUsesTOCBasePtr(MachineFunction &MF) { 2956 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2957 FuncInfo->setUsesTOCBasePtr(); 2958 } 2959 2960 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2961 setUsesTOCBasePtr(DAG.getMachineFunction()); 2962 } 2963 2964 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2965 SDValue GA) const { 2966 const bool Is64Bit = Subtarget.isPPC64(); 2967 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2968 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2969 : Subtarget.isAIXABI() 2970 ? DAG.getRegister(PPC::R2, VT) 2971 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2972 SDValue Ops[] = { GA, Reg }; 2973 return DAG.getMemIntrinsicNode( 2974 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2975 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2976 MachineMemOperand::MOLoad); 2977 } 2978 2979 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2980 SelectionDAG &DAG) const { 2981 EVT PtrVT = Op.getValueType(); 2982 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2983 const Constant *C = CP->getConstVal(); 2984 2985 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2986 // The actual address of the GlobalValue is stored in the TOC. 2987 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2988 if (Subtarget.isUsingPCRelativeCalls()) { 2989 SDLoc DL(CP); 2990 EVT Ty = getPointerTy(DAG.getDataLayout()); 2991 SDValue ConstPool = DAG.getTargetConstantPool( 2992 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2993 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2994 } 2995 setUsesTOCBasePtr(DAG); 2996 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2997 return getTOCEntry(DAG, SDLoc(CP), GA); 2998 } 2999 3000 unsigned MOHiFlag, MOLoFlag; 3001 bool IsPIC = isPositionIndependent(); 3002 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3003 3004 if (IsPIC && Subtarget.isSVR4ABI()) { 3005 SDValue GA = 3006 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3007 return getTOCEntry(DAG, SDLoc(CP), GA); 3008 } 3009 3010 SDValue CPIHi = 3011 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3012 SDValue CPILo = 3013 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3014 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3015 } 3016 3017 // For 64-bit PowerPC, prefer the more compact relative encodings. 3018 // This trades 32 bits per jump table entry for one or two instructions 3019 // on the jump site. 3020 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3021 if (isJumpTableRelative()) 3022 return MachineJumpTableInfo::EK_LabelDifference32; 3023 3024 return TargetLowering::getJumpTableEncoding(); 3025 } 3026 3027 bool PPCTargetLowering::isJumpTableRelative() const { 3028 if (UseAbsoluteJumpTables) 3029 return false; 3030 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3031 return true; 3032 return TargetLowering::isJumpTableRelative(); 3033 } 3034 3035 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3036 SelectionDAG &DAG) const { 3037 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3038 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3039 3040 switch (getTargetMachine().getCodeModel()) { 3041 case CodeModel::Small: 3042 case CodeModel::Medium: 3043 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3044 default: 3045 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3046 getPointerTy(DAG.getDataLayout())); 3047 } 3048 } 3049 3050 const MCExpr * 3051 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3052 unsigned JTI, 3053 MCContext &Ctx) const { 3054 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3055 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3056 3057 switch (getTargetMachine().getCodeModel()) { 3058 case CodeModel::Small: 3059 case CodeModel::Medium: 3060 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3061 default: 3062 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3063 } 3064 } 3065 3066 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3067 EVT PtrVT = Op.getValueType(); 3068 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3069 3070 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3071 if (Subtarget.isUsingPCRelativeCalls()) { 3072 SDLoc DL(JT); 3073 EVT Ty = getPointerTy(DAG.getDataLayout()); 3074 SDValue GA = 3075 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3076 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3077 return MatAddr; 3078 } 3079 3080 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3081 // The actual address of the GlobalValue is stored in the TOC. 3082 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3083 setUsesTOCBasePtr(DAG); 3084 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3085 return getTOCEntry(DAG, SDLoc(JT), GA); 3086 } 3087 3088 unsigned MOHiFlag, MOLoFlag; 3089 bool IsPIC = isPositionIndependent(); 3090 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3091 3092 if (IsPIC && Subtarget.isSVR4ABI()) { 3093 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3094 PPCII::MO_PIC_FLAG); 3095 return getTOCEntry(DAG, SDLoc(GA), GA); 3096 } 3097 3098 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3099 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3100 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3101 } 3102 3103 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3104 SelectionDAG &DAG) const { 3105 EVT PtrVT = Op.getValueType(); 3106 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3107 const BlockAddress *BA = BASDN->getBlockAddress(); 3108 3109 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3110 if (Subtarget.isUsingPCRelativeCalls()) { 3111 SDLoc DL(BASDN); 3112 EVT Ty = getPointerTy(DAG.getDataLayout()); 3113 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3114 PPCII::MO_PCREL_FLAG); 3115 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3116 return MatAddr; 3117 } 3118 3119 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3120 // The actual BlockAddress is stored in the TOC. 3121 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3122 setUsesTOCBasePtr(DAG); 3123 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3124 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3125 } 3126 3127 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3128 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3129 return getTOCEntry( 3130 DAG, SDLoc(BASDN), 3131 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3132 3133 unsigned MOHiFlag, MOLoFlag; 3134 bool IsPIC = isPositionIndependent(); 3135 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3136 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3137 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3138 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3139 } 3140 3141 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3142 SelectionDAG &DAG) const { 3143 // FIXME: TLS addresses currently use medium model code sequences, 3144 // which is the most useful form. Eventually support for small and 3145 // large models could be added if users need it, at the cost of 3146 // additional complexity. 3147 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3148 if (DAG.getTarget().useEmulatedTLS()) 3149 return LowerToTLSEmulatedModel(GA, DAG); 3150 3151 SDLoc dl(GA); 3152 const GlobalValue *GV = GA->getGlobal(); 3153 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3154 bool is64bit = Subtarget.isPPC64(); 3155 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3156 PICLevel::Level picLevel = M->getPICLevel(); 3157 3158 const TargetMachine &TM = getTargetMachine(); 3159 TLSModel::Model Model = TM.getTLSModel(GV); 3160 3161 if (Model == TLSModel::LocalExec) { 3162 if (Subtarget.isUsingPCRelativeCalls()) { 3163 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3164 SDValue TGA = DAG.getTargetGlobalAddress( 3165 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3166 SDValue MatAddr = 3167 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3168 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3169 } 3170 3171 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3172 PPCII::MO_TPREL_HA); 3173 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3174 PPCII::MO_TPREL_LO); 3175 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3176 : DAG.getRegister(PPC::R2, MVT::i32); 3177 3178 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3179 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3180 } 3181 3182 if (Model == TLSModel::InitialExec) { 3183 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3184 SDValue TGA = DAG.getTargetGlobalAddress( 3185 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3186 SDValue TGATLS = DAG.getTargetGlobalAddress( 3187 GV, dl, PtrVT, 0, 3188 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3189 SDValue TPOffset; 3190 if (IsPCRel) { 3191 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3192 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3193 MachinePointerInfo()); 3194 } else { 3195 SDValue GOTPtr; 3196 if (is64bit) { 3197 setUsesTOCBasePtr(DAG); 3198 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3199 GOTPtr = 3200 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3201 } else { 3202 if (!TM.isPositionIndependent()) 3203 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3204 else if (picLevel == PICLevel::SmallPIC) 3205 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3206 else 3207 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3208 } 3209 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3210 } 3211 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3212 } 3213 3214 if (Model == TLSModel::GeneralDynamic) { 3215 if (Subtarget.isUsingPCRelativeCalls()) { 3216 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3217 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3218 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3219 } 3220 3221 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3222 SDValue GOTPtr; 3223 if (is64bit) { 3224 setUsesTOCBasePtr(DAG); 3225 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3226 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3227 GOTReg, TGA); 3228 } else { 3229 if (picLevel == PICLevel::SmallPIC) 3230 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3231 else 3232 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3233 } 3234 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3235 GOTPtr, TGA, TGA); 3236 } 3237 3238 if (Model == TLSModel::LocalDynamic) { 3239 if (Subtarget.isUsingPCRelativeCalls()) { 3240 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3241 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3242 SDValue MatPCRel = 3243 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3244 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3245 } 3246 3247 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3248 SDValue GOTPtr; 3249 if (is64bit) { 3250 setUsesTOCBasePtr(DAG); 3251 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3252 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3253 GOTReg, TGA); 3254 } else { 3255 if (picLevel == PICLevel::SmallPIC) 3256 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3257 else 3258 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3259 } 3260 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3261 PtrVT, GOTPtr, TGA, TGA); 3262 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3263 PtrVT, TLSAddr, TGA); 3264 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3265 } 3266 3267 llvm_unreachable("Unknown TLS model!"); 3268 } 3269 3270 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3271 SelectionDAG &DAG) const { 3272 EVT PtrVT = Op.getValueType(); 3273 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3274 SDLoc DL(GSDN); 3275 const GlobalValue *GV = GSDN->getGlobal(); 3276 3277 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3278 // The actual address of the GlobalValue is stored in the TOC. 3279 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3280 if (Subtarget.isUsingPCRelativeCalls()) { 3281 EVT Ty = getPointerTy(DAG.getDataLayout()); 3282 if (isAccessedAsGotIndirect(Op)) { 3283 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3284 PPCII::MO_PCREL_FLAG | 3285 PPCII::MO_GOT_FLAG); 3286 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3287 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3288 MachinePointerInfo()); 3289 return Load; 3290 } else { 3291 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3292 PPCII::MO_PCREL_FLAG); 3293 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3294 } 3295 } 3296 setUsesTOCBasePtr(DAG); 3297 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3298 return getTOCEntry(DAG, DL, GA); 3299 } 3300 3301 unsigned MOHiFlag, MOLoFlag; 3302 bool IsPIC = isPositionIndependent(); 3303 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3304 3305 if (IsPIC && Subtarget.isSVR4ABI()) { 3306 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3307 GSDN->getOffset(), 3308 PPCII::MO_PIC_FLAG); 3309 return getTOCEntry(DAG, DL, GA); 3310 } 3311 3312 SDValue GAHi = 3313 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3314 SDValue GALo = 3315 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3316 3317 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3318 } 3319 3320 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3321 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3322 SDLoc dl(Op); 3323 3324 if (Op.getValueType() == MVT::v2i64) { 3325 // When the operands themselves are v2i64 values, we need to do something 3326 // special because VSX has no underlying comparison operations for these. 3327 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3328 // Equality can be handled by casting to the legal type for Altivec 3329 // comparisons, everything else needs to be expanded. 3330 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3331 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3332 DAG.getSetCC(dl, MVT::v4i32, 3333 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3334 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3335 CC)); 3336 } 3337 3338 return SDValue(); 3339 } 3340 3341 // We handle most of these in the usual way. 3342 return Op; 3343 } 3344 3345 // If we're comparing for equality to zero, expose the fact that this is 3346 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3347 // fold the new nodes. 3348 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3349 return V; 3350 3351 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3352 // Leave comparisons against 0 and -1 alone for now, since they're usually 3353 // optimized. FIXME: revisit this when we can custom lower all setcc 3354 // optimizations. 3355 if (C->isAllOnesValue() || C->isNullValue()) 3356 return SDValue(); 3357 } 3358 3359 // If we have an integer seteq/setne, turn it into a compare against zero 3360 // by xor'ing the rhs with the lhs, which is faster than setting a 3361 // condition register, reading it back out, and masking the correct bit. The 3362 // normal approach here uses sub to do this instead of xor. Using xor exposes 3363 // the result to other bit-twiddling opportunities. 3364 EVT LHSVT = Op.getOperand(0).getValueType(); 3365 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3366 EVT VT = Op.getValueType(); 3367 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3368 Op.getOperand(1)); 3369 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3370 } 3371 return SDValue(); 3372 } 3373 3374 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3375 SDNode *Node = Op.getNode(); 3376 EVT VT = Node->getValueType(0); 3377 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3378 SDValue InChain = Node->getOperand(0); 3379 SDValue VAListPtr = Node->getOperand(1); 3380 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3381 SDLoc dl(Node); 3382 3383 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3384 3385 // gpr_index 3386 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3387 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3388 InChain = GprIndex.getValue(1); 3389 3390 if (VT == MVT::i64) { 3391 // Check if GprIndex is even 3392 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3393 DAG.getConstant(1, dl, MVT::i32)); 3394 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3395 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3396 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3397 DAG.getConstant(1, dl, MVT::i32)); 3398 // Align GprIndex to be even if it isn't 3399 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3400 GprIndex); 3401 } 3402 3403 // fpr index is 1 byte after gpr 3404 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3405 DAG.getConstant(1, dl, MVT::i32)); 3406 3407 // fpr 3408 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3409 FprPtr, MachinePointerInfo(SV), MVT::i8); 3410 InChain = FprIndex.getValue(1); 3411 3412 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3413 DAG.getConstant(8, dl, MVT::i32)); 3414 3415 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3416 DAG.getConstant(4, dl, MVT::i32)); 3417 3418 // areas 3419 SDValue OverflowArea = 3420 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3421 InChain = OverflowArea.getValue(1); 3422 3423 SDValue RegSaveArea = 3424 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3425 InChain = RegSaveArea.getValue(1); 3426 3427 // select overflow_area if index > 8 3428 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3429 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3430 3431 // adjustment constant gpr_index * 4/8 3432 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3433 VT.isInteger() ? GprIndex : FprIndex, 3434 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3435 MVT::i32)); 3436 3437 // OurReg = RegSaveArea + RegConstant 3438 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3439 RegConstant); 3440 3441 // Floating types are 32 bytes into RegSaveArea 3442 if (VT.isFloatingPoint()) 3443 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3444 DAG.getConstant(32, dl, MVT::i32)); 3445 3446 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3447 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3448 VT.isInteger() ? GprIndex : FprIndex, 3449 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3450 MVT::i32)); 3451 3452 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3453 VT.isInteger() ? VAListPtr : FprPtr, 3454 MachinePointerInfo(SV), MVT::i8); 3455 3456 // determine if we should load from reg_save_area or overflow_area 3457 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3458 3459 // increase overflow_area by 4/8 if gpr/fpr > 8 3460 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3461 DAG.getConstant(VT.isInteger() ? 4 : 8, 3462 dl, MVT::i32)); 3463 3464 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3465 OverflowAreaPlusN); 3466 3467 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3468 MachinePointerInfo(), MVT::i32); 3469 3470 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3471 } 3472 3473 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3474 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3475 3476 // We have to copy the entire va_list struct: 3477 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3478 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3479 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3480 false, true, false, MachinePointerInfo(), 3481 MachinePointerInfo()); 3482 } 3483 3484 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3485 SelectionDAG &DAG) const { 3486 if (Subtarget.isAIXABI()) 3487 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3488 3489 return Op.getOperand(0); 3490 } 3491 3492 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3493 SelectionDAG &DAG) const { 3494 if (Subtarget.isAIXABI()) 3495 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3496 3497 SDValue Chain = Op.getOperand(0); 3498 SDValue Trmp = Op.getOperand(1); // trampoline 3499 SDValue FPtr = Op.getOperand(2); // nested function 3500 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3501 SDLoc dl(Op); 3502 3503 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3504 bool isPPC64 = (PtrVT == MVT::i64); 3505 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3506 3507 TargetLowering::ArgListTy Args; 3508 TargetLowering::ArgListEntry Entry; 3509 3510 Entry.Ty = IntPtrTy; 3511 Entry.Node = Trmp; Args.push_back(Entry); 3512 3513 // TrampSize == (isPPC64 ? 48 : 40); 3514 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3515 isPPC64 ? MVT::i64 : MVT::i32); 3516 Args.push_back(Entry); 3517 3518 Entry.Node = FPtr; Args.push_back(Entry); 3519 Entry.Node = Nest; Args.push_back(Entry); 3520 3521 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3522 TargetLowering::CallLoweringInfo CLI(DAG); 3523 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3524 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3525 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3526 3527 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3528 return CallResult.second; 3529 } 3530 3531 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3532 MachineFunction &MF = DAG.getMachineFunction(); 3533 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3534 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3535 3536 SDLoc dl(Op); 3537 3538 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3539 // vastart just stores the address of the VarArgsFrameIndex slot into the 3540 // memory location argument. 3541 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3542 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3543 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3544 MachinePointerInfo(SV)); 3545 } 3546 3547 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3548 // We suppose the given va_list is already allocated. 3549 // 3550 // typedef struct { 3551 // char gpr; /* index into the array of 8 GPRs 3552 // * stored in the register save area 3553 // * gpr=0 corresponds to r3, 3554 // * gpr=1 to r4, etc. 3555 // */ 3556 // char fpr; /* index into the array of 8 FPRs 3557 // * stored in the register save area 3558 // * fpr=0 corresponds to f1, 3559 // * fpr=1 to f2, etc. 3560 // */ 3561 // char *overflow_arg_area; 3562 // /* location on stack that holds 3563 // * the next overflow argument 3564 // */ 3565 // char *reg_save_area; 3566 // /* where r3:r10 and f1:f8 (if saved) 3567 // * are stored 3568 // */ 3569 // } va_list[1]; 3570 3571 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3572 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3573 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3574 PtrVT); 3575 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3576 PtrVT); 3577 3578 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3579 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3580 3581 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3582 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3583 3584 uint64_t FPROffset = 1; 3585 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3586 3587 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3588 3589 // Store first byte : number of int regs 3590 SDValue firstStore = 3591 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3592 MachinePointerInfo(SV), MVT::i8); 3593 uint64_t nextOffset = FPROffset; 3594 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3595 ConstFPROffset); 3596 3597 // Store second byte : number of float regs 3598 SDValue secondStore = 3599 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3600 MachinePointerInfo(SV, nextOffset), MVT::i8); 3601 nextOffset += StackOffset; 3602 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3603 3604 // Store second word : arguments given on stack 3605 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3606 MachinePointerInfo(SV, nextOffset)); 3607 nextOffset += FrameOffset; 3608 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3609 3610 // Store third word : arguments given in registers 3611 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3612 MachinePointerInfo(SV, nextOffset)); 3613 } 3614 3615 /// FPR - The set of FP registers that should be allocated for arguments 3616 /// on Darwin and AIX. 3617 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3618 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3619 PPC::F11, PPC::F12, PPC::F13}; 3620 3621 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3622 /// the stack. 3623 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3624 unsigned PtrByteSize) { 3625 unsigned ArgSize = ArgVT.getStoreSize(); 3626 if (Flags.isByVal()) 3627 ArgSize = Flags.getByValSize(); 3628 3629 // Round up to multiples of the pointer size, except for array members, 3630 // which are always packed. 3631 if (!Flags.isInConsecutiveRegs()) 3632 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3633 3634 return ArgSize; 3635 } 3636 3637 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3638 /// on the stack. 3639 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3640 ISD::ArgFlagsTy Flags, 3641 unsigned PtrByteSize) { 3642 Align Alignment(PtrByteSize); 3643 3644 // Altivec parameters are padded to a 16 byte boundary. 3645 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3646 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3647 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3648 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3649 Alignment = Align(16); 3650 3651 // ByVal parameters are aligned as requested. 3652 if (Flags.isByVal()) { 3653 auto BVAlign = Flags.getNonZeroByValAlign(); 3654 if (BVAlign > PtrByteSize) { 3655 if (BVAlign.value() % PtrByteSize != 0) 3656 llvm_unreachable( 3657 "ByVal alignment is not a multiple of the pointer size"); 3658 3659 Alignment = BVAlign; 3660 } 3661 } 3662 3663 // Array members are always packed to their original alignment. 3664 if (Flags.isInConsecutiveRegs()) { 3665 // If the array member was split into multiple registers, the first 3666 // needs to be aligned to the size of the full type. (Except for 3667 // ppcf128, which is only aligned as its f64 components.) 3668 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3669 Alignment = Align(OrigVT.getStoreSize()); 3670 else 3671 Alignment = Align(ArgVT.getStoreSize()); 3672 } 3673 3674 return Alignment; 3675 } 3676 3677 /// CalculateStackSlotUsed - Return whether this argument will use its 3678 /// stack slot (instead of being passed in registers). ArgOffset, 3679 /// AvailableFPRs, and AvailableVRs must hold the current argument 3680 /// position, and will be updated to account for this argument. 3681 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3682 unsigned PtrByteSize, unsigned LinkageSize, 3683 unsigned ParamAreaSize, unsigned &ArgOffset, 3684 unsigned &AvailableFPRs, 3685 unsigned &AvailableVRs) { 3686 bool UseMemory = false; 3687 3688 // Respect alignment of argument on the stack. 3689 Align Alignment = 3690 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3691 ArgOffset = alignTo(ArgOffset, Alignment); 3692 // If there's no space left in the argument save area, we must 3693 // use memory (this check also catches zero-sized arguments). 3694 if (ArgOffset >= LinkageSize + ParamAreaSize) 3695 UseMemory = true; 3696 3697 // Allocate argument on the stack. 3698 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3699 if (Flags.isInConsecutiveRegsLast()) 3700 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3701 // If we overran the argument save area, we must use memory 3702 // (this check catches arguments passed partially in memory) 3703 if (ArgOffset > LinkageSize + ParamAreaSize) 3704 UseMemory = true; 3705 3706 // However, if the argument is actually passed in an FPR or a VR, 3707 // we don't use memory after all. 3708 if (!Flags.isByVal()) { 3709 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3710 if (AvailableFPRs > 0) { 3711 --AvailableFPRs; 3712 return false; 3713 } 3714 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3715 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3716 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3717 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3718 if (AvailableVRs > 0) { 3719 --AvailableVRs; 3720 return false; 3721 } 3722 } 3723 3724 return UseMemory; 3725 } 3726 3727 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3728 /// ensure minimum alignment required for target. 3729 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3730 unsigned NumBytes) { 3731 return alignTo(NumBytes, Lowering->getStackAlign()); 3732 } 3733 3734 SDValue PPCTargetLowering::LowerFormalArguments( 3735 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3736 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3737 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3738 if (Subtarget.isAIXABI()) 3739 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3740 InVals); 3741 if (Subtarget.is64BitELFABI()) 3742 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3743 InVals); 3744 if (Subtarget.is32BitELFABI()) 3745 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3746 InVals); 3747 3748 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3749 InVals); 3750 } 3751 3752 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3753 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3754 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3755 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3756 3757 // 32-bit SVR4 ABI Stack Frame Layout: 3758 // +-----------------------------------+ 3759 // +--> | Back chain | 3760 // | +-----------------------------------+ 3761 // | | Floating-point register save area | 3762 // | +-----------------------------------+ 3763 // | | General register save area | 3764 // | +-----------------------------------+ 3765 // | | CR save word | 3766 // | +-----------------------------------+ 3767 // | | VRSAVE save word | 3768 // | +-----------------------------------+ 3769 // | | Alignment padding | 3770 // | +-----------------------------------+ 3771 // | | Vector register save area | 3772 // | +-----------------------------------+ 3773 // | | Local variable space | 3774 // | +-----------------------------------+ 3775 // | | Parameter list area | 3776 // | +-----------------------------------+ 3777 // | | LR save word | 3778 // | +-----------------------------------+ 3779 // SP--> +--- | Back chain | 3780 // +-----------------------------------+ 3781 // 3782 // Specifications: 3783 // System V Application Binary Interface PowerPC Processor Supplement 3784 // AltiVec Technology Programming Interface Manual 3785 3786 MachineFunction &MF = DAG.getMachineFunction(); 3787 MachineFrameInfo &MFI = MF.getFrameInfo(); 3788 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3789 3790 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3791 // Potential tail calls could cause overwriting of argument stack slots. 3792 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3793 (CallConv == CallingConv::Fast)); 3794 const Align PtrAlign(4); 3795 3796 // Assign locations to all of the incoming arguments. 3797 SmallVector<CCValAssign, 16> ArgLocs; 3798 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3799 *DAG.getContext()); 3800 3801 // Reserve space for the linkage area on the stack. 3802 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3803 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3804 if (useSoftFloat()) 3805 CCInfo.PreAnalyzeFormalArguments(Ins); 3806 3807 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3808 CCInfo.clearWasPPCF128(); 3809 3810 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3811 CCValAssign &VA = ArgLocs[i]; 3812 3813 // Arguments stored in registers. 3814 if (VA.isRegLoc()) { 3815 const TargetRegisterClass *RC; 3816 EVT ValVT = VA.getValVT(); 3817 3818 switch (ValVT.getSimpleVT().SimpleTy) { 3819 default: 3820 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3821 case MVT::i1: 3822 case MVT::i32: 3823 RC = &PPC::GPRCRegClass; 3824 break; 3825 case MVT::f32: 3826 if (Subtarget.hasP8Vector()) 3827 RC = &PPC::VSSRCRegClass; 3828 else if (Subtarget.hasSPE()) 3829 RC = &PPC::GPRCRegClass; 3830 else 3831 RC = &PPC::F4RCRegClass; 3832 break; 3833 case MVT::f64: 3834 if (Subtarget.hasVSX()) 3835 RC = &PPC::VSFRCRegClass; 3836 else if (Subtarget.hasSPE()) 3837 // SPE passes doubles in GPR pairs. 3838 RC = &PPC::GPRCRegClass; 3839 else 3840 RC = &PPC::F8RCRegClass; 3841 break; 3842 case MVT::v16i8: 3843 case MVT::v8i16: 3844 case MVT::v4i32: 3845 RC = &PPC::VRRCRegClass; 3846 break; 3847 case MVT::v4f32: 3848 RC = &PPC::VRRCRegClass; 3849 break; 3850 case MVT::v2f64: 3851 case MVT::v2i64: 3852 RC = &PPC::VRRCRegClass; 3853 break; 3854 } 3855 3856 SDValue ArgValue; 3857 // Transform the arguments stored in physical registers into 3858 // virtual ones. 3859 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3860 assert(i + 1 < e && "No second half of double precision argument"); 3861 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3862 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3863 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3864 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3865 if (!Subtarget.isLittleEndian()) 3866 std::swap (ArgValueLo, ArgValueHi); 3867 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3868 ArgValueHi); 3869 } else { 3870 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3871 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3872 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3873 if (ValVT == MVT::i1) 3874 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3875 } 3876 3877 InVals.push_back(ArgValue); 3878 } else { 3879 // Argument stored in memory. 3880 assert(VA.isMemLoc()); 3881 3882 // Get the extended size of the argument type in stack 3883 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3884 // Get the actual size of the argument type 3885 unsigned ObjSize = VA.getValVT().getStoreSize(); 3886 unsigned ArgOffset = VA.getLocMemOffset(); 3887 // Stack objects in PPC32 are right justified. 3888 ArgOffset += ArgSize - ObjSize; 3889 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3890 3891 // Create load nodes to retrieve arguments from the stack. 3892 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3893 InVals.push_back( 3894 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3895 } 3896 } 3897 3898 // Assign locations to all of the incoming aggregate by value arguments. 3899 // Aggregates passed by value are stored in the local variable space of the 3900 // caller's stack frame, right above the parameter list area. 3901 SmallVector<CCValAssign, 16> ByValArgLocs; 3902 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3903 ByValArgLocs, *DAG.getContext()); 3904 3905 // Reserve stack space for the allocations in CCInfo. 3906 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3907 3908 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3909 3910 // Area that is at least reserved in the caller of this function. 3911 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3912 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3913 3914 // Set the size that is at least reserved in caller of this function. Tail 3915 // call optimized function's reserved stack space needs to be aligned so that 3916 // taking the difference between two stack areas will result in an aligned 3917 // stack. 3918 MinReservedArea = 3919 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3920 FuncInfo->setMinReservedArea(MinReservedArea); 3921 3922 SmallVector<SDValue, 8> MemOps; 3923 3924 // If the function takes variable number of arguments, make a frame index for 3925 // the start of the first vararg value... for expansion of llvm.va_start. 3926 if (isVarArg) { 3927 static const MCPhysReg GPArgRegs[] = { 3928 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3929 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3930 }; 3931 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3932 3933 static const MCPhysReg FPArgRegs[] = { 3934 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3935 PPC::F8 3936 }; 3937 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3938 3939 if (useSoftFloat() || hasSPE()) 3940 NumFPArgRegs = 0; 3941 3942 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3943 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3944 3945 // Make room for NumGPArgRegs and NumFPArgRegs. 3946 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3947 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3948 3949 FuncInfo->setVarArgsStackOffset( 3950 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3951 CCInfo.getNextStackOffset(), true)); 3952 3953 FuncInfo->setVarArgsFrameIndex( 3954 MFI.CreateStackObject(Depth, Align(8), false)); 3955 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3956 3957 // The fixed integer arguments of a variadic function are stored to the 3958 // VarArgsFrameIndex on the stack so that they may be loaded by 3959 // dereferencing the result of va_next. 3960 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3961 // Get an existing live-in vreg, or add a new one. 3962 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3963 if (!VReg) 3964 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3965 3966 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3967 SDValue Store = 3968 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3969 MemOps.push_back(Store); 3970 // Increment the address by four for the next argument to store 3971 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3972 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3973 } 3974 3975 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3976 // is set. 3977 // The double arguments are stored to the VarArgsFrameIndex 3978 // on the stack. 3979 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3980 // Get an existing live-in vreg, or add a new one. 3981 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3982 if (!VReg) 3983 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3984 3985 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3986 SDValue Store = 3987 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3988 MemOps.push_back(Store); 3989 // Increment the address by eight for the next argument to store 3990 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3991 PtrVT); 3992 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3993 } 3994 } 3995 3996 if (!MemOps.empty()) 3997 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3998 3999 return Chain; 4000 } 4001 4002 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4003 // value to MVT::i64 and then truncate to the correct register size. 4004 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4005 EVT ObjectVT, SelectionDAG &DAG, 4006 SDValue ArgVal, 4007 const SDLoc &dl) const { 4008 if (Flags.isSExt()) 4009 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4010 DAG.getValueType(ObjectVT)); 4011 else if (Flags.isZExt()) 4012 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4013 DAG.getValueType(ObjectVT)); 4014 4015 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4016 } 4017 4018 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4019 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4020 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4021 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4022 // TODO: add description of PPC stack frame format, or at least some docs. 4023 // 4024 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4025 bool isLittleEndian = Subtarget.isLittleEndian(); 4026 MachineFunction &MF = DAG.getMachineFunction(); 4027 MachineFrameInfo &MFI = MF.getFrameInfo(); 4028 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4029 4030 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4031 "fastcc not supported on varargs functions"); 4032 4033 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4034 // Potential tail calls could cause overwriting of argument stack slots. 4035 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4036 (CallConv == CallingConv::Fast)); 4037 unsigned PtrByteSize = 8; 4038 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4039 4040 static const MCPhysReg GPR[] = { 4041 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4042 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4043 }; 4044 static const MCPhysReg VR[] = { 4045 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4046 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4047 }; 4048 4049 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4050 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4051 const unsigned Num_VR_Regs = array_lengthof(VR); 4052 4053 // Do a first pass over the arguments to determine whether the ABI 4054 // guarantees that our caller has allocated the parameter save area 4055 // on its stack frame. In the ELFv1 ABI, this is always the case; 4056 // in the ELFv2 ABI, it is true if this is a vararg function or if 4057 // any parameter is located in a stack slot. 4058 4059 bool HasParameterArea = !isELFv2ABI || isVarArg; 4060 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4061 unsigned NumBytes = LinkageSize; 4062 unsigned AvailableFPRs = Num_FPR_Regs; 4063 unsigned AvailableVRs = Num_VR_Regs; 4064 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4065 if (Ins[i].Flags.isNest()) 4066 continue; 4067 4068 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4069 PtrByteSize, LinkageSize, ParamAreaSize, 4070 NumBytes, AvailableFPRs, AvailableVRs)) 4071 HasParameterArea = true; 4072 } 4073 4074 // Add DAG nodes to load the arguments or copy them out of registers. On 4075 // entry to a function on PPC, the arguments start after the linkage area, 4076 // although the first ones are often in registers. 4077 4078 unsigned ArgOffset = LinkageSize; 4079 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4080 SmallVector<SDValue, 8> MemOps; 4081 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4082 unsigned CurArgIdx = 0; 4083 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4084 SDValue ArgVal; 4085 bool needsLoad = false; 4086 EVT ObjectVT = Ins[ArgNo].VT; 4087 EVT OrigVT = Ins[ArgNo].ArgVT; 4088 unsigned ObjSize = ObjectVT.getStoreSize(); 4089 unsigned ArgSize = ObjSize; 4090 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4091 if (Ins[ArgNo].isOrigArg()) { 4092 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4093 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4094 } 4095 // We re-align the argument offset for each argument, except when using the 4096 // fast calling convention, when we need to make sure we do that only when 4097 // we'll actually use a stack slot. 4098 unsigned CurArgOffset; 4099 Align Alignment; 4100 auto ComputeArgOffset = [&]() { 4101 /* Respect alignment of argument on the stack. */ 4102 Alignment = 4103 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4104 ArgOffset = alignTo(ArgOffset, Alignment); 4105 CurArgOffset = ArgOffset; 4106 }; 4107 4108 if (CallConv != CallingConv::Fast) { 4109 ComputeArgOffset(); 4110 4111 /* Compute GPR index associated with argument offset. */ 4112 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4113 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4114 } 4115 4116 // FIXME the codegen can be much improved in some cases. 4117 // We do not have to keep everything in memory. 4118 if (Flags.isByVal()) { 4119 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4120 4121 if (CallConv == CallingConv::Fast) 4122 ComputeArgOffset(); 4123 4124 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4125 ObjSize = Flags.getByValSize(); 4126 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4127 // Empty aggregate parameters do not take up registers. Examples: 4128 // struct { } a; 4129 // union { } b; 4130 // int c[0]; 4131 // etc. However, we have to provide a place-holder in InVals, so 4132 // pretend we have an 8-byte item at the current address for that 4133 // purpose. 4134 if (!ObjSize) { 4135 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4136 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4137 InVals.push_back(FIN); 4138 continue; 4139 } 4140 4141 // Create a stack object covering all stack doublewords occupied 4142 // by the argument. If the argument is (fully or partially) on 4143 // the stack, or if the argument is fully in registers but the 4144 // caller has allocated the parameter save anyway, we can refer 4145 // directly to the caller's stack frame. Otherwise, create a 4146 // local copy in our own frame. 4147 int FI; 4148 if (HasParameterArea || 4149 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4150 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4151 else 4152 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4153 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4154 4155 // Handle aggregates smaller than 8 bytes. 4156 if (ObjSize < PtrByteSize) { 4157 // The value of the object is its address, which differs from the 4158 // address of the enclosing doubleword on big-endian systems. 4159 SDValue Arg = FIN; 4160 if (!isLittleEndian) { 4161 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4162 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4163 } 4164 InVals.push_back(Arg); 4165 4166 if (GPR_idx != Num_GPR_Regs) { 4167 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4168 FuncInfo->addLiveInAttr(VReg, Flags); 4169 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4170 SDValue Store; 4171 4172 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4173 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4174 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4175 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4176 MachinePointerInfo(&*FuncArg), ObjType); 4177 } else { 4178 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4179 // store the whole register as-is to the parameter save area 4180 // slot. 4181 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4182 MachinePointerInfo(&*FuncArg)); 4183 } 4184 4185 MemOps.push_back(Store); 4186 } 4187 // Whether we copied from a register or not, advance the offset 4188 // into the parameter save area by a full doubleword. 4189 ArgOffset += PtrByteSize; 4190 continue; 4191 } 4192 4193 // The value of the object is its address, which is the address of 4194 // its first stack doubleword. 4195 InVals.push_back(FIN); 4196 4197 // Store whatever pieces of the object are in registers to memory. 4198 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4199 if (GPR_idx == Num_GPR_Regs) 4200 break; 4201 4202 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4203 FuncInfo->addLiveInAttr(VReg, Flags); 4204 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4205 SDValue Addr = FIN; 4206 if (j) { 4207 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4208 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4209 } 4210 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4211 MachinePointerInfo(&*FuncArg, j)); 4212 MemOps.push_back(Store); 4213 ++GPR_idx; 4214 } 4215 ArgOffset += ArgSize; 4216 continue; 4217 } 4218 4219 switch (ObjectVT.getSimpleVT().SimpleTy) { 4220 default: llvm_unreachable("Unhandled argument type!"); 4221 case MVT::i1: 4222 case MVT::i32: 4223 case MVT::i64: 4224 if (Flags.isNest()) { 4225 // The 'nest' parameter, if any, is passed in R11. 4226 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4227 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4228 4229 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4230 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4231 4232 break; 4233 } 4234 4235 // These can be scalar arguments or elements of an integer array type 4236 // passed directly. Clang may use those instead of "byval" aggregate 4237 // types to avoid forcing arguments to memory unnecessarily. 4238 if (GPR_idx != Num_GPR_Regs) { 4239 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4240 FuncInfo->addLiveInAttr(VReg, Flags); 4241 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4242 4243 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4244 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4245 // value to MVT::i64 and then truncate to the correct register size. 4246 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4247 } else { 4248 if (CallConv == CallingConv::Fast) 4249 ComputeArgOffset(); 4250 4251 needsLoad = true; 4252 ArgSize = PtrByteSize; 4253 } 4254 if (CallConv != CallingConv::Fast || needsLoad) 4255 ArgOffset += 8; 4256 break; 4257 4258 case MVT::f32: 4259 case MVT::f64: 4260 // These can be scalar arguments or elements of a float array type 4261 // passed directly. The latter are used to implement ELFv2 homogenous 4262 // float aggregates. 4263 if (FPR_idx != Num_FPR_Regs) { 4264 unsigned VReg; 4265 4266 if (ObjectVT == MVT::f32) 4267 VReg = MF.addLiveIn(FPR[FPR_idx], 4268 Subtarget.hasP8Vector() 4269 ? &PPC::VSSRCRegClass 4270 : &PPC::F4RCRegClass); 4271 else 4272 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4273 ? &PPC::VSFRCRegClass 4274 : &PPC::F8RCRegClass); 4275 4276 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4277 ++FPR_idx; 4278 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4279 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4280 // once we support fp <-> gpr moves. 4281 4282 // This can only ever happen in the presence of f32 array types, 4283 // since otherwise we never run out of FPRs before running out 4284 // of GPRs. 4285 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4286 FuncInfo->addLiveInAttr(VReg, Flags); 4287 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4288 4289 if (ObjectVT == MVT::f32) { 4290 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4291 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4292 DAG.getConstant(32, dl, MVT::i32)); 4293 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4294 } 4295 4296 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4297 } else { 4298 if (CallConv == CallingConv::Fast) 4299 ComputeArgOffset(); 4300 4301 needsLoad = true; 4302 } 4303 4304 // When passing an array of floats, the array occupies consecutive 4305 // space in the argument area; only round up to the next doubleword 4306 // at the end of the array. Otherwise, each float takes 8 bytes. 4307 if (CallConv != CallingConv::Fast || needsLoad) { 4308 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4309 ArgOffset += ArgSize; 4310 if (Flags.isInConsecutiveRegsLast()) 4311 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4312 } 4313 break; 4314 case MVT::v4f32: 4315 case MVT::v4i32: 4316 case MVT::v8i16: 4317 case MVT::v16i8: 4318 case MVT::v2f64: 4319 case MVT::v2i64: 4320 case MVT::v1i128: 4321 case MVT::f128: 4322 // These can be scalar arguments or elements of a vector array type 4323 // passed directly. The latter are used to implement ELFv2 homogenous 4324 // vector aggregates. 4325 if (VR_idx != Num_VR_Regs) { 4326 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4327 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4328 ++VR_idx; 4329 } else { 4330 if (CallConv == CallingConv::Fast) 4331 ComputeArgOffset(); 4332 needsLoad = true; 4333 } 4334 if (CallConv != CallingConv::Fast || needsLoad) 4335 ArgOffset += 16; 4336 break; 4337 } 4338 4339 // We need to load the argument to a virtual register if we determined 4340 // above that we ran out of physical registers of the appropriate type. 4341 if (needsLoad) { 4342 if (ObjSize < ArgSize && !isLittleEndian) 4343 CurArgOffset += ArgSize - ObjSize; 4344 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4345 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4346 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4347 } 4348 4349 InVals.push_back(ArgVal); 4350 } 4351 4352 // Area that is at least reserved in the caller of this function. 4353 unsigned MinReservedArea; 4354 if (HasParameterArea) 4355 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4356 else 4357 MinReservedArea = LinkageSize; 4358 4359 // Set the size that is at least reserved in caller of this function. Tail 4360 // call optimized functions' reserved stack space needs to be aligned so that 4361 // taking the difference between two stack areas will result in an aligned 4362 // stack. 4363 MinReservedArea = 4364 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4365 FuncInfo->setMinReservedArea(MinReservedArea); 4366 4367 // If the function takes variable number of arguments, make a frame index for 4368 // the start of the first vararg value... for expansion of llvm.va_start. 4369 // On ELFv2ABI spec, it writes: 4370 // C programs that are intended to be *portable* across different compilers 4371 // and architectures must use the header file <stdarg.h> to deal with variable 4372 // argument lists. 4373 if (isVarArg && MFI.hasVAStart()) { 4374 int Depth = ArgOffset; 4375 4376 FuncInfo->setVarArgsFrameIndex( 4377 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4378 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4379 4380 // If this function is vararg, store any remaining integer argument regs 4381 // to their spots on the stack so that they may be loaded by dereferencing 4382 // the result of va_next. 4383 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4384 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4385 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4386 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4387 SDValue Store = 4388 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4389 MemOps.push_back(Store); 4390 // Increment the address by four for the next argument to store 4391 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4392 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4393 } 4394 } 4395 4396 if (!MemOps.empty()) 4397 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4398 4399 return Chain; 4400 } 4401 4402 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4403 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4404 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4405 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4406 // TODO: add description of PPC stack frame format, or at least some docs. 4407 // 4408 MachineFunction &MF = DAG.getMachineFunction(); 4409 MachineFrameInfo &MFI = MF.getFrameInfo(); 4410 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4411 4412 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4413 bool isPPC64 = PtrVT == MVT::i64; 4414 // Potential tail calls could cause overwriting of argument stack slots. 4415 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4416 (CallConv == CallingConv::Fast)); 4417 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4418 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4419 unsigned ArgOffset = LinkageSize; 4420 // Area that is at least reserved in caller of this function. 4421 unsigned MinReservedArea = ArgOffset; 4422 4423 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4424 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4425 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4426 }; 4427 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4428 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4429 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4430 }; 4431 static const MCPhysReg VR[] = { 4432 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4433 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4434 }; 4435 4436 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4437 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4438 const unsigned Num_VR_Regs = array_lengthof( VR); 4439 4440 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4441 4442 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4443 4444 // In 32-bit non-varargs functions, the stack space for vectors is after the 4445 // stack space for non-vectors. We do not use this space unless we have 4446 // too many vectors to fit in registers, something that only occurs in 4447 // constructed examples:), but we have to walk the arglist to figure 4448 // that out...for the pathological case, compute VecArgOffset as the 4449 // start of the vector parameter area. Computing VecArgOffset is the 4450 // entire point of the following loop. 4451 unsigned VecArgOffset = ArgOffset; 4452 if (!isVarArg && !isPPC64) { 4453 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4454 ++ArgNo) { 4455 EVT ObjectVT = Ins[ArgNo].VT; 4456 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4457 4458 if (Flags.isByVal()) { 4459 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4460 unsigned ObjSize = Flags.getByValSize(); 4461 unsigned ArgSize = 4462 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4463 VecArgOffset += ArgSize; 4464 continue; 4465 } 4466 4467 switch(ObjectVT.getSimpleVT().SimpleTy) { 4468 default: llvm_unreachable("Unhandled argument type!"); 4469 case MVT::i1: 4470 case MVT::i32: 4471 case MVT::f32: 4472 VecArgOffset += 4; 4473 break; 4474 case MVT::i64: // PPC64 4475 case MVT::f64: 4476 // FIXME: We are guaranteed to be !isPPC64 at this point. 4477 // Does MVT::i64 apply? 4478 VecArgOffset += 8; 4479 break; 4480 case MVT::v4f32: 4481 case MVT::v4i32: 4482 case MVT::v8i16: 4483 case MVT::v16i8: 4484 // Nothing to do, we're only looking at Nonvector args here. 4485 break; 4486 } 4487 } 4488 } 4489 // We've found where the vector parameter area in memory is. Skip the 4490 // first 12 parameters; these don't use that memory. 4491 VecArgOffset = ((VecArgOffset+15)/16)*16; 4492 VecArgOffset += 12*16; 4493 4494 // Add DAG nodes to load the arguments or copy them out of registers. On 4495 // entry to a function on PPC, the arguments start after the linkage area, 4496 // although the first ones are often in registers. 4497 4498 SmallVector<SDValue, 8> MemOps; 4499 unsigned nAltivecParamsAtEnd = 0; 4500 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4501 unsigned CurArgIdx = 0; 4502 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4503 SDValue ArgVal; 4504 bool needsLoad = false; 4505 EVT ObjectVT = Ins[ArgNo].VT; 4506 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4507 unsigned ArgSize = ObjSize; 4508 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4509 if (Ins[ArgNo].isOrigArg()) { 4510 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4511 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4512 } 4513 unsigned CurArgOffset = ArgOffset; 4514 4515 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4516 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4517 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4518 if (isVarArg || isPPC64) { 4519 MinReservedArea = ((MinReservedArea+15)/16)*16; 4520 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4521 Flags, 4522 PtrByteSize); 4523 } else nAltivecParamsAtEnd++; 4524 } else 4525 // Calculate min reserved area. 4526 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4527 Flags, 4528 PtrByteSize); 4529 4530 // FIXME the codegen can be much improved in some cases. 4531 // We do not have to keep everything in memory. 4532 if (Flags.isByVal()) { 4533 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4534 4535 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4536 ObjSize = Flags.getByValSize(); 4537 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4538 // Objects of size 1 and 2 are right justified, everything else is 4539 // left justified. This means the memory address is adjusted forwards. 4540 if (ObjSize==1 || ObjSize==2) { 4541 CurArgOffset = CurArgOffset + (4 - ObjSize); 4542 } 4543 // The value of the object is its address. 4544 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4545 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4546 InVals.push_back(FIN); 4547 if (ObjSize==1 || ObjSize==2) { 4548 if (GPR_idx != Num_GPR_Regs) { 4549 unsigned VReg; 4550 if (isPPC64) 4551 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4552 else 4553 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4554 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4555 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4556 SDValue Store = 4557 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4558 MachinePointerInfo(&*FuncArg), ObjType); 4559 MemOps.push_back(Store); 4560 ++GPR_idx; 4561 } 4562 4563 ArgOffset += PtrByteSize; 4564 4565 continue; 4566 } 4567 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4568 // Store whatever pieces of the object are in registers 4569 // to memory. ArgOffset will be the address of the beginning 4570 // of the object. 4571 if (GPR_idx != Num_GPR_Regs) { 4572 unsigned VReg; 4573 if (isPPC64) 4574 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4575 else 4576 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4577 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4578 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4579 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4580 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4581 MachinePointerInfo(&*FuncArg, j)); 4582 MemOps.push_back(Store); 4583 ++GPR_idx; 4584 ArgOffset += PtrByteSize; 4585 } else { 4586 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4587 break; 4588 } 4589 } 4590 continue; 4591 } 4592 4593 switch (ObjectVT.getSimpleVT().SimpleTy) { 4594 default: llvm_unreachable("Unhandled argument type!"); 4595 case MVT::i1: 4596 case MVT::i32: 4597 if (!isPPC64) { 4598 if (GPR_idx != Num_GPR_Regs) { 4599 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4600 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4601 4602 if (ObjectVT == MVT::i1) 4603 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4604 4605 ++GPR_idx; 4606 } else { 4607 needsLoad = true; 4608 ArgSize = PtrByteSize; 4609 } 4610 // All int arguments reserve stack space in the Darwin ABI. 4611 ArgOffset += PtrByteSize; 4612 break; 4613 } 4614 LLVM_FALLTHROUGH; 4615 case MVT::i64: // PPC64 4616 if (GPR_idx != Num_GPR_Regs) { 4617 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4618 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4619 4620 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4621 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4622 // value to MVT::i64 and then truncate to the correct register size. 4623 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4624 4625 ++GPR_idx; 4626 } else { 4627 needsLoad = true; 4628 ArgSize = PtrByteSize; 4629 } 4630 // All int arguments reserve stack space in the Darwin ABI. 4631 ArgOffset += 8; 4632 break; 4633 4634 case MVT::f32: 4635 case MVT::f64: 4636 // Every 4 bytes of argument space consumes one of the GPRs available for 4637 // argument passing. 4638 if (GPR_idx != Num_GPR_Regs) { 4639 ++GPR_idx; 4640 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4641 ++GPR_idx; 4642 } 4643 if (FPR_idx != Num_FPR_Regs) { 4644 unsigned VReg; 4645 4646 if (ObjectVT == MVT::f32) 4647 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4648 else 4649 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4650 4651 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4652 ++FPR_idx; 4653 } else { 4654 needsLoad = true; 4655 } 4656 4657 // All FP arguments reserve stack space in the Darwin ABI. 4658 ArgOffset += isPPC64 ? 8 : ObjSize; 4659 break; 4660 case MVT::v4f32: 4661 case MVT::v4i32: 4662 case MVT::v8i16: 4663 case MVT::v16i8: 4664 // Note that vector arguments in registers don't reserve stack space, 4665 // except in varargs functions. 4666 if (VR_idx != Num_VR_Regs) { 4667 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4668 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4669 if (isVarArg) { 4670 while ((ArgOffset % 16) != 0) { 4671 ArgOffset += PtrByteSize; 4672 if (GPR_idx != Num_GPR_Regs) 4673 GPR_idx++; 4674 } 4675 ArgOffset += 16; 4676 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4677 } 4678 ++VR_idx; 4679 } else { 4680 if (!isVarArg && !isPPC64) { 4681 // Vectors go after all the nonvectors. 4682 CurArgOffset = VecArgOffset; 4683 VecArgOffset += 16; 4684 } else { 4685 // Vectors are aligned. 4686 ArgOffset = ((ArgOffset+15)/16)*16; 4687 CurArgOffset = ArgOffset; 4688 ArgOffset += 16; 4689 } 4690 needsLoad = true; 4691 } 4692 break; 4693 } 4694 4695 // We need to load the argument to a virtual register if we determined above 4696 // that we ran out of physical registers of the appropriate type. 4697 if (needsLoad) { 4698 int FI = MFI.CreateFixedObject(ObjSize, 4699 CurArgOffset + (ArgSize - ObjSize), 4700 isImmutable); 4701 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4702 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4703 } 4704 4705 InVals.push_back(ArgVal); 4706 } 4707 4708 // Allow for Altivec parameters at the end, if needed. 4709 if (nAltivecParamsAtEnd) { 4710 MinReservedArea = ((MinReservedArea+15)/16)*16; 4711 MinReservedArea += 16*nAltivecParamsAtEnd; 4712 } 4713 4714 // Area that is at least reserved in the caller of this function. 4715 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4716 4717 // Set the size that is at least reserved in caller of this function. Tail 4718 // call optimized functions' reserved stack space needs to be aligned so that 4719 // taking the difference between two stack areas will result in an aligned 4720 // stack. 4721 MinReservedArea = 4722 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4723 FuncInfo->setMinReservedArea(MinReservedArea); 4724 4725 // If the function takes variable number of arguments, make a frame index for 4726 // the start of the first vararg value... for expansion of llvm.va_start. 4727 if (isVarArg) { 4728 int Depth = ArgOffset; 4729 4730 FuncInfo->setVarArgsFrameIndex( 4731 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4732 Depth, true)); 4733 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4734 4735 // If this function is vararg, store any remaining integer argument regs 4736 // to their spots on the stack so that they may be loaded by dereferencing 4737 // the result of va_next. 4738 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4739 unsigned VReg; 4740 4741 if (isPPC64) 4742 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4743 else 4744 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4745 4746 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4747 SDValue Store = 4748 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4749 MemOps.push_back(Store); 4750 // Increment the address by four for the next argument to store 4751 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4752 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4753 } 4754 } 4755 4756 if (!MemOps.empty()) 4757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4758 4759 return Chain; 4760 } 4761 4762 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4763 /// adjusted to accommodate the arguments for the tailcall. 4764 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4765 unsigned ParamSize) { 4766 4767 if (!isTailCall) return 0; 4768 4769 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4770 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4771 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4772 // Remember only if the new adjustment is bigger. 4773 if (SPDiff < FI->getTailCallSPDelta()) 4774 FI->setTailCallSPDelta(SPDiff); 4775 4776 return SPDiff; 4777 } 4778 4779 static bool isFunctionGlobalAddress(SDValue Callee); 4780 4781 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4782 const TargetMachine &TM) { 4783 // It does not make sense to call callsShareTOCBase() with a caller that 4784 // is PC Relative since PC Relative callers do not have a TOC. 4785 #ifndef NDEBUG 4786 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4787 assert(!STICaller->isUsingPCRelativeCalls() && 4788 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4789 #endif 4790 4791 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4792 // don't have enough information to determine if the caller and callee share 4793 // the same TOC base, so we have to pessimistically assume they don't for 4794 // correctness. 4795 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4796 if (!G) 4797 return false; 4798 4799 const GlobalValue *GV = G->getGlobal(); 4800 4801 // If the callee is preemptable, then the static linker will use a plt-stub 4802 // which saves the toc to the stack, and needs a nop after the call 4803 // instruction to convert to a toc-restore. 4804 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4805 return false; 4806 4807 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4808 // We may need a TOC restore in the situation where the caller requires a 4809 // valid TOC but the callee is PC Relative and does not. 4810 const Function *F = dyn_cast<Function>(GV); 4811 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4812 4813 // If we have an Alias we can try to get the function from there. 4814 if (Alias) { 4815 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4816 F = dyn_cast<Function>(GlobalObj); 4817 } 4818 4819 // If we still have no valid function pointer we do not have enough 4820 // information to determine if the callee uses PC Relative calls so we must 4821 // assume that it does. 4822 if (!F) 4823 return false; 4824 4825 // If the callee uses PC Relative we cannot guarantee that the callee won't 4826 // clobber the TOC of the caller and so we must assume that the two 4827 // functions do not share a TOC base. 4828 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4829 if (STICallee->isUsingPCRelativeCalls()) 4830 return false; 4831 4832 // If the GV is not a strong definition then we need to assume it can be 4833 // replaced by another function at link time. The function that replaces 4834 // it may not share the same TOC as the caller since the callee may be 4835 // replaced by a PC Relative version of the same function. 4836 if (!GV->isStrongDefinitionForLinker()) 4837 return false; 4838 4839 // The medium and large code models are expected to provide a sufficiently 4840 // large TOC to provide all data addressing needs of a module with a 4841 // single TOC. 4842 if (CodeModel::Medium == TM.getCodeModel() || 4843 CodeModel::Large == TM.getCodeModel()) 4844 return true; 4845 4846 // Any explicitly-specified sections and section prefixes must also match. 4847 // Also, if we're using -ffunction-sections, then each function is always in 4848 // a different section (the same is true for COMDAT functions). 4849 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4850 GV->getSection() != Caller->getSection()) 4851 return false; 4852 if (const auto *F = dyn_cast<Function>(GV)) { 4853 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4854 return false; 4855 } 4856 4857 return true; 4858 } 4859 4860 static bool 4861 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4862 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4863 assert(Subtarget.is64BitELFABI()); 4864 4865 const unsigned PtrByteSize = 8; 4866 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4867 4868 static const MCPhysReg GPR[] = { 4869 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4870 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4871 }; 4872 static const MCPhysReg VR[] = { 4873 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4874 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4875 }; 4876 4877 const unsigned NumGPRs = array_lengthof(GPR); 4878 const unsigned NumFPRs = 13; 4879 const unsigned NumVRs = array_lengthof(VR); 4880 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4881 4882 unsigned NumBytes = LinkageSize; 4883 unsigned AvailableFPRs = NumFPRs; 4884 unsigned AvailableVRs = NumVRs; 4885 4886 for (const ISD::OutputArg& Param : Outs) { 4887 if (Param.Flags.isNest()) continue; 4888 4889 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4890 LinkageSize, ParamAreaSize, NumBytes, 4891 AvailableFPRs, AvailableVRs)) 4892 return true; 4893 } 4894 return false; 4895 } 4896 4897 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4898 if (CB.arg_size() != CallerFn->arg_size()) 4899 return false; 4900 4901 auto CalleeArgIter = CB.arg_begin(); 4902 auto CalleeArgEnd = CB.arg_end(); 4903 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4904 4905 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4906 const Value* CalleeArg = *CalleeArgIter; 4907 const Value* CallerArg = &(*CallerArgIter); 4908 if (CalleeArg == CallerArg) 4909 continue; 4910 4911 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4912 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4913 // } 4914 // 1st argument of callee is undef and has the same type as caller. 4915 if (CalleeArg->getType() == CallerArg->getType() && 4916 isa<UndefValue>(CalleeArg)) 4917 continue; 4918 4919 return false; 4920 } 4921 4922 return true; 4923 } 4924 4925 // Returns true if TCO is possible between the callers and callees 4926 // calling conventions. 4927 static bool 4928 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4929 CallingConv::ID CalleeCC) { 4930 // Tail calls are possible with fastcc and ccc. 4931 auto isTailCallableCC = [] (CallingConv::ID CC){ 4932 return CC == CallingConv::C || CC == CallingConv::Fast; 4933 }; 4934 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4935 return false; 4936 4937 // We can safely tail call both fastcc and ccc callees from a c calling 4938 // convention caller. If the caller is fastcc, we may have less stack space 4939 // than a non-fastcc caller with the same signature so disable tail-calls in 4940 // that case. 4941 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4942 } 4943 4944 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4945 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4946 const SmallVectorImpl<ISD::OutputArg> &Outs, 4947 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4948 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4949 4950 if (DisableSCO && !TailCallOpt) return false; 4951 4952 // Variadic argument functions are not supported. 4953 if (isVarArg) return false; 4954 4955 auto &Caller = DAG.getMachineFunction().getFunction(); 4956 // Check that the calling conventions are compatible for tco. 4957 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4958 return false; 4959 4960 // Caller contains any byval parameter is not supported. 4961 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4962 return false; 4963 4964 // Callee contains any byval parameter is not supported, too. 4965 // Note: This is a quick work around, because in some cases, e.g. 4966 // caller's stack size > callee's stack size, we are still able to apply 4967 // sibling call optimization. For example, gcc is able to do SCO for caller1 4968 // in the following example, but not for caller2. 4969 // struct test { 4970 // long int a; 4971 // char ary[56]; 4972 // } gTest; 4973 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4974 // b->a = v.a; 4975 // return 0; 4976 // } 4977 // void caller1(struct test a, struct test c, struct test *b) { 4978 // callee(gTest, b); } 4979 // void caller2(struct test *b) { callee(gTest, b); } 4980 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4981 return false; 4982 4983 // If callee and caller use different calling conventions, we cannot pass 4984 // parameters on stack since offsets for the parameter area may be different. 4985 if (Caller.getCallingConv() != CalleeCC && 4986 needStackSlotPassParameters(Subtarget, Outs)) 4987 return false; 4988 4989 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4990 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4991 // callee potentially have different TOC bases then we cannot tail call since 4992 // we need to restore the TOC pointer after the call. 4993 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4994 // We cannot guarantee this for indirect calls or calls to external functions. 4995 // When PC-Relative addressing is used, the concept of the TOC is no longer 4996 // applicable so this check is not required. 4997 // Check first for indirect calls. 4998 if (!Subtarget.isUsingPCRelativeCalls() && 4999 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 5000 return false; 5001 5002 // Check if we share the TOC base. 5003 if (!Subtarget.isUsingPCRelativeCalls() && 5004 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 5005 return false; 5006 5007 // TCO allows altering callee ABI, so we don't have to check further. 5008 if (CalleeCC == CallingConv::Fast && TailCallOpt) 5009 return true; 5010 5011 if (DisableSCO) return false; 5012 5013 // If callee use the same argument list that caller is using, then we can 5014 // apply SCO on this case. If it is not, then we need to check if callee needs 5015 // stack for passing arguments. 5016 // PC Relative tail calls may not have a CallBase. 5017 // If there is no CallBase we cannot verify if we have the same argument 5018 // list so assume that we don't have the same argument list. 5019 if (CB && !hasSameArgumentList(&Caller, *CB) && 5020 needStackSlotPassParameters(Subtarget, Outs)) 5021 return false; 5022 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 5023 return false; 5024 5025 return true; 5026 } 5027 5028 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 5029 /// for tail call optimization. Targets which want to do tail call 5030 /// optimization should implement this function. 5031 bool 5032 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 5033 CallingConv::ID CalleeCC, 5034 bool isVarArg, 5035 const SmallVectorImpl<ISD::InputArg> &Ins, 5036 SelectionDAG& DAG) const { 5037 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5038 return false; 5039 5040 // Variable argument functions are not supported. 5041 if (isVarArg) 5042 return false; 5043 5044 MachineFunction &MF = DAG.getMachineFunction(); 5045 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 5046 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 5047 // Functions containing by val parameters are not supported. 5048 for (unsigned i = 0; i != Ins.size(); i++) { 5049 ISD::ArgFlagsTy Flags = Ins[i].Flags; 5050 if (Flags.isByVal()) return false; 5051 } 5052 5053 // Non-PIC/GOT tail calls are supported. 5054 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 5055 return true; 5056 5057 // At the moment we can only do local tail calls (in same module, hidden 5058 // or protected) if we are generating PIC. 5059 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 5060 return G->getGlobal()->hasHiddenVisibility() 5061 || G->getGlobal()->hasProtectedVisibility(); 5062 } 5063 5064 return false; 5065 } 5066 5067 /// isCallCompatibleAddress - Return the immediate to use if the specified 5068 /// 32-bit value is representable in the immediate field of a BxA instruction. 5069 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 5070 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 5071 if (!C) return nullptr; 5072 5073 int Addr = C->getZExtValue(); 5074 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 5075 SignExtend32<26>(Addr) != Addr) 5076 return nullptr; // Top 6 bits have to be sext of immediate. 5077 5078 return DAG 5079 .getConstant( 5080 (int)C->getZExtValue() >> 2, SDLoc(Op), 5081 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 5082 .getNode(); 5083 } 5084 5085 namespace { 5086 5087 struct TailCallArgumentInfo { 5088 SDValue Arg; 5089 SDValue FrameIdxOp; 5090 int FrameIdx = 0; 5091 5092 TailCallArgumentInfo() = default; 5093 }; 5094 5095 } // end anonymous namespace 5096 5097 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 5098 static void StoreTailCallArgumentsToStackSlot( 5099 SelectionDAG &DAG, SDValue Chain, 5100 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 5101 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 5102 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 5103 SDValue Arg = TailCallArgs[i].Arg; 5104 SDValue FIN = TailCallArgs[i].FrameIdxOp; 5105 int FI = TailCallArgs[i].FrameIdx; 5106 // Store relative to framepointer. 5107 MemOpChains.push_back(DAG.getStore( 5108 Chain, dl, Arg, FIN, 5109 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 5110 } 5111 } 5112 5113 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 5114 /// the appropriate stack slot for the tail call optimized function call. 5115 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 5116 SDValue OldRetAddr, SDValue OldFP, 5117 int SPDiff, const SDLoc &dl) { 5118 if (SPDiff) { 5119 // Calculate the new stack slot for the return address. 5120 MachineFunction &MF = DAG.getMachineFunction(); 5121 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5122 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5123 bool isPPC64 = Subtarget.isPPC64(); 5124 int SlotSize = isPPC64 ? 8 : 4; 5125 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5126 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5127 NewRetAddrLoc, true); 5128 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5129 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5130 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5131 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5132 } 5133 return Chain; 5134 } 5135 5136 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5137 /// the position of the argument. 5138 static void 5139 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5140 SDValue Arg, int SPDiff, unsigned ArgOffset, 5141 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5142 int Offset = ArgOffset + SPDiff; 5143 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5144 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5145 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5146 SDValue FIN = DAG.getFrameIndex(FI, VT); 5147 TailCallArgumentInfo Info; 5148 Info.Arg = Arg; 5149 Info.FrameIdxOp = FIN; 5150 Info.FrameIdx = FI; 5151 TailCallArguments.push_back(Info); 5152 } 5153 5154 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5155 /// stack slot. Returns the chain as result and the loaded frame pointers in 5156 /// LROpOut/FPOpout. Used when tail calling. 5157 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5158 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5159 SDValue &FPOpOut, const SDLoc &dl) const { 5160 if (SPDiff) { 5161 // Load the LR and FP stack slot for later adjusting. 5162 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5163 LROpOut = getReturnAddrFrameIndex(DAG); 5164 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5165 Chain = SDValue(LROpOut.getNode(), 1); 5166 } 5167 return Chain; 5168 } 5169 5170 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5171 /// by "Src" to address "Dst" of size "Size". Alignment information is 5172 /// specified by the specific parameter attribute. The copy will be passed as 5173 /// a byval function parameter. 5174 /// Sometimes what we are copying is the end of a larger object, the part that 5175 /// does not fit in registers. 5176 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5177 SDValue Chain, ISD::ArgFlagsTy Flags, 5178 SelectionDAG &DAG, const SDLoc &dl) { 5179 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5180 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5181 Flags.getNonZeroByValAlign(), false, false, false, 5182 MachinePointerInfo(), MachinePointerInfo()); 5183 } 5184 5185 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5186 /// tail calls. 5187 static void LowerMemOpCallTo( 5188 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5189 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5190 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5191 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5192 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5193 if (!isTailCall) { 5194 if (isVector) { 5195 SDValue StackPtr; 5196 if (isPPC64) 5197 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5198 else 5199 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5200 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5201 DAG.getConstant(ArgOffset, dl, PtrVT)); 5202 } 5203 MemOpChains.push_back( 5204 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5205 // Calculate and remember argument location. 5206 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5207 TailCallArguments); 5208 } 5209 5210 static void 5211 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5212 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5213 SDValue FPOp, 5214 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5215 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5216 // might overwrite each other in case of tail call optimization. 5217 SmallVector<SDValue, 8> MemOpChains2; 5218 // Do not flag preceding copytoreg stuff together with the following stuff. 5219 InFlag = SDValue(); 5220 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5221 MemOpChains2, dl); 5222 if (!MemOpChains2.empty()) 5223 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5224 5225 // Store the return address to the appropriate stack slot. 5226 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5227 5228 // Emit callseq_end just before tailcall node. 5229 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5230 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5231 InFlag = Chain.getValue(1); 5232 } 5233 5234 // Is this global address that of a function that can be called by name? (as 5235 // opposed to something that must hold a descriptor for an indirect call). 5236 static bool isFunctionGlobalAddress(SDValue Callee) { 5237 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5238 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5239 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5240 return false; 5241 5242 return G->getGlobal()->getValueType()->isFunctionTy(); 5243 } 5244 5245 return false; 5246 } 5247 5248 SDValue PPCTargetLowering::LowerCallResult( 5249 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5250 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5251 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5252 SmallVector<CCValAssign, 16> RVLocs; 5253 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5254 *DAG.getContext()); 5255 5256 CCRetInfo.AnalyzeCallResult( 5257 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5258 ? RetCC_PPC_Cold 5259 : RetCC_PPC); 5260 5261 // Copy all of the result registers out of their specified physreg. 5262 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5263 CCValAssign &VA = RVLocs[i]; 5264 assert(VA.isRegLoc() && "Can only return in registers!"); 5265 5266 SDValue Val; 5267 5268 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5269 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5270 InFlag); 5271 Chain = Lo.getValue(1); 5272 InFlag = Lo.getValue(2); 5273 VA = RVLocs[++i]; // skip ahead to next loc 5274 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5275 InFlag); 5276 Chain = Hi.getValue(1); 5277 InFlag = Hi.getValue(2); 5278 if (!Subtarget.isLittleEndian()) 5279 std::swap (Lo, Hi); 5280 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5281 } else { 5282 Val = DAG.getCopyFromReg(Chain, dl, 5283 VA.getLocReg(), VA.getLocVT(), InFlag); 5284 Chain = Val.getValue(1); 5285 InFlag = Val.getValue(2); 5286 } 5287 5288 switch (VA.getLocInfo()) { 5289 default: llvm_unreachable("Unknown loc info!"); 5290 case CCValAssign::Full: break; 5291 case CCValAssign::AExt: 5292 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5293 break; 5294 case CCValAssign::ZExt: 5295 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5296 DAG.getValueType(VA.getValVT())); 5297 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5298 break; 5299 case CCValAssign::SExt: 5300 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5301 DAG.getValueType(VA.getValVT())); 5302 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5303 break; 5304 } 5305 5306 InVals.push_back(Val); 5307 } 5308 5309 return Chain; 5310 } 5311 5312 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5313 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5314 // PatchPoint calls are not indirect. 5315 if (isPatchPoint) 5316 return false; 5317 5318 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5319 return false; 5320 5321 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5322 // becuase the immediate function pointer points to a descriptor instead of 5323 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5324 // pointer immediate points to the global entry point, while the BLA would 5325 // need to jump to the local entry point (see rL211174). 5326 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5327 isBLACompatibleAddress(Callee, DAG)) 5328 return false; 5329 5330 return true; 5331 } 5332 5333 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5334 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5335 return Subtarget.isAIXABI() || 5336 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5337 } 5338 5339 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5340 const Function &Caller, 5341 const SDValue &Callee, 5342 const PPCSubtarget &Subtarget, 5343 const TargetMachine &TM) { 5344 if (CFlags.IsTailCall) 5345 return PPCISD::TC_RETURN; 5346 5347 // This is a call through a function pointer. 5348 if (CFlags.IsIndirect) { 5349 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5350 // indirect calls. The save of the caller's TOC pointer to the stack will be 5351 // inserted into the DAG as part of call lowering. The restore of the TOC 5352 // pointer is modeled by using a pseudo instruction for the call opcode that 5353 // represents the 2 instruction sequence of an indirect branch and link, 5354 // immediately followed by a load of the TOC pointer from the the stack save 5355 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5356 // as it is not saved or used. 5357 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5358 : PPCISD::BCTRL; 5359 } 5360 5361 if (Subtarget.isUsingPCRelativeCalls()) { 5362 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5363 return PPCISD::CALL_NOTOC; 5364 } 5365 5366 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5367 // immediately following the call instruction if the caller and callee may 5368 // have different TOC bases. At link time if the linker determines the calls 5369 // may not share a TOC base, the call is redirected to a trampoline inserted 5370 // by the linker. The trampoline will (among other things) save the callers 5371 // TOC pointer at an ABI designated offset in the linkage area and the linker 5372 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5373 // into gpr2. 5374 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5375 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5376 : PPCISD::CALL_NOP; 5377 5378 return PPCISD::CALL; 5379 } 5380 5381 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5382 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5383 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5384 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5385 return SDValue(Dest, 0); 5386 5387 // Returns true if the callee is local, and false otherwise. 5388 auto isLocalCallee = [&]() { 5389 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5390 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5391 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5392 5393 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5394 !dyn_cast_or_null<GlobalIFunc>(GV); 5395 }; 5396 5397 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5398 // a static relocation model causes some versions of GNU LD (2.17.50, at 5399 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5400 // built with secure-PLT. 5401 bool UsePlt = 5402 Subtarget.is32BitELFABI() && !isLocalCallee() && 5403 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5404 5405 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5406 const TargetMachine &TM = Subtarget.getTargetMachine(); 5407 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5408 MCSymbolXCOFF *S = 5409 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5410 5411 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5412 return DAG.getMCSymbol(S, PtrVT); 5413 }; 5414 5415 if (isFunctionGlobalAddress(Callee)) { 5416 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5417 5418 if (Subtarget.isAIXABI()) { 5419 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5420 return getAIXFuncEntryPointSymbolSDNode(GV); 5421 } 5422 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5423 UsePlt ? PPCII::MO_PLT : 0); 5424 } 5425 5426 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5427 const char *SymName = S->getSymbol(); 5428 if (Subtarget.isAIXABI()) { 5429 // If there exists a user-declared function whose name is the same as the 5430 // ExternalSymbol's, then we pick up the user-declared version. 5431 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5432 if (const Function *F = 5433 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5434 return getAIXFuncEntryPointSymbolSDNode(F); 5435 5436 // On AIX, direct function calls reference the symbol for the function's 5437 // entry point, which is named by prepending a "." before the function's 5438 // C-linkage name. A Qualname is returned here because an external 5439 // function entry point is a csect with XTY_ER property. 5440 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5441 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5442 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5443 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5444 SectionKind::getMetadata()); 5445 return Sec->getQualNameSymbol(); 5446 }; 5447 5448 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5449 } 5450 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5451 UsePlt ? PPCII::MO_PLT : 0); 5452 } 5453 5454 // No transformation needed. 5455 assert(Callee.getNode() && "What no callee?"); 5456 return Callee; 5457 } 5458 5459 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5460 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5461 "Expected a CALLSEQ_STARTSDNode."); 5462 5463 // The last operand is the chain, except when the node has glue. If the node 5464 // has glue, then the last operand is the glue, and the chain is the second 5465 // last operand. 5466 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5467 if (LastValue.getValueType() != MVT::Glue) 5468 return LastValue; 5469 5470 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5471 } 5472 5473 // Creates the node that moves a functions address into the count register 5474 // to prepare for an indirect call instruction. 5475 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5476 SDValue &Glue, SDValue &Chain, 5477 const SDLoc &dl) { 5478 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5479 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5480 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5481 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5482 // The glue is the second value produced. 5483 Glue = Chain.getValue(1); 5484 } 5485 5486 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5487 SDValue &Glue, SDValue &Chain, 5488 SDValue CallSeqStart, 5489 const CallBase *CB, const SDLoc &dl, 5490 bool hasNest, 5491 const PPCSubtarget &Subtarget) { 5492 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5493 // entry point, but to the function descriptor (the function entry point 5494 // address is part of the function descriptor though). 5495 // The function descriptor is a three doubleword structure with the 5496 // following fields: function entry point, TOC base address and 5497 // environment pointer. 5498 // Thus for a call through a function pointer, the following actions need 5499 // to be performed: 5500 // 1. Save the TOC of the caller in the TOC save area of its stack 5501 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5502 // 2. Load the address of the function entry point from the function 5503 // descriptor. 5504 // 3. Load the TOC of the callee from the function descriptor into r2. 5505 // 4. Load the environment pointer from the function descriptor into 5506 // r11. 5507 // 5. Branch to the function entry point address. 5508 // 6. On return of the callee, the TOC of the caller needs to be 5509 // restored (this is done in FinishCall()). 5510 // 5511 // The loads are scheduled at the beginning of the call sequence, and the 5512 // register copies are flagged together to ensure that no other 5513 // operations can be scheduled in between. E.g. without flagging the 5514 // copies together, a TOC access in the caller could be scheduled between 5515 // the assignment of the callee TOC and the branch to the callee, which leads 5516 // to incorrect code. 5517 5518 // Start by loading the function address from the descriptor. 5519 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5520 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5521 ? (MachineMemOperand::MODereferenceable | 5522 MachineMemOperand::MOInvariant) 5523 : MachineMemOperand::MONone; 5524 5525 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5526 5527 // Registers used in building the DAG. 5528 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5529 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5530 5531 // Offsets of descriptor members. 5532 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5533 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5534 5535 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5536 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5537 5538 // One load for the functions entry point address. 5539 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5540 Alignment, MMOFlags); 5541 5542 // One for loading the TOC anchor for the module that contains the called 5543 // function. 5544 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5545 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5546 SDValue TOCPtr = 5547 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5548 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5549 5550 // One for loading the environment pointer. 5551 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5552 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5553 SDValue LoadEnvPtr = 5554 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5555 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5556 5557 5558 // Then copy the newly loaded TOC anchor to the TOC pointer. 5559 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5560 Chain = TOCVal.getValue(0); 5561 Glue = TOCVal.getValue(1); 5562 5563 // If the function call has an explicit 'nest' parameter, it takes the 5564 // place of the environment pointer. 5565 assert((!hasNest || !Subtarget.isAIXABI()) && 5566 "Nest parameter is not supported on AIX."); 5567 if (!hasNest) { 5568 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5569 Chain = EnvVal.getValue(0); 5570 Glue = EnvVal.getValue(1); 5571 } 5572 5573 // The rest of the indirect call sequence is the same as the non-descriptor 5574 // DAG. 5575 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5576 } 5577 5578 static void 5579 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5580 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5581 SelectionDAG &DAG, 5582 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5583 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5584 const PPCSubtarget &Subtarget) { 5585 const bool IsPPC64 = Subtarget.isPPC64(); 5586 // MVT for a general purpose register. 5587 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5588 5589 // First operand is always the chain. 5590 Ops.push_back(Chain); 5591 5592 // If it's a direct call pass the callee as the second operand. 5593 if (!CFlags.IsIndirect) 5594 Ops.push_back(Callee); 5595 else { 5596 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5597 5598 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5599 // on the stack (this would have been done in `LowerCall_64SVR4` or 5600 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5601 // represents both the indirect branch and a load that restores the TOC 5602 // pointer from the linkage area. The operand for the TOC restore is an add 5603 // of the TOC save offset to the stack pointer. This must be the second 5604 // operand: after the chain input but before any other variadic arguments. 5605 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5606 // saved or used. 5607 if (isTOCSaveRestoreRequired(Subtarget)) { 5608 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5609 5610 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5611 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5612 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5613 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5614 Ops.push_back(AddTOC); 5615 } 5616 5617 // Add the register used for the environment pointer. 5618 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5619 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5620 RegVT)); 5621 5622 5623 // Add CTR register as callee so a bctr can be emitted later. 5624 if (CFlags.IsTailCall) 5625 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5626 } 5627 5628 // If this is a tail call add stack pointer delta. 5629 if (CFlags.IsTailCall) 5630 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5631 5632 // Add argument registers to the end of the list so that they are known live 5633 // into the call. 5634 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5635 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5636 RegsToPass[i].second.getValueType())); 5637 5638 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5639 // no way to mark dependencies as implicit here. 5640 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5641 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5642 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5643 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5644 5645 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5646 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5647 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5648 5649 // Add a register mask operand representing the call-preserved registers. 5650 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5651 const uint32_t *Mask = 5652 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5653 assert(Mask && "Missing call preserved mask for calling convention"); 5654 Ops.push_back(DAG.getRegisterMask(Mask)); 5655 5656 // If the glue is valid, it is the last operand. 5657 if (Glue.getNode()) 5658 Ops.push_back(Glue); 5659 } 5660 5661 SDValue PPCTargetLowering::FinishCall( 5662 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5663 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5664 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5665 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5666 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5667 5668 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5669 Subtarget.isAIXABI()) 5670 setUsesTOCBasePtr(DAG); 5671 5672 unsigned CallOpc = 5673 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5674 Subtarget, DAG.getTarget()); 5675 5676 if (!CFlags.IsIndirect) 5677 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5678 else if (Subtarget.usesFunctionDescriptors()) 5679 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5680 dl, CFlags.HasNest, Subtarget); 5681 else 5682 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5683 5684 // Build the operand list for the call instruction. 5685 SmallVector<SDValue, 8> Ops; 5686 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5687 SPDiff, Subtarget); 5688 5689 // Emit tail call. 5690 if (CFlags.IsTailCall) { 5691 // Indirect tail call when using PC Relative calls do not have the same 5692 // constraints. 5693 assert(((Callee.getOpcode() == ISD::Register && 5694 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5695 Callee.getOpcode() == ISD::TargetExternalSymbol || 5696 Callee.getOpcode() == ISD::TargetGlobalAddress || 5697 isa<ConstantSDNode>(Callee) || 5698 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5699 "Expecting a global address, external symbol, absolute value, " 5700 "register or an indirect tail call when PC Relative calls are " 5701 "used."); 5702 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5703 assert(CallOpc == PPCISD::TC_RETURN && 5704 "Unexpected call opcode for a tail call."); 5705 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5706 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5707 } 5708 5709 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5710 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5711 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5712 Glue = Chain.getValue(1); 5713 5714 // When performing tail call optimization the callee pops its arguments off 5715 // the stack. Account for this here so these bytes can be pushed back on in 5716 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5717 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5718 getTargetMachine().Options.GuaranteedTailCallOpt) 5719 ? NumBytes 5720 : 0; 5721 5722 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5723 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5724 Glue, dl); 5725 Glue = Chain.getValue(1); 5726 5727 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5728 DAG, InVals); 5729 } 5730 5731 SDValue 5732 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5733 SmallVectorImpl<SDValue> &InVals) const { 5734 SelectionDAG &DAG = CLI.DAG; 5735 SDLoc &dl = CLI.DL; 5736 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5737 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5738 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5739 SDValue Chain = CLI.Chain; 5740 SDValue Callee = CLI.Callee; 5741 bool &isTailCall = CLI.IsTailCall; 5742 CallingConv::ID CallConv = CLI.CallConv; 5743 bool isVarArg = CLI.IsVarArg; 5744 bool isPatchPoint = CLI.IsPatchPoint; 5745 const CallBase *CB = CLI.CB; 5746 5747 if (isTailCall) { 5748 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5749 isTailCall = false; 5750 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5751 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5752 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5753 else 5754 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5755 Ins, DAG); 5756 if (isTailCall) { 5757 ++NumTailCalls; 5758 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5759 ++NumSiblingCalls; 5760 5761 // PC Relative calls no longer guarantee that the callee is a Global 5762 // Address Node. The callee could be an indirect tail call in which 5763 // case the SDValue for the callee could be a load (to load the address 5764 // of a function pointer) or it may be a register copy (to move the 5765 // address of the callee from a function parameter into a virtual 5766 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5767 assert((Subtarget.isUsingPCRelativeCalls() || 5768 isa<GlobalAddressSDNode>(Callee)) && 5769 "Callee should be an llvm::Function object."); 5770 5771 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5772 << "\nTCO callee: "); 5773 LLVM_DEBUG(Callee.dump()); 5774 } 5775 } 5776 5777 if (!isTailCall && CB && CB->isMustTailCall()) 5778 report_fatal_error("failed to perform tail call elimination on a call " 5779 "site marked musttail"); 5780 5781 // When long calls (i.e. indirect calls) are always used, calls are always 5782 // made via function pointer. If we have a function name, first translate it 5783 // into a pointer. 5784 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5785 !isTailCall) 5786 Callee = LowerGlobalAddress(Callee, DAG); 5787 5788 CallFlags CFlags( 5789 CallConv, isTailCall, isVarArg, isPatchPoint, 5790 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5791 // hasNest 5792 Subtarget.is64BitELFABI() && 5793 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5794 CLI.NoMerge); 5795 5796 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5797 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5798 InVals, CB); 5799 5800 if (Subtarget.isSVR4ABI()) 5801 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5802 InVals, CB); 5803 5804 if (Subtarget.isAIXABI()) 5805 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5806 InVals, CB); 5807 5808 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5809 InVals, CB); 5810 } 5811 5812 SDValue PPCTargetLowering::LowerCall_32SVR4( 5813 SDValue Chain, SDValue Callee, CallFlags CFlags, 5814 const SmallVectorImpl<ISD::OutputArg> &Outs, 5815 const SmallVectorImpl<SDValue> &OutVals, 5816 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5817 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5818 const CallBase *CB) const { 5819 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5820 // of the 32-bit SVR4 ABI stack frame layout. 5821 5822 const CallingConv::ID CallConv = CFlags.CallConv; 5823 const bool IsVarArg = CFlags.IsVarArg; 5824 const bool IsTailCall = CFlags.IsTailCall; 5825 5826 assert((CallConv == CallingConv::C || 5827 CallConv == CallingConv::Cold || 5828 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5829 5830 const Align PtrAlign(4); 5831 5832 MachineFunction &MF = DAG.getMachineFunction(); 5833 5834 // Mark this function as potentially containing a function that contains a 5835 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5836 // and restoring the callers stack pointer in this functions epilog. This is 5837 // done because by tail calling the called function might overwrite the value 5838 // in this function's (MF) stack pointer stack slot 0(SP). 5839 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5840 CallConv == CallingConv::Fast) 5841 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5842 5843 // Count how many bytes are to be pushed on the stack, including the linkage 5844 // area, parameter list area and the part of the local variable space which 5845 // contains copies of aggregates which are passed by value. 5846 5847 // Assign locations to all of the outgoing arguments. 5848 SmallVector<CCValAssign, 16> ArgLocs; 5849 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5850 5851 // Reserve space for the linkage area on the stack. 5852 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5853 PtrAlign); 5854 if (useSoftFloat()) 5855 CCInfo.PreAnalyzeCallOperands(Outs); 5856 5857 if (IsVarArg) { 5858 // Handle fixed and variable vector arguments differently. 5859 // Fixed vector arguments go into registers as long as registers are 5860 // available. Variable vector arguments always go into memory. 5861 unsigned NumArgs = Outs.size(); 5862 5863 for (unsigned i = 0; i != NumArgs; ++i) { 5864 MVT ArgVT = Outs[i].VT; 5865 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5866 bool Result; 5867 5868 if (Outs[i].IsFixed) { 5869 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5870 CCInfo); 5871 } else { 5872 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5873 ArgFlags, CCInfo); 5874 } 5875 5876 if (Result) { 5877 #ifndef NDEBUG 5878 errs() << "Call operand #" << i << " has unhandled type " 5879 << EVT(ArgVT).getEVTString() << "\n"; 5880 #endif 5881 llvm_unreachable(nullptr); 5882 } 5883 } 5884 } else { 5885 // All arguments are treated the same. 5886 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5887 } 5888 CCInfo.clearWasPPCF128(); 5889 5890 // Assign locations to all of the outgoing aggregate by value arguments. 5891 SmallVector<CCValAssign, 16> ByValArgLocs; 5892 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5893 5894 // Reserve stack space for the allocations in CCInfo. 5895 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5896 5897 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5898 5899 // Size of the linkage area, parameter list area and the part of the local 5900 // space variable where copies of aggregates which are passed by value are 5901 // stored. 5902 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5903 5904 // Calculate by how many bytes the stack has to be adjusted in case of tail 5905 // call optimization. 5906 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5907 5908 // Adjust the stack pointer for the new arguments... 5909 // These operations are automatically eliminated by the prolog/epilog pass 5910 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5911 SDValue CallSeqStart = Chain; 5912 5913 // Load the return address and frame pointer so it can be moved somewhere else 5914 // later. 5915 SDValue LROp, FPOp; 5916 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5917 5918 // Set up a copy of the stack pointer for use loading and storing any 5919 // arguments that may not fit in the registers available for argument 5920 // passing. 5921 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5922 5923 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5924 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5925 SmallVector<SDValue, 8> MemOpChains; 5926 5927 bool seenFloatArg = false; 5928 // Walk the register/memloc assignments, inserting copies/loads. 5929 // i - Tracks the index into the list of registers allocated for the call 5930 // RealArgIdx - Tracks the index into the list of actual function arguments 5931 // j - Tracks the index into the list of byval arguments 5932 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5933 i != e; 5934 ++i, ++RealArgIdx) { 5935 CCValAssign &VA = ArgLocs[i]; 5936 SDValue Arg = OutVals[RealArgIdx]; 5937 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5938 5939 if (Flags.isByVal()) { 5940 // Argument is an aggregate which is passed by value, thus we need to 5941 // create a copy of it in the local variable space of the current stack 5942 // frame (which is the stack frame of the caller) and pass the address of 5943 // this copy to the callee. 5944 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5945 CCValAssign &ByValVA = ByValArgLocs[j++]; 5946 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5947 5948 // Memory reserved in the local variable space of the callers stack frame. 5949 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5950 5951 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5952 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5953 StackPtr, PtrOff); 5954 5955 // Create a copy of the argument in the local area of the current 5956 // stack frame. 5957 SDValue MemcpyCall = 5958 CreateCopyOfByValArgument(Arg, PtrOff, 5959 CallSeqStart.getNode()->getOperand(0), 5960 Flags, DAG, dl); 5961 5962 // This must go outside the CALLSEQ_START..END. 5963 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5964 SDLoc(MemcpyCall)); 5965 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5966 NewCallSeqStart.getNode()); 5967 Chain = CallSeqStart = NewCallSeqStart; 5968 5969 // Pass the address of the aggregate copy on the stack either in a 5970 // physical register or in the parameter list area of the current stack 5971 // frame to the callee. 5972 Arg = PtrOff; 5973 } 5974 5975 // When useCRBits() is true, there can be i1 arguments. 5976 // It is because getRegisterType(MVT::i1) => MVT::i1, 5977 // and for other integer types getRegisterType() => MVT::i32. 5978 // Extend i1 and ensure callee will get i32. 5979 if (Arg.getValueType() == MVT::i1) 5980 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5981 dl, MVT::i32, Arg); 5982 5983 if (VA.isRegLoc()) { 5984 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5985 // Put argument in a physical register. 5986 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5987 bool IsLE = Subtarget.isLittleEndian(); 5988 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5989 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5990 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5991 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5992 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5993 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5994 SVal.getValue(0))); 5995 } else 5996 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5997 } else { 5998 // Put argument in the parameter list area of the current stack frame. 5999 assert(VA.isMemLoc()); 6000 unsigned LocMemOffset = VA.getLocMemOffset(); 6001 6002 if (!IsTailCall) { 6003 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 6004 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 6005 StackPtr, PtrOff); 6006 6007 MemOpChains.push_back( 6008 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 6009 } else { 6010 // Calculate and remember argument location. 6011 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 6012 TailCallArguments); 6013 } 6014 } 6015 } 6016 6017 if (!MemOpChains.empty()) 6018 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6019 6020 // Build a sequence of copy-to-reg nodes chained together with token chain 6021 // and flag operands which copy the outgoing args into the appropriate regs. 6022 SDValue InFlag; 6023 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6024 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6025 RegsToPass[i].second, InFlag); 6026 InFlag = Chain.getValue(1); 6027 } 6028 6029 // Set CR bit 6 to true if this is a vararg call with floating args passed in 6030 // registers. 6031 if (IsVarArg) { 6032 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 6033 SDValue Ops[] = { Chain, InFlag }; 6034 6035 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 6036 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 6037 6038 InFlag = Chain.getValue(1); 6039 } 6040 6041 if (IsTailCall) 6042 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6043 TailCallArguments); 6044 6045 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6046 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6047 } 6048 6049 // Copy an argument into memory, being careful to do this outside the 6050 // call sequence for the call to which the argument belongs. 6051 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 6052 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 6053 SelectionDAG &DAG, const SDLoc &dl) const { 6054 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 6055 CallSeqStart.getNode()->getOperand(0), 6056 Flags, DAG, dl); 6057 // The MEMCPY must go outside the CALLSEQ_START..END. 6058 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 6059 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 6060 SDLoc(MemcpyCall)); 6061 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 6062 NewCallSeqStart.getNode()); 6063 return NewCallSeqStart; 6064 } 6065 6066 SDValue PPCTargetLowering::LowerCall_64SVR4( 6067 SDValue Chain, SDValue Callee, CallFlags CFlags, 6068 const SmallVectorImpl<ISD::OutputArg> &Outs, 6069 const SmallVectorImpl<SDValue> &OutVals, 6070 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6071 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6072 const CallBase *CB) const { 6073 bool isELFv2ABI = Subtarget.isELFv2ABI(); 6074 bool isLittleEndian = Subtarget.isLittleEndian(); 6075 unsigned NumOps = Outs.size(); 6076 bool IsSibCall = false; 6077 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 6078 6079 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6080 unsigned PtrByteSize = 8; 6081 6082 MachineFunction &MF = DAG.getMachineFunction(); 6083 6084 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 6085 IsSibCall = true; 6086 6087 // Mark this function as potentially containing a function that contains a 6088 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6089 // and restoring the callers stack pointer in this functions epilog. This is 6090 // done because by tail calling the called function might overwrite the value 6091 // in this function's (MF) stack pointer stack slot 0(SP). 6092 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6093 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6094 6095 assert(!(IsFastCall && CFlags.IsVarArg) && 6096 "fastcc not supported on varargs functions"); 6097 6098 // Count how many bytes are to be pushed on the stack, including the linkage 6099 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 6100 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 6101 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 6102 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6103 unsigned NumBytes = LinkageSize; 6104 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6105 6106 static const MCPhysReg GPR[] = { 6107 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6108 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6109 }; 6110 static const MCPhysReg VR[] = { 6111 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6112 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6113 }; 6114 6115 const unsigned NumGPRs = array_lengthof(GPR); 6116 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6117 const unsigned NumVRs = array_lengthof(VR); 6118 6119 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6120 // can be passed to the callee in registers. 6121 // For the fast calling convention, there is another check below. 6122 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6123 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6124 if (!HasParameterArea) { 6125 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6126 unsigned AvailableFPRs = NumFPRs; 6127 unsigned AvailableVRs = NumVRs; 6128 unsigned NumBytesTmp = NumBytes; 6129 for (unsigned i = 0; i != NumOps; ++i) { 6130 if (Outs[i].Flags.isNest()) continue; 6131 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6132 PtrByteSize, LinkageSize, ParamAreaSize, 6133 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6134 HasParameterArea = true; 6135 } 6136 } 6137 6138 // When using the fast calling convention, we don't provide backing for 6139 // arguments that will be in registers. 6140 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6141 6142 // Avoid allocating parameter area for fastcc functions if all the arguments 6143 // can be passed in the registers. 6144 if (IsFastCall) 6145 HasParameterArea = false; 6146 6147 // Add up all the space actually used. 6148 for (unsigned i = 0; i != NumOps; ++i) { 6149 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6150 EVT ArgVT = Outs[i].VT; 6151 EVT OrigVT = Outs[i].ArgVT; 6152 6153 if (Flags.isNest()) 6154 continue; 6155 6156 if (IsFastCall) { 6157 if (Flags.isByVal()) { 6158 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6159 if (NumGPRsUsed > NumGPRs) 6160 HasParameterArea = true; 6161 } else { 6162 switch (ArgVT.getSimpleVT().SimpleTy) { 6163 default: llvm_unreachable("Unexpected ValueType for argument!"); 6164 case MVT::i1: 6165 case MVT::i32: 6166 case MVT::i64: 6167 if (++NumGPRsUsed <= NumGPRs) 6168 continue; 6169 break; 6170 case MVT::v4i32: 6171 case MVT::v8i16: 6172 case MVT::v16i8: 6173 case MVT::v2f64: 6174 case MVT::v2i64: 6175 case MVT::v1i128: 6176 case MVT::f128: 6177 if (++NumVRsUsed <= NumVRs) 6178 continue; 6179 break; 6180 case MVT::v4f32: 6181 if (++NumVRsUsed <= NumVRs) 6182 continue; 6183 break; 6184 case MVT::f32: 6185 case MVT::f64: 6186 if (++NumFPRsUsed <= NumFPRs) 6187 continue; 6188 break; 6189 } 6190 HasParameterArea = true; 6191 } 6192 } 6193 6194 /* Respect alignment of argument on the stack. */ 6195 auto Alignement = 6196 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6197 NumBytes = alignTo(NumBytes, Alignement); 6198 6199 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6200 if (Flags.isInConsecutiveRegsLast()) 6201 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6202 } 6203 6204 unsigned NumBytesActuallyUsed = NumBytes; 6205 6206 // In the old ELFv1 ABI, 6207 // the prolog code of the callee may store up to 8 GPR argument registers to 6208 // the stack, allowing va_start to index over them in memory if its varargs. 6209 // Because we cannot tell if this is needed on the caller side, we have to 6210 // conservatively assume that it is needed. As such, make sure we have at 6211 // least enough stack space for the caller to store the 8 GPRs. 6212 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6213 // really requires memory operands, e.g. a vararg function. 6214 if (HasParameterArea) 6215 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6216 else 6217 NumBytes = LinkageSize; 6218 6219 // Tail call needs the stack to be aligned. 6220 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6221 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6222 6223 int SPDiff = 0; 6224 6225 // Calculate by how many bytes the stack has to be adjusted in case of tail 6226 // call optimization. 6227 if (!IsSibCall) 6228 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6229 6230 // To protect arguments on the stack from being clobbered in a tail call, 6231 // force all the loads to happen before doing any other lowering. 6232 if (CFlags.IsTailCall) 6233 Chain = DAG.getStackArgumentTokenFactor(Chain); 6234 6235 // Adjust the stack pointer for the new arguments... 6236 // These operations are automatically eliminated by the prolog/epilog pass 6237 if (!IsSibCall) 6238 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6239 SDValue CallSeqStart = Chain; 6240 6241 // Load the return address and frame pointer so it can be move somewhere else 6242 // later. 6243 SDValue LROp, FPOp; 6244 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6245 6246 // Set up a copy of the stack pointer for use loading and storing any 6247 // arguments that may not fit in the registers available for argument 6248 // passing. 6249 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6250 6251 // Figure out which arguments are going to go in registers, and which in 6252 // memory. Also, if this is a vararg function, floating point operations 6253 // must be stored to our stack, and loaded into integer regs as well, if 6254 // any integer regs are available for argument passing. 6255 unsigned ArgOffset = LinkageSize; 6256 6257 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6258 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6259 6260 SmallVector<SDValue, 8> MemOpChains; 6261 for (unsigned i = 0; i != NumOps; ++i) { 6262 SDValue Arg = OutVals[i]; 6263 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6264 EVT ArgVT = Outs[i].VT; 6265 EVT OrigVT = Outs[i].ArgVT; 6266 6267 // PtrOff will be used to store the current argument to the stack if a 6268 // register cannot be found for it. 6269 SDValue PtrOff; 6270 6271 // We re-align the argument offset for each argument, except when using the 6272 // fast calling convention, when we need to make sure we do that only when 6273 // we'll actually use a stack slot. 6274 auto ComputePtrOff = [&]() { 6275 /* Respect alignment of argument on the stack. */ 6276 auto Alignment = 6277 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6278 ArgOffset = alignTo(ArgOffset, Alignment); 6279 6280 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6281 6282 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6283 }; 6284 6285 if (!IsFastCall) { 6286 ComputePtrOff(); 6287 6288 /* Compute GPR index associated with argument offset. */ 6289 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6290 GPR_idx = std::min(GPR_idx, NumGPRs); 6291 } 6292 6293 // Promote integers to 64-bit values. 6294 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6295 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6296 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6297 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6298 } 6299 6300 // FIXME memcpy is used way more than necessary. Correctness first. 6301 // Note: "by value" is code for passing a structure by value, not 6302 // basic types. 6303 if (Flags.isByVal()) { 6304 // Note: Size includes alignment padding, so 6305 // struct x { short a; char b; } 6306 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6307 // These are the proper values we need for right-justifying the 6308 // aggregate in a parameter register. 6309 unsigned Size = Flags.getByValSize(); 6310 6311 // An empty aggregate parameter takes up no storage and no 6312 // registers. 6313 if (Size == 0) 6314 continue; 6315 6316 if (IsFastCall) 6317 ComputePtrOff(); 6318 6319 // All aggregates smaller than 8 bytes must be passed right-justified. 6320 if (Size==1 || Size==2 || Size==4) { 6321 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6322 if (GPR_idx != NumGPRs) { 6323 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6324 MachinePointerInfo(), VT); 6325 MemOpChains.push_back(Load.getValue(1)); 6326 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6327 6328 ArgOffset += PtrByteSize; 6329 continue; 6330 } 6331 } 6332 6333 if (GPR_idx == NumGPRs && Size < 8) { 6334 SDValue AddPtr = PtrOff; 6335 if (!isLittleEndian) { 6336 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6337 PtrOff.getValueType()); 6338 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6339 } 6340 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6341 CallSeqStart, 6342 Flags, DAG, dl); 6343 ArgOffset += PtrByteSize; 6344 continue; 6345 } 6346 // Copy entire object into memory. There are cases where gcc-generated 6347 // code assumes it is there, even if it could be put entirely into 6348 // registers. (This is not what the doc says.) 6349 6350 // FIXME: The above statement is likely due to a misunderstanding of the 6351 // documents. All arguments must be copied into the parameter area BY 6352 // THE CALLEE in the event that the callee takes the address of any 6353 // formal argument. That has not yet been implemented. However, it is 6354 // reasonable to use the stack area as a staging area for the register 6355 // load. 6356 6357 // Skip this for small aggregates, as we will use the same slot for a 6358 // right-justified copy, below. 6359 if (Size >= 8) 6360 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6361 CallSeqStart, 6362 Flags, DAG, dl); 6363 6364 // When a register is available, pass a small aggregate right-justified. 6365 if (Size < 8 && GPR_idx != NumGPRs) { 6366 // The easiest way to get this right-justified in a register 6367 // is to copy the structure into the rightmost portion of a 6368 // local variable slot, then load the whole slot into the 6369 // register. 6370 // FIXME: The memcpy seems to produce pretty awful code for 6371 // small aggregates, particularly for packed ones. 6372 // FIXME: It would be preferable to use the slot in the 6373 // parameter save area instead of a new local variable. 6374 SDValue AddPtr = PtrOff; 6375 if (!isLittleEndian) { 6376 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6377 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6378 } 6379 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6380 CallSeqStart, 6381 Flags, DAG, dl); 6382 6383 // Load the slot into the register. 6384 SDValue Load = 6385 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6386 MemOpChains.push_back(Load.getValue(1)); 6387 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6388 6389 // Done with this argument. 6390 ArgOffset += PtrByteSize; 6391 continue; 6392 } 6393 6394 // For aggregates larger than PtrByteSize, copy the pieces of the 6395 // object that fit into registers from the parameter save area. 6396 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6397 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6398 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6399 if (GPR_idx != NumGPRs) { 6400 SDValue Load = 6401 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6402 MemOpChains.push_back(Load.getValue(1)); 6403 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6404 ArgOffset += PtrByteSize; 6405 } else { 6406 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6407 break; 6408 } 6409 } 6410 continue; 6411 } 6412 6413 switch (Arg.getSimpleValueType().SimpleTy) { 6414 default: llvm_unreachable("Unexpected ValueType for argument!"); 6415 case MVT::i1: 6416 case MVT::i32: 6417 case MVT::i64: 6418 if (Flags.isNest()) { 6419 // The 'nest' parameter, if any, is passed in R11. 6420 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6421 break; 6422 } 6423 6424 // These can be scalar arguments or elements of an integer array type 6425 // passed directly. Clang may use those instead of "byval" aggregate 6426 // types to avoid forcing arguments to memory unnecessarily. 6427 if (GPR_idx != NumGPRs) { 6428 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6429 } else { 6430 if (IsFastCall) 6431 ComputePtrOff(); 6432 6433 assert(HasParameterArea && 6434 "Parameter area must exist to pass an argument in memory."); 6435 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6436 true, CFlags.IsTailCall, false, MemOpChains, 6437 TailCallArguments, dl); 6438 if (IsFastCall) 6439 ArgOffset += PtrByteSize; 6440 } 6441 if (!IsFastCall) 6442 ArgOffset += PtrByteSize; 6443 break; 6444 case MVT::f32: 6445 case MVT::f64: { 6446 // These can be scalar arguments or elements of a float array type 6447 // passed directly. The latter are used to implement ELFv2 homogenous 6448 // float aggregates. 6449 6450 // Named arguments go into FPRs first, and once they overflow, the 6451 // remaining arguments go into GPRs and then the parameter save area. 6452 // Unnamed arguments for vararg functions always go to GPRs and 6453 // then the parameter save area. For now, put all arguments to vararg 6454 // routines always in both locations (FPR *and* GPR or stack slot). 6455 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6456 bool NeededLoad = false; 6457 6458 // First load the argument into the next available FPR. 6459 if (FPR_idx != NumFPRs) 6460 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6461 6462 // Next, load the argument into GPR or stack slot if needed. 6463 if (!NeedGPROrStack) 6464 ; 6465 else if (GPR_idx != NumGPRs && !IsFastCall) { 6466 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6467 // once we support fp <-> gpr moves. 6468 6469 // In the non-vararg case, this can only ever happen in the 6470 // presence of f32 array types, since otherwise we never run 6471 // out of FPRs before running out of GPRs. 6472 SDValue ArgVal; 6473 6474 // Double values are always passed in a single GPR. 6475 if (Arg.getValueType() != MVT::f32) { 6476 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6477 6478 // Non-array float values are extended and passed in a GPR. 6479 } else if (!Flags.isInConsecutiveRegs()) { 6480 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6481 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6482 6483 // If we have an array of floats, we collect every odd element 6484 // together with its predecessor into one GPR. 6485 } else if (ArgOffset % PtrByteSize != 0) { 6486 SDValue Lo, Hi; 6487 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6488 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6489 if (!isLittleEndian) 6490 std::swap(Lo, Hi); 6491 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6492 6493 // The final element, if even, goes into the first half of a GPR. 6494 } else if (Flags.isInConsecutiveRegsLast()) { 6495 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6496 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6497 if (!isLittleEndian) 6498 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6499 DAG.getConstant(32, dl, MVT::i32)); 6500 6501 // Non-final even elements are skipped; they will be handled 6502 // together the with subsequent argument on the next go-around. 6503 } else 6504 ArgVal = SDValue(); 6505 6506 if (ArgVal.getNode()) 6507 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6508 } else { 6509 if (IsFastCall) 6510 ComputePtrOff(); 6511 6512 // Single-precision floating-point values are mapped to the 6513 // second (rightmost) word of the stack doubleword. 6514 if (Arg.getValueType() == MVT::f32 && 6515 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6516 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6517 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6518 } 6519 6520 assert(HasParameterArea && 6521 "Parameter area must exist to pass an argument in memory."); 6522 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6523 true, CFlags.IsTailCall, false, MemOpChains, 6524 TailCallArguments, dl); 6525 6526 NeededLoad = true; 6527 } 6528 // When passing an array of floats, the array occupies consecutive 6529 // space in the argument area; only round up to the next doubleword 6530 // at the end of the array. Otherwise, each float takes 8 bytes. 6531 if (!IsFastCall || NeededLoad) { 6532 ArgOffset += (Arg.getValueType() == MVT::f32 && 6533 Flags.isInConsecutiveRegs()) ? 4 : 8; 6534 if (Flags.isInConsecutiveRegsLast()) 6535 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6536 } 6537 break; 6538 } 6539 case MVT::v4f32: 6540 case MVT::v4i32: 6541 case MVT::v8i16: 6542 case MVT::v16i8: 6543 case MVT::v2f64: 6544 case MVT::v2i64: 6545 case MVT::v1i128: 6546 case MVT::f128: 6547 // These can be scalar arguments or elements of a vector array type 6548 // passed directly. The latter are used to implement ELFv2 homogenous 6549 // vector aggregates. 6550 6551 // For a varargs call, named arguments go into VRs or on the stack as 6552 // usual; unnamed arguments always go to the stack or the corresponding 6553 // GPRs when within range. For now, we always put the value in both 6554 // locations (or even all three). 6555 if (CFlags.IsVarArg) { 6556 assert(HasParameterArea && 6557 "Parameter area must exist if we have a varargs call."); 6558 // We could elide this store in the case where the object fits 6559 // entirely in R registers. Maybe later. 6560 SDValue Store = 6561 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6562 MemOpChains.push_back(Store); 6563 if (VR_idx != NumVRs) { 6564 SDValue Load = 6565 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6566 MemOpChains.push_back(Load.getValue(1)); 6567 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6568 } 6569 ArgOffset += 16; 6570 for (unsigned i=0; i<16; i+=PtrByteSize) { 6571 if (GPR_idx == NumGPRs) 6572 break; 6573 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6574 DAG.getConstant(i, dl, PtrVT)); 6575 SDValue Load = 6576 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6577 MemOpChains.push_back(Load.getValue(1)); 6578 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6579 } 6580 break; 6581 } 6582 6583 // Non-varargs Altivec params go into VRs or on the stack. 6584 if (VR_idx != NumVRs) { 6585 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6586 } else { 6587 if (IsFastCall) 6588 ComputePtrOff(); 6589 6590 assert(HasParameterArea && 6591 "Parameter area must exist to pass an argument in memory."); 6592 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6593 true, CFlags.IsTailCall, true, MemOpChains, 6594 TailCallArguments, dl); 6595 if (IsFastCall) 6596 ArgOffset += 16; 6597 } 6598 6599 if (!IsFastCall) 6600 ArgOffset += 16; 6601 break; 6602 } 6603 } 6604 6605 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6606 "mismatch in size of parameter area"); 6607 (void)NumBytesActuallyUsed; 6608 6609 if (!MemOpChains.empty()) 6610 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6611 6612 // Check if this is an indirect call (MTCTR/BCTRL). 6613 // See prepareDescriptorIndirectCall and buildCallOperands for more 6614 // information about calls through function pointers in the 64-bit SVR4 ABI. 6615 if (CFlags.IsIndirect) { 6616 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6617 // caller in the TOC save area. 6618 if (isTOCSaveRestoreRequired(Subtarget)) { 6619 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6620 // Load r2 into a virtual register and store it to the TOC save area. 6621 setUsesTOCBasePtr(DAG); 6622 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6623 // TOC save area offset. 6624 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6625 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6626 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6627 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6628 MachinePointerInfo::getStack( 6629 DAG.getMachineFunction(), TOCSaveOffset)); 6630 } 6631 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6632 // This does not mean the MTCTR instruction must use R12; it's easier 6633 // to model this as an extra parameter, so do that. 6634 if (isELFv2ABI && !CFlags.IsPatchPoint) 6635 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6636 } 6637 6638 // Build a sequence of copy-to-reg nodes chained together with token chain 6639 // and flag operands which copy the outgoing args into the appropriate regs. 6640 SDValue InFlag; 6641 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6642 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6643 RegsToPass[i].second, InFlag); 6644 InFlag = Chain.getValue(1); 6645 } 6646 6647 if (CFlags.IsTailCall && !IsSibCall) 6648 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6649 TailCallArguments); 6650 6651 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6652 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6653 } 6654 6655 SDValue PPCTargetLowering::LowerCall_Darwin( 6656 SDValue Chain, SDValue Callee, CallFlags CFlags, 6657 const SmallVectorImpl<ISD::OutputArg> &Outs, 6658 const SmallVectorImpl<SDValue> &OutVals, 6659 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6660 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6661 const CallBase *CB) const { 6662 unsigned NumOps = Outs.size(); 6663 6664 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6665 bool isPPC64 = PtrVT == MVT::i64; 6666 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6667 6668 MachineFunction &MF = DAG.getMachineFunction(); 6669 6670 // Mark this function as potentially containing a function that contains a 6671 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6672 // and restoring the callers stack pointer in this functions epilog. This is 6673 // done because by tail calling the called function might overwrite the value 6674 // in this function's (MF) stack pointer stack slot 0(SP). 6675 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6676 CFlags.CallConv == CallingConv::Fast) 6677 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6678 6679 // Count how many bytes are to be pushed on the stack, including the linkage 6680 // area, and parameter passing area. We start with 24/48 bytes, which is 6681 // prereserved space for [SP][CR][LR][3 x unused]. 6682 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6683 unsigned NumBytes = LinkageSize; 6684 6685 // Add up all the space actually used. 6686 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6687 // they all go in registers, but we must reserve stack space for them for 6688 // possible use by the caller. In varargs or 64-bit calls, parameters are 6689 // assigned stack space in order, with padding so Altivec parameters are 6690 // 16-byte aligned. 6691 unsigned nAltivecParamsAtEnd = 0; 6692 for (unsigned i = 0; i != NumOps; ++i) { 6693 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6694 EVT ArgVT = Outs[i].VT; 6695 // Varargs Altivec parameters are padded to a 16 byte boundary. 6696 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6697 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6698 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6699 if (!CFlags.IsVarArg && !isPPC64) { 6700 // Non-varargs Altivec parameters go after all the non-Altivec 6701 // parameters; handle those later so we know how much padding we need. 6702 nAltivecParamsAtEnd++; 6703 continue; 6704 } 6705 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6706 NumBytes = ((NumBytes+15)/16)*16; 6707 } 6708 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6709 } 6710 6711 // Allow for Altivec parameters at the end, if needed. 6712 if (nAltivecParamsAtEnd) { 6713 NumBytes = ((NumBytes+15)/16)*16; 6714 NumBytes += 16*nAltivecParamsAtEnd; 6715 } 6716 6717 // The prolog code of the callee may store up to 8 GPR argument registers to 6718 // the stack, allowing va_start to index over them in memory if its varargs. 6719 // Because we cannot tell if this is needed on the caller side, we have to 6720 // conservatively assume that it is needed. As such, make sure we have at 6721 // least enough stack space for the caller to store the 8 GPRs. 6722 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6723 6724 // Tail call needs the stack to be aligned. 6725 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6726 CFlags.CallConv == CallingConv::Fast) 6727 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6728 6729 // Calculate by how many bytes the stack has to be adjusted in case of tail 6730 // call optimization. 6731 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6732 6733 // To protect arguments on the stack from being clobbered in a tail call, 6734 // force all the loads to happen before doing any other lowering. 6735 if (CFlags.IsTailCall) 6736 Chain = DAG.getStackArgumentTokenFactor(Chain); 6737 6738 // Adjust the stack pointer for the new arguments... 6739 // These operations are automatically eliminated by the prolog/epilog pass 6740 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6741 SDValue CallSeqStart = Chain; 6742 6743 // Load the return address and frame pointer so it can be move somewhere else 6744 // later. 6745 SDValue LROp, FPOp; 6746 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6747 6748 // Set up a copy of the stack pointer for use loading and storing any 6749 // arguments that may not fit in the registers available for argument 6750 // passing. 6751 SDValue StackPtr; 6752 if (isPPC64) 6753 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6754 else 6755 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6756 6757 // Figure out which arguments are going to go in registers, and which in 6758 // memory. Also, if this is a vararg function, floating point operations 6759 // must be stored to our stack, and loaded into integer regs as well, if 6760 // any integer regs are available for argument passing. 6761 unsigned ArgOffset = LinkageSize; 6762 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6763 6764 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6765 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6766 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6767 }; 6768 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6769 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6770 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6771 }; 6772 static const MCPhysReg VR[] = { 6773 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6774 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6775 }; 6776 const unsigned NumGPRs = array_lengthof(GPR_32); 6777 const unsigned NumFPRs = 13; 6778 const unsigned NumVRs = array_lengthof(VR); 6779 6780 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6781 6782 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6783 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6784 6785 SmallVector<SDValue, 8> MemOpChains; 6786 for (unsigned i = 0; i != NumOps; ++i) { 6787 SDValue Arg = OutVals[i]; 6788 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6789 6790 // PtrOff will be used to store the current argument to the stack if a 6791 // register cannot be found for it. 6792 SDValue PtrOff; 6793 6794 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6795 6796 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6797 6798 // On PPC64, promote integers to 64-bit values. 6799 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6800 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6801 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6802 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6803 } 6804 6805 // FIXME memcpy is used way more than necessary. Correctness first. 6806 // Note: "by value" is code for passing a structure by value, not 6807 // basic types. 6808 if (Flags.isByVal()) { 6809 unsigned Size = Flags.getByValSize(); 6810 // Very small objects are passed right-justified. Everything else is 6811 // passed left-justified. 6812 if (Size==1 || Size==2) { 6813 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6814 if (GPR_idx != NumGPRs) { 6815 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6816 MachinePointerInfo(), VT); 6817 MemOpChains.push_back(Load.getValue(1)); 6818 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6819 6820 ArgOffset += PtrByteSize; 6821 } else { 6822 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6823 PtrOff.getValueType()); 6824 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6825 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6826 CallSeqStart, 6827 Flags, DAG, dl); 6828 ArgOffset += PtrByteSize; 6829 } 6830 continue; 6831 } 6832 // Copy entire object into memory. There are cases where gcc-generated 6833 // code assumes it is there, even if it could be put entirely into 6834 // registers. (This is not what the doc says.) 6835 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6836 CallSeqStart, 6837 Flags, DAG, dl); 6838 6839 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6840 // copy the pieces of the object that fit into registers from the 6841 // parameter save area. 6842 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6843 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6844 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6845 if (GPR_idx != NumGPRs) { 6846 SDValue Load = 6847 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6848 MemOpChains.push_back(Load.getValue(1)); 6849 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6850 ArgOffset += PtrByteSize; 6851 } else { 6852 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6853 break; 6854 } 6855 } 6856 continue; 6857 } 6858 6859 switch (Arg.getSimpleValueType().SimpleTy) { 6860 default: llvm_unreachable("Unexpected ValueType for argument!"); 6861 case MVT::i1: 6862 case MVT::i32: 6863 case MVT::i64: 6864 if (GPR_idx != NumGPRs) { 6865 if (Arg.getValueType() == MVT::i1) 6866 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6867 6868 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6869 } else { 6870 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6871 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6872 TailCallArguments, dl); 6873 } 6874 ArgOffset += PtrByteSize; 6875 break; 6876 case MVT::f32: 6877 case MVT::f64: 6878 if (FPR_idx != NumFPRs) { 6879 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6880 6881 if (CFlags.IsVarArg) { 6882 SDValue Store = 6883 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6884 MemOpChains.push_back(Store); 6885 6886 // Float varargs are always shadowed in available integer registers 6887 if (GPR_idx != NumGPRs) { 6888 SDValue Load = 6889 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6890 MemOpChains.push_back(Load.getValue(1)); 6891 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6892 } 6893 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6894 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6895 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6896 SDValue Load = 6897 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6898 MemOpChains.push_back(Load.getValue(1)); 6899 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6900 } 6901 } else { 6902 // If we have any FPRs remaining, we may also have GPRs remaining. 6903 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6904 // GPRs. 6905 if (GPR_idx != NumGPRs) 6906 ++GPR_idx; 6907 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6908 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6909 ++GPR_idx; 6910 } 6911 } else 6912 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6913 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6914 TailCallArguments, dl); 6915 if (isPPC64) 6916 ArgOffset += 8; 6917 else 6918 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6919 break; 6920 case MVT::v4f32: 6921 case MVT::v4i32: 6922 case MVT::v8i16: 6923 case MVT::v16i8: 6924 if (CFlags.IsVarArg) { 6925 // These go aligned on the stack, or in the corresponding R registers 6926 // when within range. The Darwin PPC ABI doc claims they also go in 6927 // V registers; in fact gcc does this only for arguments that are 6928 // prototyped, not for those that match the ... We do it for all 6929 // arguments, seems to work. 6930 while (ArgOffset % 16 !=0) { 6931 ArgOffset += PtrByteSize; 6932 if (GPR_idx != NumGPRs) 6933 GPR_idx++; 6934 } 6935 // We could elide this store in the case where the object fits 6936 // entirely in R registers. Maybe later. 6937 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6938 DAG.getConstant(ArgOffset, dl, PtrVT)); 6939 SDValue Store = 6940 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6941 MemOpChains.push_back(Store); 6942 if (VR_idx != NumVRs) { 6943 SDValue Load = 6944 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6945 MemOpChains.push_back(Load.getValue(1)); 6946 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6947 } 6948 ArgOffset += 16; 6949 for (unsigned i=0; i<16; i+=PtrByteSize) { 6950 if (GPR_idx == NumGPRs) 6951 break; 6952 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6953 DAG.getConstant(i, dl, PtrVT)); 6954 SDValue Load = 6955 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6956 MemOpChains.push_back(Load.getValue(1)); 6957 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6958 } 6959 break; 6960 } 6961 6962 // Non-varargs Altivec params generally go in registers, but have 6963 // stack space allocated at the end. 6964 if (VR_idx != NumVRs) { 6965 // Doesn't have GPR space allocated. 6966 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6967 } else if (nAltivecParamsAtEnd==0) { 6968 // We are emitting Altivec params in order. 6969 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6970 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6971 TailCallArguments, dl); 6972 ArgOffset += 16; 6973 } 6974 break; 6975 } 6976 } 6977 // If all Altivec parameters fit in registers, as they usually do, 6978 // they get stack space following the non-Altivec parameters. We 6979 // don't track this here because nobody below needs it. 6980 // If there are more Altivec parameters than fit in registers emit 6981 // the stores here. 6982 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6983 unsigned j = 0; 6984 // Offset is aligned; skip 1st 12 params which go in V registers. 6985 ArgOffset = ((ArgOffset+15)/16)*16; 6986 ArgOffset += 12*16; 6987 for (unsigned i = 0; i != NumOps; ++i) { 6988 SDValue Arg = OutVals[i]; 6989 EVT ArgType = Outs[i].VT; 6990 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6991 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6992 if (++j > NumVRs) { 6993 SDValue PtrOff; 6994 // We are emitting Altivec params in order. 6995 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6996 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6997 TailCallArguments, dl); 6998 ArgOffset += 16; 6999 } 7000 } 7001 } 7002 } 7003 7004 if (!MemOpChains.empty()) 7005 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7006 7007 // On Darwin, R12 must contain the address of an indirect callee. This does 7008 // not mean the MTCTR instruction must use R12; it's easier to model this as 7009 // an extra parameter, so do that. 7010 if (CFlags.IsIndirect) { 7011 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7012 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 7013 PPC::R12), Callee)); 7014 } 7015 7016 // Build a sequence of copy-to-reg nodes chained together with token chain 7017 // and flag operands which copy the outgoing args into the appropriate regs. 7018 SDValue InFlag; 7019 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 7020 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 7021 RegsToPass[i].second, InFlag); 7022 InFlag = Chain.getValue(1); 7023 } 7024 7025 if (CFlags.IsTailCall) 7026 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 7027 TailCallArguments); 7028 7029 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7030 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7031 } 7032 7033 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 7034 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 7035 CCState &State) { 7036 7037 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 7038 State.getMachineFunction().getSubtarget()); 7039 const bool IsPPC64 = Subtarget.isPPC64(); 7040 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 7041 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 7042 7043 if (ValVT.isVector() && !State.getMachineFunction() 7044 .getTarget() 7045 .Options.EnableAIXExtendedAltivecABI) 7046 report_fatal_error("the default Altivec AIX ABI is not yet supported"); 7047 7048 if (ValVT == MVT::f128) 7049 report_fatal_error("f128 is unimplemented on AIX."); 7050 7051 if (ArgFlags.isNest()) 7052 report_fatal_error("Nest arguments are unimplemented."); 7053 7054 static const MCPhysReg GPR_32[] = {// 32-bit registers. 7055 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7056 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7057 static const MCPhysReg GPR_64[] = {// 64-bit registers. 7058 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7059 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7060 7061 static const MCPhysReg VR[] = {// Vector registers. 7062 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 7063 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 7064 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 7065 7066 if (ArgFlags.isByVal()) { 7067 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 7068 report_fatal_error("Pass-by-value arguments with alignment greater than " 7069 "register width are not supported."); 7070 7071 const unsigned ByValSize = ArgFlags.getByValSize(); 7072 7073 // An empty aggregate parameter takes up no storage and no registers, 7074 // but needs a MemLoc for a stack slot for the formal arguments side. 7075 if (ByValSize == 0) { 7076 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7077 State.getNextStackOffset(), RegVT, 7078 LocInfo)); 7079 return false; 7080 } 7081 7082 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 7083 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 7084 for (const unsigned E = Offset + StackSize; Offset < E; 7085 Offset += PtrAlign.value()) { 7086 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7087 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7088 else { 7089 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7090 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7091 LocInfo)); 7092 break; 7093 } 7094 } 7095 return false; 7096 } 7097 7098 // Arguments always reserve parameter save area. 7099 switch (ValVT.SimpleTy) { 7100 default: 7101 report_fatal_error("Unhandled value type for argument."); 7102 case MVT::i64: 7103 // i64 arguments should have been split to i32 for PPC32. 7104 assert(IsPPC64 && "PPC32 should have split i64 values."); 7105 LLVM_FALLTHROUGH; 7106 case MVT::i1: 7107 case MVT::i32: { 7108 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 7109 // AIX integer arguments are always passed in register width. 7110 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 7111 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7112 : CCValAssign::LocInfo::ZExt; 7113 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7114 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7115 else 7116 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7117 7118 return false; 7119 } 7120 case MVT::f32: 7121 case MVT::f64: { 7122 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7123 const unsigned StoreSize = LocVT.getStoreSize(); 7124 // Floats are always 4-byte aligned in the PSA on AIX. 7125 // This includes f64 in 64-bit mode for ABI compatibility. 7126 const unsigned Offset = 7127 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 7128 unsigned FReg = State.AllocateReg(FPR); 7129 if (FReg) 7130 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7131 7132 // Reserve and initialize GPRs or initialize the PSA as required. 7133 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 7134 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7135 assert(FReg && "An FPR should be available when a GPR is reserved."); 7136 if (State.isVarArg()) { 7137 // Successfully reserved GPRs are only initialized for vararg calls. 7138 // Custom handling is required for: 7139 // f64 in PPC32 needs to be split into 2 GPRs. 7140 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7141 State.addLoc( 7142 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7143 } 7144 } else { 7145 // If there are insufficient GPRs, the PSA needs to be initialized. 7146 // Initialization occurs even if an FPR was initialized for 7147 // compatibility with the AIX XL compiler. The full memory for the 7148 // argument will be initialized even if a prior word is saved in GPR. 7149 // A custom memLoc is used when the argument also passes in FPR so 7150 // that the callee handling can skip over it easily. 7151 State.addLoc( 7152 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7153 LocInfo) 7154 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7155 break; 7156 } 7157 } 7158 7159 return false; 7160 } 7161 case MVT::v4f32: 7162 case MVT::v4i32: 7163 case MVT::v8i16: 7164 case MVT::v16i8: 7165 case MVT::v2i64: 7166 case MVT::v2f64: 7167 case MVT::v1i128: { 7168 if (State.isVarArg()) 7169 report_fatal_error( 7170 "variadic arguments for vector types are unimplemented for AIX"); 7171 7172 if (unsigned VReg = State.AllocateReg(VR)) 7173 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 7174 else { 7175 report_fatal_error( 7176 "passing vector parameters to the stack is unimplemented for AIX"); 7177 } 7178 return false; 7179 } 7180 } 7181 return true; 7182 } 7183 7184 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7185 bool IsPPC64) { 7186 assert((IsPPC64 || SVT != MVT::i64) && 7187 "i64 should have been split for 32-bit codegen."); 7188 7189 switch (SVT) { 7190 default: 7191 report_fatal_error("Unexpected value type for formal argument"); 7192 case MVT::i1: 7193 case MVT::i32: 7194 case MVT::i64: 7195 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7196 case MVT::f32: 7197 return &PPC::F4RCRegClass; 7198 case MVT::f64: 7199 return &PPC::F8RCRegClass; 7200 case MVT::v4f32: 7201 case MVT::v4i32: 7202 case MVT::v8i16: 7203 case MVT::v16i8: 7204 case MVT::v2i64: 7205 case MVT::v2f64: 7206 case MVT::v1i128: 7207 return &PPC::VRRCRegClass; 7208 } 7209 } 7210 7211 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7212 SelectionDAG &DAG, SDValue ArgValue, 7213 MVT LocVT, const SDLoc &dl) { 7214 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7215 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 7216 7217 if (Flags.isSExt()) 7218 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7219 DAG.getValueType(ValVT)); 7220 else if (Flags.isZExt()) 7221 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7222 DAG.getValueType(ValVT)); 7223 7224 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7225 } 7226 7227 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7228 const unsigned LASize = FL->getLinkageSize(); 7229 7230 if (PPC::GPRCRegClass.contains(Reg)) { 7231 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7232 "Reg must be a valid argument register!"); 7233 return LASize + 4 * (Reg - PPC::R3); 7234 } 7235 7236 if (PPC::G8RCRegClass.contains(Reg)) { 7237 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7238 "Reg must be a valid argument register!"); 7239 return LASize + 8 * (Reg - PPC::X3); 7240 } 7241 7242 llvm_unreachable("Only general purpose registers expected."); 7243 } 7244 7245 // AIX ABI Stack Frame Layout: 7246 // 7247 // Low Memory +--------------------------------------------+ 7248 // SP +---> | Back chain | ---+ 7249 // | +--------------------------------------------+ | 7250 // | | Saved Condition Register | | 7251 // | +--------------------------------------------+ | 7252 // | | Saved Linkage Register | | 7253 // | +--------------------------------------------+ | Linkage Area 7254 // | | Reserved for compilers | | 7255 // | +--------------------------------------------+ | 7256 // | | Reserved for binders | | 7257 // | +--------------------------------------------+ | 7258 // | | Saved TOC pointer | ---+ 7259 // | +--------------------------------------------+ 7260 // | | Parameter save area | 7261 // | +--------------------------------------------+ 7262 // | | Alloca space | 7263 // | +--------------------------------------------+ 7264 // | | Local variable space | 7265 // | +--------------------------------------------+ 7266 // | | Float/int conversion temporary | 7267 // | +--------------------------------------------+ 7268 // | | Save area for AltiVec registers | 7269 // | +--------------------------------------------+ 7270 // | | AltiVec alignment padding | 7271 // | +--------------------------------------------+ 7272 // | | Save area for VRSAVE register | 7273 // | +--------------------------------------------+ 7274 // | | Save area for General Purpose registers | 7275 // | +--------------------------------------------+ 7276 // | | Save area for Floating Point registers | 7277 // | +--------------------------------------------+ 7278 // +---- | Back chain | 7279 // High Memory +--------------------------------------------+ 7280 // 7281 // Specifications: 7282 // AIX 7.2 Assembler Language Reference 7283 // Subroutine linkage convention 7284 7285 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7286 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7287 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7288 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7289 7290 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7291 CallConv == CallingConv::Fast) && 7292 "Unexpected calling convention!"); 7293 7294 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7295 report_fatal_error("Tail call support is unimplemented on AIX."); 7296 7297 if (useSoftFloat()) 7298 report_fatal_error("Soft float support is unimplemented on AIX."); 7299 7300 const PPCSubtarget &Subtarget = 7301 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7302 7303 const bool IsPPC64 = Subtarget.isPPC64(); 7304 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7305 7306 // Assign locations to all of the incoming arguments. 7307 SmallVector<CCValAssign, 16> ArgLocs; 7308 MachineFunction &MF = DAG.getMachineFunction(); 7309 MachineFrameInfo &MFI = MF.getFrameInfo(); 7310 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7311 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7312 7313 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7314 // Reserve space for the linkage area on the stack. 7315 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7316 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7317 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7318 7319 SmallVector<SDValue, 8> MemOps; 7320 7321 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7322 CCValAssign &VA = ArgLocs[I++]; 7323 MVT LocVT = VA.getLocVT(); 7324 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7325 if (VA.isMemLoc() && VA.getValVT().isVector()) 7326 report_fatal_error( 7327 "passing vector parameters to the stack is unimplemented for AIX"); 7328 7329 // For compatibility with the AIX XL compiler, the float args in the 7330 // parameter save area are initialized even if the argument is available 7331 // in register. The caller is required to initialize both the register 7332 // and memory, however, the callee can choose to expect it in either. 7333 // The memloc is dismissed here because the argument is retrieved from 7334 // the register. 7335 if (VA.isMemLoc() && VA.needsCustom()) 7336 continue; 7337 7338 if (VA.isRegLoc()) { 7339 if (VA.getValVT().isScalarInteger()) 7340 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7341 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) 7342 FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32 7343 ? PPCFunctionInfo::ShortFloatPoint 7344 : PPCFunctionInfo::LongFloatPoint); 7345 } 7346 7347 if (Flags.isByVal() && VA.isMemLoc()) { 7348 const unsigned Size = 7349 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7350 PtrByteSize); 7351 const int FI = MF.getFrameInfo().CreateFixedObject( 7352 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7353 /* IsAliased */ true); 7354 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7355 InVals.push_back(FIN); 7356 7357 continue; 7358 } 7359 7360 if (Flags.isByVal()) { 7361 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7362 7363 const MCPhysReg ArgReg = VA.getLocReg(); 7364 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7365 7366 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7367 report_fatal_error("Over aligned byvals not supported yet."); 7368 7369 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7370 const int FI = MF.getFrameInfo().CreateFixedObject( 7371 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7372 /* IsAliased */ true); 7373 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7374 InVals.push_back(FIN); 7375 7376 // Add live ins for all the RegLocs for the same ByVal. 7377 const TargetRegisterClass *RegClass = 7378 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7379 7380 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7381 unsigned Offset) { 7382 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7383 // Since the callers side has left justified the aggregate in the 7384 // register, we can simply store the entire register into the stack 7385 // slot. 7386 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7387 // The store to the fixedstack object is needed becuase accessing a 7388 // field of the ByVal will use a gep and load. Ideally we will optimize 7389 // to extracting the value from the register directly, and elide the 7390 // stores when the arguments address is not taken, but that will need to 7391 // be future work. 7392 SDValue Store = DAG.getStore( 7393 CopyFrom.getValue(1), dl, CopyFrom, 7394 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7395 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7396 7397 MemOps.push_back(Store); 7398 }; 7399 7400 unsigned Offset = 0; 7401 HandleRegLoc(VA.getLocReg(), Offset); 7402 Offset += PtrByteSize; 7403 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7404 Offset += PtrByteSize) { 7405 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7406 "RegLocs should be for ByVal argument."); 7407 7408 const CCValAssign RL = ArgLocs[I++]; 7409 HandleRegLoc(RL.getLocReg(), Offset); 7410 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7411 } 7412 7413 if (Offset != StackSize) { 7414 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7415 "Expected MemLoc for remaining bytes."); 7416 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7417 // Consume the MemLoc.The InVal has already been emitted, so nothing 7418 // more needs to be done. 7419 ++I; 7420 } 7421 7422 continue; 7423 } 7424 7425 EVT ValVT = VA.getValVT(); 7426 if (VA.isRegLoc() && !VA.needsCustom()) { 7427 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7428 unsigned VReg = 7429 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7430 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7431 if (ValVT.isScalarInteger() && 7432 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7433 ArgValue = 7434 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7435 } 7436 InVals.push_back(ArgValue); 7437 continue; 7438 } 7439 if (VA.isMemLoc()) { 7440 const unsigned LocSize = LocVT.getStoreSize(); 7441 const unsigned ValSize = ValVT.getStoreSize(); 7442 assert((ValSize <= LocSize) && 7443 "Object size is larger than size of MemLoc"); 7444 int CurArgOffset = VA.getLocMemOffset(); 7445 // Objects are right-justified because AIX is big-endian. 7446 if (LocSize > ValSize) 7447 CurArgOffset += LocSize - ValSize; 7448 // Potential tail calls could cause overwriting of argument stack slots. 7449 const bool IsImmutable = 7450 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7451 (CallConv == CallingConv::Fast)); 7452 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7453 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7454 SDValue ArgValue = 7455 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7456 InVals.push_back(ArgValue); 7457 continue; 7458 } 7459 } 7460 7461 // On AIX a minimum of 8 words is saved to the parameter save area. 7462 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7463 // Area that is at least reserved in the caller of this function. 7464 unsigned CallerReservedArea = 7465 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7466 7467 // Set the size that is at least reserved in caller of this function. Tail 7468 // call optimized function's reserved stack space needs to be aligned so 7469 // that taking the difference between two stack areas will result in an 7470 // aligned stack. 7471 CallerReservedArea = 7472 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7473 FuncInfo->setMinReservedArea(CallerReservedArea); 7474 7475 if (isVarArg) { 7476 FuncInfo->setVarArgsFrameIndex( 7477 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7478 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7479 7480 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7481 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7482 7483 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7484 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7485 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7486 7487 // The fixed integer arguments of a variadic function are stored to the 7488 // VarArgsFrameIndex on the stack so that they may be loaded by 7489 // dereferencing the result of va_next. 7490 for (unsigned GPRIndex = 7491 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7492 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7493 7494 const unsigned VReg = 7495 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7496 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7497 7498 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7499 SDValue Store = 7500 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7501 MemOps.push_back(Store); 7502 // Increment the address for the next argument to store. 7503 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7504 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7505 } 7506 } 7507 7508 if (!MemOps.empty()) 7509 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7510 7511 return Chain; 7512 } 7513 7514 SDValue PPCTargetLowering::LowerCall_AIX( 7515 SDValue Chain, SDValue Callee, CallFlags CFlags, 7516 const SmallVectorImpl<ISD::OutputArg> &Outs, 7517 const SmallVectorImpl<SDValue> &OutVals, 7518 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7519 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7520 const CallBase *CB) const { 7521 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7522 // AIX ABI stack frame layout. 7523 7524 assert((CFlags.CallConv == CallingConv::C || 7525 CFlags.CallConv == CallingConv::Cold || 7526 CFlags.CallConv == CallingConv::Fast) && 7527 "Unexpected calling convention!"); 7528 7529 if (CFlags.IsPatchPoint) 7530 report_fatal_error("This call type is unimplemented on AIX."); 7531 7532 const PPCSubtarget& Subtarget = 7533 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7534 7535 MachineFunction &MF = DAG.getMachineFunction(); 7536 SmallVector<CCValAssign, 16> ArgLocs; 7537 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7538 *DAG.getContext()); 7539 7540 // Reserve space for the linkage save area (LSA) on the stack. 7541 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7542 // [SP][CR][LR][2 x reserved][TOC]. 7543 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7544 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7545 const bool IsPPC64 = Subtarget.isPPC64(); 7546 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7547 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7548 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7549 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7550 7551 // The prolog code of the callee may store up to 8 GPR argument registers to 7552 // the stack, allowing va_start to index over them in memory if the callee 7553 // is variadic. 7554 // Because we cannot tell if this is needed on the caller side, we have to 7555 // conservatively assume that it is needed. As such, make sure we have at 7556 // least enough stack space for the caller to store the 8 GPRs. 7557 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7558 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7559 CCInfo.getNextStackOffset()); 7560 7561 // Adjust the stack pointer for the new arguments... 7562 // These operations are automatically eliminated by the prolog/epilog pass. 7563 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7564 SDValue CallSeqStart = Chain; 7565 7566 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7567 SmallVector<SDValue, 8> MemOpChains; 7568 7569 // Set up a copy of the stack pointer for loading and storing any 7570 // arguments that may not fit in the registers available for argument 7571 // passing. 7572 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7573 : DAG.getRegister(PPC::R1, MVT::i32); 7574 7575 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7576 const unsigned ValNo = ArgLocs[I].getValNo(); 7577 SDValue Arg = OutVals[ValNo]; 7578 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7579 7580 if (Flags.isByVal()) { 7581 const unsigned ByValSize = Flags.getByValSize(); 7582 7583 // Nothing to do for zero-sized ByVals on the caller side. 7584 if (!ByValSize) { 7585 ++I; 7586 continue; 7587 } 7588 7589 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7590 return DAG.getExtLoad( 7591 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7592 (LoadOffset != 0) 7593 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7594 : Arg, 7595 MachinePointerInfo(), VT); 7596 }; 7597 7598 unsigned LoadOffset = 0; 7599 7600 // Initialize registers, which are fully occupied by the by-val argument. 7601 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7602 SDValue Load = GetLoad(PtrVT, LoadOffset); 7603 MemOpChains.push_back(Load.getValue(1)); 7604 LoadOffset += PtrByteSize; 7605 const CCValAssign &ByValVA = ArgLocs[I++]; 7606 assert(ByValVA.getValNo() == ValNo && 7607 "Unexpected location for pass-by-value argument."); 7608 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7609 } 7610 7611 if (LoadOffset == ByValSize) 7612 continue; 7613 7614 // There must be one more loc to handle the remainder. 7615 assert(ArgLocs[I].getValNo() == ValNo && 7616 "Expected additional location for by-value argument."); 7617 7618 if (ArgLocs[I].isMemLoc()) { 7619 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7620 const CCValAssign &ByValVA = ArgLocs[I++]; 7621 ISD::ArgFlagsTy MemcpyFlags = Flags; 7622 // Only memcpy the bytes that don't pass in register. 7623 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7624 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7625 (LoadOffset != 0) 7626 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7627 : Arg, 7628 DAG.getObjectPtrOffset(dl, StackPtr, 7629 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7630 CallSeqStart, MemcpyFlags, DAG, dl); 7631 continue; 7632 } 7633 7634 // Initialize the final register residue. 7635 // Any residue that occupies the final by-val arg register must be 7636 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7637 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7638 // 2 and 1 byte loads. 7639 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7640 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7641 "Unexpected register residue for by-value argument."); 7642 SDValue ResidueVal; 7643 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7644 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7645 const MVT VT = 7646 N == 1 ? MVT::i8 7647 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7648 SDValue Load = GetLoad(VT, LoadOffset); 7649 MemOpChains.push_back(Load.getValue(1)); 7650 LoadOffset += N; 7651 Bytes += N; 7652 7653 // By-val arguments are passed left-justfied in register. 7654 // Every load here needs to be shifted, otherwise a full register load 7655 // should have been used. 7656 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7657 "Unexpected load emitted during handling of pass-by-value " 7658 "argument."); 7659 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7660 EVT ShiftAmountTy = 7661 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7662 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7663 SDValue ShiftedLoad = 7664 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7665 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7666 ShiftedLoad) 7667 : ShiftedLoad; 7668 } 7669 7670 const CCValAssign &ByValVA = ArgLocs[I++]; 7671 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7672 continue; 7673 } 7674 7675 CCValAssign &VA = ArgLocs[I++]; 7676 const MVT LocVT = VA.getLocVT(); 7677 const MVT ValVT = VA.getValVT(); 7678 7679 if (VA.isMemLoc() && VA.getValVT().isVector()) 7680 report_fatal_error( 7681 "passing vector parameters to the stack is unimplemented for AIX"); 7682 7683 switch (VA.getLocInfo()) { 7684 default: 7685 report_fatal_error("Unexpected argument extension type."); 7686 case CCValAssign::Full: 7687 break; 7688 case CCValAssign::ZExt: 7689 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7690 break; 7691 case CCValAssign::SExt: 7692 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7693 break; 7694 } 7695 7696 if (VA.isRegLoc() && !VA.needsCustom()) { 7697 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7698 continue; 7699 } 7700 7701 if (VA.isMemLoc()) { 7702 SDValue PtrOff = 7703 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7704 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7705 MemOpChains.push_back( 7706 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7707 7708 continue; 7709 } 7710 7711 // Custom handling is used for GPR initializations for vararg float 7712 // arguments. 7713 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7714 ValVT.isFloatingPoint() && LocVT.isInteger() && 7715 "Unexpected register handling for calling convention."); 7716 7717 SDValue ArgAsInt = 7718 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7719 7720 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7721 // f32 in 32-bit GPR 7722 // f64 in 64-bit GPR 7723 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7724 else if (Arg.getValueType().getFixedSizeInBits() < 7725 LocVT.getFixedSizeInBits()) 7726 // f32 in 64-bit GPR. 7727 RegsToPass.push_back(std::make_pair( 7728 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7729 else { 7730 // f64 in two 32-bit GPRs 7731 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7732 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7733 "Unexpected custom register for argument!"); 7734 CCValAssign &GPR1 = VA; 7735 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7736 DAG.getConstant(32, dl, MVT::i8)); 7737 RegsToPass.push_back(std::make_pair( 7738 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7739 7740 if (I != E) { 7741 // If only 1 GPR was available, there will only be one custom GPR and 7742 // the argument will also pass in memory. 7743 CCValAssign &PeekArg = ArgLocs[I]; 7744 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7745 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7746 CCValAssign &GPR2 = ArgLocs[I++]; 7747 RegsToPass.push_back(std::make_pair( 7748 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7749 } 7750 } 7751 } 7752 } 7753 7754 if (!MemOpChains.empty()) 7755 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7756 7757 // For indirect calls, we need to save the TOC base to the stack for 7758 // restoration after the call. 7759 if (CFlags.IsIndirect) { 7760 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7761 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7762 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7763 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7764 const unsigned TOCSaveOffset = 7765 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7766 7767 setUsesTOCBasePtr(DAG); 7768 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7769 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7770 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7771 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7772 Chain = DAG.getStore( 7773 Val.getValue(1), dl, Val, AddPtr, 7774 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7775 } 7776 7777 // Build a sequence of copy-to-reg nodes chained together with token chain 7778 // and flag operands which copy the outgoing args into the appropriate regs. 7779 SDValue InFlag; 7780 for (auto Reg : RegsToPass) { 7781 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7782 InFlag = Chain.getValue(1); 7783 } 7784 7785 const int SPDiff = 0; 7786 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7787 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7788 } 7789 7790 bool 7791 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7792 MachineFunction &MF, bool isVarArg, 7793 const SmallVectorImpl<ISD::OutputArg> &Outs, 7794 LLVMContext &Context) const { 7795 SmallVector<CCValAssign, 16> RVLocs; 7796 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7797 return CCInfo.CheckReturn( 7798 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7799 ? RetCC_PPC_Cold 7800 : RetCC_PPC); 7801 } 7802 7803 SDValue 7804 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7805 bool isVarArg, 7806 const SmallVectorImpl<ISD::OutputArg> &Outs, 7807 const SmallVectorImpl<SDValue> &OutVals, 7808 const SDLoc &dl, SelectionDAG &DAG) const { 7809 SmallVector<CCValAssign, 16> RVLocs; 7810 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7811 *DAG.getContext()); 7812 CCInfo.AnalyzeReturn(Outs, 7813 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7814 ? RetCC_PPC_Cold 7815 : RetCC_PPC); 7816 7817 SDValue Flag; 7818 SmallVector<SDValue, 4> RetOps(1, Chain); 7819 7820 // Copy the result values into the output registers. 7821 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7822 CCValAssign &VA = RVLocs[i]; 7823 assert(VA.isRegLoc() && "Can only return in registers!"); 7824 7825 SDValue Arg = OutVals[RealResIdx]; 7826 7827 switch (VA.getLocInfo()) { 7828 default: llvm_unreachable("Unknown loc info!"); 7829 case CCValAssign::Full: break; 7830 case CCValAssign::AExt: 7831 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7832 break; 7833 case CCValAssign::ZExt: 7834 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7835 break; 7836 case CCValAssign::SExt: 7837 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7838 break; 7839 } 7840 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7841 bool isLittleEndian = Subtarget.isLittleEndian(); 7842 // Legalize ret f64 -> ret 2 x i32. 7843 SDValue SVal = 7844 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7845 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7846 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7847 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7848 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7849 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7850 Flag = Chain.getValue(1); 7851 VA = RVLocs[++i]; // skip ahead to next loc 7852 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7853 } else 7854 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7855 Flag = Chain.getValue(1); 7856 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7857 } 7858 7859 RetOps[0] = Chain; // Update chain. 7860 7861 // Add the flag if we have it. 7862 if (Flag.getNode()) 7863 RetOps.push_back(Flag); 7864 7865 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7866 } 7867 7868 SDValue 7869 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7870 SelectionDAG &DAG) const { 7871 SDLoc dl(Op); 7872 7873 // Get the correct type for integers. 7874 EVT IntVT = Op.getValueType(); 7875 7876 // Get the inputs. 7877 SDValue Chain = Op.getOperand(0); 7878 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7879 // Build a DYNAREAOFFSET node. 7880 SDValue Ops[2] = {Chain, FPSIdx}; 7881 SDVTList VTs = DAG.getVTList(IntVT); 7882 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7883 } 7884 7885 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7886 SelectionDAG &DAG) const { 7887 // When we pop the dynamic allocation we need to restore the SP link. 7888 SDLoc dl(Op); 7889 7890 // Get the correct type for pointers. 7891 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7892 7893 // Construct the stack pointer operand. 7894 bool isPPC64 = Subtarget.isPPC64(); 7895 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7896 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7897 7898 // Get the operands for the STACKRESTORE. 7899 SDValue Chain = Op.getOperand(0); 7900 SDValue SaveSP = Op.getOperand(1); 7901 7902 // Load the old link SP. 7903 SDValue LoadLinkSP = 7904 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7905 7906 // Restore the stack pointer. 7907 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7908 7909 // Store the old link SP. 7910 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7911 } 7912 7913 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7914 MachineFunction &MF = DAG.getMachineFunction(); 7915 bool isPPC64 = Subtarget.isPPC64(); 7916 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7917 7918 // Get current frame pointer save index. The users of this index will be 7919 // primarily DYNALLOC instructions. 7920 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7921 int RASI = FI->getReturnAddrSaveIndex(); 7922 7923 // If the frame pointer save index hasn't been defined yet. 7924 if (!RASI) { 7925 // Find out what the fix offset of the frame pointer save area. 7926 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7927 // Allocate the frame index for frame pointer save area. 7928 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7929 // Save the result. 7930 FI->setReturnAddrSaveIndex(RASI); 7931 } 7932 return DAG.getFrameIndex(RASI, PtrVT); 7933 } 7934 7935 SDValue 7936 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7937 MachineFunction &MF = DAG.getMachineFunction(); 7938 bool isPPC64 = Subtarget.isPPC64(); 7939 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7940 7941 // Get current frame pointer save index. The users of this index will be 7942 // primarily DYNALLOC instructions. 7943 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7944 int FPSI = FI->getFramePointerSaveIndex(); 7945 7946 // If the frame pointer save index hasn't been defined yet. 7947 if (!FPSI) { 7948 // Find out what the fix offset of the frame pointer save area. 7949 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7950 // Allocate the frame index for frame pointer save area. 7951 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7952 // Save the result. 7953 FI->setFramePointerSaveIndex(FPSI); 7954 } 7955 return DAG.getFrameIndex(FPSI, PtrVT); 7956 } 7957 7958 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7959 SelectionDAG &DAG) const { 7960 MachineFunction &MF = DAG.getMachineFunction(); 7961 // Get the inputs. 7962 SDValue Chain = Op.getOperand(0); 7963 SDValue Size = Op.getOperand(1); 7964 SDLoc dl(Op); 7965 7966 // Get the correct type for pointers. 7967 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7968 // Negate the size. 7969 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7970 DAG.getConstant(0, dl, PtrVT), Size); 7971 // Construct a node for the frame pointer save index. 7972 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7973 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7974 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7975 if (hasInlineStackProbe(MF)) 7976 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7977 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7978 } 7979 7980 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7981 SelectionDAG &DAG) const { 7982 MachineFunction &MF = DAG.getMachineFunction(); 7983 7984 bool isPPC64 = Subtarget.isPPC64(); 7985 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7986 7987 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7988 return DAG.getFrameIndex(FI, PtrVT); 7989 } 7990 7991 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7992 SelectionDAG &DAG) const { 7993 SDLoc DL(Op); 7994 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7995 DAG.getVTList(MVT::i32, MVT::Other), 7996 Op.getOperand(0), Op.getOperand(1)); 7997 } 7998 7999 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 8000 SelectionDAG &DAG) const { 8001 SDLoc DL(Op); 8002 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 8003 Op.getOperand(0), Op.getOperand(1)); 8004 } 8005 8006 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8007 if (Op.getValueType().isVector()) 8008 return LowerVectorLoad(Op, DAG); 8009 8010 assert(Op.getValueType() == MVT::i1 && 8011 "Custom lowering only for i1 loads"); 8012 8013 // First, load 8 bits into 32 bits, then truncate to 1 bit. 8014 8015 SDLoc dl(Op); 8016 LoadSDNode *LD = cast<LoadSDNode>(Op); 8017 8018 SDValue Chain = LD->getChain(); 8019 SDValue BasePtr = LD->getBasePtr(); 8020 MachineMemOperand *MMO = LD->getMemOperand(); 8021 8022 SDValue NewLD = 8023 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 8024 BasePtr, MVT::i8, MMO); 8025 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 8026 8027 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 8028 return DAG.getMergeValues(Ops, dl); 8029 } 8030 8031 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8032 if (Op.getOperand(1).getValueType().isVector()) 8033 return LowerVectorStore(Op, DAG); 8034 8035 assert(Op.getOperand(1).getValueType() == MVT::i1 && 8036 "Custom lowering only for i1 stores"); 8037 8038 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 8039 8040 SDLoc dl(Op); 8041 StoreSDNode *ST = cast<StoreSDNode>(Op); 8042 8043 SDValue Chain = ST->getChain(); 8044 SDValue BasePtr = ST->getBasePtr(); 8045 SDValue Value = ST->getValue(); 8046 MachineMemOperand *MMO = ST->getMemOperand(); 8047 8048 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 8049 Value); 8050 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 8051 } 8052 8053 // FIXME: Remove this once the ANDI glue bug is fixed: 8054 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 8055 assert(Op.getValueType() == MVT::i1 && 8056 "Custom lowering only for i1 results"); 8057 8058 SDLoc DL(Op); 8059 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 8060 } 8061 8062 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 8063 SelectionDAG &DAG) const { 8064 8065 // Implements a vector truncate that fits in a vector register as a shuffle. 8066 // We want to legalize vector truncates down to where the source fits in 8067 // a vector register (and target is therefore smaller than vector register 8068 // size). At that point legalization will try to custom lower the sub-legal 8069 // result and get here - where we can contain the truncate as a single target 8070 // operation. 8071 8072 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 8073 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 8074 // 8075 // We will implement it for big-endian ordering as this (where x denotes 8076 // undefined): 8077 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 8078 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 8079 // 8080 // The same operation in little-endian ordering will be: 8081 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 8082 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 8083 8084 EVT TrgVT = Op.getValueType(); 8085 assert(TrgVT.isVector() && "Vector type expected."); 8086 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 8087 EVT EltVT = TrgVT.getVectorElementType(); 8088 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 8089 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 8090 !isPowerOf2_32(EltVT.getSizeInBits())) 8091 return SDValue(); 8092 8093 SDValue N1 = Op.getOperand(0); 8094 EVT SrcVT = N1.getValueType(); 8095 unsigned SrcSize = SrcVT.getSizeInBits(); 8096 if (SrcSize > 256 || 8097 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 8098 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 8099 return SDValue(); 8100 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 8101 return SDValue(); 8102 8103 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8104 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8105 8106 SDLoc DL(Op); 8107 SDValue Op1, Op2; 8108 if (SrcSize == 256) { 8109 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 8110 EVT SplitVT = 8111 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 8112 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 8113 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 8114 DAG.getConstant(0, DL, VecIdxTy)); 8115 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 8116 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 8117 } 8118 else { 8119 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 8120 Op2 = DAG.getUNDEF(WideVT); 8121 } 8122 8123 // First list the elements we want to keep. 8124 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 8125 SmallVector<int, 16> ShuffV; 8126 if (Subtarget.isLittleEndian()) 8127 for (unsigned i = 0; i < TrgNumElts; ++i) 8128 ShuffV.push_back(i * SizeMult); 8129 else 8130 for (unsigned i = 1; i <= TrgNumElts; ++i) 8131 ShuffV.push_back(i * SizeMult - 1); 8132 8133 // Populate the remaining elements with undefs. 8134 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 8135 // ShuffV.push_back(i + WideNumElts); 8136 ShuffV.push_back(WideNumElts + 1); 8137 8138 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 8139 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 8140 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 8141 } 8142 8143 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 8144 /// possible. 8145 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 8146 // Not FP, or using SPE? Not a fsel. 8147 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 8148 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 8149 return Op; 8150 8151 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 8152 8153 EVT ResVT = Op.getValueType(); 8154 EVT CmpVT = Op.getOperand(0).getValueType(); 8155 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8156 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 8157 SDLoc dl(Op); 8158 SDNodeFlags Flags = Op.getNode()->getFlags(); 8159 8160 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 8161 // presence of infinities. 8162 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 8163 switch (CC) { 8164 default: 8165 break; 8166 case ISD::SETOGT: 8167 case ISD::SETGT: 8168 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8169 case ISD::SETOLT: 8170 case ISD::SETLT: 8171 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8172 } 8173 } 8174 8175 // We might be able to do better than this under some circumstances, but in 8176 // general, fsel-based lowering of select is a finite-math-only optimization. 8177 // For more information, see section F.3 of the 2.06 ISA specification. 8178 // With ISA 3.0 8179 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8180 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8181 return Op; 8182 8183 // If the RHS of the comparison is a 0.0, we don't need to do the 8184 // subtraction at all. 8185 SDValue Sel1; 8186 if (isFloatingPointZero(RHS)) 8187 switch (CC) { 8188 default: break; // SETUO etc aren't handled by fsel. 8189 case ISD::SETNE: 8190 std::swap(TV, FV); 8191 LLVM_FALLTHROUGH; 8192 case ISD::SETEQ: 8193 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8194 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8195 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8196 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8197 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8198 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8199 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8200 case ISD::SETULT: 8201 case ISD::SETLT: 8202 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8203 LLVM_FALLTHROUGH; 8204 case ISD::SETOGE: 8205 case ISD::SETGE: 8206 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8207 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8208 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8209 case ISD::SETUGT: 8210 case ISD::SETGT: 8211 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8212 LLVM_FALLTHROUGH; 8213 case ISD::SETOLE: 8214 case ISD::SETLE: 8215 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8216 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8217 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8218 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8219 } 8220 8221 SDValue Cmp; 8222 switch (CC) { 8223 default: break; // SETUO etc aren't handled by fsel. 8224 case ISD::SETNE: 8225 std::swap(TV, FV); 8226 LLVM_FALLTHROUGH; 8227 case ISD::SETEQ: 8228 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8229 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8230 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8231 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8232 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8233 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8234 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8235 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8236 case ISD::SETULT: 8237 case ISD::SETLT: 8238 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8239 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8240 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8241 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8242 case ISD::SETOGE: 8243 case ISD::SETGE: 8244 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8245 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8246 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8247 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8248 case ISD::SETUGT: 8249 case ISD::SETGT: 8250 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8251 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8252 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8253 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8254 case ISD::SETOLE: 8255 case ISD::SETLE: 8256 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8257 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8258 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8259 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8260 } 8261 return Op; 8262 } 8263 8264 static unsigned getPPCStrictOpcode(unsigned Opc) { 8265 switch (Opc) { 8266 default: 8267 llvm_unreachable("No strict version of this opcode!"); 8268 case PPCISD::FCTIDZ: 8269 return PPCISD::STRICT_FCTIDZ; 8270 case PPCISD::FCTIWZ: 8271 return PPCISD::STRICT_FCTIWZ; 8272 case PPCISD::FCTIDUZ: 8273 return PPCISD::STRICT_FCTIDUZ; 8274 case PPCISD::FCTIWUZ: 8275 return PPCISD::STRICT_FCTIWUZ; 8276 case PPCISD::FCFID: 8277 return PPCISD::STRICT_FCFID; 8278 case PPCISD::FCFIDU: 8279 return PPCISD::STRICT_FCFIDU; 8280 case PPCISD::FCFIDS: 8281 return PPCISD::STRICT_FCFIDS; 8282 case PPCISD::FCFIDUS: 8283 return PPCISD::STRICT_FCFIDUS; 8284 } 8285 } 8286 8287 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8288 const PPCSubtarget &Subtarget) { 8289 SDLoc dl(Op); 8290 bool IsStrict = Op->isStrictFPOpcode(); 8291 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8292 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8293 8294 // TODO: Any other flags to propagate? 8295 SDNodeFlags Flags; 8296 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8297 8298 // For strict nodes, source is the second operand. 8299 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8300 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8301 assert(Src.getValueType().isFloatingPoint()); 8302 if (Src.getValueType() == MVT::f32) { 8303 if (IsStrict) { 8304 Src = 8305 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8306 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8307 Chain = Src.getValue(1); 8308 } else 8309 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8310 } 8311 SDValue Conv; 8312 unsigned Opc = ISD::DELETED_NODE; 8313 switch (Op.getSimpleValueType().SimpleTy) { 8314 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8315 case MVT::i32: 8316 Opc = IsSigned ? PPCISD::FCTIWZ 8317 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8318 break; 8319 case MVT::i64: 8320 assert((IsSigned || Subtarget.hasFPCVT()) && 8321 "i64 FP_TO_UINT is supported only with FPCVT"); 8322 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8323 } 8324 if (IsStrict) { 8325 Opc = getPPCStrictOpcode(Opc); 8326 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8327 {Chain, Src}, Flags); 8328 } else { 8329 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8330 } 8331 return Conv; 8332 } 8333 8334 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8335 SelectionDAG &DAG, 8336 const SDLoc &dl) const { 8337 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8338 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8339 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8340 bool IsStrict = Op->isStrictFPOpcode(); 8341 8342 // Convert the FP value to an int value through memory. 8343 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8344 (IsSigned || Subtarget.hasFPCVT()); 8345 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8346 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8347 MachinePointerInfo MPI = 8348 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8349 8350 // Emit a store to the stack slot. 8351 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8352 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8353 if (i32Stack) { 8354 MachineFunction &MF = DAG.getMachineFunction(); 8355 Alignment = Align(4); 8356 MachineMemOperand *MMO = 8357 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8358 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8359 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8360 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8361 } else 8362 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8363 8364 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8365 // add in a bias on big endian. 8366 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8367 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8368 DAG.getConstant(4, dl, FIPtr.getValueType())); 8369 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8370 } 8371 8372 RLI.Chain = Chain; 8373 RLI.Ptr = FIPtr; 8374 RLI.MPI = MPI; 8375 RLI.Alignment = Alignment; 8376 } 8377 8378 /// Custom lowers floating point to integer conversions to use 8379 /// the direct move instructions available in ISA 2.07 to avoid the 8380 /// need for load/store combinations. 8381 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8382 SelectionDAG &DAG, 8383 const SDLoc &dl) const { 8384 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8385 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8386 if (Op->isStrictFPOpcode()) 8387 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8388 else 8389 return Mov; 8390 } 8391 8392 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8393 const SDLoc &dl) const { 8394 bool IsStrict = Op->isStrictFPOpcode(); 8395 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8396 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8397 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8398 EVT SrcVT = Src.getValueType(); 8399 EVT DstVT = Op.getValueType(); 8400 8401 // FP to INT conversions are legal for f128. 8402 if (SrcVT == MVT::f128) 8403 return Subtarget.hasP9Vector() ? Op : SDValue(); 8404 8405 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8406 // PPC (the libcall is not available). 8407 if (SrcVT == MVT::ppcf128) { 8408 if (DstVT == MVT::i32) { 8409 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8410 // set other fast-math flags to FP operations in both strict and 8411 // non-strict cases. (FP_TO_SINT, FSUB) 8412 SDNodeFlags Flags; 8413 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8414 8415 if (IsSigned) { 8416 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8417 DAG.getIntPtrConstant(0, dl)); 8418 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8419 DAG.getIntPtrConstant(1, dl)); 8420 8421 // Add the two halves of the long double in round-to-zero mode, and use 8422 // a smaller FP_TO_SINT. 8423 if (IsStrict) { 8424 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8425 DAG.getVTList(MVT::f64, MVT::Other), 8426 {Op.getOperand(0), Lo, Hi}, Flags); 8427 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8428 DAG.getVTList(MVT::i32, MVT::Other), 8429 {Res.getValue(1), Res}, Flags); 8430 } else { 8431 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8432 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8433 } 8434 } else { 8435 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8436 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8437 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8438 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8439 if (IsStrict) { 8440 // Sel = Src < 0x80000000 8441 // FltOfs = select Sel, 0.0, 0x80000000 8442 // IntOfs = select Sel, 0, 0x80000000 8443 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8444 SDValue Chain = Op.getOperand(0); 8445 EVT SetCCVT = 8446 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8447 EVT DstSetCCVT = 8448 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8449 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8450 Chain, true); 8451 Chain = Sel.getValue(1); 8452 8453 SDValue FltOfs = DAG.getSelect( 8454 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8455 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8456 8457 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8458 DAG.getVTList(SrcVT, MVT::Other), 8459 {Chain, Src, FltOfs}, Flags); 8460 Chain = Val.getValue(1); 8461 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8462 DAG.getVTList(DstVT, MVT::Other), 8463 {Chain, Val}, Flags); 8464 Chain = SInt.getValue(1); 8465 SDValue IntOfs = DAG.getSelect( 8466 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8467 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8468 return DAG.getMergeValues({Result, Chain}, dl); 8469 } else { 8470 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8471 // FIXME: generated code sucks. 8472 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8473 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8474 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8475 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8476 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8477 } 8478 } 8479 } 8480 8481 return SDValue(); 8482 } 8483 8484 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8485 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8486 8487 ReuseLoadInfo RLI; 8488 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8489 8490 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8491 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8492 } 8493 8494 // We're trying to insert a regular store, S, and then a load, L. If the 8495 // incoming value, O, is a load, we might just be able to have our load use the 8496 // address used by O. However, we don't know if anything else will store to 8497 // that address before we can load from it. To prevent this situation, we need 8498 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8499 // the same chain operand as O, we create a token factor from the chain results 8500 // of O and L, and we replace all uses of O's chain result with that token 8501 // factor (see spliceIntoChain below for this last part). 8502 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8503 ReuseLoadInfo &RLI, 8504 SelectionDAG &DAG, 8505 ISD::LoadExtType ET) const { 8506 // Conservatively skip reusing for constrained FP nodes. 8507 if (Op->isStrictFPOpcode()) 8508 return false; 8509 8510 SDLoc dl(Op); 8511 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8512 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8513 if (ET == ISD::NON_EXTLOAD && 8514 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8515 isOperationLegalOrCustom(Op.getOpcode(), 8516 Op.getOperand(0).getValueType())) { 8517 8518 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8519 return true; 8520 } 8521 8522 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8523 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8524 LD->isNonTemporal()) 8525 return false; 8526 if (LD->getMemoryVT() != MemVT) 8527 return false; 8528 8529 // If the result of the load is an illegal type, then we can't build a 8530 // valid chain for reuse since the legalised loads and token factor node that 8531 // ties the legalised loads together uses a different output chain then the 8532 // illegal load. 8533 if (!isTypeLegal(LD->getValueType(0))) 8534 return false; 8535 8536 RLI.Ptr = LD->getBasePtr(); 8537 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8538 assert(LD->getAddressingMode() == ISD::PRE_INC && 8539 "Non-pre-inc AM on PPC?"); 8540 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8541 LD->getOffset()); 8542 } 8543 8544 RLI.Chain = LD->getChain(); 8545 RLI.MPI = LD->getPointerInfo(); 8546 RLI.IsDereferenceable = LD->isDereferenceable(); 8547 RLI.IsInvariant = LD->isInvariant(); 8548 RLI.Alignment = LD->getAlign(); 8549 RLI.AAInfo = LD->getAAInfo(); 8550 RLI.Ranges = LD->getRanges(); 8551 8552 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8553 return true; 8554 } 8555 8556 // Given the head of the old chain, ResChain, insert a token factor containing 8557 // it and NewResChain, and make users of ResChain now be users of that token 8558 // factor. 8559 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8560 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8561 SDValue NewResChain, 8562 SelectionDAG &DAG) const { 8563 if (!ResChain) 8564 return; 8565 8566 SDLoc dl(NewResChain); 8567 8568 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8569 NewResChain, DAG.getUNDEF(MVT::Other)); 8570 assert(TF.getNode() != NewResChain.getNode() && 8571 "A new TF really is required here"); 8572 8573 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8574 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8575 } 8576 8577 /// Analyze profitability of direct move 8578 /// prefer float load to int load plus direct move 8579 /// when there is no integer use of int load 8580 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8581 SDNode *Origin = Op.getOperand(0).getNode(); 8582 if (Origin->getOpcode() != ISD::LOAD) 8583 return true; 8584 8585 // If there is no LXSIBZX/LXSIHZX, like Power8, 8586 // prefer direct move if the memory size is 1 or 2 bytes. 8587 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8588 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8589 return true; 8590 8591 for (SDNode::use_iterator UI = Origin->use_begin(), 8592 UE = Origin->use_end(); 8593 UI != UE; ++UI) { 8594 8595 // Only look at the users of the loaded value. 8596 if (UI.getUse().get().getResNo() != 0) 8597 continue; 8598 8599 if (UI->getOpcode() != ISD::SINT_TO_FP && 8600 UI->getOpcode() != ISD::UINT_TO_FP && 8601 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8602 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8603 return true; 8604 } 8605 8606 return false; 8607 } 8608 8609 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8610 const PPCSubtarget &Subtarget, 8611 SDValue Chain = SDValue()) { 8612 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8613 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8614 SDLoc dl(Op); 8615 8616 // TODO: Any other flags to propagate? 8617 SDNodeFlags Flags; 8618 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8619 8620 // If we have FCFIDS, then use it when converting to single-precision. 8621 // Otherwise, convert to double-precision and then round. 8622 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8623 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8624 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8625 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8626 if (Op->isStrictFPOpcode()) { 8627 if (!Chain) 8628 Chain = Op.getOperand(0); 8629 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8630 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8631 } else 8632 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8633 } 8634 8635 /// Custom lowers integer to floating point conversions to use 8636 /// the direct move instructions available in ISA 2.07 to avoid the 8637 /// need for load/store combinations. 8638 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8639 SelectionDAG &DAG, 8640 const SDLoc &dl) const { 8641 assert((Op.getValueType() == MVT::f32 || 8642 Op.getValueType() == MVT::f64) && 8643 "Invalid floating point type as target of conversion"); 8644 assert(Subtarget.hasFPCVT() && 8645 "Int to FP conversions with direct moves require FPCVT"); 8646 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8647 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8648 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8649 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8650 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8651 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8652 return convertIntToFP(Op, Mov, DAG, Subtarget); 8653 } 8654 8655 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8656 8657 EVT VecVT = Vec.getValueType(); 8658 assert(VecVT.isVector() && "Expected a vector type."); 8659 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8660 8661 EVT EltVT = VecVT.getVectorElementType(); 8662 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8663 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8664 8665 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8666 SmallVector<SDValue, 16> Ops(NumConcat); 8667 Ops[0] = Vec; 8668 SDValue UndefVec = DAG.getUNDEF(VecVT); 8669 for (unsigned i = 1; i < NumConcat; ++i) 8670 Ops[i] = UndefVec; 8671 8672 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8673 } 8674 8675 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8676 const SDLoc &dl) const { 8677 bool IsStrict = Op->isStrictFPOpcode(); 8678 unsigned Opc = Op.getOpcode(); 8679 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8680 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8681 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8682 "Unexpected conversion type"); 8683 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8684 "Supports conversions to v2f64/v4f32 only."); 8685 8686 // TODO: Any other flags to propagate? 8687 SDNodeFlags Flags; 8688 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8689 8690 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8691 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8692 8693 SDValue Wide = widenVec(DAG, Src, dl); 8694 EVT WideVT = Wide.getValueType(); 8695 unsigned WideNumElts = WideVT.getVectorNumElements(); 8696 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8697 8698 SmallVector<int, 16> ShuffV; 8699 for (unsigned i = 0; i < WideNumElts; ++i) 8700 ShuffV.push_back(i + WideNumElts); 8701 8702 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8703 int SaveElts = FourEltRes ? 4 : 2; 8704 if (Subtarget.isLittleEndian()) 8705 for (int i = 0; i < SaveElts; i++) 8706 ShuffV[i * Stride] = i; 8707 else 8708 for (int i = 1; i <= SaveElts; i++) 8709 ShuffV[i * Stride - 1] = i - 1; 8710 8711 SDValue ShuffleSrc2 = 8712 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8713 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8714 8715 SDValue Extend; 8716 if (SignedConv) { 8717 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8718 EVT ExtVT = Src.getValueType(); 8719 if (Subtarget.hasP9Altivec()) 8720 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8721 IntermediateVT.getVectorNumElements()); 8722 8723 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8724 DAG.getValueType(ExtVT)); 8725 } else 8726 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8727 8728 if (IsStrict) 8729 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8730 {Op.getOperand(0), Extend}, Flags); 8731 8732 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8733 } 8734 8735 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8736 SelectionDAG &DAG) const { 8737 SDLoc dl(Op); 8738 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8739 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8740 bool IsStrict = Op->isStrictFPOpcode(); 8741 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8742 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8743 8744 // TODO: Any other flags to propagate? 8745 SDNodeFlags Flags; 8746 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8747 8748 EVT InVT = Src.getValueType(); 8749 EVT OutVT = Op.getValueType(); 8750 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8751 isOperationCustom(Op.getOpcode(), InVT)) 8752 return LowerINT_TO_FPVector(Op, DAG, dl); 8753 8754 // Conversions to f128 are legal. 8755 if (Op.getValueType() == MVT::f128) 8756 return Subtarget.hasP9Vector() ? Op : SDValue(); 8757 8758 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8759 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8760 return SDValue(); 8761 8762 if (Src.getValueType() == MVT::i1) { 8763 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8764 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8765 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8766 if (IsStrict) 8767 return DAG.getMergeValues({Sel, Chain}, dl); 8768 else 8769 return Sel; 8770 } 8771 8772 // If we have direct moves, we can do all the conversion, skip the store/load 8773 // however, without FPCVT we can't do most conversions. 8774 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8775 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8776 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8777 8778 assert((IsSigned || Subtarget.hasFPCVT()) && 8779 "UINT_TO_FP is supported only with FPCVT"); 8780 8781 if (Src.getValueType() == MVT::i64) { 8782 SDValue SINT = Src; 8783 // When converting to single-precision, we actually need to convert 8784 // to double-precision first and then round to single-precision. 8785 // To avoid double-rounding effects during that operation, we have 8786 // to prepare the input operand. Bits that might be truncated when 8787 // converting to double-precision are replaced by a bit that won't 8788 // be lost at this stage, but is below the single-precision rounding 8789 // position. 8790 // 8791 // However, if -enable-unsafe-fp-math is in effect, accept double 8792 // rounding to avoid the extra overhead. 8793 if (Op.getValueType() == MVT::f32 && 8794 !Subtarget.hasFPCVT() && 8795 !DAG.getTarget().Options.UnsafeFPMath) { 8796 8797 // Twiddle input to make sure the low 11 bits are zero. (If this 8798 // is the case, we are guaranteed the value will fit into the 53 bit 8799 // mantissa of an IEEE double-precision value without rounding.) 8800 // If any of those low 11 bits were not zero originally, make sure 8801 // bit 12 (value 2048) is set instead, so that the final rounding 8802 // to single-precision gets the correct result. 8803 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8804 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8805 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8806 Round, DAG.getConstant(2047, dl, MVT::i64)); 8807 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8808 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8809 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8810 8811 // However, we cannot use that value unconditionally: if the magnitude 8812 // of the input value is small, the bit-twiddling we did above might 8813 // end up visibly changing the output. Fortunately, in that case, we 8814 // don't need to twiddle bits since the original input will convert 8815 // exactly to double-precision floating-point already. Therefore, 8816 // construct a conditional to use the original value if the top 11 8817 // bits are all sign-bit copies, and use the rounded value computed 8818 // above otherwise. 8819 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8820 SINT, DAG.getConstant(53, dl, MVT::i32)); 8821 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8822 Cond, DAG.getConstant(1, dl, MVT::i64)); 8823 Cond = DAG.getSetCC( 8824 dl, 8825 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8826 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8827 8828 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8829 } 8830 8831 ReuseLoadInfo RLI; 8832 SDValue Bits; 8833 8834 MachineFunction &MF = DAG.getMachineFunction(); 8835 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8836 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8837 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8838 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8839 } else if (Subtarget.hasLFIWAX() && 8840 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8841 MachineMemOperand *MMO = 8842 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8843 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8844 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8845 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8846 DAG.getVTList(MVT::f64, MVT::Other), 8847 Ops, MVT::i32, MMO); 8848 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8849 } else if (Subtarget.hasFPCVT() && 8850 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8851 MachineMemOperand *MMO = 8852 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8853 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8854 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8855 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8856 DAG.getVTList(MVT::f64, MVT::Other), 8857 Ops, MVT::i32, MMO); 8858 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8859 } else if (((Subtarget.hasLFIWAX() && 8860 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8861 (Subtarget.hasFPCVT() && 8862 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8863 SINT.getOperand(0).getValueType() == MVT::i32) { 8864 MachineFrameInfo &MFI = MF.getFrameInfo(); 8865 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8866 8867 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8868 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8869 8870 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8871 MachinePointerInfo::getFixedStack( 8872 DAG.getMachineFunction(), FrameIdx)); 8873 Chain = Store; 8874 8875 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8876 "Expected an i32 store"); 8877 8878 RLI.Ptr = FIdx; 8879 RLI.Chain = Chain; 8880 RLI.MPI = 8881 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8882 RLI.Alignment = Align(4); 8883 8884 MachineMemOperand *MMO = 8885 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8886 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8887 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8888 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8889 PPCISD::LFIWZX : PPCISD::LFIWAX, 8890 dl, DAG.getVTList(MVT::f64, MVT::Other), 8891 Ops, MVT::i32, MMO); 8892 Chain = Bits.getValue(1); 8893 } else 8894 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8895 8896 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8897 if (IsStrict) 8898 Chain = FP.getValue(1); 8899 8900 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8901 if (IsStrict) 8902 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8903 DAG.getVTList(MVT::f32, MVT::Other), 8904 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8905 else 8906 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8907 DAG.getIntPtrConstant(0, dl)); 8908 } 8909 return FP; 8910 } 8911 8912 assert(Src.getValueType() == MVT::i32 && 8913 "Unhandled INT_TO_FP type in custom expander!"); 8914 // Since we only generate this in 64-bit mode, we can take advantage of 8915 // 64-bit registers. In particular, sign extend the input value into the 8916 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8917 // then lfd it and fcfid it. 8918 MachineFunction &MF = DAG.getMachineFunction(); 8919 MachineFrameInfo &MFI = MF.getFrameInfo(); 8920 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8921 8922 SDValue Ld; 8923 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8924 ReuseLoadInfo RLI; 8925 bool ReusingLoad; 8926 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8927 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8928 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8929 8930 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8931 MachinePointerInfo::getFixedStack( 8932 DAG.getMachineFunction(), FrameIdx)); 8933 Chain = Store; 8934 8935 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8936 "Expected an i32 store"); 8937 8938 RLI.Ptr = FIdx; 8939 RLI.Chain = Chain; 8940 RLI.MPI = 8941 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8942 RLI.Alignment = Align(4); 8943 } 8944 8945 MachineMemOperand *MMO = 8946 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8947 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8948 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8949 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8950 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8951 MVT::i32, MMO); 8952 Chain = Ld.getValue(1); 8953 if (ReusingLoad) 8954 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8955 } else { 8956 assert(Subtarget.isPPC64() && 8957 "i32->FP without LFIWAX supported only on PPC64"); 8958 8959 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8960 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8961 8962 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8963 8964 // STD the extended value into the stack slot. 8965 SDValue Store = DAG.getStore( 8966 Chain, dl, Ext64, FIdx, 8967 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8968 Chain = Store; 8969 8970 // Load the value as a double. 8971 Ld = DAG.getLoad( 8972 MVT::f64, dl, Chain, FIdx, 8973 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8974 Chain = Ld.getValue(1); 8975 } 8976 8977 // FCFID it and return it. 8978 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8979 if (IsStrict) 8980 Chain = FP.getValue(1); 8981 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8982 if (IsStrict) 8983 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8984 DAG.getVTList(MVT::f32, MVT::Other), 8985 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8986 else 8987 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8988 DAG.getIntPtrConstant(0, dl)); 8989 } 8990 return FP; 8991 } 8992 8993 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8994 SelectionDAG &DAG) const { 8995 SDLoc dl(Op); 8996 /* 8997 The rounding mode is in bits 30:31 of FPSR, and has the following 8998 settings: 8999 00 Round to nearest 9000 01 Round to 0 9001 10 Round to +inf 9002 11 Round to -inf 9003 9004 FLT_ROUNDS, on the other hand, expects the following: 9005 -1 Undefined 9006 0 Round to 0 9007 1 Round to nearest 9008 2 Round to +inf 9009 3 Round to -inf 9010 9011 To perform the conversion, we do: 9012 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 9013 */ 9014 9015 MachineFunction &MF = DAG.getMachineFunction(); 9016 EVT VT = Op.getValueType(); 9017 EVT PtrVT = getPointerTy(MF.getDataLayout()); 9018 9019 // Save FP Control Word to register 9020 SDValue Chain = Op.getOperand(0); 9021 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 9022 Chain = MFFS.getValue(1); 9023 9024 SDValue CWD; 9025 if (isTypeLegal(MVT::i64)) { 9026 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 9027 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 9028 } else { 9029 // Save FP register to stack slot 9030 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 9031 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 9032 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 9033 9034 // Load FP Control Word from low 32 bits of stack slot. 9035 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 9036 "Stack slot adjustment is valid only on big endian subtargets!"); 9037 SDValue Four = DAG.getConstant(4, dl, PtrVT); 9038 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 9039 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 9040 Chain = CWD.getValue(1); 9041 } 9042 9043 // Transform as necessary 9044 SDValue CWD1 = 9045 DAG.getNode(ISD::AND, dl, MVT::i32, 9046 CWD, DAG.getConstant(3, dl, MVT::i32)); 9047 SDValue CWD2 = 9048 DAG.getNode(ISD::SRL, dl, MVT::i32, 9049 DAG.getNode(ISD::AND, dl, MVT::i32, 9050 DAG.getNode(ISD::XOR, dl, MVT::i32, 9051 CWD, DAG.getConstant(3, dl, MVT::i32)), 9052 DAG.getConstant(3, dl, MVT::i32)), 9053 DAG.getConstant(1, dl, MVT::i32)); 9054 9055 SDValue RetVal = 9056 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 9057 9058 RetVal = 9059 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 9060 dl, VT, RetVal); 9061 9062 return DAG.getMergeValues({RetVal, Chain}, dl); 9063 } 9064 9065 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 9066 EVT VT = Op.getValueType(); 9067 unsigned BitWidth = VT.getSizeInBits(); 9068 SDLoc dl(Op); 9069 assert(Op.getNumOperands() == 3 && 9070 VT == Op.getOperand(1).getValueType() && 9071 "Unexpected SHL!"); 9072 9073 // Expand into a bunch of logical ops. Note that these ops 9074 // depend on the PPC behavior for oversized shift amounts. 9075 SDValue Lo = Op.getOperand(0); 9076 SDValue Hi = Op.getOperand(1); 9077 SDValue Amt = Op.getOperand(2); 9078 EVT AmtVT = Amt.getValueType(); 9079 9080 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 9081 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 9082 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 9083 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 9084 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 9085 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 9086 DAG.getConstant(-BitWidth, dl, AmtVT)); 9087 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 9088 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 9089 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 9090 SDValue OutOps[] = { OutLo, OutHi }; 9091 return DAG.getMergeValues(OutOps, dl); 9092 } 9093 9094 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 9095 EVT VT = Op.getValueType(); 9096 SDLoc dl(Op); 9097 unsigned BitWidth = VT.getSizeInBits(); 9098 assert(Op.getNumOperands() == 3 && 9099 VT == Op.getOperand(1).getValueType() && 9100 "Unexpected SRL!"); 9101 9102 // Expand into a bunch of logical ops. Note that these ops 9103 // depend on the PPC behavior for oversized shift amounts. 9104 SDValue Lo = Op.getOperand(0); 9105 SDValue Hi = Op.getOperand(1); 9106 SDValue Amt = Op.getOperand(2); 9107 EVT AmtVT = Amt.getValueType(); 9108 9109 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 9110 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 9111 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 9112 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 9113 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9114 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 9115 DAG.getConstant(-BitWidth, dl, AmtVT)); 9116 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 9117 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 9118 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 9119 SDValue OutOps[] = { OutLo, OutHi }; 9120 return DAG.getMergeValues(OutOps, dl); 9121 } 9122 9123 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 9124 SDLoc dl(Op); 9125 EVT VT = Op.getValueType(); 9126 unsigned BitWidth = VT.getSizeInBits(); 9127 assert(Op.getNumOperands() == 3 && 9128 VT == Op.getOperand(1).getValueType() && 9129 "Unexpected SRA!"); 9130 9131 // Expand into a bunch of logical ops, followed by a select_cc. 9132 SDValue Lo = Op.getOperand(0); 9133 SDValue Hi = Op.getOperand(1); 9134 SDValue Amt = Op.getOperand(2); 9135 EVT AmtVT = Amt.getValueType(); 9136 9137 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 9138 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 9139 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 9140 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 9141 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9142 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 9143 DAG.getConstant(-BitWidth, dl, AmtVT)); 9144 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 9145 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 9146 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 9147 Tmp4, Tmp6, ISD::SETLE); 9148 SDValue OutOps[] = { OutLo, OutHi }; 9149 return DAG.getMergeValues(OutOps, dl); 9150 } 9151 9152 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 9153 SelectionDAG &DAG) const { 9154 SDLoc dl(Op); 9155 EVT VT = Op.getValueType(); 9156 unsigned BitWidth = VT.getSizeInBits(); 9157 9158 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 9159 SDValue X = Op.getOperand(0); 9160 SDValue Y = Op.getOperand(1); 9161 SDValue Z = Op.getOperand(2); 9162 EVT AmtVT = Z.getValueType(); 9163 9164 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 9165 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 9166 // This is simpler than TargetLowering::expandFunnelShift because we can rely 9167 // on PowerPC shift by BW being well defined. 9168 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 9169 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 9170 SDValue SubZ = 9171 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 9172 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 9173 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 9174 return DAG.getNode(ISD::OR, dl, VT, X, Y); 9175 } 9176 9177 //===----------------------------------------------------------------------===// 9178 // Vector related lowering. 9179 // 9180 9181 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 9182 /// element size of SplatSize. Cast the result to VT. 9183 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 9184 SelectionDAG &DAG, const SDLoc &dl) { 9185 static const MVT VTys[] = { // canonical VT to use for each size. 9186 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 9187 }; 9188 9189 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 9190 9191 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 9192 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 9193 SplatSize = 1; 9194 Val = 0xFF; 9195 } 9196 9197 EVT CanonicalVT = VTys[SplatSize-1]; 9198 9199 // Build a canonical splat for this value. 9200 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 9201 } 9202 9203 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 9204 /// specified intrinsic ID. 9205 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 9206 const SDLoc &dl, EVT DestVT = MVT::Other) { 9207 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 9208 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9209 DAG.getConstant(IID, dl, MVT::i32), Op); 9210 } 9211 9212 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 9213 /// specified intrinsic ID. 9214 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 9215 SelectionDAG &DAG, const SDLoc &dl, 9216 EVT DestVT = MVT::Other) { 9217 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 9218 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9219 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 9220 } 9221 9222 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 9223 /// specified intrinsic ID. 9224 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 9225 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 9226 EVT DestVT = MVT::Other) { 9227 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 9228 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9229 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 9230 } 9231 9232 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9233 /// amount. The result has the specified value type. 9234 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9235 SelectionDAG &DAG, const SDLoc &dl) { 9236 // Force LHS/RHS to be the right type. 9237 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9238 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9239 9240 int Ops[16]; 9241 for (unsigned i = 0; i != 16; ++i) 9242 Ops[i] = i + Amt; 9243 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9244 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9245 } 9246 9247 /// Do we have an efficient pattern in a .td file for this node? 9248 /// 9249 /// \param V - pointer to the BuildVectorSDNode being matched 9250 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9251 /// 9252 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9253 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9254 /// the opposite is true (expansion is beneficial) are: 9255 /// - The node builds a vector out of integers that are not 32 or 64-bits 9256 /// - The node builds a vector out of constants 9257 /// - The node is a "load-and-splat" 9258 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9259 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9260 bool HasDirectMove, 9261 bool HasP8Vector) { 9262 EVT VecVT = V->getValueType(0); 9263 bool RightType = VecVT == MVT::v2f64 || 9264 (HasP8Vector && VecVT == MVT::v4f32) || 9265 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9266 if (!RightType) 9267 return false; 9268 9269 bool IsSplat = true; 9270 bool IsLoad = false; 9271 SDValue Op0 = V->getOperand(0); 9272 9273 // This function is called in a block that confirms the node is not a constant 9274 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9275 // different constants. 9276 if (V->isConstant()) 9277 return false; 9278 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9279 if (V->getOperand(i).isUndef()) 9280 return false; 9281 // We want to expand nodes that represent load-and-splat even if the 9282 // loaded value is a floating point truncation or conversion to int. 9283 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9284 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9285 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9286 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9287 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9288 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9289 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9290 IsLoad = true; 9291 // If the operands are different or the input is not a load and has more 9292 // uses than just this BV node, then it isn't a splat. 9293 if (V->getOperand(i) != Op0 || 9294 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9295 IsSplat = false; 9296 } 9297 return !(IsSplat && IsLoad); 9298 } 9299 9300 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9301 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9302 9303 SDLoc dl(Op); 9304 SDValue Op0 = Op->getOperand(0); 9305 9306 if ((Op.getValueType() != MVT::f128) || 9307 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9308 (Op0.getOperand(0).getValueType() != MVT::i64) || 9309 (Op0.getOperand(1).getValueType() != MVT::i64)) 9310 return SDValue(); 9311 9312 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9313 Op0.getOperand(1)); 9314 } 9315 9316 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9317 const SDValue *InputLoad = &Op; 9318 if (InputLoad->getOpcode() == ISD::BITCAST) 9319 InputLoad = &InputLoad->getOperand(0); 9320 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9321 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9322 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9323 InputLoad = &InputLoad->getOperand(0); 9324 } 9325 if (InputLoad->getOpcode() != ISD::LOAD) 9326 return nullptr; 9327 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9328 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9329 } 9330 9331 // Convert the argument APFloat to a single precision APFloat if there is no 9332 // loss in information during the conversion to single precision APFloat and the 9333 // resulting number is not a denormal number. Return true if successful. 9334 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9335 APFloat APFloatToConvert = ArgAPFloat; 9336 bool LosesInfo = true; 9337 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9338 &LosesInfo); 9339 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9340 if (Success) 9341 ArgAPFloat = APFloatToConvert; 9342 return Success; 9343 } 9344 9345 // Bitcast the argument APInt to a double and convert it to a single precision 9346 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9347 // argument if there is no loss in information during the conversion from 9348 // double to single precision APFloat and the resulting number is not a denormal 9349 // number. Return true if successful. 9350 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9351 double DpValue = ArgAPInt.bitsToDouble(); 9352 APFloat APFloatDp(DpValue); 9353 bool Success = convertToNonDenormSingle(APFloatDp); 9354 if (Success) 9355 ArgAPInt = APFloatDp.bitcastToAPInt(); 9356 return Success; 9357 } 9358 9359 // If this is a case we can't handle, return null and let the default 9360 // expansion code take care of it. If we CAN select this case, and if it 9361 // selects to a single instruction, return Op. Otherwise, if we can codegen 9362 // this case more efficiently than a constant pool load, lower it to the 9363 // sequence of ops that should be used. 9364 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9365 SelectionDAG &DAG) const { 9366 SDLoc dl(Op); 9367 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9368 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9369 9370 // Check if this is a splat of a constant value. 9371 APInt APSplatBits, APSplatUndef; 9372 unsigned SplatBitSize; 9373 bool HasAnyUndefs; 9374 bool BVNIsConstantSplat = 9375 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9376 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9377 9378 // If it is a splat of a double, check if we can shrink it to a 32 bit 9379 // non-denormal float which when converted back to double gives us the same 9380 // double. This is to exploit the XXSPLTIDP instruction. 9381 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9382 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9383 convertToNonDenormSingle(APSplatBits)) { 9384 SDValue SplatNode = DAG.getNode( 9385 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9386 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9387 return DAG.getBitcast(Op.getValueType(), SplatNode); 9388 } 9389 9390 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9391 9392 bool IsPermutedLoad = false; 9393 const SDValue *InputLoad = 9394 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9395 // Handle load-and-splat patterns as we have instructions that will do this 9396 // in one go. 9397 if (InputLoad && DAG.isSplatValue(Op, true)) { 9398 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9399 9400 // We have handling for 4 and 8 byte elements. 9401 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9402 9403 // Checking for a single use of this load, we have to check for vector 9404 // width (128 bits) / ElementSize uses (since each operand of the 9405 // BUILD_VECTOR is a separate use of the value. 9406 unsigned NumUsesOfInputLD = 128 / ElementSize; 9407 for (SDValue BVInOp : Op->ops()) 9408 if (BVInOp.isUndef()) 9409 NumUsesOfInputLD--; 9410 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9411 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9412 ((Subtarget.hasVSX() && ElementSize == 64) || 9413 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9414 SDValue Ops[] = { 9415 LD->getChain(), // Chain 9416 LD->getBasePtr(), // Ptr 9417 DAG.getValueType(Op.getValueType()) // VT 9418 }; 9419 SDValue LdSplt = DAG.getMemIntrinsicNode( 9420 PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 9421 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9422 // Replace all uses of the output chain of the original load with the 9423 // output chain of the new load. 9424 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9425 LdSplt.getValue(1)); 9426 return LdSplt; 9427 } 9428 } 9429 9430 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9431 // 32-bits can be lowered to VSX instructions under certain conditions. 9432 // Without VSX, there is no pattern more efficient than expanding the node. 9433 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9434 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9435 Subtarget.hasP8Vector())) 9436 return Op; 9437 return SDValue(); 9438 } 9439 9440 uint64_t SplatBits = APSplatBits.getZExtValue(); 9441 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9442 unsigned SplatSize = SplatBitSize / 8; 9443 9444 // First, handle single instruction cases. 9445 9446 // All zeros? 9447 if (SplatBits == 0) { 9448 // Canonicalize all zero vectors to be v4i32. 9449 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9450 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9451 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9452 } 9453 return Op; 9454 } 9455 9456 // We have XXSPLTIW for constant splats four bytes wide. 9457 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9458 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9459 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9460 // turned into a 4-byte splat of 0xABABABAB. 9461 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9462 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9463 Op.getValueType(), DAG, dl); 9464 9465 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9466 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9467 dl); 9468 9469 // We have XXSPLTIB for constant splats one byte wide. 9470 if (Subtarget.hasP9Vector() && SplatSize == 1) 9471 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9472 dl); 9473 9474 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9475 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9476 (32-SplatBitSize)); 9477 if (SextVal >= -16 && SextVal <= 15) 9478 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9479 dl); 9480 9481 // Two instruction sequences. 9482 9483 // If this value is in the range [-32,30] and is even, use: 9484 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9485 // If this value is in the range [17,31] and is odd, use: 9486 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9487 // If this value is in the range [-31,-17] and is odd, use: 9488 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9489 // Note the last two are three-instruction sequences. 9490 if (SextVal >= -32 && SextVal <= 31) { 9491 // To avoid having these optimizations undone by constant folding, 9492 // we convert to a pseudo that will be expanded later into one of 9493 // the above forms. 9494 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9495 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9496 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9497 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9498 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9499 if (VT == Op.getValueType()) 9500 return RetVal; 9501 else 9502 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9503 } 9504 9505 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9506 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9507 // for fneg/fabs. 9508 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9509 // Make -1 and vspltisw -1: 9510 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9511 9512 // Make the VSLW intrinsic, computing 0x8000_0000. 9513 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9514 OnesV, DAG, dl); 9515 9516 // xor by OnesV to invert it. 9517 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9518 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9519 } 9520 9521 // Check to see if this is a wide variety of vsplti*, binop self cases. 9522 static const signed char SplatCsts[] = { 9523 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9524 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9525 }; 9526 9527 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9528 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9529 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9530 int i = SplatCsts[idx]; 9531 9532 // Figure out what shift amount will be used by altivec if shifted by i in 9533 // this splat size. 9534 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9535 9536 // vsplti + shl self. 9537 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9538 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9539 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9540 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9541 Intrinsic::ppc_altivec_vslw 9542 }; 9543 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9544 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9545 } 9546 9547 // vsplti + srl self. 9548 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9549 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9550 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9551 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9552 Intrinsic::ppc_altivec_vsrw 9553 }; 9554 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9555 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9556 } 9557 9558 // vsplti + rol self. 9559 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9560 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9561 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9562 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9563 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9564 Intrinsic::ppc_altivec_vrlw 9565 }; 9566 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9567 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9568 } 9569 9570 // t = vsplti c, result = vsldoi t, t, 1 9571 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9572 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9573 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9574 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9575 } 9576 // t = vsplti c, result = vsldoi t, t, 2 9577 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9578 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9579 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9580 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9581 } 9582 // t = vsplti c, result = vsldoi t, t, 3 9583 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9584 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9585 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9586 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9587 } 9588 } 9589 9590 return SDValue(); 9591 } 9592 9593 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9594 /// the specified operations to build the shuffle. 9595 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9596 SDValue RHS, SelectionDAG &DAG, 9597 const SDLoc &dl) { 9598 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9599 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9600 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9601 9602 enum { 9603 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9604 OP_VMRGHW, 9605 OP_VMRGLW, 9606 OP_VSPLTISW0, 9607 OP_VSPLTISW1, 9608 OP_VSPLTISW2, 9609 OP_VSPLTISW3, 9610 OP_VSLDOI4, 9611 OP_VSLDOI8, 9612 OP_VSLDOI12 9613 }; 9614 9615 if (OpNum == OP_COPY) { 9616 if (LHSID == (1*9+2)*9+3) return LHS; 9617 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9618 return RHS; 9619 } 9620 9621 SDValue OpLHS, OpRHS; 9622 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9623 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9624 9625 int ShufIdxs[16]; 9626 switch (OpNum) { 9627 default: llvm_unreachable("Unknown i32 permute!"); 9628 case OP_VMRGHW: 9629 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9630 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9631 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9632 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9633 break; 9634 case OP_VMRGLW: 9635 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9636 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9637 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9638 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9639 break; 9640 case OP_VSPLTISW0: 9641 for (unsigned i = 0; i != 16; ++i) 9642 ShufIdxs[i] = (i&3)+0; 9643 break; 9644 case OP_VSPLTISW1: 9645 for (unsigned i = 0; i != 16; ++i) 9646 ShufIdxs[i] = (i&3)+4; 9647 break; 9648 case OP_VSPLTISW2: 9649 for (unsigned i = 0; i != 16; ++i) 9650 ShufIdxs[i] = (i&3)+8; 9651 break; 9652 case OP_VSPLTISW3: 9653 for (unsigned i = 0; i != 16; ++i) 9654 ShufIdxs[i] = (i&3)+12; 9655 break; 9656 case OP_VSLDOI4: 9657 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9658 case OP_VSLDOI8: 9659 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9660 case OP_VSLDOI12: 9661 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9662 } 9663 EVT VT = OpLHS.getValueType(); 9664 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9665 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9666 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9667 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9668 } 9669 9670 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9671 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9672 /// SDValue. 9673 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9674 SelectionDAG &DAG) const { 9675 const unsigned BytesInVector = 16; 9676 bool IsLE = Subtarget.isLittleEndian(); 9677 SDLoc dl(N); 9678 SDValue V1 = N->getOperand(0); 9679 SDValue V2 = N->getOperand(1); 9680 unsigned ShiftElts = 0, InsertAtByte = 0; 9681 bool Swap = false; 9682 9683 // Shifts required to get the byte we want at element 7. 9684 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9685 0, 15, 14, 13, 12, 11, 10, 9}; 9686 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9687 1, 2, 3, 4, 5, 6, 7, 8}; 9688 9689 ArrayRef<int> Mask = N->getMask(); 9690 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9691 9692 // For each mask element, find out if we're just inserting something 9693 // from V2 into V1 or vice versa. 9694 // Possible permutations inserting an element from V2 into V1: 9695 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9696 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9697 // ... 9698 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9699 // Inserting from V1 into V2 will be similar, except mask range will be 9700 // [16,31]. 9701 9702 bool FoundCandidate = false; 9703 // If both vector operands for the shuffle are the same vector, the mask 9704 // will contain only elements from the first one and the second one will be 9705 // undef. 9706 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9707 // Go through the mask of half-words to find an element that's being moved 9708 // from one vector to the other. 9709 for (unsigned i = 0; i < BytesInVector; ++i) { 9710 unsigned CurrentElement = Mask[i]; 9711 // If 2nd operand is undefined, we should only look for element 7 in the 9712 // Mask. 9713 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9714 continue; 9715 9716 bool OtherElementsInOrder = true; 9717 // Examine the other elements in the Mask to see if they're in original 9718 // order. 9719 for (unsigned j = 0; j < BytesInVector; ++j) { 9720 if (j == i) 9721 continue; 9722 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9723 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9724 // in which we always assume we're always picking from the 1st operand. 9725 int MaskOffset = 9726 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9727 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9728 OtherElementsInOrder = false; 9729 break; 9730 } 9731 } 9732 // If other elements are in original order, we record the number of shifts 9733 // we need to get the element we want into element 7. Also record which byte 9734 // in the vector we should insert into. 9735 if (OtherElementsInOrder) { 9736 // If 2nd operand is undefined, we assume no shifts and no swapping. 9737 if (V2.isUndef()) { 9738 ShiftElts = 0; 9739 Swap = false; 9740 } else { 9741 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9742 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9743 : BigEndianShifts[CurrentElement & 0xF]; 9744 Swap = CurrentElement < BytesInVector; 9745 } 9746 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9747 FoundCandidate = true; 9748 break; 9749 } 9750 } 9751 9752 if (!FoundCandidate) 9753 return SDValue(); 9754 9755 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9756 // optionally with VECSHL if shift is required. 9757 if (Swap) 9758 std::swap(V1, V2); 9759 if (V2.isUndef()) 9760 V2 = V1; 9761 if (ShiftElts) { 9762 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9763 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9764 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9765 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9766 } 9767 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9768 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9769 } 9770 9771 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9772 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9773 /// SDValue. 9774 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9775 SelectionDAG &DAG) const { 9776 const unsigned NumHalfWords = 8; 9777 const unsigned BytesInVector = NumHalfWords * 2; 9778 // Check that the shuffle is on half-words. 9779 if (!isNByteElemShuffleMask(N, 2, 1)) 9780 return SDValue(); 9781 9782 bool IsLE = Subtarget.isLittleEndian(); 9783 SDLoc dl(N); 9784 SDValue V1 = N->getOperand(0); 9785 SDValue V2 = N->getOperand(1); 9786 unsigned ShiftElts = 0, InsertAtByte = 0; 9787 bool Swap = false; 9788 9789 // Shifts required to get the half-word we want at element 3. 9790 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9791 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9792 9793 uint32_t Mask = 0; 9794 uint32_t OriginalOrderLow = 0x1234567; 9795 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9796 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9797 // 32-bit space, only need 4-bit nibbles per element. 9798 for (unsigned i = 0; i < NumHalfWords; ++i) { 9799 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9800 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9801 } 9802 9803 // For each mask element, find out if we're just inserting something 9804 // from V2 into V1 or vice versa. Possible permutations inserting an element 9805 // from V2 into V1: 9806 // X, 1, 2, 3, 4, 5, 6, 7 9807 // 0, X, 2, 3, 4, 5, 6, 7 9808 // 0, 1, X, 3, 4, 5, 6, 7 9809 // 0, 1, 2, X, 4, 5, 6, 7 9810 // 0, 1, 2, 3, X, 5, 6, 7 9811 // 0, 1, 2, 3, 4, X, 6, 7 9812 // 0, 1, 2, 3, 4, 5, X, 7 9813 // 0, 1, 2, 3, 4, 5, 6, X 9814 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9815 9816 bool FoundCandidate = false; 9817 // Go through the mask of half-words to find an element that's being moved 9818 // from one vector to the other. 9819 for (unsigned i = 0; i < NumHalfWords; ++i) { 9820 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9821 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9822 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9823 uint32_t TargetOrder = 0x0; 9824 9825 // If both vector operands for the shuffle are the same vector, the mask 9826 // will contain only elements from the first one and the second one will be 9827 // undef. 9828 if (V2.isUndef()) { 9829 ShiftElts = 0; 9830 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9831 TargetOrder = OriginalOrderLow; 9832 Swap = false; 9833 // Skip if not the correct element or mask of other elements don't equal 9834 // to our expected order. 9835 if (MaskOneElt == VINSERTHSrcElem && 9836 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9837 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9838 FoundCandidate = true; 9839 break; 9840 } 9841 } else { // If both operands are defined. 9842 // Target order is [8,15] if the current mask is between [0,7]. 9843 TargetOrder = 9844 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9845 // Skip if mask of other elements don't equal our expected order. 9846 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9847 // We only need the last 3 bits for the number of shifts. 9848 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9849 : BigEndianShifts[MaskOneElt & 0x7]; 9850 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9851 Swap = MaskOneElt < NumHalfWords; 9852 FoundCandidate = true; 9853 break; 9854 } 9855 } 9856 } 9857 9858 if (!FoundCandidate) 9859 return SDValue(); 9860 9861 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9862 // optionally with VECSHL if shift is required. 9863 if (Swap) 9864 std::swap(V1, V2); 9865 if (V2.isUndef()) 9866 V2 = V1; 9867 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9868 if (ShiftElts) { 9869 // Double ShiftElts because we're left shifting on v16i8 type. 9870 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9871 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9872 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9873 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9874 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9875 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9876 } 9877 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9878 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9879 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9880 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9881 } 9882 9883 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9884 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9885 /// return the default SDValue. 9886 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9887 SelectionDAG &DAG) const { 9888 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9889 // to v16i8. Peek through the bitcasts to get the actual operands. 9890 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9891 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9892 9893 auto ShuffleMask = SVN->getMask(); 9894 SDValue VecShuffle(SVN, 0); 9895 SDLoc DL(SVN); 9896 9897 // Check that we have a four byte shuffle. 9898 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9899 return SDValue(); 9900 9901 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9902 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9903 std::swap(LHS, RHS); 9904 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9905 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9906 } 9907 9908 // Ensure that the RHS is a vector of constants. 9909 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9910 if (!BVN) 9911 return SDValue(); 9912 9913 // Check if RHS is a splat of 4-bytes (or smaller). 9914 APInt APSplatValue, APSplatUndef; 9915 unsigned SplatBitSize; 9916 bool HasAnyUndefs; 9917 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9918 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9919 SplatBitSize > 32) 9920 return SDValue(); 9921 9922 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9923 // The instruction splats a constant C into two words of the source vector 9924 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9925 // Thus we check that the shuffle mask is the equivalent of 9926 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9927 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9928 // within each word are consecutive, so we only need to check the first byte. 9929 SDValue Index; 9930 bool IsLE = Subtarget.isLittleEndian(); 9931 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9932 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9933 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9934 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9935 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9936 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9937 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9938 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9939 else 9940 return SDValue(); 9941 9942 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9943 // for XXSPLTI32DX. 9944 unsigned SplatVal = APSplatValue.getZExtValue(); 9945 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9946 SplatVal |= (SplatVal << SplatBitSize); 9947 9948 SDValue SplatNode = DAG.getNode( 9949 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9950 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9951 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9952 } 9953 9954 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9955 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9956 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9957 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9958 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9959 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9960 assert(Op.getValueType() == MVT::v1i128 && 9961 "Only set v1i128 as custom, other type shouldn't reach here!"); 9962 SDLoc dl(Op); 9963 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9964 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9965 unsigned SHLAmt = N1.getConstantOperandVal(0); 9966 if (SHLAmt % 8 == 0) { 9967 SmallVector<int, 16> Mask(16, 0); 9968 std::iota(Mask.begin(), Mask.end(), 0); 9969 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9970 if (SDValue Shuffle = 9971 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9972 DAG.getUNDEF(MVT::v16i8), Mask)) 9973 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9974 } 9975 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9976 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9977 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9978 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9979 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9980 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9981 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9982 } 9983 9984 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9985 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9986 /// return the code it can be lowered into. Worst case, it can always be 9987 /// lowered into a vperm. 9988 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9989 SelectionDAG &DAG) const { 9990 SDLoc dl(Op); 9991 SDValue V1 = Op.getOperand(0); 9992 SDValue V2 = Op.getOperand(1); 9993 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9994 9995 // Any nodes that were combined in the target-independent combiner prior 9996 // to vector legalization will not be sent to the target combine. Try to 9997 // combine it here. 9998 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9999 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 10000 return NewShuffle; 10001 Op = NewShuffle; 10002 SVOp = cast<ShuffleVectorSDNode>(Op); 10003 V1 = Op.getOperand(0); 10004 V2 = Op.getOperand(1); 10005 } 10006 EVT VT = Op.getValueType(); 10007 bool isLittleEndian = Subtarget.isLittleEndian(); 10008 10009 unsigned ShiftElts, InsertAtByte; 10010 bool Swap = false; 10011 10012 // If this is a load-and-splat, we can do that with a single instruction 10013 // in some cases. However if the load has multiple uses, we don't want to 10014 // combine it because that will just produce multiple loads. 10015 bool IsPermutedLoad = false; 10016 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 10017 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 10018 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 10019 InputLoad->hasOneUse()) { 10020 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 10021 int SplatIdx = 10022 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 10023 10024 // The splat index for permuted loads will be in the left half of the vector 10025 // which is strictly wider than the loaded value by 8 bytes. So we need to 10026 // adjust the splat index to point to the correct address in memory. 10027 if (IsPermutedLoad) { 10028 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 10029 SplatIdx += IsFourByte ? 2 : 1; 10030 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 10031 "Splat of a value outside of the loaded memory"); 10032 } 10033 10034 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 10035 // For 4-byte load-and-splat, we need Power9. 10036 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 10037 uint64_t Offset = 0; 10038 if (IsFourByte) 10039 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 10040 else 10041 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 10042 10043 SDValue BasePtr = LD->getBasePtr(); 10044 if (Offset != 0) 10045 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 10046 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 10047 SDValue Ops[] = { 10048 LD->getChain(), // Chain 10049 BasePtr, // BasePtr 10050 DAG.getValueType(Op.getValueType()) // VT 10051 }; 10052 SDVTList VTL = 10053 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 10054 SDValue LdSplt = 10055 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 10056 Ops, LD->getMemoryVT(), LD->getMemOperand()); 10057 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 10058 if (LdSplt.getValueType() != SVOp->getValueType(0)) 10059 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 10060 return LdSplt; 10061 } 10062 } 10063 if (Subtarget.hasP9Vector() && 10064 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 10065 isLittleEndian)) { 10066 if (Swap) 10067 std::swap(V1, V2); 10068 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10069 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 10070 if (ShiftElts) { 10071 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 10072 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10073 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 10074 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10075 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 10076 } 10077 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 10078 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10079 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 10080 } 10081 10082 if (Subtarget.hasPrefixInstrs()) { 10083 SDValue SplatInsertNode; 10084 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 10085 return SplatInsertNode; 10086 } 10087 10088 if (Subtarget.hasP9Altivec()) { 10089 SDValue NewISDNode; 10090 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 10091 return NewISDNode; 10092 10093 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 10094 return NewISDNode; 10095 } 10096 10097 if (Subtarget.hasVSX() && 10098 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 10099 if (Swap) 10100 std::swap(V1, V2); 10101 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10102 SDValue Conv2 = 10103 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 10104 10105 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 10106 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10107 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 10108 } 10109 10110 if (Subtarget.hasVSX() && 10111 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 10112 if (Swap) 10113 std::swap(V1, V2); 10114 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10115 SDValue Conv2 = 10116 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 10117 10118 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 10119 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10120 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 10121 } 10122 10123 if (Subtarget.hasP9Vector()) { 10124 if (PPC::isXXBRHShuffleMask(SVOp)) { 10125 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 10126 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 10127 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 10128 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 10129 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10130 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 10131 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 10132 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 10133 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10134 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 10135 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 10136 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 10137 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 10138 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 10139 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 10140 } 10141 } 10142 10143 if (Subtarget.hasVSX()) { 10144 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 10145 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 10146 10147 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10148 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 10149 DAG.getConstant(SplatIdx, dl, MVT::i32)); 10150 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 10151 } 10152 10153 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 10154 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 10155 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 10156 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 10157 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 10158 } 10159 } 10160 10161 // Cases that are handled by instructions that take permute immediates 10162 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10163 // selected by the instruction selector. 10164 if (V2.isUndef()) { 10165 if (PPC::isSplatShuffleMask(SVOp, 1) || 10166 PPC::isSplatShuffleMask(SVOp, 2) || 10167 PPC::isSplatShuffleMask(SVOp, 4) || 10168 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10169 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10170 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10171 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10172 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10173 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10174 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10175 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10176 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10177 (Subtarget.hasP8Altivec() && ( 10178 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10179 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10180 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10181 return Op; 10182 } 10183 } 10184 10185 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10186 // and produce a fixed permutation. If any of these match, do not lower to 10187 // VPERM. 10188 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10189 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10190 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10191 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10192 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10193 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10194 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10195 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10196 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10197 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10198 (Subtarget.hasP8Altivec() && ( 10199 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10200 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10201 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10202 return Op; 10203 10204 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10205 // perfect shuffle table to emit an optimal matching sequence. 10206 ArrayRef<int> PermMask = SVOp->getMask(); 10207 10208 unsigned PFIndexes[4]; 10209 bool isFourElementShuffle = true; 10210 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 10211 unsigned EltNo = 8; // Start out undef. 10212 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10213 if (PermMask[i*4+j] < 0) 10214 continue; // Undef, ignore it. 10215 10216 unsigned ByteSource = PermMask[i*4+j]; 10217 if ((ByteSource & 3) != j) { 10218 isFourElementShuffle = false; 10219 break; 10220 } 10221 10222 if (EltNo == 8) { 10223 EltNo = ByteSource/4; 10224 } else if (EltNo != ByteSource/4) { 10225 isFourElementShuffle = false; 10226 break; 10227 } 10228 } 10229 PFIndexes[i] = EltNo; 10230 } 10231 10232 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10233 // perfect shuffle vector to determine if it is cost effective to do this as 10234 // discrete instructions, or whether we should use a vperm. 10235 // For now, we skip this for little endian until such time as we have a 10236 // little-endian perfect shuffle table. 10237 if (isFourElementShuffle && !isLittleEndian) { 10238 // Compute the index in the perfect shuffle table. 10239 unsigned PFTableIndex = 10240 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10241 10242 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10243 unsigned Cost = (PFEntry >> 30); 10244 10245 // Determining when to avoid vperm is tricky. Many things affect the cost 10246 // of vperm, particularly how many times the perm mask needs to be computed. 10247 // For example, if the perm mask can be hoisted out of a loop or is already 10248 // used (perhaps because there are multiple permutes with the same shuffle 10249 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10250 // the loop requires an extra register. 10251 // 10252 // As a compromise, we only emit discrete instructions if the shuffle can be 10253 // generated in 3 or fewer operations. When we have loop information 10254 // available, if this block is within a loop, we should avoid using vperm 10255 // for 3-operation perms and use a constant pool load instead. 10256 if (Cost < 3) 10257 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10258 } 10259 10260 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10261 // vector that will get spilled to the constant pool. 10262 if (V2.isUndef()) V2 = V1; 10263 10264 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10265 // that it is in input element units, not in bytes. Convert now. 10266 10267 // For little endian, the order of the input vectors is reversed, and 10268 // the permutation mask is complemented with respect to 31. This is 10269 // necessary to produce proper semantics with the big-endian-biased vperm 10270 // instruction. 10271 EVT EltVT = V1.getValueType().getVectorElementType(); 10272 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10273 10274 SmallVector<SDValue, 16> ResultMask; 10275 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10276 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10277 10278 for (unsigned j = 0; j != BytesPerElement; ++j) 10279 if (isLittleEndian) 10280 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10281 dl, MVT::i32)); 10282 else 10283 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10284 MVT::i32)); 10285 } 10286 10287 ShufflesHandledWithVPERM++; 10288 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10289 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10290 LLVM_DEBUG(SVOp->dump()); 10291 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10292 LLVM_DEBUG(VPermMask.dump()); 10293 10294 if (isLittleEndian) 10295 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10296 V2, V1, VPermMask); 10297 else 10298 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10299 V1, V2, VPermMask); 10300 } 10301 10302 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10303 /// vector comparison. If it is, return true and fill in Opc/isDot with 10304 /// information about the intrinsic. 10305 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10306 bool &isDot, const PPCSubtarget &Subtarget) { 10307 unsigned IntrinsicID = 10308 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10309 CompareOpc = -1; 10310 isDot = false; 10311 switch (IntrinsicID) { 10312 default: 10313 return false; 10314 // Comparison predicates. 10315 case Intrinsic::ppc_altivec_vcmpbfp_p: 10316 CompareOpc = 966; 10317 isDot = true; 10318 break; 10319 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10320 CompareOpc = 198; 10321 isDot = true; 10322 break; 10323 case Intrinsic::ppc_altivec_vcmpequb_p: 10324 CompareOpc = 6; 10325 isDot = true; 10326 break; 10327 case Intrinsic::ppc_altivec_vcmpequh_p: 10328 CompareOpc = 70; 10329 isDot = true; 10330 break; 10331 case Intrinsic::ppc_altivec_vcmpequw_p: 10332 CompareOpc = 134; 10333 isDot = true; 10334 break; 10335 case Intrinsic::ppc_altivec_vcmpequd_p: 10336 if (Subtarget.hasP8Altivec()) { 10337 CompareOpc = 199; 10338 isDot = true; 10339 } else 10340 return false; 10341 break; 10342 case Intrinsic::ppc_altivec_vcmpneb_p: 10343 case Intrinsic::ppc_altivec_vcmpneh_p: 10344 case Intrinsic::ppc_altivec_vcmpnew_p: 10345 case Intrinsic::ppc_altivec_vcmpnezb_p: 10346 case Intrinsic::ppc_altivec_vcmpnezh_p: 10347 case Intrinsic::ppc_altivec_vcmpnezw_p: 10348 if (Subtarget.hasP9Altivec()) { 10349 switch (IntrinsicID) { 10350 default: 10351 llvm_unreachable("Unknown comparison intrinsic."); 10352 case Intrinsic::ppc_altivec_vcmpneb_p: 10353 CompareOpc = 7; 10354 break; 10355 case Intrinsic::ppc_altivec_vcmpneh_p: 10356 CompareOpc = 71; 10357 break; 10358 case Intrinsic::ppc_altivec_vcmpnew_p: 10359 CompareOpc = 135; 10360 break; 10361 case Intrinsic::ppc_altivec_vcmpnezb_p: 10362 CompareOpc = 263; 10363 break; 10364 case Intrinsic::ppc_altivec_vcmpnezh_p: 10365 CompareOpc = 327; 10366 break; 10367 case Intrinsic::ppc_altivec_vcmpnezw_p: 10368 CompareOpc = 391; 10369 break; 10370 } 10371 isDot = true; 10372 } else 10373 return false; 10374 break; 10375 case Intrinsic::ppc_altivec_vcmpgefp_p: 10376 CompareOpc = 454; 10377 isDot = true; 10378 break; 10379 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10380 CompareOpc = 710; 10381 isDot = true; 10382 break; 10383 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10384 CompareOpc = 774; 10385 isDot = true; 10386 break; 10387 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10388 CompareOpc = 838; 10389 isDot = true; 10390 break; 10391 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10392 CompareOpc = 902; 10393 isDot = true; 10394 break; 10395 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10396 if (Subtarget.hasP8Altivec()) { 10397 CompareOpc = 967; 10398 isDot = true; 10399 } else 10400 return false; 10401 break; 10402 case Intrinsic::ppc_altivec_vcmpgtub_p: 10403 CompareOpc = 518; 10404 isDot = true; 10405 break; 10406 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10407 CompareOpc = 582; 10408 isDot = true; 10409 break; 10410 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10411 CompareOpc = 646; 10412 isDot = true; 10413 break; 10414 case Intrinsic::ppc_altivec_vcmpgtud_p: 10415 if (Subtarget.hasP8Altivec()) { 10416 CompareOpc = 711; 10417 isDot = true; 10418 } else 10419 return false; 10420 break; 10421 10422 case Intrinsic::ppc_altivec_vcmpequq: 10423 case Intrinsic::ppc_altivec_vcmpgtsq: 10424 case Intrinsic::ppc_altivec_vcmpgtuq: 10425 if (!Subtarget.isISA3_1()) 10426 return false; 10427 switch (IntrinsicID) { 10428 default: 10429 llvm_unreachable("Unknown comparison intrinsic."); 10430 case Intrinsic::ppc_altivec_vcmpequq: 10431 CompareOpc = 455; 10432 break; 10433 case Intrinsic::ppc_altivec_vcmpgtsq: 10434 CompareOpc = 903; 10435 break; 10436 case Intrinsic::ppc_altivec_vcmpgtuq: 10437 CompareOpc = 647; 10438 break; 10439 } 10440 break; 10441 10442 // VSX predicate comparisons use the same infrastructure 10443 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10444 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10445 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10446 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10447 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10448 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10449 if (Subtarget.hasVSX()) { 10450 switch (IntrinsicID) { 10451 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10452 CompareOpc = 99; 10453 break; 10454 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10455 CompareOpc = 115; 10456 break; 10457 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10458 CompareOpc = 107; 10459 break; 10460 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10461 CompareOpc = 67; 10462 break; 10463 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10464 CompareOpc = 83; 10465 break; 10466 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10467 CompareOpc = 75; 10468 break; 10469 } 10470 isDot = true; 10471 } else 10472 return false; 10473 break; 10474 10475 // Normal Comparisons. 10476 case Intrinsic::ppc_altivec_vcmpbfp: 10477 CompareOpc = 966; 10478 break; 10479 case Intrinsic::ppc_altivec_vcmpeqfp: 10480 CompareOpc = 198; 10481 break; 10482 case Intrinsic::ppc_altivec_vcmpequb: 10483 CompareOpc = 6; 10484 break; 10485 case Intrinsic::ppc_altivec_vcmpequh: 10486 CompareOpc = 70; 10487 break; 10488 case Intrinsic::ppc_altivec_vcmpequw: 10489 CompareOpc = 134; 10490 break; 10491 case Intrinsic::ppc_altivec_vcmpequd: 10492 if (Subtarget.hasP8Altivec()) 10493 CompareOpc = 199; 10494 else 10495 return false; 10496 break; 10497 case Intrinsic::ppc_altivec_vcmpneb: 10498 case Intrinsic::ppc_altivec_vcmpneh: 10499 case Intrinsic::ppc_altivec_vcmpnew: 10500 case Intrinsic::ppc_altivec_vcmpnezb: 10501 case Intrinsic::ppc_altivec_vcmpnezh: 10502 case Intrinsic::ppc_altivec_vcmpnezw: 10503 if (Subtarget.hasP9Altivec()) 10504 switch (IntrinsicID) { 10505 default: 10506 llvm_unreachable("Unknown comparison intrinsic."); 10507 case Intrinsic::ppc_altivec_vcmpneb: 10508 CompareOpc = 7; 10509 break; 10510 case Intrinsic::ppc_altivec_vcmpneh: 10511 CompareOpc = 71; 10512 break; 10513 case Intrinsic::ppc_altivec_vcmpnew: 10514 CompareOpc = 135; 10515 break; 10516 case Intrinsic::ppc_altivec_vcmpnezb: 10517 CompareOpc = 263; 10518 break; 10519 case Intrinsic::ppc_altivec_vcmpnezh: 10520 CompareOpc = 327; 10521 break; 10522 case Intrinsic::ppc_altivec_vcmpnezw: 10523 CompareOpc = 391; 10524 break; 10525 } 10526 else 10527 return false; 10528 break; 10529 case Intrinsic::ppc_altivec_vcmpgefp: 10530 CompareOpc = 454; 10531 break; 10532 case Intrinsic::ppc_altivec_vcmpgtfp: 10533 CompareOpc = 710; 10534 break; 10535 case Intrinsic::ppc_altivec_vcmpgtsb: 10536 CompareOpc = 774; 10537 break; 10538 case Intrinsic::ppc_altivec_vcmpgtsh: 10539 CompareOpc = 838; 10540 break; 10541 case Intrinsic::ppc_altivec_vcmpgtsw: 10542 CompareOpc = 902; 10543 break; 10544 case Intrinsic::ppc_altivec_vcmpgtsd: 10545 if (Subtarget.hasP8Altivec()) 10546 CompareOpc = 967; 10547 else 10548 return false; 10549 break; 10550 case Intrinsic::ppc_altivec_vcmpgtub: 10551 CompareOpc = 518; 10552 break; 10553 case Intrinsic::ppc_altivec_vcmpgtuh: 10554 CompareOpc = 582; 10555 break; 10556 case Intrinsic::ppc_altivec_vcmpgtuw: 10557 CompareOpc = 646; 10558 break; 10559 case Intrinsic::ppc_altivec_vcmpgtud: 10560 if (Subtarget.hasP8Altivec()) 10561 CompareOpc = 711; 10562 else 10563 return false; 10564 break; 10565 case Intrinsic::ppc_altivec_vcmpequq_p: 10566 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10567 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10568 if (!Subtarget.isISA3_1()) 10569 return false; 10570 switch (IntrinsicID) { 10571 default: 10572 llvm_unreachable("Unknown comparison intrinsic."); 10573 case Intrinsic::ppc_altivec_vcmpequq_p: 10574 CompareOpc = 455; 10575 break; 10576 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10577 CompareOpc = 903; 10578 break; 10579 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10580 CompareOpc = 647; 10581 break; 10582 } 10583 isDot = true; 10584 break; 10585 } 10586 return true; 10587 } 10588 10589 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10590 /// lower, do it, otherwise return null. 10591 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10592 SelectionDAG &DAG) const { 10593 unsigned IntrinsicID = 10594 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10595 10596 SDLoc dl(Op); 10597 10598 switch (IntrinsicID) { 10599 case Intrinsic::thread_pointer: 10600 // Reads the thread pointer register, used for __builtin_thread_pointer. 10601 if (Subtarget.isPPC64()) 10602 return DAG.getRegister(PPC::X13, MVT::i64); 10603 return DAG.getRegister(PPC::R2, MVT::i32); 10604 10605 case Intrinsic::ppc_mma_disassemble_acc: 10606 case Intrinsic::ppc_vsx_disassemble_pair: { 10607 int NumVecs = 2; 10608 SDValue WideVec = Op.getOperand(1); 10609 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10610 NumVecs = 4; 10611 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10612 } 10613 SmallVector<SDValue, 4> RetOps; 10614 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10615 SDValue Extract = DAG.getNode( 10616 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10617 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10618 : VecNo, 10619 dl, MVT::i64)); 10620 RetOps.push_back(Extract); 10621 } 10622 return DAG.getMergeValues(RetOps, dl); 10623 } 10624 } 10625 10626 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10627 // opcode number of the comparison. 10628 int CompareOpc; 10629 bool isDot; 10630 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10631 return SDValue(); // Don't custom lower most intrinsics. 10632 10633 // If this is a non-dot comparison, make the VCMP node and we are done. 10634 if (!isDot) { 10635 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10636 Op.getOperand(1), Op.getOperand(2), 10637 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10638 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10639 } 10640 10641 // Create the PPCISD altivec 'dot' comparison node. 10642 SDValue Ops[] = { 10643 Op.getOperand(2), // LHS 10644 Op.getOperand(3), // RHS 10645 DAG.getConstant(CompareOpc, dl, MVT::i32) 10646 }; 10647 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10648 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10649 10650 // Now that we have the comparison, emit a copy from the CR to a GPR. 10651 // This is flagged to the above dot comparison. 10652 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10653 DAG.getRegister(PPC::CR6, MVT::i32), 10654 CompNode.getValue(1)); 10655 10656 // Unpack the result based on how the target uses it. 10657 unsigned BitNo; // Bit # of CR6. 10658 bool InvertBit; // Invert result? 10659 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10660 default: // Can't happen, don't crash on invalid number though. 10661 case 0: // Return the value of the EQ bit of CR6. 10662 BitNo = 0; InvertBit = false; 10663 break; 10664 case 1: // Return the inverted value of the EQ bit of CR6. 10665 BitNo = 0; InvertBit = true; 10666 break; 10667 case 2: // Return the value of the LT bit of CR6. 10668 BitNo = 2; InvertBit = false; 10669 break; 10670 case 3: // Return the inverted value of the LT bit of CR6. 10671 BitNo = 2; InvertBit = true; 10672 break; 10673 } 10674 10675 // Shift the bit into the low position. 10676 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10677 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10678 // Isolate the bit. 10679 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10680 DAG.getConstant(1, dl, MVT::i32)); 10681 10682 // If we are supposed to, toggle the bit. 10683 if (InvertBit) 10684 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10685 DAG.getConstant(1, dl, MVT::i32)); 10686 return Flags; 10687 } 10688 10689 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10690 SelectionDAG &DAG) const { 10691 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10692 // the beginning of the argument list. 10693 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10694 SDLoc DL(Op); 10695 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10696 case Intrinsic::ppc_cfence: { 10697 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10698 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10699 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10700 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10701 Op.getOperand(ArgStart + 1)), 10702 Op.getOperand(0)), 10703 0); 10704 } 10705 default: 10706 break; 10707 } 10708 return SDValue(); 10709 } 10710 10711 // Lower scalar BSWAP64 to xxbrd. 10712 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10713 SDLoc dl(Op); 10714 // MTVSRDD 10715 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10716 Op.getOperand(0)); 10717 // XXBRD 10718 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10719 // MFVSRD 10720 int VectorIndex = 0; 10721 if (Subtarget.isLittleEndian()) 10722 VectorIndex = 1; 10723 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10724 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10725 return Op; 10726 } 10727 10728 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10729 // compared to a value that is atomically loaded (atomic loads zero-extend). 10730 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10731 SelectionDAG &DAG) const { 10732 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10733 "Expecting an atomic compare-and-swap here."); 10734 SDLoc dl(Op); 10735 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10736 EVT MemVT = AtomicNode->getMemoryVT(); 10737 if (MemVT.getSizeInBits() >= 32) 10738 return Op; 10739 10740 SDValue CmpOp = Op.getOperand(2); 10741 // If this is already correctly zero-extended, leave it alone. 10742 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10743 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10744 return Op; 10745 10746 // Clear the high bits of the compare operand. 10747 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10748 SDValue NewCmpOp = 10749 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10750 DAG.getConstant(MaskVal, dl, MVT::i32)); 10751 10752 // Replace the existing compare operand with the properly zero-extended one. 10753 SmallVector<SDValue, 4> Ops; 10754 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10755 Ops.push_back(AtomicNode->getOperand(i)); 10756 Ops[2] = NewCmpOp; 10757 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10758 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10759 auto NodeTy = 10760 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10761 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10762 } 10763 10764 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10765 SelectionDAG &DAG) const { 10766 SDLoc dl(Op); 10767 // Create a stack slot that is 16-byte aligned. 10768 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10769 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10770 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10771 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10772 10773 // Store the input value into Value#0 of the stack slot. 10774 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10775 MachinePointerInfo()); 10776 // Load it out. 10777 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10778 } 10779 10780 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10781 SelectionDAG &DAG) const { 10782 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10783 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10784 10785 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10786 // We have legal lowering for constant indices but not for variable ones. 10787 if (!C) 10788 return SDValue(); 10789 10790 EVT VT = Op.getValueType(); 10791 SDLoc dl(Op); 10792 SDValue V1 = Op.getOperand(0); 10793 SDValue V2 = Op.getOperand(1); 10794 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10795 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10796 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10797 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10798 unsigned InsertAtElement = C->getZExtValue(); 10799 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10800 if (Subtarget.isLittleEndian()) { 10801 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10802 } 10803 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10804 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10805 } 10806 return Op; 10807 } 10808 10809 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10810 SelectionDAG &DAG) const { 10811 SDLoc dl(Op); 10812 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10813 SDValue LoadChain = LN->getChain(); 10814 SDValue BasePtr = LN->getBasePtr(); 10815 EVT VT = Op.getValueType(); 10816 10817 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10818 return Op; 10819 10820 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10821 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10822 // 2 or 4 vsx registers. 10823 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10824 "Type unsupported without MMA"); 10825 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10826 "Type unsupported without paired vector support"); 10827 Align Alignment = LN->getAlign(); 10828 SmallVector<SDValue, 4> Loads; 10829 SmallVector<SDValue, 4> LoadChains; 10830 unsigned NumVecs = VT.getSizeInBits() / 128; 10831 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10832 SDValue Load = 10833 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10834 LN->getPointerInfo().getWithOffset(Idx * 16), 10835 commonAlignment(Alignment, Idx * 16), 10836 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10837 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10838 DAG.getConstant(16, dl, BasePtr.getValueType())); 10839 Loads.push_back(Load); 10840 LoadChains.push_back(Load.getValue(1)); 10841 } 10842 if (Subtarget.isLittleEndian()) { 10843 std::reverse(Loads.begin(), Loads.end()); 10844 std::reverse(LoadChains.begin(), LoadChains.end()); 10845 } 10846 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10847 SDValue Value = 10848 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10849 dl, VT, Loads); 10850 SDValue RetOps[] = {Value, TF}; 10851 return DAG.getMergeValues(RetOps, dl); 10852 } 10853 10854 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10855 SelectionDAG &DAG) const { 10856 SDLoc dl(Op); 10857 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10858 SDValue StoreChain = SN->getChain(); 10859 SDValue BasePtr = SN->getBasePtr(); 10860 SDValue Value = SN->getValue(); 10861 EVT StoreVT = Value.getValueType(); 10862 10863 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10864 return Op; 10865 10866 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10867 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10868 // underlying registers individually. 10869 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10870 "Type unsupported without MMA"); 10871 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10872 "Type unsupported without paired vector support"); 10873 Align Alignment = SN->getAlign(); 10874 SmallVector<SDValue, 4> Stores; 10875 unsigned NumVecs = 2; 10876 if (StoreVT == MVT::v512i1) { 10877 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10878 NumVecs = 4; 10879 } 10880 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10881 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10882 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10883 DAG.getConstant(VecNum, dl, MVT::i64)); 10884 SDValue Store = 10885 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10886 SN->getPointerInfo().getWithOffset(Idx * 16), 10887 commonAlignment(Alignment, Idx * 16), 10888 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10889 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10890 DAG.getConstant(16, dl, BasePtr.getValueType())); 10891 Stores.push_back(Store); 10892 } 10893 SDValue TF = DAG.getTokenFactor(dl, Stores); 10894 return TF; 10895 } 10896 10897 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10898 SDLoc dl(Op); 10899 if (Op.getValueType() == MVT::v4i32) { 10900 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10901 10902 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10903 // +16 as shift amt. 10904 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10905 SDValue RHSSwap = // = vrlw RHS, 16 10906 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10907 10908 // Shrinkify inputs to v8i16. 10909 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10910 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10911 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10912 10913 // Low parts multiplied together, generating 32-bit results (we ignore the 10914 // top parts). 10915 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10916 LHS, RHS, DAG, dl, MVT::v4i32); 10917 10918 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10919 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10920 // Shift the high parts up 16 bits. 10921 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10922 Neg16, DAG, dl); 10923 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10924 } else if (Op.getValueType() == MVT::v16i8) { 10925 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10926 bool isLittleEndian = Subtarget.isLittleEndian(); 10927 10928 // Multiply the even 8-bit parts, producing 16-bit sums. 10929 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10930 LHS, RHS, DAG, dl, MVT::v8i16); 10931 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10932 10933 // Multiply the odd 8-bit parts, producing 16-bit sums. 10934 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10935 LHS, RHS, DAG, dl, MVT::v8i16); 10936 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10937 10938 // Merge the results together. Because vmuleub and vmuloub are 10939 // instructions with a big-endian bias, we must reverse the 10940 // element numbering and reverse the meaning of "odd" and "even" 10941 // when generating little endian code. 10942 int Ops[16]; 10943 for (unsigned i = 0; i != 8; ++i) { 10944 if (isLittleEndian) { 10945 Ops[i*2 ] = 2*i; 10946 Ops[i*2+1] = 2*i+16; 10947 } else { 10948 Ops[i*2 ] = 2*i+1; 10949 Ops[i*2+1] = 2*i+1+16; 10950 } 10951 } 10952 if (isLittleEndian) 10953 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10954 else 10955 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10956 } else { 10957 llvm_unreachable("Unknown mul to lower!"); 10958 } 10959 } 10960 10961 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10962 bool IsStrict = Op->isStrictFPOpcode(); 10963 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10964 !Subtarget.hasP9Vector()) 10965 return SDValue(); 10966 10967 return Op; 10968 } 10969 10970 // Custom lowering for fpext vf32 to v2f64 10971 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10972 10973 assert(Op.getOpcode() == ISD::FP_EXTEND && 10974 "Should only be called for ISD::FP_EXTEND"); 10975 10976 // FIXME: handle extends from half precision float vectors on P9. 10977 // We only want to custom lower an extend from v2f32 to v2f64. 10978 if (Op.getValueType() != MVT::v2f64 || 10979 Op.getOperand(0).getValueType() != MVT::v2f32) 10980 return SDValue(); 10981 10982 SDLoc dl(Op); 10983 SDValue Op0 = Op.getOperand(0); 10984 10985 switch (Op0.getOpcode()) { 10986 default: 10987 return SDValue(); 10988 case ISD::EXTRACT_SUBVECTOR: { 10989 assert(Op0.getNumOperands() == 2 && 10990 isa<ConstantSDNode>(Op0->getOperand(1)) && 10991 "Node should have 2 operands with second one being a constant!"); 10992 10993 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10994 return SDValue(); 10995 10996 // Custom lower is only done for high or low doubleword. 10997 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10998 if (Idx % 2 != 0) 10999 return SDValue(); 11000 11001 // Since input is v4f32, at this point Idx is either 0 or 2. 11002 // Shift to get the doubleword position we want. 11003 int DWord = Idx >> 1; 11004 11005 // High and low word positions are different on little endian. 11006 if (Subtarget.isLittleEndian()) 11007 DWord ^= 0x1; 11008 11009 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 11010 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 11011 } 11012 case ISD::FADD: 11013 case ISD::FMUL: 11014 case ISD::FSUB: { 11015 SDValue NewLoad[2]; 11016 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11017 // Ensure both input are loads. 11018 SDValue LdOp = Op0.getOperand(i); 11019 if (LdOp.getOpcode() != ISD::LOAD) 11020 return SDValue(); 11021 // Generate new load node. 11022 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11023 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11024 NewLoad[i] = DAG.getMemIntrinsicNode( 11025 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11026 LD->getMemoryVT(), LD->getMemOperand()); 11027 } 11028 SDValue NewOp = 11029 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11030 NewLoad[1], Op0.getNode()->getFlags()); 11031 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11032 DAG.getConstant(0, dl, MVT::i32)); 11033 } 11034 case ISD::LOAD: { 11035 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11036 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11037 SDValue NewLd = DAG.getMemIntrinsicNode( 11038 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11039 LD->getMemoryVT(), LD->getMemOperand()); 11040 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11041 DAG.getConstant(0, dl, MVT::i32)); 11042 } 11043 } 11044 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11045 } 11046 11047 /// LowerOperation - Provide custom lowering hooks for some operations. 11048 /// 11049 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11050 switch (Op.getOpcode()) { 11051 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11052 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11053 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11054 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11055 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11056 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11057 case ISD::SETCC: return LowerSETCC(Op, DAG); 11058 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11059 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11060 11061 // Variable argument lowering. 11062 case ISD::VASTART: return LowerVASTART(Op, DAG); 11063 case ISD::VAARG: return LowerVAARG(Op, DAG); 11064 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11065 11066 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11067 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11068 case ISD::GET_DYNAMIC_AREA_OFFSET: 11069 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11070 11071 // Exception handling lowering. 11072 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11073 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11074 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11075 11076 case ISD::LOAD: return LowerLOAD(Op, DAG); 11077 case ISD::STORE: return LowerSTORE(Op, DAG); 11078 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11079 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11080 case ISD::STRICT_FP_TO_UINT: 11081 case ISD::STRICT_FP_TO_SINT: 11082 case ISD::FP_TO_UINT: 11083 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11084 case ISD::STRICT_UINT_TO_FP: 11085 case ISD::STRICT_SINT_TO_FP: 11086 case ISD::UINT_TO_FP: 11087 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11088 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11089 11090 // Lower 64-bit shifts. 11091 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11092 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11093 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11094 11095 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11096 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11097 11098 // Vector-related lowering. 11099 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11100 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11101 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11102 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11103 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11104 case ISD::MUL: return LowerMUL(Op, DAG); 11105 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11106 case ISD::STRICT_FP_ROUND: 11107 case ISD::FP_ROUND: 11108 return LowerFP_ROUND(Op, DAG); 11109 case ISD::ROTL: return LowerROTL(Op, DAG); 11110 11111 // For counter-based loop handling. 11112 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11113 11114 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11115 11116 // Frame & Return address. 11117 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11118 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11119 11120 case ISD::INTRINSIC_VOID: 11121 return LowerINTRINSIC_VOID(Op, DAG); 11122 case ISD::BSWAP: 11123 return LowerBSWAP(Op, DAG); 11124 case ISD::ATOMIC_CMP_SWAP: 11125 return LowerATOMIC_CMP_SWAP(Op, DAG); 11126 } 11127 } 11128 11129 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11130 SmallVectorImpl<SDValue>&Results, 11131 SelectionDAG &DAG) const { 11132 SDLoc dl(N); 11133 switch (N->getOpcode()) { 11134 default: 11135 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11136 case ISD::READCYCLECOUNTER: { 11137 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11138 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11139 11140 Results.push_back( 11141 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11142 Results.push_back(RTB.getValue(2)); 11143 break; 11144 } 11145 case ISD::INTRINSIC_W_CHAIN: { 11146 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11147 Intrinsic::loop_decrement) 11148 break; 11149 11150 assert(N->getValueType(0) == MVT::i1 && 11151 "Unexpected result type for CTR decrement intrinsic"); 11152 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11153 N->getValueType(0)); 11154 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11155 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11156 N->getOperand(1)); 11157 11158 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11159 Results.push_back(NewInt.getValue(1)); 11160 break; 11161 } 11162 case ISD::VAARG: { 11163 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11164 return; 11165 11166 EVT VT = N->getValueType(0); 11167 11168 if (VT == MVT::i64) { 11169 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11170 11171 Results.push_back(NewNode); 11172 Results.push_back(NewNode.getValue(1)); 11173 } 11174 return; 11175 } 11176 case ISD::STRICT_FP_TO_SINT: 11177 case ISD::STRICT_FP_TO_UINT: 11178 case ISD::FP_TO_SINT: 11179 case ISD::FP_TO_UINT: 11180 // LowerFP_TO_INT() can only handle f32 and f64. 11181 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11182 MVT::ppcf128) 11183 return; 11184 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11185 return; 11186 case ISD::TRUNCATE: { 11187 if (!N->getValueType(0).isVector()) 11188 return; 11189 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11190 if (Lowered) 11191 Results.push_back(Lowered); 11192 return; 11193 } 11194 case ISD::FSHL: 11195 case ISD::FSHR: 11196 // Don't handle funnel shifts here. 11197 return; 11198 case ISD::BITCAST: 11199 // Don't handle bitcast here. 11200 return; 11201 case ISD::FP_EXTEND: 11202 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11203 if (Lowered) 11204 Results.push_back(Lowered); 11205 return; 11206 } 11207 } 11208 11209 //===----------------------------------------------------------------------===// 11210 // Other Lowering Code 11211 //===----------------------------------------------------------------------===// 11212 11213 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11214 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11215 Function *Func = Intrinsic::getDeclaration(M, Id); 11216 return Builder.CreateCall(Func, {}); 11217 } 11218 11219 // The mappings for emitLeading/TrailingFence is taken from 11220 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11221 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11222 Instruction *Inst, 11223 AtomicOrdering Ord) const { 11224 if (Ord == AtomicOrdering::SequentiallyConsistent) 11225 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11226 if (isReleaseOrStronger(Ord)) 11227 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11228 return nullptr; 11229 } 11230 11231 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11232 Instruction *Inst, 11233 AtomicOrdering Ord) const { 11234 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11235 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11236 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11237 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11238 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11239 return Builder.CreateCall( 11240 Intrinsic::getDeclaration( 11241 Builder.GetInsertBlock()->getParent()->getParent(), 11242 Intrinsic::ppc_cfence, {Inst->getType()}), 11243 {Inst}); 11244 // FIXME: Can use isync for rmw operation. 11245 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11246 } 11247 return nullptr; 11248 } 11249 11250 MachineBasicBlock * 11251 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11252 unsigned AtomicSize, 11253 unsigned BinOpcode, 11254 unsigned CmpOpcode, 11255 unsigned CmpPred) const { 11256 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11257 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11258 11259 auto LoadMnemonic = PPC::LDARX; 11260 auto StoreMnemonic = PPC::STDCX; 11261 switch (AtomicSize) { 11262 default: 11263 llvm_unreachable("Unexpected size of atomic entity"); 11264 case 1: 11265 LoadMnemonic = PPC::LBARX; 11266 StoreMnemonic = PPC::STBCX; 11267 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11268 break; 11269 case 2: 11270 LoadMnemonic = PPC::LHARX; 11271 StoreMnemonic = PPC::STHCX; 11272 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11273 break; 11274 case 4: 11275 LoadMnemonic = PPC::LWARX; 11276 StoreMnemonic = PPC::STWCX; 11277 break; 11278 case 8: 11279 LoadMnemonic = PPC::LDARX; 11280 StoreMnemonic = PPC::STDCX; 11281 break; 11282 } 11283 11284 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11285 MachineFunction *F = BB->getParent(); 11286 MachineFunction::iterator It = ++BB->getIterator(); 11287 11288 Register dest = MI.getOperand(0).getReg(); 11289 Register ptrA = MI.getOperand(1).getReg(); 11290 Register ptrB = MI.getOperand(2).getReg(); 11291 Register incr = MI.getOperand(3).getReg(); 11292 DebugLoc dl = MI.getDebugLoc(); 11293 11294 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11295 MachineBasicBlock *loop2MBB = 11296 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11297 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11298 F->insert(It, loopMBB); 11299 if (CmpOpcode) 11300 F->insert(It, loop2MBB); 11301 F->insert(It, exitMBB); 11302 exitMBB->splice(exitMBB->begin(), BB, 11303 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11304 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11305 11306 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11307 Register TmpReg = (!BinOpcode) ? incr : 11308 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11309 : &PPC::GPRCRegClass); 11310 11311 // thisMBB: 11312 // ... 11313 // fallthrough --> loopMBB 11314 BB->addSuccessor(loopMBB); 11315 11316 // loopMBB: 11317 // l[wd]arx dest, ptr 11318 // add r0, dest, incr 11319 // st[wd]cx. r0, ptr 11320 // bne- loopMBB 11321 // fallthrough --> exitMBB 11322 11323 // For max/min... 11324 // loopMBB: 11325 // l[wd]arx dest, ptr 11326 // cmpl?[wd] incr, dest 11327 // bgt exitMBB 11328 // loop2MBB: 11329 // st[wd]cx. dest, ptr 11330 // bne- loopMBB 11331 // fallthrough --> exitMBB 11332 11333 BB = loopMBB; 11334 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11335 .addReg(ptrA).addReg(ptrB); 11336 if (BinOpcode) 11337 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11338 if (CmpOpcode) { 11339 // Signed comparisons of byte or halfword values must be sign-extended. 11340 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11341 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11342 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11343 ExtReg).addReg(dest); 11344 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11345 .addReg(incr).addReg(ExtReg); 11346 } else 11347 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11348 .addReg(incr).addReg(dest); 11349 11350 BuildMI(BB, dl, TII->get(PPC::BCC)) 11351 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11352 BB->addSuccessor(loop2MBB); 11353 BB->addSuccessor(exitMBB); 11354 BB = loop2MBB; 11355 } 11356 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11357 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11358 BuildMI(BB, dl, TII->get(PPC::BCC)) 11359 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11360 BB->addSuccessor(loopMBB); 11361 BB->addSuccessor(exitMBB); 11362 11363 // exitMBB: 11364 // ... 11365 BB = exitMBB; 11366 return BB; 11367 } 11368 11369 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11370 MachineInstr &MI, MachineBasicBlock *BB, 11371 bool is8bit, // operation 11372 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11373 // If we support part-word atomic mnemonics, just use them 11374 if (Subtarget.hasPartwordAtomics()) 11375 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11376 CmpPred); 11377 11378 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11379 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11380 // In 64 bit mode we have to use 64 bits for addresses, even though the 11381 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11382 // registers without caring whether they're 32 or 64, but here we're 11383 // doing actual arithmetic on the addresses. 11384 bool is64bit = Subtarget.isPPC64(); 11385 bool isLittleEndian = Subtarget.isLittleEndian(); 11386 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11387 11388 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11389 MachineFunction *F = BB->getParent(); 11390 MachineFunction::iterator It = ++BB->getIterator(); 11391 11392 Register dest = MI.getOperand(0).getReg(); 11393 Register ptrA = MI.getOperand(1).getReg(); 11394 Register ptrB = MI.getOperand(2).getReg(); 11395 Register incr = MI.getOperand(3).getReg(); 11396 DebugLoc dl = MI.getDebugLoc(); 11397 11398 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11399 MachineBasicBlock *loop2MBB = 11400 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11401 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11402 F->insert(It, loopMBB); 11403 if (CmpOpcode) 11404 F->insert(It, loop2MBB); 11405 F->insert(It, exitMBB); 11406 exitMBB->splice(exitMBB->begin(), BB, 11407 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11408 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11409 11410 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11411 const TargetRegisterClass *RC = 11412 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11413 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11414 11415 Register PtrReg = RegInfo.createVirtualRegister(RC); 11416 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11417 Register ShiftReg = 11418 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11419 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11420 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11421 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11422 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11423 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11424 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11425 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11426 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11427 Register Ptr1Reg; 11428 Register TmpReg = 11429 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11430 11431 // thisMBB: 11432 // ... 11433 // fallthrough --> loopMBB 11434 BB->addSuccessor(loopMBB); 11435 11436 // The 4-byte load must be aligned, while a char or short may be 11437 // anywhere in the word. Hence all this nasty bookkeeping code. 11438 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11439 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11440 // xori shift, shift1, 24 [16] 11441 // rlwinm ptr, ptr1, 0, 0, 29 11442 // slw incr2, incr, shift 11443 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11444 // slw mask, mask2, shift 11445 // loopMBB: 11446 // lwarx tmpDest, ptr 11447 // add tmp, tmpDest, incr2 11448 // andc tmp2, tmpDest, mask 11449 // and tmp3, tmp, mask 11450 // or tmp4, tmp3, tmp2 11451 // stwcx. tmp4, ptr 11452 // bne- loopMBB 11453 // fallthrough --> exitMBB 11454 // srw dest, tmpDest, shift 11455 if (ptrA != ZeroReg) { 11456 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11457 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11458 .addReg(ptrA) 11459 .addReg(ptrB); 11460 } else { 11461 Ptr1Reg = ptrB; 11462 } 11463 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11464 // mode. 11465 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11466 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11467 .addImm(3) 11468 .addImm(27) 11469 .addImm(is8bit ? 28 : 27); 11470 if (!isLittleEndian) 11471 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11472 .addReg(Shift1Reg) 11473 .addImm(is8bit ? 24 : 16); 11474 if (is64bit) 11475 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11476 .addReg(Ptr1Reg) 11477 .addImm(0) 11478 .addImm(61); 11479 else 11480 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11481 .addReg(Ptr1Reg) 11482 .addImm(0) 11483 .addImm(0) 11484 .addImm(29); 11485 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11486 if (is8bit) 11487 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11488 else { 11489 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11490 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11491 .addReg(Mask3Reg) 11492 .addImm(65535); 11493 } 11494 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11495 .addReg(Mask2Reg) 11496 .addReg(ShiftReg); 11497 11498 BB = loopMBB; 11499 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11500 .addReg(ZeroReg) 11501 .addReg(PtrReg); 11502 if (BinOpcode) 11503 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11504 .addReg(Incr2Reg) 11505 .addReg(TmpDestReg); 11506 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11507 .addReg(TmpDestReg) 11508 .addReg(MaskReg); 11509 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11510 if (CmpOpcode) { 11511 // For unsigned comparisons, we can directly compare the shifted values. 11512 // For signed comparisons we shift and sign extend. 11513 Register SReg = RegInfo.createVirtualRegister(GPRC); 11514 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11515 .addReg(TmpDestReg) 11516 .addReg(MaskReg); 11517 unsigned ValueReg = SReg; 11518 unsigned CmpReg = Incr2Reg; 11519 if (CmpOpcode == PPC::CMPW) { 11520 ValueReg = RegInfo.createVirtualRegister(GPRC); 11521 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11522 .addReg(SReg) 11523 .addReg(ShiftReg); 11524 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11525 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11526 .addReg(ValueReg); 11527 ValueReg = ValueSReg; 11528 CmpReg = incr; 11529 } 11530 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11531 .addReg(CmpReg) 11532 .addReg(ValueReg); 11533 BuildMI(BB, dl, TII->get(PPC::BCC)) 11534 .addImm(CmpPred) 11535 .addReg(PPC::CR0) 11536 .addMBB(exitMBB); 11537 BB->addSuccessor(loop2MBB); 11538 BB->addSuccessor(exitMBB); 11539 BB = loop2MBB; 11540 } 11541 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11542 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11543 .addReg(Tmp4Reg) 11544 .addReg(ZeroReg) 11545 .addReg(PtrReg); 11546 BuildMI(BB, dl, TII->get(PPC::BCC)) 11547 .addImm(PPC::PRED_NE) 11548 .addReg(PPC::CR0) 11549 .addMBB(loopMBB); 11550 BB->addSuccessor(loopMBB); 11551 BB->addSuccessor(exitMBB); 11552 11553 // exitMBB: 11554 // ... 11555 BB = exitMBB; 11556 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11557 .addReg(TmpDestReg) 11558 .addReg(ShiftReg); 11559 return BB; 11560 } 11561 11562 llvm::MachineBasicBlock * 11563 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11564 MachineBasicBlock *MBB) const { 11565 DebugLoc DL = MI.getDebugLoc(); 11566 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11567 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11568 11569 MachineFunction *MF = MBB->getParent(); 11570 MachineRegisterInfo &MRI = MF->getRegInfo(); 11571 11572 const BasicBlock *BB = MBB->getBasicBlock(); 11573 MachineFunction::iterator I = ++MBB->getIterator(); 11574 11575 Register DstReg = MI.getOperand(0).getReg(); 11576 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11577 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11578 Register mainDstReg = MRI.createVirtualRegister(RC); 11579 Register restoreDstReg = MRI.createVirtualRegister(RC); 11580 11581 MVT PVT = getPointerTy(MF->getDataLayout()); 11582 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11583 "Invalid Pointer Size!"); 11584 // For v = setjmp(buf), we generate 11585 // 11586 // thisMBB: 11587 // SjLjSetup mainMBB 11588 // bl mainMBB 11589 // v_restore = 1 11590 // b sinkMBB 11591 // 11592 // mainMBB: 11593 // buf[LabelOffset] = LR 11594 // v_main = 0 11595 // 11596 // sinkMBB: 11597 // v = phi(main, restore) 11598 // 11599 11600 MachineBasicBlock *thisMBB = MBB; 11601 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11602 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11603 MF->insert(I, mainMBB); 11604 MF->insert(I, sinkMBB); 11605 11606 MachineInstrBuilder MIB; 11607 11608 // Transfer the remainder of BB and its successor edges to sinkMBB. 11609 sinkMBB->splice(sinkMBB->begin(), MBB, 11610 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11611 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11612 11613 // Note that the structure of the jmp_buf used here is not compatible 11614 // with that used by libc, and is not designed to be. Specifically, it 11615 // stores only those 'reserved' registers that LLVM does not otherwise 11616 // understand how to spill. Also, by convention, by the time this 11617 // intrinsic is called, Clang has already stored the frame address in the 11618 // first slot of the buffer and stack address in the third. Following the 11619 // X86 target code, we'll store the jump address in the second slot. We also 11620 // need to save the TOC pointer (R2) to handle jumps between shared 11621 // libraries, and that will be stored in the fourth slot. The thread 11622 // identifier (R13) is not affected. 11623 11624 // thisMBB: 11625 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11626 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11627 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11628 11629 // Prepare IP either in reg. 11630 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11631 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11632 Register BufReg = MI.getOperand(1).getReg(); 11633 11634 if (Subtarget.is64BitELFABI()) { 11635 setUsesTOCBasePtr(*MBB->getParent()); 11636 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11637 .addReg(PPC::X2) 11638 .addImm(TOCOffset) 11639 .addReg(BufReg) 11640 .cloneMemRefs(MI); 11641 } 11642 11643 // Naked functions never have a base pointer, and so we use r1. For all 11644 // other functions, this decision must be delayed until during PEI. 11645 unsigned BaseReg; 11646 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11647 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11648 else 11649 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11650 11651 MIB = BuildMI(*thisMBB, MI, DL, 11652 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11653 .addReg(BaseReg) 11654 .addImm(BPOffset) 11655 .addReg(BufReg) 11656 .cloneMemRefs(MI); 11657 11658 // Setup 11659 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11660 MIB.addRegMask(TRI->getNoPreservedMask()); 11661 11662 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11663 11664 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11665 .addMBB(mainMBB); 11666 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11667 11668 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11669 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11670 11671 // mainMBB: 11672 // mainDstReg = 0 11673 MIB = 11674 BuildMI(mainMBB, DL, 11675 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11676 11677 // Store IP 11678 if (Subtarget.isPPC64()) { 11679 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11680 .addReg(LabelReg) 11681 .addImm(LabelOffset) 11682 .addReg(BufReg); 11683 } else { 11684 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11685 .addReg(LabelReg) 11686 .addImm(LabelOffset) 11687 .addReg(BufReg); 11688 } 11689 MIB.cloneMemRefs(MI); 11690 11691 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11692 mainMBB->addSuccessor(sinkMBB); 11693 11694 // sinkMBB: 11695 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11696 TII->get(PPC::PHI), DstReg) 11697 .addReg(mainDstReg).addMBB(mainMBB) 11698 .addReg(restoreDstReg).addMBB(thisMBB); 11699 11700 MI.eraseFromParent(); 11701 return sinkMBB; 11702 } 11703 11704 MachineBasicBlock * 11705 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11706 MachineBasicBlock *MBB) const { 11707 DebugLoc DL = MI.getDebugLoc(); 11708 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11709 11710 MachineFunction *MF = MBB->getParent(); 11711 MachineRegisterInfo &MRI = MF->getRegInfo(); 11712 11713 MVT PVT = getPointerTy(MF->getDataLayout()); 11714 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11715 "Invalid Pointer Size!"); 11716 11717 const TargetRegisterClass *RC = 11718 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11719 Register Tmp = MRI.createVirtualRegister(RC); 11720 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11721 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11722 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11723 unsigned BP = 11724 (PVT == MVT::i64) 11725 ? PPC::X30 11726 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11727 : PPC::R30); 11728 11729 MachineInstrBuilder MIB; 11730 11731 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11732 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11733 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11734 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11735 11736 Register BufReg = MI.getOperand(0).getReg(); 11737 11738 // Reload FP (the jumped-to function may not have had a 11739 // frame pointer, and if so, then its r31 will be restored 11740 // as necessary). 11741 if (PVT == MVT::i64) { 11742 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11743 .addImm(0) 11744 .addReg(BufReg); 11745 } else { 11746 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11747 .addImm(0) 11748 .addReg(BufReg); 11749 } 11750 MIB.cloneMemRefs(MI); 11751 11752 // Reload IP 11753 if (PVT == MVT::i64) { 11754 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11755 .addImm(LabelOffset) 11756 .addReg(BufReg); 11757 } else { 11758 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11759 .addImm(LabelOffset) 11760 .addReg(BufReg); 11761 } 11762 MIB.cloneMemRefs(MI); 11763 11764 // Reload SP 11765 if (PVT == MVT::i64) { 11766 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11767 .addImm(SPOffset) 11768 .addReg(BufReg); 11769 } else { 11770 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11771 .addImm(SPOffset) 11772 .addReg(BufReg); 11773 } 11774 MIB.cloneMemRefs(MI); 11775 11776 // Reload BP 11777 if (PVT == MVT::i64) { 11778 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11779 .addImm(BPOffset) 11780 .addReg(BufReg); 11781 } else { 11782 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11783 .addImm(BPOffset) 11784 .addReg(BufReg); 11785 } 11786 MIB.cloneMemRefs(MI); 11787 11788 // Reload TOC 11789 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11790 setUsesTOCBasePtr(*MBB->getParent()); 11791 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11792 .addImm(TOCOffset) 11793 .addReg(BufReg) 11794 .cloneMemRefs(MI); 11795 } 11796 11797 // Jump 11798 BuildMI(*MBB, MI, DL, 11799 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11800 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11801 11802 MI.eraseFromParent(); 11803 return MBB; 11804 } 11805 11806 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11807 // If the function specifically requests inline stack probes, emit them. 11808 if (MF.getFunction().hasFnAttribute("probe-stack")) 11809 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11810 "inline-asm"; 11811 return false; 11812 } 11813 11814 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11815 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11816 unsigned StackAlign = TFI->getStackAlignment(); 11817 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11818 "Unexpected stack alignment"); 11819 // The default stack probe size is 4096 if the function has no 11820 // stack-probe-size attribute. 11821 unsigned StackProbeSize = 4096; 11822 const Function &Fn = MF.getFunction(); 11823 if (Fn.hasFnAttribute("stack-probe-size")) 11824 Fn.getFnAttribute("stack-probe-size") 11825 .getValueAsString() 11826 .getAsInteger(0, StackProbeSize); 11827 // Round down to the stack alignment. 11828 StackProbeSize &= ~(StackAlign - 1); 11829 return StackProbeSize ? StackProbeSize : StackAlign; 11830 } 11831 11832 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11833 // into three phases. In the first phase, it uses pseudo instruction 11834 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11835 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11836 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11837 // MaxCallFrameSize so that it can calculate correct data area pointer. 11838 MachineBasicBlock * 11839 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11840 MachineBasicBlock *MBB) const { 11841 const bool isPPC64 = Subtarget.isPPC64(); 11842 MachineFunction *MF = MBB->getParent(); 11843 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11844 DebugLoc DL = MI.getDebugLoc(); 11845 const unsigned ProbeSize = getStackProbeSize(*MF); 11846 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11847 MachineRegisterInfo &MRI = MF->getRegInfo(); 11848 // The CFG of probing stack looks as 11849 // +-----+ 11850 // | MBB | 11851 // +--+--+ 11852 // | 11853 // +----v----+ 11854 // +--->+ TestMBB +---+ 11855 // | +----+----+ | 11856 // | | | 11857 // | +-----v----+ | 11858 // +---+ BlockMBB | | 11859 // +----------+ | 11860 // | 11861 // +---------+ | 11862 // | TailMBB +<--+ 11863 // +---------+ 11864 // In MBB, calculate previous frame pointer and final stack pointer. 11865 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11866 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11867 // TailMBB is spliced via \p MI. 11868 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11869 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11870 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11871 11872 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11873 MF->insert(MBBIter, TestMBB); 11874 MF->insert(MBBIter, BlockMBB); 11875 MF->insert(MBBIter, TailMBB); 11876 11877 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11878 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11879 11880 Register DstReg = MI.getOperand(0).getReg(); 11881 Register NegSizeReg = MI.getOperand(1).getReg(); 11882 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11883 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11884 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11885 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11886 11887 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11888 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11889 // NegSize. 11890 unsigned ProbeOpc; 11891 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11892 ProbeOpc = 11893 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11894 else 11895 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11896 // and NegSizeReg will be allocated in the same phyreg to avoid 11897 // redundant copy when NegSizeReg has only one use which is current MI and 11898 // will be replaced by PREPARE_PROBED_ALLOCA then. 11899 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11900 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11901 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11902 .addDef(ActualNegSizeReg) 11903 .addReg(NegSizeReg) 11904 .add(MI.getOperand(2)) 11905 .add(MI.getOperand(3)); 11906 11907 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11908 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11909 FinalStackPtr) 11910 .addReg(SPReg) 11911 .addReg(ActualNegSizeReg); 11912 11913 // Materialize a scratch register for update. 11914 int64_t NegProbeSize = -(int64_t)ProbeSize; 11915 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11916 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11917 if (!isInt<16>(NegProbeSize)) { 11918 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11919 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11920 .addImm(NegProbeSize >> 16); 11921 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11922 ScratchReg) 11923 .addReg(TempReg) 11924 .addImm(NegProbeSize & 0xFFFF); 11925 } else 11926 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11927 .addImm(NegProbeSize); 11928 11929 { 11930 // Probing leading residual part. 11931 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11932 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11933 .addReg(ActualNegSizeReg) 11934 .addReg(ScratchReg); 11935 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11936 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11937 .addReg(Div) 11938 .addReg(ScratchReg); 11939 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11940 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11941 .addReg(Mul) 11942 .addReg(ActualNegSizeReg); 11943 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11944 .addReg(FramePointer) 11945 .addReg(SPReg) 11946 .addReg(NegMod); 11947 } 11948 11949 { 11950 // Remaining part should be multiple of ProbeSize. 11951 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11952 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11953 .addReg(SPReg) 11954 .addReg(FinalStackPtr); 11955 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11956 .addImm(PPC::PRED_EQ) 11957 .addReg(CmpResult) 11958 .addMBB(TailMBB); 11959 TestMBB->addSuccessor(BlockMBB); 11960 TestMBB->addSuccessor(TailMBB); 11961 } 11962 11963 { 11964 // Touch the block. 11965 // |P...|P...|P... 11966 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11967 .addReg(FramePointer) 11968 .addReg(SPReg) 11969 .addReg(ScratchReg); 11970 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11971 BlockMBB->addSuccessor(TestMBB); 11972 } 11973 11974 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11975 // DYNAREAOFFSET pseudo instruction to get the future result. 11976 Register MaxCallFrameSizeReg = 11977 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11978 BuildMI(TailMBB, DL, 11979 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11980 MaxCallFrameSizeReg) 11981 .add(MI.getOperand(2)) 11982 .add(MI.getOperand(3)); 11983 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11984 .addReg(SPReg) 11985 .addReg(MaxCallFrameSizeReg); 11986 11987 // Splice instructions after MI to TailMBB. 11988 TailMBB->splice(TailMBB->end(), MBB, 11989 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11990 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11991 MBB->addSuccessor(TestMBB); 11992 11993 // Delete the pseudo instruction. 11994 MI.eraseFromParent(); 11995 11996 ++NumDynamicAllocaProbed; 11997 return TailMBB; 11998 } 11999 12000 MachineBasicBlock * 12001 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12002 MachineBasicBlock *BB) const { 12003 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12004 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12005 if (Subtarget.is64BitELFABI() && 12006 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12007 !Subtarget.isUsingPCRelativeCalls()) { 12008 // Call lowering should have added an r2 operand to indicate a dependence 12009 // on the TOC base pointer value. It can't however, because there is no 12010 // way to mark the dependence as implicit there, and so the stackmap code 12011 // will confuse it with a regular operand. Instead, add the dependence 12012 // here. 12013 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12014 } 12015 12016 return emitPatchPoint(MI, BB); 12017 } 12018 12019 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12020 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12021 return emitEHSjLjSetJmp(MI, BB); 12022 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12023 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12024 return emitEHSjLjLongJmp(MI, BB); 12025 } 12026 12027 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12028 12029 // To "insert" these instructions we actually have to insert their 12030 // control-flow patterns. 12031 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12032 MachineFunction::iterator It = ++BB->getIterator(); 12033 12034 MachineFunction *F = BB->getParent(); 12035 12036 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12037 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12038 MI.getOpcode() == PPC::SELECT_I8) { 12039 SmallVector<MachineOperand, 2> Cond; 12040 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12041 MI.getOpcode() == PPC::SELECT_CC_I8) 12042 Cond.push_back(MI.getOperand(4)); 12043 else 12044 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12045 Cond.push_back(MI.getOperand(1)); 12046 12047 DebugLoc dl = MI.getDebugLoc(); 12048 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12049 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12050 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12051 MI.getOpcode() == PPC::SELECT_CC_F8 || 12052 MI.getOpcode() == PPC::SELECT_CC_F16 || 12053 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12054 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12055 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12056 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12057 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12058 MI.getOpcode() == PPC::SELECT_CC_SPE || 12059 MI.getOpcode() == PPC::SELECT_F4 || 12060 MI.getOpcode() == PPC::SELECT_F8 || 12061 MI.getOpcode() == PPC::SELECT_F16 || 12062 MI.getOpcode() == PPC::SELECT_SPE || 12063 MI.getOpcode() == PPC::SELECT_SPE4 || 12064 MI.getOpcode() == PPC::SELECT_VRRC || 12065 MI.getOpcode() == PPC::SELECT_VSFRC || 12066 MI.getOpcode() == PPC::SELECT_VSSRC || 12067 MI.getOpcode() == PPC::SELECT_VSRC) { 12068 // The incoming instruction knows the destination vreg to set, the 12069 // condition code register to branch on, the true/false values to 12070 // select between, and a branch opcode to use. 12071 12072 // thisMBB: 12073 // ... 12074 // TrueVal = ... 12075 // cmpTY ccX, r1, r2 12076 // bCC copy1MBB 12077 // fallthrough --> copy0MBB 12078 MachineBasicBlock *thisMBB = BB; 12079 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12080 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12081 DebugLoc dl = MI.getDebugLoc(); 12082 F->insert(It, copy0MBB); 12083 F->insert(It, sinkMBB); 12084 12085 // Transfer the remainder of BB and its successor edges to sinkMBB. 12086 sinkMBB->splice(sinkMBB->begin(), BB, 12087 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12088 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12089 12090 // Next, add the true and fallthrough blocks as its successors. 12091 BB->addSuccessor(copy0MBB); 12092 BB->addSuccessor(sinkMBB); 12093 12094 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12095 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12096 MI.getOpcode() == PPC::SELECT_F16 || 12097 MI.getOpcode() == PPC::SELECT_SPE4 || 12098 MI.getOpcode() == PPC::SELECT_SPE || 12099 MI.getOpcode() == PPC::SELECT_VRRC || 12100 MI.getOpcode() == PPC::SELECT_VSFRC || 12101 MI.getOpcode() == PPC::SELECT_VSSRC || 12102 MI.getOpcode() == PPC::SELECT_VSRC) { 12103 BuildMI(BB, dl, TII->get(PPC::BC)) 12104 .addReg(MI.getOperand(1).getReg()) 12105 .addMBB(sinkMBB); 12106 } else { 12107 unsigned SelectPred = MI.getOperand(4).getImm(); 12108 BuildMI(BB, dl, TII->get(PPC::BCC)) 12109 .addImm(SelectPred) 12110 .addReg(MI.getOperand(1).getReg()) 12111 .addMBB(sinkMBB); 12112 } 12113 12114 // copy0MBB: 12115 // %FalseValue = ... 12116 // # fallthrough to sinkMBB 12117 BB = copy0MBB; 12118 12119 // Update machine-CFG edges 12120 BB->addSuccessor(sinkMBB); 12121 12122 // sinkMBB: 12123 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12124 // ... 12125 BB = sinkMBB; 12126 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12127 .addReg(MI.getOperand(3).getReg()) 12128 .addMBB(copy0MBB) 12129 .addReg(MI.getOperand(2).getReg()) 12130 .addMBB(thisMBB); 12131 } else if (MI.getOpcode() == PPC::ReadTB) { 12132 // To read the 64-bit time-base register on a 32-bit target, we read the 12133 // two halves. Should the counter have wrapped while it was being read, we 12134 // need to try again. 12135 // ... 12136 // readLoop: 12137 // mfspr Rx,TBU # load from TBU 12138 // mfspr Ry,TB # load from TB 12139 // mfspr Rz,TBU # load from TBU 12140 // cmpw crX,Rx,Rz # check if 'old'='new' 12141 // bne readLoop # branch if they're not equal 12142 // ... 12143 12144 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12145 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12146 DebugLoc dl = MI.getDebugLoc(); 12147 F->insert(It, readMBB); 12148 F->insert(It, sinkMBB); 12149 12150 // Transfer the remainder of BB and its successor edges to sinkMBB. 12151 sinkMBB->splice(sinkMBB->begin(), BB, 12152 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12153 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12154 12155 BB->addSuccessor(readMBB); 12156 BB = readMBB; 12157 12158 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12159 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12160 Register LoReg = MI.getOperand(0).getReg(); 12161 Register HiReg = MI.getOperand(1).getReg(); 12162 12163 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12164 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12165 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12166 12167 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12168 12169 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12170 .addReg(HiReg) 12171 .addReg(ReadAgainReg); 12172 BuildMI(BB, dl, TII->get(PPC::BCC)) 12173 .addImm(PPC::PRED_NE) 12174 .addReg(CmpReg) 12175 .addMBB(readMBB); 12176 12177 BB->addSuccessor(readMBB); 12178 BB->addSuccessor(sinkMBB); 12179 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12180 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12181 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12182 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12183 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12184 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12185 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12186 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12187 12188 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12189 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12190 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12191 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12192 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12193 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12194 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12195 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12196 12197 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12198 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12199 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12200 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12201 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12202 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12203 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12204 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12205 12206 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12207 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12208 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12209 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12210 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12211 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12212 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12213 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12214 12215 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12216 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12217 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12218 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12219 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12220 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12221 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12222 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12223 12224 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12225 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12226 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12227 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12228 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12229 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12230 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12231 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12232 12233 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12234 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12235 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12236 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12237 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12238 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12239 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12240 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12241 12242 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12243 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12244 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12245 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12246 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12247 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12248 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12249 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12250 12251 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12252 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12253 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12254 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12255 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12256 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12257 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12258 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12259 12260 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12261 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12262 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12263 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12264 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12265 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12266 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12267 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12268 12269 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12270 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12271 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12272 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12273 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12274 BB = EmitAtomicBinary(MI, BB, 4, 0); 12275 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12276 BB = EmitAtomicBinary(MI, BB, 8, 0); 12277 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12278 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12279 (Subtarget.hasPartwordAtomics() && 12280 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12281 (Subtarget.hasPartwordAtomics() && 12282 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12283 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12284 12285 auto LoadMnemonic = PPC::LDARX; 12286 auto StoreMnemonic = PPC::STDCX; 12287 switch (MI.getOpcode()) { 12288 default: 12289 llvm_unreachable("Compare and swap of unknown size"); 12290 case PPC::ATOMIC_CMP_SWAP_I8: 12291 LoadMnemonic = PPC::LBARX; 12292 StoreMnemonic = PPC::STBCX; 12293 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12294 break; 12295 case PPC::ATOMIC_CMP_SWAP_I16: 12296 LoadMnemonic = PPC::LHARX; 12297 StoreMnemonic = PPC::STHCX; 12298 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12299 break; 12300 case PPC::ATOMIC_CMP_SWAP_I32: 12301 LoadMnemonic = PPC::LWARX; 12302 StoreMnemonic = PPC::STWCX; 12303 break; 12304 case PPC::ATOMIC_CMP_SWAP_I64: 12305 LoadMnemonic = PPC::LDARX; 12306 StoreMnemonic = PPC::STDCX; 12307 break; 12308 } 12309 Register dest = MI.getOperand(0).getReg(); 12310 Register ptrA = MI.getOperand(1).getReg(); 12311 Register ptrB = MI.getOperand(2).getReg(); 12312 Register oldval = MI.getOperand(3).getReg(); 12313 Register newval = MI.getOperand(4).getReg(); 12314 DebugLoc dl = MI.getDebugLoc(); 12315 12316 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12317 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12318 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12319 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12320 F->insert(It, loop1MBB); 12321 F->insert(It, loop2MBB); 12322 F->insert(It, midMBB); 12323 F->insert(It, exitMBB); 12324 exitMBB->splice(exitMBB->begin(), BB, 12325 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12326 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12327 12328 // thisMBB: 12329 // ... 12330 // fallthrough --> loopMBB 12331 BB->addSuccessor(loop1MBB); 12332 12333 // loop1MBB: 12334 // l[bhwd]arx dest, ptr 12335 // cmp[wd] dest, oldval 12336 // bne- midMBB 12337 // loop2MBB: 12338 // st[bhwd]cx. newval, ptr 12339 // bne- loopMBB 12340 // b exitBB 12341 // midMBB: 12342 // st[bhwd]cx. dest, ptr 12343 // exitBB: 12344 BB = loop1MBB; 12345 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12346 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12347 .addReg(oldval) 12348 .addReg(dest); 12349 BuildMI(BB, dl, TII->get(PPC::BCC)) 12350 .addImm(PPC::PRED_NE) 12351 .addReg(PPC::CR0) 12352 .addMBB(midMBB); 12353 BB->addSuccessor(loop2MBB); 12354 BB->addSuccessor(midMBB); 12355 12356 BB = loop2MBB; 12357 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12358 .addReg(newval) 12359 .addReg(ptrA) 12360 .addReg(ptrB); 12361 BuildMI(BB, dl, TII->get(PPC::BCC)) 12362 .addImm(PPC::PRED_NE) 12363 .addReg(PPC::CR0) 12364 .addMBB(loop1MBB); 12365 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12366 BB->addSuccessor(loop1MBB); 12367 BB->addSuccessor(exitMBB); 12368 12369 BB = midMBB; 12370 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12371 .addReg(dest) 12372 .addReg(ptrA) 12373 .addReg(ptrB); 12374 BB->addSuccessor(exitMBB); 12375 12376 // exitMBB: 12377 // ... 12378 BB = exitMBB; 12379 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12380 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12381 // We must use 64-bit registers for addresses when targeting 64-bit, 12382 // since we're actually doing arithmetic on them. Other registers 12383 // can be 32-bit. 12384 bool is64bit = Subtarget.isPPC64(); 12385 bool isLittleEndian = Subtarget.isLittleEndian(); 12386 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12387 12388 Register dest = MI.getOperand(0).getReg(); 12389 Register ptrA = MI.getOperand(1).getReg(); 12390 Register ptrB = MI.getOperand(2).getReg(); 12391 Register oldval = MI.getOperand(3).getReg(); 12392 Register newval = MI.getOperand(4).getReg(); 12393 DebugLoc dl = MI.getDebugLoc(); 12394 12395 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12396 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12397 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12398 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12399 F->insert(It, loop1MBB); 12400 F->insert(It, loop2MBB); 12401 F->insert(It, midMBB); 12402 F->insert(It, exitMBB); 12403 exitMBB->splice(exitMBB->begin(), BB, 12404 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12405 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12406 12407 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12408 const TargetRegisterClass *RC = 12409 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12410 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12411 12412 Register PtrReg = RegInfo.createVirtualRegister(RC); 12413 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12414 Register ShiftReg = 12415 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12416 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12417 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12418 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12419 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12420 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12421 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12422 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12423 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12424 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12425 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12426 Register Ptr1Reg; 12427 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12428 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12429 // thisMBB: 12430 // ... 12431 // fallthrough --> loopMBB 12432 BB->addSuccessor(loop1MBB); 12433 12434 // The 4-byte load must be aligned, while a char or short may be 12435 // anywhere in the word. Hence all this nasty bookkeeping code. 12436 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12437 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12438 // xori shift, shift1, 24 [16] 12439 // rlwinm ptr, ptr1, 0, 0, 29 12440 // slw newval2, newval, shift 12441 // slw oldval2, oldval,shift 12442 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12443 // slw mask, mask2, shift 12444 // and newval3, newval2, mask 12445 // and oldval3, oldval2, mask 12446 // loop1MBB: 12447 // lwarx tmpDest, ptr 12448 // and tmp, tmpDest, mask 12449 // cmpw tmp, oldval3 12450 // bne- midMBB 12451 // loop2MBB: 12452 // andc tmp2, tmpDest, mask 12453 // or tmp4, tmp2, newval3 12454 // stwcx. tmp4, ptr 12455 // bne- loop1MBB 12456 // b exitBB 12457 // midMBB: 12458 // stwcx. tmpDest, ptr 12459 // exitBB: 12460 // srw dest, tmpDest, shift 12461 if (ptrA != ZeroReg) { 12462 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12463 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12464 .addReg(ptrA) 12465 .addReg(ptrB); 12466 } else { 12467 Ptr1Reg = ptrB; 12468 } 12469 12470 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12471 // mode. 12472 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12473 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12474 .addImm(3) 12475 .addImm(27) 12476 .addImm(is8bit ? 28 : 27); 12477 if (!isLittleEndian) 12478 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12479 .addReg(Shift1Reg) 12480 .addImm(is8bit ? 24 : 16); 12481 if (is64bit) 12482 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12483 .addReg(Ptr1Reg) 12484 .addImm(0) 12485 .addImm(61); 12486 else 12487 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12488 .addReg(Ptr1Reg) 12489 .addImm(0) 12490 .addImm(0) 12491 .addImm(29); 12492 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12493 .addReg(newval) 12494 .addReg(ShiftReg); 12495 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12496 .addReg(oldval) 12497 .addReg(ShiftReg); 12498 if (is8bit) 12499 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12500 else { 12501 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12502 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12503 .addReg(Mask3Reg) 12504 .addImm(65535); 12505 } 12506 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12507 .addReg(Mask2Reg) 12508 .addReg(ShiftReg); 12509 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12510 .addReg(NewVal2Reg) 12511 .addReg(MaskReg); 12512 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12513 .addReg(OldVal2Reg) 12514 .addReg(MaskReg); 12515 12516 BB = loop1MBB; 12517 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12518 .addReg(ZeroReg) 12519 .addReg(PtrReg); 12520 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12521 .addReg(TmpDestReg) 12522 .addReg(MaskReg); 12523 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12524 .addReg(TmpReg) 12525 .addReg(OldVal3Reg); 12526 BuildMI(BB, dl, TII->get(PPC::BCC)) 12527 .addImm(PPC::PRED_NE) 12528 .addReg(PPC::CR0) 12529 .addMBB(midMBB); 12530 BB->addSuccessor(loop2MBB); 12531 BB->addSuccessor(midMBB); 12532 12533 BB = loop2MBB; 12534 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12535 .addReg(TmpDestReg) 12536 .addReg(MaskReg); 12537 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12538 .addReg(Tmp2Reg) 12539 .addReg(NewVal3Reg); 12540 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12541 .addReg(Tmp4Reg) 12542 .addReg(ZeroReg) 12543 .addReg(PtrReg); 12544 BuildMI(BB, dl, TII->get(PPC::BCC)) 12545 .addImm(PPC::PRED_NE) 12546 .addReg(PPC::CR0) 12547 .addMBB(loop1MBB); 12548 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12549 BB->addSuccessor(loop1MBB); 12550 BB->addSuccessor(exitMBB); 12551 12552 BB = midMBB; 12553 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12554 .addReg(TmpDestReg) 12555 .addReg(ZeroReg) 12556 .addReg(PtrReg); 12557 BB->addSuccessor(exitMBB); 12558 12559 // exitMBB: 12560 // ... 12561 BB = exitMBB; 12562 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12563 .addReg(TmpReg) 12564 .addReg(ShiftReg); 12565 } else if (MI.getOpcode() == PPC::FADDrtz) { 12566 // This pseudo performs an FADD with rounding mode temporarily forced 12567 // to round-to-zero. We emit this via custom inserter since the FPSCR 12568 // is not modeled at the SelectionDAG level. 12569 Register Dest = MI.getOperand(0).getReg(); 12570 Register Src1 = MI.getOperand(1).getReg(); 12571 Register Src2 = MI.getOperand(2).getReg(); 12572 DebugLoc dl = MI.getDebugLoc(); 12573 12574 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12575 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12576 12577 // Save FPSCR value. 12578 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12579 12580 // Set rounding mode to round-to-zero. 12581 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12582 .addImm(31) 12583 .addReg(PPC::RM, RegState::ImplicitDefine); 12584 12585 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12586 .addImm(30) 12587 .addReg(PPC::RM, RegState::ImplicitDefine); 12588 12589 // Perform addition. 12590 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12591 .addReg(Src1) 12592 .addReg(Src2); 12593 if (MI.getFlag(MachineInstr::NoFPExcept)) 12594 MIB.setMIFlag(MachineInstr::NoFPExcept); 12595 12596 // Restore FPSCR value. 12597 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12598 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12599 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12600 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12601 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12602 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12603 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12604 ? PPC::ANDI8_rec 12605 : PPC::ANDI_rec; 12606 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12607 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12608 12609 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12610 Register Dest = RegInfo.createVirtualRegister( 12611 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12612 12613 DebugLoc Dl = MI.getDebugLoc(); 12614 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12615 .addReg(MI.getOperand(1).getReg()) 12616 .addImm(1); 12617 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12618 MI.getOperand(0).getReg()) 12619 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12620 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12621 DebugLoc Dl = MI.getDebugLoc(); 12622 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12623 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12624 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12625 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12626 MI.getOperand(0).getReg()) 12627 .addReg(CRReg); 12628 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12629 DebugLoc Dl = MI.getDebugLoc(); 12630 unsigned Imm = MI.getOperand(1).getImm(); 12631 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12632 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12633 MI.getOperand(0).getReg()) 12634 .addReg(PPC::CR0EQ); 12635 } else if (MI.getOpcode() == PPC::SETRNDi) { 12636 DebugLoc dl = MI.getDebugLoc(); 12637 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12638 12639 // Save FPSCR value. 12640 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12641 12642 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12643 // the following settings: 12644 // 00 Round to nearest 12645 // 01 Round to 0 12646 // 10 Round to +inf 12647 // 11 Round to -inf 12648 12649 // When the operand is immediate, using the two least significant bits of 12650 // the immediate to set the bits 62:63 of FPSCR. 12651 unsigned Mode = MI.getOperand(1).getImm(); 12652 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12653 .addImm(31) 12654 .addReg(PPC::RM, RegState::ImplicitDefine); 12655 12656 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12657 .addImm(30) 12658 .addReg(PPC::RM, RegState::ImplicitDefine); 12659 } else if (MI.getOpcode() == PPC::SETRND) { 12660 DebugLoc dl = MI.getDebugLoc(); 12661 12662 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12663 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12664 // If the target doesn't have DirectMove, we should use stack to do the 12665 // conversion, because the target doesn't have the instructions like mtvsrd 12666 // or mfvsrd to do this conversion directly. 12667 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12668 if (Subtarget.hasDirectMove()) { 12669 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12670 .addReg(SrcReg); 12671 } else { 12672 // Use stack to do the register copy. 12673 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12674 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12675 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12676 if (RC == &PPC::F8RCRegClass) { 12677 // Copy register from F8RCRegClass to G8RCRegclass. 12678 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12679 "Unsupported RegClass."); 12680 12681 StoreOp = PPC::STFD; 12682 LoadOp = PPC::LD; 12683 } else { 12684 // Copy register from G8RCRegClass to F8RCRegclass. 12685 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12686 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12687 "Unsupported RegClass."); 12688 } 12689 12690 MachineFrameInfo &MFI = F->getFrameInfo(); 12691 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12692 12693 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12694 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12695 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12696 MFI.getObjectAlign(FrameIdx)); 12697 12698 // Store the SrcReg into the stack. 12699 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12700 .addReg(SrcReg) 12701 .addImm(0) 12702 .addFrameIndex(FrameIdx) 12703 .addMemOperand(MMOStore); 12704 12705 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12706 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12707 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12708 MFI.getObjectAlign(FrameIdx)); 12709 12710 // Load from the stack where SrcReg is stored, and save to DestReg, 12711 // so we have done the RegClass conversion from RegClass::SrcReg to 12712 // RegClass::DestReg. 12713 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12714 .addImm(0) 12715 .addFrameIndex(FrameIdx) 12716 .addMemOperand(MMOLoad); 12717 } 12718 }; 12719 12720 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12721 12722 // Save FPSCR value. 12723 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12724 12725 // When the operand is gprc register, use two least significant bits of the 12726 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12727 // 12728 // copy OldFPSCRTmpReg, OldFPSCRReg 12729 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12730 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12731 // copy NewFPSCRReg, NewFPSCRTmpReg 12732 // mtfsf 255, NewFPSCRReg 12733 MachineOperand SrcOp = MI.getOperand(1); 12734 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12735 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12736 12737 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12738 12739 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12740 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12741 12742 // The first operand of INSERT_SUBREG should be a register which has 12743 // subregisters, we only care about its RegClass, so we should use an 12744 // IMPLICIT_DEF register. 12745 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12746 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12747 .addReg(ImDefReg) 12748 .add(SrcOp) 12749 .addImm(1); 12750 12751 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12752 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12753 .addReg(OldFPSCRTmpReg) 12754 .addReg(ExtSrcReg) 12755 .addImm(0) 12756 .addImm(62); 12757 12758 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12759 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12760 12761 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12762 // bits of FPSCR. 12763 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12764 .addImm(255) 12765 .addReg(NewFPSCRReg) 12766 .addImm(0) 12767 .addImm(0); 12768 } else if (MI.getOpcode() == PPC::SETFLM) { 12769 DebugLoc Dl = MI.getDebugLoc(); 12770 12771 // Result of setflm is previous FPSCR content, so we need to save it first. 12772 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12773 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12774 12775 // Put bits in 32:63 to FPSCR. 12776 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12777 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12778 .addImm(255) 12779 .addReg(NewFPSCRReg) 12780 .addImm(0) 12781 .addImm(0); 12782 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12783 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12784 return emitProbedAlloca(MI, BB); 12785 } else { 12786 llvm_unreachable("Unexpected instr type to insert"); 12787 } 12788 12789 MI.eraseFromParent(); // The pseudo instruction is gone now. 12790 return BB; 12791 } 12792 12793 //===----------------------------------------------------------------------===// 12794 // Target Optimization Hooks 12795 //===----------------------------------------------------------------------===// 12796 12797 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12798 // For the estimates, convergence is quadratic, so we essentially double the 12799 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12800 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12801 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12802 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12803 if (VT.getScalarType() == MVT::f64) 12804 RefinementSteps++; 12805 return RefinementSteps; 12806 } 12807 12808 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12809 const DenormalMode &Mode) const { 12810 // We only have VSX Vector Test for software Square Root. 12811 EVT VT = Op.getValueType(); 12812 if (!isTypeLegal(MVT::i1) || 12813 (VT != MVT::f64 && 12814 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12815 return SDValue(); 12816 12817 SDLoc DL(Op); 12818 // The output register of FTSQRT is CR field. 12819 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12820 // ftsqrt BF,FRB 12821 // Let e_b be the unbiased exponent of the double-precision 12822 // floating-point operand in register FRB. 12823 // fe_flag is set to 1 if either of the following conditions occurs. 12824 // - The double-precision floating-point operand in register FRB is a zero, 12825 // a NaN, or an infinity, or a negative value. 12826 // - e_b is less than or equal to -970. 12827 // Otherwise fe_flag is set to 0. 12828 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12829 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12830 // exponent is less than -970) 12831 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12832 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12833 FTSQRT, SRIdxVal), 12834 0); 12835 } 12836 12837 SDValue 12838 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12839 SelectionDAG &DAG) const { 12840 // We only have VSX Vector Square Root. 12841 EVT VT = Op.getValueType(); 12842 if (VT != MVT::f64 && 12843 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12844 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12845 12846 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12847 } 12848 12849 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12850 int Enabled, int &RefinementSteps, 12851 bool &UseOneConstNR, 12852 bool Reciprocal) const { 12853 EVT VT = Operand.getValueType(); 12854 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12855 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12856 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12857 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12858 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12859 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12860 12861 // The Newton-Raphson computation with a single constant does not provide 12862 // enough accuracy on some CPUs. 12863 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12864 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12865 } 12866 return SDValue(); 12867 } 12868 12869 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12870 int Enabled, 12871 int &RefinementSteps) const { 12872 EVT VT = Operand.getValueType(); 12873 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12874 (VT == MVT::f64 && Subtarget.hasFRE()) || 12875 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12876 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12877 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12878 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12879 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12880 } 12881 return SDValue(); 12882 } 12883 12884 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12885 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12886 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12887 // enabled for division), this functionality is redundant with the default 12888 // combiner logic (once the division -> reciprocal/multiply transformation 12889 // has taken place). As a result, this matters more for older cores than for 12890 // newer ones. 12891 12892 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12893 // reciprocal if there are two or more FDIVs (for embedded cores with only 12894 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12895 switch (Subtarget.getCPUDirective()) { 12896 default: 12897 return 3; 12898 case PPC::DIR_440: 12899 case PPC::DIR_A2: 12900 case PPC::DIR_E500: 12901 case PPC::DIR_E500mc: 12902 case PPC::DIR_E5500: 12903 return 2; 12904 } 12905 } 12906 12907 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12908 // collapsed, and so we need to look through chains of them. 12909 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12910 int64_t& Offset, SelectionDAG &DAG) { 12911 if (DAG.isBaseWithConstantOffset(Loc)) { 12912 Base = Loc.getOperand(0); 12913 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12914 12915 // The base might itself be a base plus an offset, and if so, accumulate 12916 // that as well. 12917 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12918 } 12919 } 12920 12921 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12922 unsigned Bytes, int Dist, 12923 SelectionDAG &DAG) { 12924 if (VT.getSizeInBits() / 8 != Bytes) 12925 return false; 12926 12927 SDValue BaseLoc = Base->getBasePtr(); 12928 if (Loc.getOpcode() == ISD::FrameIndex) { 12929 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12930 return false; 12931 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12932 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12933 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12934 int FS = MFI.getObjectSize(FI); 12935 int BFS = MFI.getObjectSize(BFI); 12936 if (FS != BFS || FS != (int)Bytes) return false; 12937 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12938 } 12939 12940 SDValue Base1 = Loc, Base2 = BaseLoc; 12941 int64_t Offset1 = 0, Offset2 = 0; 12942 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12943 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12944 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12945 return true; 12946 12947 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12948 const GlobalValue *GV1 = nullptr; 12949 const GlobalValue *GV2 = nullptr; 12950 Offset1 = 0; 12951 Offset2 = 0; 12952 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12953 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12954 if (isGA1 && isGA2 && GV1 == GV2) 12955 return Offset1 == (Offset2 + Dist*Bytes); 12956 return false; 12957 } 12958 12959 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12960 // not enforce equality of the chain operands. 12961 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12962 unsigned Bytes, int Dist, 12963 SelectionDAG &DAG) { 12964 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12965 EVT VT = LS->getMemoryVT(); 12966 SDValue Loc = LS->getBasePtr(); 12967 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12968 } 12969 12970 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12971 EVT VT; 12972 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12973 default: return false; 12974 case Intrinsic::ppc_altivec_lvx: 12975 case Intrinsic::ppc_altivec_lvxl: 12976 case Intrinsic::ppc_vsx_lxvw4x: 12977 case Intrinsic::ppc_vsx_lxvw4x_be: 12978 VT = MVT::v4i32; 12979 break; 12980 case Intrinsic::ppc_vsx_lxvd2x: 12981 case Intrinsic::ppc_vsx_lxvd2x_be: 12982 VT = MVT::v2f64; 12983 break; 12984 case Intrinsic::ppc_altivec_lvebx: 12985 VT = MVT::i8; 12986 break; 12987 case Intrinsic::ppc_altivec_lvehx: 12988 VT = MVT::i16; 12989 break; 12990 case Intrinsic::ppc_altivec_lvewx: 12991 VT = MVT::i32; 12992 break; 12993 } 12994 12995 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12996 } 12997 12998 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12999 EVT VT; 13000 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13001 default: return false; 13002 case Intrinsic::ppc_altivec_stvx: 13003 case Intrinsic::ppc_altivec_stvxl: 13004 case Intrinsic::ppc_vsx_stxvw4x: 13005 VT = MVT::v4i32; 13006 break; 13007 case Intrinsic::ppc_vsx_stxvd2x: 13008 VT = MVT::v2f64; 13009 break; 13010 case Intrinsic::ppc_vsx_stxvw4x_be: 13011 VT = MVT::v4i32; 13012 break; 13013 case Intrinsic::ppc_vsx_stxvd2x_be: 13014 VT = MVT::v2f64; 13015 break; 13016 case Intrinsic::ppc_altivec_stvebx: 13017 VT = MVT::i8; 13018 break; 13019 case Intrinsic::ppc_altivec_stvehx: 13020 VT = MVT::i16; 13021 break; 13022 case Intrinsic::ppc_altivec_stvewx: 13023 VT = MVT::i32; 13024 break; 13025 } 13026 13027 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13028 } 13029 13030 return false; 13031 } 13032 13033 // Return true is there is a nearyby consecutive load to the one provided 13034 // (regardless of alignment). We search up and down the chain, looking though 13035 // token factors and other loads (but nothing else). As a result, a true result 13036 // indicates that it is safe to create a new consecutive load adjacent to the 13037 // load provided. 13038 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13039 SDValue Chain = LD->getChain(); 13040 EVT VT = LD->getMemoryVT(); 13041 13042 SmallSet<SDNode *, 16> LoadRoots; 13043 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13044 SmallSet<SDNode *, 16> Visited; 13045 13046 // First, search up the chain, branching to follow all token-factor operands. 13047 // If we find a consecutive load, then we're done, otherwise, record all 13048 // nodes just above the top-level loads and token factors. 13049 while (!Queue.empty()) { 13050 SDNode *ChainNext = Queue.pop_back_val(); 13051 if (!Visited.insert(ChainNext).second) 13052 continue; 13053 13054 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13055 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13056 return true; 13057 13058 if (!Visited.count(ChainLD->getChain().getNode())) 13059 Queue.push_back(ChainLD->getChain().getNode()); 13060 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13061 for (const SDUse &O : ChainNext->ops()) 13062 if (!Visited.count(O.getNode())) 13063 Queue.push_back(O.getNode()); 13064 } else 13065 LoadRoots.insert(ChainNext); 13066 } 13067 13068 // Second, search down the chain, starting from the top-level nodes recorded 13069 // in the first phase. These top-level nodes are the nodes just above all 13070 // loads and token factors. Starting with their uses, recursively look though 13071 // all loads (just the chain uses) and token factors to find a consecutive 13072 // load. 13073 Visited.clear(); 13074 Queue.clear(); 13075 13076 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 13077 IE = LoadRoots.end(); I != IE; ++I) { 13078 Queue.push_back(*I); 13079 13080 while (!Queue.empty()) { 13081 SDNode *LoadRoot = Queue.pop_back_val(); 13082 if (!Visited.insert(LoadRoot).second) 13083 continue; 13084 13085 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13086 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13087 return true; 13088 13089 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 13090 UE = LoadRoot->use_end(); UI != UE; ++UI) 13091 if (((isa<MemSDNode>(*UI) && 13092 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 13093 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 13094 Queue.push_back(*UI); 13095 } 13096 } 13097 13098 return false; 13099 } 13100 13101 /// This function is called when we have proved that a SETCC node can be replaced 13102 /// by subtraction (and other supporting instructions) so that the result of 13103 /// comparison is kept in a GPR instead of CR. This function is purely for 13104 /// codegen purposes and has some flags to guide the codegen process. 13105 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13106 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13107 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13108 13109 // Zero extend the operands to the largest legal integer. Originally, they 13110 // must be of a strictly smaller size. 13111 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13112 DAG.getConstant(Size, DL, MVT::i32)); 13113 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13114 DAG.getConstant(Size, DL, MVT::i32)); 13115 13116 // Swap if needed. Depends on the condition code. 13117 if (Swap) 13118 std::swap(Op0, Op1); 13119 13120 // Subtract extended integers. 13121 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13122 13123 // Move the sign bit to the least significant position and zero out the rest. 13124 // Now the least significant bit carries the result of original comparison. 13125 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13126 DAG.getConstant(Size - 1, DL, MVT::i32)); 13127 auto Final = Shifted; 13128 13129 // Complement the result if needed. Based on the condition code. 13130 if (Complement) 13131 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13132 DAG.getConstant(1, DL, MVT::i64)); 13133 13134 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13135 } 13136 13137 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13138 DAGCombinerInfo &DCI) const { 13139 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13140 13141 SelectionDAG &DAG = DCI.DAG; 13142 SDLoc DL(N); 13143 13144 // Size of integers being compared has a critical role in the following 13145 // analysis, so we prefer to do this when all types are legal. 13146 if (!DCI.isAfterLegalizeDAG()) 13147 return SDValue(); 13148 13149 // If all users of SETCC extend its value to a legal integer type 13150 // then we replace SETCC with a subtraction 13151 for (SDNode::use_iterator UI = N->use_begin(), 13152 UE = N->use_end(); UI != UE; ++UI) { 13153 if (UI->getOpcode() != ISD::ZERO_EXTEND) 13154 return SDValue(); 13155 } 13156 13157 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13158 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13159 13160 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13161 13162 if (OpSize < Size) { 13163 switch (CC) { 13164 default: break; 13165 case ISD::SETULT: 13166 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13167 case ISD::SETULE: 13168 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13169 case ISD::SETUGT: 13170 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13171 case ISD::SETUGE: 13172 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13173 } 13174 } 13175 13176 return SDValue(); 13177 } 13178 13179 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13180 DAGCombinerInfo &DCI) const { 13181 SelectionDAG &DAG = DCI.DAG; 13182 SDLoc dl(N); 13183 13184 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13185 // If we're tracking CR bits, we need to be careful that we don't have: 13186 // trunc(binary-ops(zext(x), zext(y))) 13187 // or 13188 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13189 // such that we're unnecessarily moving things into GPRs when it would be 13190 // better to keep them in CR bits. 13191 13192 // Note that trunc here can be an actual i1 trunc, or can be the effective 13193 // truncation that comes from a setcc or select_cc. 13194 if (N->getOpcode() == ISD::TRUNCATE && 13195 N->getValueType(0) != MVT::i1) 13196 return SDValue(); 13197 13198 if (N->getOperand(0).getValueType() != MVT::i32 && 13199 N->getOperand(0).getValueType() != MVT::i64) 13200 return SDValue(); 13201 13202 if (N->getOpcode() == ISD::SETCC || 13203 N->getOpcode() == ISD::SELECT_CC) { 13204 // If we're looking at a comparison, then we need to make sure that the 13205 // high bits (all except for the first) don't matter the result. 13206 ISD::CondCode CC = 13207 cast<CondCodeSDNode>(N->getOperand( 13208 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13209 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13210 13211 if (ISD::isSignedIntSetCC(CC)) { 13212 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13213 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13214 return SDValue(); 13215 } else if (ISD::isUnsignedIntSetCC(CC)) { 13216 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13217 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13218 !DAG.MaskedValueIsZero(N->getOperand(1), 13219 APInt::getHighBitsSet(OpBits, OpBits-1))) 13220 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13221 : SDValue()); 13222 } else { 13223 // This is neither a signed nor an unsigned comparison, just make sure 13224 // that the high bits are equal. 13225 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13226 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13227 13228 // We don't really care about what is known about the first bit (if 13229 // anything), so pretend that it is known zero for both to ensure they can 13230 // be compared as constants. 13231 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13232 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13233 13234 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13235 Op1Known.getConstant() != Op2Known.getConstant()) 13236 return SDValue(); 13237 } 13238 } 13239 13240 // We now know that the higher-order bits are irrelevant, we just need to 13241 // make sure that all of the intermediate operations are bit operations, and 13242 // all inputs are extensions. 13243 if (N->getOperand(0).getOpcode() != ISD::AND && 13244 N->getOperand(0).getOpcode() != ISD::OR && 13245 N->getOperand(0).getOpcode() != ISD::XOR && 13246 N->getOperand(0).getOpcode() != ISD::SELECT && 13247 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13248 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13249 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13250 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13251 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13252 return SDValue(); 13253 13254 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13255 N->getOperand(1).getOpcode() != ISD::AND && 13256 N->getOperand(1).getOpcode() != ISD::OR && 13257 N->getOperand(1).getOpcode() != ISD::XOR && 13258 N->getOperand(1).getOpcode() != ISD::SELECT && 13259 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13260 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13261 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13262 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13263 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13264 return SDValue(); 13265 13266 SmallVector<SDValue, 4> Inputs; 13267 SmallVector<SDValue, 8> BinOps, PromOps; 13268 SmallPtrSet<SDNode *, 16> Visited; 13269 13270 for (unsigned i = 0; i < 2; ++i) { 13271 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13272 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13273 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13274 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13275 isa<ConstantSDNode>(N->getOperand(i))) 13276 Inputs.push_back(N->getOperand(i)); 13277 else 13278 BinOps.push_back(N->getOperand(i)); 13279 13280 if (N->getOpcode() == ISD::TRUNCATE) 13281 break; 13282 } 13283 13284 // Visit all inputs, collect all binary operations (and, or, xor and 13285 // select) that are all fed by extensions. 13286 while (!BinOps.empty()) { 13287 SDValue BinOp = BinOps.back(); 13288 BinOps.pop_back(); 13289 13290 if (!Visited.insert(BinOp.getNode()).second) 13291 continue; 13292 13293 PromOps.push_back(BinOp); 13294 13295 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13296 // The condition of the select is not promoted. 13297 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13298 continue; 13299 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13300 continue; 13301 13302 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13303 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13304 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13305 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13306 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13307 Inputs.push_back(BinOp.getOperand(i)); 13308 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13309 BinOp.getOperand(i).getOpcode() == ISD::OR || 13310 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13311 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13312 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13313 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13314 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13315 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13316 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13317 BinOps.push_back(BinOp.getOperand(i)); 13318 } else { 13319 // We have an input that is not an extension or another binary 13320 // operation; we'll abort this transformation. 13321 return SDValue(); 13322 } 13323 } 13324 } 13325 13326 // Make sure that this is a self-contained cluster of operations (which 13327 // is not quite the same thing as saying that everything has only one 13328 // use). 13329 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13330 if (isa<ConstantSDNode>(Inputs[i])) 13331 continue; 13332 13333 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13334 UE = Inputs[i].getNode()->use_end(); 13335 UI != UE; ++UI) { 13336 SDNode *User = *UI; 13337 if (User != N && !Visited.count(User)) 13338 return SDValue(); 13339 13340 // Make sure that we're not going to promote the non-output-value 13341 // operand(s) or SELECT or SELECT_CC. 13342 // FIXME: Although we could sometimes handle this, and it does occur in 13343 // practice that one of the condition inputs to the select is also one of 13344 // the outputs, we currently can't deal with this. 13345 if (User->getOpcode() == ISD::SELECT) { 13346 if (User->getOperand(0) == Inputs[i]) 13347 return SDValue(); 13348 } else if (User->getOpcode() == ISD::SELECT_CC) { 13349 if (User->getOperand(0) == Inputs[i] || 13350 User->getOperand(1) == Inputs[i]) 13351 return SDValue(); 13352 } 13353 } 13354 } 13355 13356 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13357 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13358 UE = PromOps[i].getNode()->use_end(); 13359 UI != UE; ++UI) { 13360 SDNode *User = *UI; 13361 if (User != N && !Visited.count(User)) 13362 return SDValue(); 13363 13364 // Make sure that we're not going to promote the non-output-value 13365 // operand(s) or SELECT or SELECT_CC. 13366 // FIXME: Although we could sometimes handle this, and it does occur in 13367 // practice that one of the condition inputs to the select is also one of 13368 // the outputs, we currently can't deal with this. 13369 if (User->getOpcode() == ISD::SELECT) { 13370 if (User->getOperand(0) == PromOps[i]) 13371 return SDValue(); 13372 } else if (User->getOpcode() == ISD::SELECT_CC) { 13373 if (User->getOperand(0) == PromOps[i] || 13374 User->getOperand(1) == PromOps[i]) 13375 return SDValue(); 13376 } 13377 } 13378 } 13379 13380 // Replace all inputs with the extension operand. 13381 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13382 // Constants may have users outside the cluster of to-be-promoted nodes, 13383 // and so we need to replace those as we do the promotions. 13384 if (isa<ConstantSDNode>(Inputs[i])) 13385 continue; 13386 else 13387 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13388 } 13389 13390 std::list<HandleSDNode> PromOpHandles; 13391 for (auto &PromOp : PromOps) 13392 PromOpHandles.emplace_back(PromOp); 13393 13394 // Replace all operations (these are all the same, but have a different 13395 // (i1) return type). DAG.getNode will validate that the types of 13396 // a binary operator match, so go through the list in reverse so that 13397 // we've likely promoted both operands first. Any intermediate truncations or 13398 // extensions disappear. 13399 while (!PromOpHandles.empty()) { 13400 SDValue PromOp = PromOpHandles.back().getValue(); 13401 PromOpHandles.pop_back(); 13402 13403 if (PromOp.getOpcode() == ISD::TRUNCATE || 13404 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13405 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13406 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13407 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13408 PromOp.getOperand(0).getValueType() != MVT::i1) { 13409 // The operand is not yet ready (see comment below). 13410 PromOpHandles.emplace_front(PromOp); 13411 continue; 13412 } 13413 13414 SDValue RepValue = PromOp.getOperand(0); 13415 if (isa<ConstantSDNode>(RepValue)) 13416 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13417 13418 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13419 continue; 13420 } 13421 13422 unsigned C; 13423 switch (PromOp.getOpcode()) { 13424 default: C = 0; break; 13425 case ISD::SELECT: C = 1; break; 13426 case ISD::SELECT_CC: C = 2; break; 13427 } 13428 13429 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13430 PromOp.getOperand(C).getValueType() != MVT::i1) || 13431 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13432 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13433 // The to-be-promoted operands of this node have not yet been 13434 // promoted (this should be rare because we're going through the 13435 // list backward, but if one of the operands has several users in 13436 // this cluster of to-be-promoted nodes, it is possible). 13437 PromOpHandles.emplace_front(PromOp); 13438 continue; 13439 } 13440 13441 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13442 PromOp.getNode()->op_end()); 13443 13444 // If there are any constant inputs, make sure they're replaced now. 13445 for (unsigned i = 0; i < 2; ++i) 13446 if (isa<ConstantSDNode>(Ops[C+i])) 13447 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13448 13449 DAG.ReplaceAllUsesOfValueWith(PromOp, 13450 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13451 } 13452 13453 // Now we're left with the initial truncation itself. 13454 if (N->getOpcode() == ISD::TRUNCATE) 13455 return N->getOperand(0); 13456 13457 // Otherwise, this is a comparison. The operands to be compared have just 13458 // changed type (to i1), but everything else is the same. 13459 return SDValue(N, 0); 13460 } 13461 13462 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13463 DAGCombinerInfo &DCI) const { 13464 SelectionDAG &DAG = DCI.DAG; 13465 SDLoc dl(N); 13466 13467 // If we're tracking CR bits, we need to be careful that we don't have: 13468 // zext(binary-ops(trunc(x), trunc(y))) 13469 // or 13470 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13471 // such that we're unnecessarily moving things into CR bits that can more 13472 // efficiently stay in GPRs. Note that if we're not certain that the high 13473 // bits are set as required by the final extension, we still may need to do 13474 // some masking to get the proper behavior. 13475 13476 // This same functionality is important on PPC64 when dealing with 13477 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13478 // the return values of functions. Because it is so similar, it is handled 13479 // here as well. 13480 13481 if (N->getValueType(0) != MVT::i32 && 13482 N->getValueType(0) != MVT::i64) 13483 return SDValue(); 13484 13485 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13486 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13487 return SDValue(); 13488 13489 if (N->getOperand(0).getOpcode() != ISD::AND && 13490 N->getOperand(0).getOpcode() != ISD::OR && 13491 N->getOperand(0).getOpcode() != ISD::XOR && 13492 N->getOperand(0).getOpcode() != ISD::SELECT && 13493 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13494 return SDValue(); 13495 13496 SmallVector<SDValue, 4> Inputs; 13497 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13498 SmallPtrSet<SDNode *, 16> Visited; 13499 13500 // Visit all inputs, collect all binary operations (and, or, xor and 13501 // select) that are all fed by truncations. 13502 while (!BinOps.empty()) { 13503 SDValue BinOp = BinOps.back(); 13504 BinOps.pop_back(); 13505 13506 if (!Visited.insert(BinOp.getNode()).second) 13507 continue; 13508 13509 PromOps.push_back(BinOp); 13510 13511 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13512 // The condition of the select is not promoted. 13513 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13514 continue; 13515 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13516 continue; 13517 13518 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13519 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13520 Inputs.push_back(BinOp.getOperand(i)); 13521 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13522 BinOp.getOperand(i).getOpcode() == ISD::OR || 13523 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13524 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13525 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13526 BinOps.push_back(BinOp.getOperand(i)); 13527 } else { 13528 // We have an input that is not a truncation or another binary 13529 // operation; we'll abort this transformation. 13530 return SDValue(); 13531 } 13532 } 13533 } 13534 13535 // The operands of a select that must be truncated when the select is 13536 // promoted because the operand is actually part of the to-be-promoted set. 13537 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13538 13539 // Make sure that this is a self-contained cluster of operations (which 13540 // is not quite the same thing as saying that everything has only one 13541 // use). 13542 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13543 if (isa<ConstantSDNode>(Inputs[i])) 13544 continue; 13545 13546 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13547 UE = Inputs[i].getNode()->use_end(); 13548 UI != UE; ++UI) { 13549 SDNode *User = *UI; 13550 if (User != N && !Visited.count(User)) 13551 return SDValue(); 13552 13553 // If we're going to promote the non-output-value operand(s) or SELECT or 13554 // SELECT_CC, record them for truncation. 13555 if (User->getOpcode() == ISD::SELECT) { 13556 if (User->getOperand(0) == Inputs[i]) 13557 SelectTruncOp[0].insert(std::make_pair(User, 13558 User->getOperand(0).getValueType())); 13559 } else if (User->getOpcode() == ISD::SELECT_CC) { 13560 if (User->getOperand(0) == Inputs[i]) 13561 SelectTruncOp[0].insert(std::make_pair(User, 13562 User->getOperand(0).getValueType())); 13563 if (User->getOperand(1) == Inputs[i]) 13564 SelectTruncOp[1].insert(std::make_pair(User, 13565 User->getOperand(1).getValueType())); 13566 } 13567 } 13568 } 13569 13570 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13571 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13572 UE = PromOps[i].getNode()->use_end(); 13573 UI != UE; ++UI) { 13574 SDNode *User = *UI; 13575 if (User != N && !Visited.count(User)) 13576 return SDValue(); 13577 13578 // If we're going to promote the non-output-value operand(s) or SELECT or 13579 // SELECT_CC, record them for truncation. 13580 if (User->getOpcode() == ISD::SELECT) { 13581 if (User->getOperand(0) == PromOps[i]) 13582 SelectTruncOp[0].insert(std::make_pair(User, 13583 User->getOperand(0).getValueType())); 13584 } else if (User->getOpcode() == ISD::SELECT_CC) { 13585 if (User->getOperand(0) == PromOps[i]) 13586 SelectTruncOp[0].insert(std::make_pair(User, 13587 User->getOperand(0).getValueType())); 13588 if (User->getOperand(1) == PromOps[i]) 13589 SelectTruncOp[1].insert(std::make_pair(User, 13590 User->getOperand(1).getValueType())); 13591 } 13592 } 13593 } 13594 13595 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13596 bool ReallyNeedsExt = false; 13597 if (N->getOpcode() != ISD::ANY_EXTEND) { 13598 // If all of the inputs are not already sign/zero extended, then 13599 // we'll still need to do that at the end. 13600 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13601 if (isa<ConstantSDNode>(Inputs[i])) 13602 continue; 13603 13604 unsigned OpBits = 13605 Inputs[i].getOperand(0).getValueSizeInBits(); 13606 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13607 13608 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13609 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13610 APInt::getHighBitsSet(OpBits, 13611 OpBits-PromBits))) || 13612 (N->getOpcode() == ISD::SIGN_EXTEND && 13613 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13614 (OpBits-(PromBits-1)))) { 13615 ReallyNeedsExt = true; 13616 break; 13617 } 13618 } 13619 } 13620 13621 // Replace all inputs, either with the truncation operand, or a 13622 // truncation or extension to the final output type. 13623 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13624 // Constant inputs need to be replaced with the to-be-promoted nodes that 13625 // use them because they might have users outside of the cluster of 13626 // promoted nodes. 13627 if (isa<ConstantSDNode>(Inputs[i])) 13628 continue; 13629 13630 SDValue InSrc = Inputs[i].getOperand(0); 13631 if (Inputs[i].getValueType() == N->getValueType(0)) 13632 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13633 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13634 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13635 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13636 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13637 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13638 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13639 else 13640 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13641 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13642 } 13643 13644 std::list<HandleSDNode> PromOpHandles; 13645 for (auto &PromOp : PromOps) 13646 PromOpHandles.emplace_back(PromOp); 13647 13648 // Replace all operations (these are all the same, but have a different 13649 // (promoted) return type). DAG.getNode will validate that the types of 13650 // a binary operator match, so go through the list in reverse so that 13651 // we've likely promoted both operands first. 13652 while (!PromOpHandles.empty()) { 13653 SDValue PromOp = PromOpHandles.back().getValue(); 13654 PromOpHandles.pop_back(); 13655 13656 unsigned C; 13657 switch (PromOp.getOpcode()) { 13658 default: C = 0; break; 13659 case ISD::SELECT: C = 1; break; 13660 case ISD::SELECT_CC: C = 2; break; 13661 } 13662 13663 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13664 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13665 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13666 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13667 // The to-be-promoted operands of this node have not yet been 13668 // promoted (this should be rare because we're going through the 13669 // list backward, but if one of the operands has several users in 13670 // this cluster of to-be-promoted nodes, it is possible). 13671 PromOpHandles.emplace_front(PromOp); 13672 continue; 13673 } 13674 13675 // For SELECT and SELECT_CC nodes, we do a similar check for any 13676 // to-be-promoted comparison inputs. 13677 if (PromOp.getOpcode() == ISD::SELECT || 13678 PromOp.getOpcode() == ISD::SELECT_CC) { 13679 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13680 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13681 (SelectTruncOp[1].count(PromOp.getNode()) && 13682 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13683 PromOpHandles.emplace_front(PromOp); 13684 continue; 13685 } 13686 } 13687 13688 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13689 PromOp.getNode()->op_end()); 13690 13691 // If this node has constant inputs, then they'll need to be promoted here. 13692 for (unsigned i = 0; i < 2; ++i) { 13693 if (!isa<ConstantSDNode>(Ops[C+i])) 13694 continue; 13695 if (Ops[C+i].getValueType() == N->getValueType(0)) 13696 continue; 13697 13698 if (N->getOpcode() == ISD::SIGN_EXTEND) 13699 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13700 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13701 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13702 else 13703 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13704 } 13705 13706 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13707 // truncate them again to the original value type. 13708 if (PromOp.getOpcode() == ISD::SELECT || 13709 PromOp.getOpcode() == ISD::SELECT_CC) { 13710 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13711 if (SI0 != SelectTruncOp[0].end()) 13712 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13713 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13714 if (SI1 != SelectTruncOp[1].end()) 13715 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13716 } 13717 13718 DAG.ReplaceAllUsesOfValueWith(PromOp, 13719 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13720 } 13721 13722 // Now we're left with the initial extension itself. 13723 if (!ReallyNeedsExt) 13724 return N->getOperand(0); 13725 13726 // To zero extend, just mask off everything except for the first bit (in the 13727 // i1 case). 13728 if (N->getOpcode() == ISD::ZERO_EXTEND) 13729 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13730 DAG.getConstant(APInt::getLowBitsSet( 13731 N->getValueSizeInBits(0), PromBits), 13732 dl, N->getValueType(0))); 13733 13734 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13735 "Invalid extension type"); 13736 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13737 SDValue ShiftCst = 13738 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13739 return DAG.getNode( 13740 ISD::SRA, dl, N->getValueType(0), 13741 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13742 ShiftCst); 13743 } 13744 13745 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13746 DAGCombinerInfo &DCI) const { 13747 assert(N->getOpcode() == ISD::SETCC && 13748 "Should be called with a SETCC node"); 13749 13750 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13751 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13752 SDValue LHS = N->getOperand(0); 13753 SDValue RHS = N->getOperand(1); 13754 13755 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13756 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13757 LHS.hasOneUse()) 13758 std::swap(LHS, RHS); 13759 13760 // x == 0-y --> x+y == 0 13761 // x != 0-y --> x+y != 0 13762 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13763 RHS.hasOneUse()) { 13764 SDLoc DL(N); 13765 SelectionDAG &DAG = DCI.DAG; 13766 EVT VT = N->getValueType(0); 13767 EVT OpVT = LHS.getValueType(); 13768 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13769 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13770 } 13771 } 13772 13773 return DAGCombineTruncBoolExt(N, DCI); 13774 } 13775 13776 // Is this an extending load from an f32 to an f64? 13777 static bool isFPExtLoad(SDValue Op) { 13778 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13779 return LD->getExtensionType() == ISD::EXTLOAD && 13780 Op.getValueType() == MVT::f64; 13781 return false; 13782 } 13783 13784 /// Reduces the number of fp-to-int conversion when building a vector. 13785 /// 13786 /// If this vector is built out of floating to integer conversions, 13787 /// transform it to a vector built out of floating point values followed by a 13788 /// single floating to integer conversion of the vector. 13789 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13790 /// becomes (fptosi (build_vector ($A, $B, ...))) 13791 SDValue PPCTargetLowering:: 13792 combineElementTruncationToVectorTruncation(SDNode *N, 13793 DAGCombinerInfo &DCI) const { 13794 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13795 "Should be called with a BUILD_VECTOR node"); 13796 13797 SelectionDAG &DAG = DCI.DAG; 13798 SDLoc dl(N); 13799 13800 SDValue FirstInput = N->getOperand(0); 13801 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13802 "The input operand must be an fp-to-int conversion."); 13803 13804 // This combine happens after legalization so the fp_to_[su]i nodes are 13805 // already converted to PPCSISD nodes. 13806 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13807 if (FirstConversion == PPCISD::FCTIDZ || 13808 FirstConversion == PPCISD::FCTIDUZ || 13809 FirstConversion == PPCISD::FCTIWZ || 13810 FirstConversion == PPCISD::FCTIWUZ) { 13811 bool IsSplat = true; 13812 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13813 FirstConversion == PPCISD::FCTIWUZ; 13814 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13815 SmallVector<SDValue, 4> Ops; 13816 EVT TargetVT = N->getValueType(0); 13817 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13818 SDValue NextOp = N->getOperand(i); 13819 if (NextOp.getOpcode() != PPCISD::MFVSR) 13820 return SDValue(); 13821 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13822 if (NextConversion != FirstConversion) 13823 return SDValue(); 13824 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13825 // This is not valid if the input was originally double precision. It is 13826 // also not profitable to do unless this is an extending load in which 13827 // case doing this combine will allow us to combine consecutive loads. 13828 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13829 return SDValue(); 13830 if (N->getOperand(i) != FirstInput) 13831 IsSplat = false; 13832 } 13833 13834 // If this is a splat, we leave it as-is since there will be only a single 13835 // fp-to-int conversion followed by a splat of the integer. This is better 13836 // for 32-bit and smaller ints and neutral for 64-bit ints. 13837 if (IsSplat) 13838 return SDValue(); 13839 13840 // Now that we know we have the right type of node, get its operands 13841 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13842 SDValue In = N->getOperand(i).getOperand(0); 13843 if (Is32Bit) { 13844 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13845 // here, we know that all inputs are extending loads so this is safe). 13846 if (In.isUndef()) 13847 Ops.push_back(DAG.getUNDEF(SrcVT)); 13848 else { 13849 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13850 MVT::f32, In.getOperand(0), 13851 DAG.getIntPtrConstant(1, dl)); 13852 Ops.push_back(Trunc); 13853 } 13854 } else 13855 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13856 } 13857 13858 unsigned Opcode; 13859 if (FirstConversion == PPCISD::FCTIDZ || 13860 FirstConversion == PPCISD::FCTIWZ) 13861 Opcode = ISD::FP_TO_SINT; 13862 else 13863 Opcode = ISD::FP_TO_UINT; 13864 13865 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13866 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13867 return DAG.getNode(Opcode, dl, TargetVT, BV); 13868 } 13869 return SDValue(); 13870 } 13871 13872 /// Reduce the number of loads when building a vector. 13873 /// 13874 /// Building a vector out of multiple loads can be converted to a load 13875 /// of the vector type if the loads are consecutive. If the loads are 13876 /// consecutive but in descending order, a shuffle is added at the end 13877 /// to reorder the vector. 13878 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13879 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13880 "Should be called with a BUILD_VECTOR node"); 13881 13882 SDLoc dl(N); 13883 13884 // Return early for non byte-sized type, as they can't be consecutive. 13885 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13886 return SDValue(); 13887 13888 bool InputsAreConsecutiveLoads = true; 13889 bool InputsAreReverseConsecutive = true; 13890 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13891 SDValue FirstInput = N->getOperand(0); 13892 bool IsRoundOfExtLoad = false; 13893 13894 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13895 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13896 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13897 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13898 } 13899 // Not a build vector of (possibly fp_rounded) loads. 13900 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13901 N->getNumOperands() == 1) 13902 return SDValue(); 13903 13904 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13905 // If any inputs are fp_round(extload), they all must be. 13906 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13907 return SDValue(); 13908 13909 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13910 N->getOperand(i); 13911 if (NextInput.getOpcode() != ISD::LOAD) 13912 return SDValue(); 13913 13914 SDValue PreviousInput = 13915 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13916 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13917 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13918 13919 // If any inputs are fp_round(extload), they all must be. 13920 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13921 return SDValue(); 13922 13923 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13924 InputsAreConsecutiveLoads = false; 13925 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13926 InputsAreReverseConsecutive = false; 13927 13928 // Exit early if the loads are neither consecutive nor reverse consecutive. 13929 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13930 return SDValue(); 13931 } 13932 13933 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13934 "The loads cannot be both consecutive and reverse consecutive."); 13935 13936 SDValue FirstLoadOp = 13937 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13938 SDValue LastLoadOp = 13939 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13940 N->getOperand(N->getNumOperands()-1); 13941 13942 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13943 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13944 if (InputsAreConsecutiveLoads) { 13945 assert(LD1 && "Input needs to be a LoadSDNode."); 13946 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13947 LD1->getBasePtr(), LD1->getPointerInfo(), 13948 LD1->getAlignment()); 13949 } 13950 if (InputsAreReverseConsecutive) { 13951 assert(LDL && "Input needs to be a LoadSDNode."); 13952 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13953 LDL->getBasePtr(), LDL->getPointerInfo(), 13954 LDL->getAlignment()); 13955 SmallVector<int, 16> Ops; 13956 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13957 Ops.push_back(i); 13958 13959 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13960 DAG.getUNDEF(N->getValueType(0)), Ops); 13961 } 13962 return SDValue(); 13963 } 13964 13965 // This function adds the required vector_shuffle needed to get 13966 // the elements of the vector extract in the correct position 13967 // as specified by the CorrectElems encoding. 13968 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13969 SDValue Input, uint64_t Elems, 13970 uint64_t CorrectElems) { 13971 SDLoc dl(N); 13972 13973 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13974 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13975 13976 // Knowing the element indices being extracted from the original 13977 // vector and the order in which they're being inserted, just put 13978 // them at element indices required for the instruction. 13979 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13980 if (DAG.getDataLayout().isLittleEndian()) 13981 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13982 else 13983 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13984 CorrectElems = CorrectElems >> 8; 13985 Elems = Elems >> 8; 13986 } 13987 13988 SDValue Shuffle = 13989 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13990 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13991 13992 EVT VT = N->getValueType(0); 13993 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13994 13995 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13996 Input.getValueType().getVectorElementType(), 13997 VT.getVectorNumElements()); 13998 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13999 DAG.getValueType(ExtVT)); 14000 } 14001 14002 // Look for build vector patterns where input operands come from sign 14003 // extended vector_extract elements of specific indices. If the correct indices 14004 // aren't used, add a vector shuffle to fix up the indices and create 14005 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14006 // during instruction selection. 14007 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14008 // This array encodes the indices that the vector sign extend instructions 14009 // extract from when extending from one type to another for both BE and LE. 14010 // The right nibble of each byte corresponds to the LE incides. 14011 // and the left nibble of each byte corresponds to the BE incides. 14012 // For example: 0x3074B8FC byte->word 14013 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14014 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14015 // For example: 0x000070F8 byte->double word 14016 // For LE: the allowed indices are: 0x0,0x8 14017 // For BE: the allowed indices are: 0x7,0xF 14018 uint64_t TargetElems[] = { 14019 0x3074B8FC, // b->w 14020 0x000070F8, // b->d 14021 0x10325476, // h->w 14022 0x00003074, // h->d 14023 0x00001032, // w->d 14024 }; 14025 14026 uint64_t Elems = 0; 14027 int Index; 14028 SDValue Input; 14029 14030 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14031 if (!Op) 14032 return false; 14033 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14034 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14035 return false; 14036 14037 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14038 // of the right width. 14039 SDValue Extract = Op.getOperand(0); 14040 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14041 Extract = Extract.getOperand(0); 14042 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14043 return false; 14044 14045 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14046 if (!ExtOp) 14047 return false; 14048 14049 Index = ExtOp->getZExtValue(); 14050 if (Input && Input != Extract.getOperand(0)) 14051 return false; 14052 14053 if (!Input) 14054 Input = Extract.getOperand(0); 14055 14056 Elems = Elems << 8; 14057 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14058 Elems |= Index; 14059 14060 return true; 14061 }; 14062 14063 // If the build vector operands aren't sign extended vector extracts, 14064 // of the same input vector, then return. 14065 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14066 if (!isSExtOfVecExtract(N->getOperand(i))) { 14067 return SDValue(); 14068 } 14069 } 14070 14071 // If the vector extract indicies are not correct, add the appropriate 14072 // vector_shuffle. 14073 int TgtElemArrayIdx; 14074 int InputSize = Input.getValueType().getScalarSizeInBits(); 14075 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14076 if (InputSize + OutputSize == 40) 14077 TgtElemArrayIdx = 0; 14078 else if (InputSize + OutputSize == 72) 14079 TgtElemArrayIdx = 1; 14080 else if (InputSize + OutputSize == 48) 14081 TgtElemArrayIdx = 2; 14082 else if (InputSize + OutputSize == 80) 14083 TgtElemArrayIdx = 3; 14084 else if (InputSize + OutputSize == 96) 14085 TgtElemArrayIdx = 4; 14086 else 14087 return SDValue(); 14088 14089 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14090 CorrectElems = DAG.getDataLayout().isLittleEndian() 14091 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14092 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14093 if (Elems != CorrectElems) { 14094 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14095 } 14096 14097 // Regular lowering will catch cases where a shuffle is not needed. 14098 return SDValue(); 14099 } 14100 14101 // Look for the pattern of a load from a narrow width to i128, feeding 14102 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14103 // (LXVRZX). This node represents a zero extending load that will be matched 14104 // to the Load VSX Vector Rightmost instructions. 14105 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14106 SDLoc DL(N); 14107 14108 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14109 if (N->getValueType(0) != MVT::v1i128) 14110 return SDValue(); 14111 14112 SDValue Operand = N->getOperand(0); 14113 // Proceed with the transformation if the operand to the BUILD_VECTOR 14114 // is a load instruction. 14115 if (Operand.getOpcode() != ISD::LOAD) 14116 return SDValue(); 14117 14118 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 14119 EVT MemoryType = LD->getMemoryVT(); 14120 14121 // This transformation is only valid if the we are loading either a byte, 14122 // halfword, word, or doubleword. 14123 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14124 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14125 14126 // Ensure that the load from the narrow width is being zero extended to i128. 14127 if (!ValidLDType || 14128 (LD->getExtensionType() != ISD::ZEXTLOAD && 14129 LD->getExtensionType() != ISD::EXTLOAD)) 14130 return SDValue(); 14131 14132 SDValue LoadOps[] = { 14133 LD->getChain(), LD->getBasePtr(), 14134 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14135 14136 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14137 DAG.getVTList(MVT::v1i128, MVT::Other), 14138 LoadOps, MemoryType, LD->getMemOperand()); 14139 } 14140 14141 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14142 DAGCombinerInfo &DCI) const { 14143 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14144 "Should be called with a BUILD_VECTOR node"); 14145 14146 SelectionDAG &DAG = DCI.DAG; 14147 SDLoc dl(N); 14148 14149 if (!Subtarget.hasVSX()) 14150 return SDValue(); 14151 14152 // The target independent DAG combiner will leave a build_vector of 14153 // float-to-int conversions intact. We can generate MUCH better code for 14154 // a float-to-int conversion of a vector of floats. 14155 SDValue FirstInput = N->getOperand(0); 14156 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14157 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14158 if (Reduced) 14159 return Reduced; 14160 } 14161 14162 // If we're building a vector out of consecutive loads, just load that 14163 // vector type. 14164 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14165 if (Reduced) 14166 return Reduced; 14167 14168 // If we're building a vector out of extended elements from another vector 14169 // we have P9 vector integer extend instructions. The code assumes legal 14170 // input types (i.e. it can't handle things like v4i16) so do not run before 14171 // legalization. 14172 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14173 Reduced = combineBVOfVecSExt(N, DAG); 14174 if (Reduced) 14175 return Reduced; 14176 } 14177 14178 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14179 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14180 // is a load from <valid narrow width> to i128. 14181 if (Subtarget.isISA3_1()) { 14182 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14183 if (BVOfZLoad) 14184 return BVOfZLoad; 14185 } 14186 14187 if (N->getValueType(0) != MVT::v2f64) 14188 return SDValue(); 14189 14190 // Looking for: 14191 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14192 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14193 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14194 return SDValue(); 14195 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14196 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14197 return SDValue(); 14198 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14199 return SDValue(); 14200 14201 SDValue Ext1 = FirstInput.getOperand(0); 14202 SDValue Ext2 = N->getOperand(1).getOperand(0); 14203 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14204 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14205 return SDValue(); 14206 14207 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14208 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14209 if (!Ext1Op || !Ext2Op) 14210 return SDValue(); 14211 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14212 Ext1.getOperand(0) != Ext2.getOperand(0)) 14213 return SDValue(); 14214 14215 int FirstElem = Ext1Op->getZExtValue(); 14216 int SecondElem = Ext2Op->getZExtValue(); 14217 int SubvecIdx; 14218 if (FirstElem == 0 && SecondElem == 1) 14219 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14220 else if (FirstElem == 2 && SecondElem == 3) 14221 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14222 else 14223 return SDValue(); 14224 14225 SDValue SrcVec = Ext1.getOperand(0); 14226 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14227 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14228 return DAG.getNode(NodeType, dl, MVT::v2f64, 14229 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14230 } 14231 14232 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14233 DAGCombinerInfo &DCI) const { 14234 assert((N->getOpcode() == ISD::SINT_TO_FP || 14235 N->getOpcode() == ISD::UINT_TO_FP) && 14236 "Need an int -> FP conversion node here"); 14237 14238 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14239 return SDValue(); 14240 14241 SelectionDAG &DAG = DCI.DAG; 14242 SDLoc dl(N); 14243 SDValue Op(N, 0); 14244 14245 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14246 // from the hardware. 14247 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14248 return SDValue(); 14249 if (!Op.getOperand(0).getValueType().isSimple()) 14250 return SDValue(); 14251 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14252 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14253 return SDValue(); 14254 14255 SDValue FirstOperand(Op.getOperand(0)); 14256 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14257 (FirstOperand.getValueType() == MVT::i8 || 14258 FirstOperand.getValueType() == MVT::i16); 14259 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14260 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14261 bool DstDouble = Op.getValueType() == MVT::f64; 14262 unsigned ConvOp = Signed ? 14263 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14264 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14265 SDValue WidthConst = 14266 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14267 dl, false); 14268 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14269 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14270 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14271 DAG.getVTList(MVT::f64, MVT::Other), 14272 Ops, MVT::i8, LDN->getMemOperand()); 14273 14274 // For signed conversion, we need to sign-extend the value in the VSR 14275 if (Signed) { 14276 SDValue ExtOps[] = { Ld, WidthConst }; 14277 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14278 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14279 } else 14280 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14281 } 14282 14283 14284 // For i32 intermediate values, unfortunately, the conversion functions 14285 // leave the upper 32 bits of the value are undefined. Within the set of 14286 // scalar instructions, we have no method for zero- or sign-extending the 14287 // value. Thus, we cannot handle i32 intermediate values here. 14288 if (Op.getOperand(0).getValueType() == MVT::i32) 14289 return SDValue(); 14290 14291 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14292 "UINT_TO_FP is supported only with FPCVT"); 14293 14294 // If we have FCFIDS, then use it when converting to single-precision. 14295 // Otherwise, convert to double-precision and then round. 14296 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14297 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14298 : PPCISD::FCFIDS) 14299 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14300 : PPCISD::FCFID); 14301 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14302 ? MVT::f32 14303 : MVT::f64; 14304 14305 // If we're converting from a float, to an int, and back to a float again, 14306 // then we don't need the store/load pair at all. 14307 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14308 Subtarget.hasFPCVT()) || 14309 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14310 SDValue Src = Op.getOperand(0).getOperand(0); 14311 if (Src.getValueType() == MVT::f32) { 14312 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14313 DCI.AddToWorklist(Src.getNode()); 14314 } else if (Src.getValueType() != MVT::f64) { 14315 // Make sure that we don't pick up a ppc_fp128 source value. 14316 return SDValue(); 14317 } 14318 14319 unsigned FCTOp = 14320 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14321 PPCISD::FCTIDUZ; 14322 14323 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14324 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14325 14326 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14327 FP = DAG.getNode(ISD::FP_ROUND, dl, 14328 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14329 DCI.AddToWorklist(FP.getNode()); 14330 } 14331 14332 return FP; 14333 } 14334 14335 return SDValue(); 14336 } 14337 14338 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14339 // builtins) into loads with swaps. 14340 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14341 DAGCombinerInfo &DCI) const { 14342 SelectionDAG &DAG = DCI.DAG; 14343 SDLoc dl(N); 14344 SDValue Chain; 14345 SDValue Base; 14346 MachineMemOperand *MMO; 14347 14348 switch (N->getOpcode()) { 14349 default: 14350 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14351 case ISD::LOAD: { 14352 LoadSDNode *LD = cast<LoadSDNode>(N); 14353 Chain = LD->getChain(); 14354 Base = LD->getBasePtr(); 14355 MMO = LD->getMemOperand(); 14356 // If the MMO suggests this isn't a load of a full vector, leave 14357 // things alone. For a built-in, we have to make the change for 14358 // correctness, so if there is a size problem that will be a bug. 14359 if (MMO->getSize() < 16) 14360 return SDValue(); 14361 break; 14362 } 14363 case ISD::INTRINSIC_W_CHAIN: { 14364 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14365 Chain = Intrin->getChain(); 14366 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14367 // us what we want. Get operand 2 instead. 14368 Base = Intrin->getOperand(2); 14369 MMO = Intrin->getMemOperand(); 14370 break; 14371 } 14372 } 14373 14374 MVT VecTy = N->getValueType(0).getSimpleVT(); 14375 14376 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14377 // aligned and the type is a vector with elements up to 4 bytes 14378 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14379 VecTy.getScalarSizeInBits() <= 32) { 14380 return SDValue(); 14381 } 14382 14383 SDValue LoadOps[] = { Chain, Base }; 14384 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14385 DAG.getVTList(MVT::v2f64, MVT::Other), 14386 LoadOps, MVT::v2f64, MMO); 14387 14388 DCI.AddToWorklist(Load.getNode()); 14389 Chain = Load.getValue(1); 14390 SDValue Swap = DAG.getNode( 14391 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14392 DCI.AddToWorklist(Swap.getNode()); 14393 14394 // Add a bitcast if the resulting load type doesn't match v2f64. 14395 if (VecTy != MVT::v2f64) { 14396 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14397 DCI.AddToWorklist(N.getNode()); 14398 // Package {bitcast value, swap's chain} to match Load's shape. 14399 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14400 N, Swap.getValue(1)); 14401 } 14402 14403 return Swap; 14404 } 14405 14406 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14407 // builtins) into stores with swaps. 14408 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14409 DAGCombinerInfo &DCI) const { 14410 SelectionDAG &DAG = DCI.DAG; 14411 SDLoc dl(N); 14412 SDValue Chain; 14413 SDValue Base; 14414 unsigned SrcOpnd; 14415 MachineMemOperand *MMO; 14416 14417 switch (N->getOpcode()) { 14418 default: 14419 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14420 case ISD::STORE: { 14421 StoreSDNode *ST = cast<StoreSDNode>(N); 14422 Chain = ST->getChain(); 14423 Base = ST->getBasePtr(); 14424 MMO = ST->getMemOperand(); 14425 SrcOpnd = 1; 14426 // If the MMO suggests this isn't a store of a full vector, leave 14427 // things alone. For a built-in, we have to make the change for 14428 // correctness, so if there is a size problem that will be a bug. 14429 if (MMO->getSize() < 16) 14430 return SDValue(); 14431 break; 14432 } 14433 case ISD::INTRINSIC_VOID: { 14434 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14435 Chain = Intrin->getChain(); 14436 // Intrin->getBasePtr() oddly does not get what we want. 14437 Base = Intrin->getOperand(3); 14438 MMO = Intrin->getMemOperand(); 14439 SrcOpnd = 2; 14440 break; 14441 } 14442 } 14443 14444 SDValue Src = N->getOperand(SrcOpnd); 14445 MVT VecTy = Src.getValueType().getSimpleVT(); 14446 14447 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14448 // aligned and the type is a vector with elements up to 4 bytes 14449 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14450 VecTy.getScalarSizeInBits() <= 32) { 14451 return SDValue(); 14452 } 14453 14454 // All stores are done as v2f64 and possible bit cast. 14455 if (VecTy != MVT::v2f64) { 14456 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14457 DCI.AddToWorklist(Src.getNode()); 14458 } 14459 14460 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14461 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14462 DCI.AddToWorklist(Swap.getNode()); 14463 Chain = Swap.getValue(1); 14464 SDValue StoreOps[] = { Chain, Swap, Base }; 14465 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14466 DAG.getVTList(MVT::Other), 14467 StoreOps, VecTy, MMO); 14468 DCI.AddToWorklist(Store.getNode()); 14469 return Store; 14470 } 14471 14472 // Handle DAG combine for STORE (FP_TO_INT F). 14473 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14474 DAGCombinerInfo &DCI) const { 14475 14476 SelectionDAG &DAG = DCI.DAG; 14477 SDLoc dl(N); 14478 unsigned Opcode = N->getOperand(1).getOpcode(); 14479 14480 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14481 && "Not a FP_TO_INT Instruction!"); 14482 14483 SDValue Val = N->getOperand(1).getOperand(0); 14484 EVT Op1VT = N->getOperand(1).getValueType(); 14485 EVT ResVT = Val.getValueType(); 14486 14487 if (!isTypeLegal(ResVT)) 14488 return SDValue(); 14489 14490 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14491 bool ValidTypeForStoreFltAsInt = 14492 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14493 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14494 14495 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14496 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14497 return SDValue(); 14498 14499 // Extend f32 values to f64 14500 if (ResVT.getScalarSizeInBits() == 32) { 14501 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14502 DCI.AddToWorklist(Val.getNode()); 14503 } 14504 14505 // Set signed or unsigned conversion opcode. 14506 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14507 PPCISD::FP_TO_SINT_IN_VSR : 14508 PPCISD::FP_TO_UINT_IN_VSR; 14509 14510 Val = DAG.getNode(ConvOpcode, 14511 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14512 DCI.AddToWorklist(Val.getNode()); 14513 14514 // Set number of bytes being converted. 14515 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14516 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14517 DAG.getIntPtrConstant(ByteSize, dl, false), 14518 DAG.getValueType(Op1VT) }; 14519 14520 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14521 DAG.getVTList(MVT::Other), Ops, 14522 cast<StoreSDNode>(N)->getMemoryVT(), 14523 cast<StoreSDNode>(N)->getMemOperand()); 14524 14525 DCI.AddToWorklist(Val.getNode()); 14526 return Val; 14527 } 14528 14529 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14530 // Check that the source of the element keeps flipping 14531 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14532 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14533 for (int i = 1, e = Mask.size(); i < e; i++) { 14534 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14535 return false; 14536 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14537 return false; 14538 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14539 } 14540 return true; 14541 } 14542 14543 static bool isSplatBV(SDValue Op) { 14544 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14545 return false; 14546 SDValue FirstOp; 14547 14548 // Find first non-undef input. 14549 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14550 FirstOp = Op.getOperand(i); 14551 if (!FirstOp.isUndef()) 14552 break; 14553 } 14554 14555 // All inputs are undef or the same as the first non-undef input. 14556 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14557 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14558 return false; 14559 return true; 14560 } 14561 14562 static SDValue isScalarToVec(SDValue Op) { 14563 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14564 return Op; 14565 if (Op.getOpcode() != ISD::BITCAST) 14566 return SDValue(); 14567 Op = Op.getOperand(0); 14568 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14569 return Op; 14570 return SDValue(); 14571 } 14572 14573 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14574 int LHSMaxIdx, int RHSMinIdx, 14575 int RHSMaxIdx, int HalfVec) { 14576 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14577 int Idx = ShuffV[i]; 14578 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14579 ShuffV[i] += HalfVec; 14580 } 14581 return; 14582 } 14583 14584 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14585 // the original is: 14586 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14587 // In such a case, just change the shuffle mask to extract the element 14588 // from the permuted index. 14589 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14590 SDLoc dl(OrigSToV); 14591 EVT VT = OrigSToV.getValueType(); 14592 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14593 "Expecting a SCALAR_TO_VECTOR here"); 14594 SDValue Input = OrigSToV.getOperand(0); 14595 14596 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14597 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14598 SDValue OrigVector = Input.getOperand(0); 14599 14600 // Can't handle non-const element indices or different vector types 14601 // for the input to the extract and the output of the scalar_to_vector. 14602 if (Idx && VT == OrigVector.getValueType()) { 14603 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14604 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14605 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14606 } 14607 } 14608 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14609 OrigSToV.getOperand(0)); 14610 } 14611 14612 // On little endian subtargets, combine shuffles such as: 14613 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14614 // into: 14615 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14616 // because the latter can be matched to a single instruction merge. 14617 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14618 // to put the value into element zero. Adjust the shuffle mask so that the 14619 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14620 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14621 SelectionDAG &DAG) const { 14622 SDValue LHS = SVN->getOperand(0); 14623 SDValue RHS = SVN->getOperand(1); 14624 auto Mask = SVN->getMask(); 14625 int NumElts = LHS.getValueType().getVectorNumElements(); 14626 SDValue Res(SVN, 0); 14627 SDLoc dl(SVN); 14628 14629 // None of these combines are useful on big endian systems since the ISA 14630 // already has a big endian bias. 14631 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14632 return Res; 14633 14634 // If this is not a shuffle of a shuffle and the first element comes from 14635 // the second vector, canonicalize to the commuted form. This will make it 14636 // more likely to match one of the single instruction patterns. 14637 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14638 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14639 std::swap(LHS, RHS); 14640 Res = DAG.getCommutedVectorShuffle(*SVN); 14641 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14642 } 14643 14644 // Adjust the shuffle mask if either input vector comes from a 14645 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14646 // form (to prevent the need for a swap). 14647 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14648 SDValue SToVLHS = isScalarToVec(LHS); 14649 SDValue SToVRHS = isScalarToVec(RHS); 14650 if (SToVLHS || SToVRHS) { 14651 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14652 : SToVRHS.getValueType().getVectorNumElements(); 14653 int NumEltsOut = ShuffV.size(); 14654 14655 // Initially assume that neither input is permuted. These will be adjusted 14656 // accordingly if either input is. 14657 int LHSMaxIdx = -1; 14658 int RHSMinIdx = -1; 14659 int RHSMaxIdx = -1; 14660 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14661 14662 // Get the permuted scalar to vector nodes for the source(s) that come from 14663 // ISD::SCALAR_TO_VECTOR. 14664 if (SToVLHS) { 14665 // Set up the values for the shuffle vector fixup. 14666 LHSMaxIdx = NumEltsOut / NumEltsIn; 14667 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14668 if (SToVLHS.getValueType() != LHS.getValueType()) 14669 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14670 LHS = SToVLHS; 14671 } 14672 if (SToVRHS) { 14673 RHSMinIdx = NumEltsOut; 14674 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14675 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14676 if (SToVRHS.getValueType() != RHS.getValueType()) 14677 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14678 RHS = SToVRHS; 14679 } 14680 14681 // Fix up the shuffle mask to reflect where the desired element actually is. 14682 // The minimum and maximum indices that correspond to element zero for both 14683 // the LHS and RHS are computed and will control which shuffle mask entries 14684 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14685 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14686 // HalfVec to refer to the corresponding element in the permuted vector. 14687 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14688 HalfVec); 14689 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14690 14691 // We may have simplified away the shuffle. We won't be able to do anything 14692 // further with it here. 14693 if (!isa<ShuffleVectorSDNode>(Res)) 14694 return Res; 14695 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14696 } 14697 14698 // The common case after we commuted the shuffle is that the RHS is a splat 14699 // and we have elements coming in from the splat at indices that are not 14700 // conducive to using a merge. 14701 // Example: 14702 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14703 if (!isSplatBV(RHS)) 14704 return Res; 14705 14706 // We are looking for a mask such that all even elements are from 14707 // one vector and all odd elements from the other. 14708 if (!isAlternatingShuffMask(Mask, NumElts)) 14709 return Res; 14710 14711 // Adjust the mask so we are pulling in the same index from the splat 14712 // as the index from the interesting vector in consecutive elements. 14713 // Example (even elements from first vector): 14714 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14715 if (Mask[0] < NumElts) 14716 for (int i = 1, e = Mask.size(); i < e; i += 2) 14717 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14718 // Example (odd elements from first vector): 14719 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14720 else 14721 for (int i = 0, e = Mask.size(); i < e; i += 2) 14722 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14723 14724 // If the RHS has undefs, we need to remove them since we may have created 14725 // a shuffle that adds those instead of the splat value. 14726 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14727 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14728 14729 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14730 return Res; 14731 } 14732 14733 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14734 LSBaseSDNode *LSBase, 14735 DAGCombinerInfo &DCI) const { 14736 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14737 "Not a reverse memop pattern!"); 14738 14739 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14740 auto Mask = SVN->getMask(); 14741 int i = 0; 14742 auto I = Mask.rbegin(); 14743 auto E = Mask.rend(); 14744 14745 for (; I != E; ++I) { 14746 if (*I != i) 14747 return false; 14748 i++; 14749 } 14750 return true; 14751 }; 14752 14753 SelectionDAG &DAG = DCI.DAG; 14754 EVT VT = SVN->getValueType(0); 14755 14756 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14757 return SDValue(); 14758 14759 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14760 // See comment in PPCVSXSwapRemoval.cpp. 14761 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14762 if (!Subtarget.hasP9Vector()) 14763 return SDValue(); 14764 14765 if(!IsElementReverse(SVN)) 14766 return SDValue(); 14767 14768 if (LSBase->getOpcode() == ISD::LOAD) { 14769 SDLoc dl(SVN); 14770 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14771 return DAG.getMemIntrinsicNode( 14772 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14773 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14774 } 14775 14776 if (LSBase->getOpcode() == ISD::STORE) { 14777 SDLoc dl(LSBase); 14778 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14779 LSBase->getBasePtr()}; 14780 return DAG.getMemIntrinsicNode( 14781 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14782 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14783 } 14784 14785 llvm_unreachable("Expected a load or store node here"); 14786 } 14787 14788 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14789 DAGCombinerInfo &DCI) const { 14790 SelectionDAG &DAG = DCI.DAG; 14791 SDLoc dl(N); 14792 switch (N->getOpcode()) { 14793 default: break; 14794 case ISD::ADD: 14795 return combineADD(N, DCI); 14796 case ISD::SHL: 14797 return combineSHL(N, DCI); 14798 case ISD::SRA: 14799 return combineSRA(N, DCI); 14800 case ISD::SRL: 14801 return combineSRL(N, DCI); 14802 case ISD::MUL: 14803 return combineMUL(N, DCI); 14804 case ISD::FMA: 14805 case PPCISD::FNMSUB: 14806 return combineFMALike(N, DCI); 14807 case PPCISD::SHL: 14808 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14809 return N->getOperand(0); 14810 break; 14811 case PPCISD::SRL: 14812 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14813 return N->getOperand(0); 14814 break; 14815 case PPCISD::SRA: 14816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14817 if (C->isNullValue() || // 0 >>s V -> 0. 14818 C->isAllOnesValue()) // -1 >>s V -> -1. 14819 return N->getOperand(0); 14820 } 14821 break; 14822 case ISD::SIGN_EXTEND: 14823 case ISD::ZERO_EXTEND: 14824 case ISD::ANY_EXTEND: 14825 return DAGCombineExtBoolTrunc(N, DCI); 14826 case ISD::TRUNCATE: 14827 return combineTRUNCATE(N, DCI); 14828 case ISD::SETCC: 14829 if (SDValue CSCC = combineSetCC(N, DCI)) 14830 return CSCC; 14831 LLVM_FALLTHROUGH; 14832 case ISD::SELECT_CC: 14833 return DAGCombineTruncBoolExt(N, DCI); 14834 case ISD::SINT_TO_FP: 14835 case ISD::UINT_TO_FP: 14836 return combineFPToIntToFP(N, DCI); 14837 case ISD::VECTOR_SHUFFLE: 14838 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14839 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14840 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14841 } 14842 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14843 case ISD::STORE: { 14844 14845 EVT Op1VT = N->getOperand(1).getValueType(); 14846 unsigned Opcode = N->getOperand(1).getOpcode(); 14847 14848 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14849 SDValue Val= combineStoreFPToInt(N, DCI); 14850 if (Val) 14851 return Val; 14852 } 14853 14854 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14855 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14856 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14857 if (Val) 14858 return Val; 14859 } 14860 14861 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14862 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14863 N->getOperand(1).getNode()->hasOneUse() && 14864 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14865 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14866 14867 // STBRX can only handle simple types and it makes no sense to store less 14868 // two bytes in byte-reversed order. 14869 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14870 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14871 break; 14872 14873 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14874 // Do an any-extend to 32-bits if this is a half-word input. 14875 if (BSwapOp.getValueType() == MVT::i16) 14876 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14877 14878 // If the type of BSWAP operand is wider than stored memory width 14879 // it need to be shifted to the right side before STBRX. 14880 if (Op1VT.bitsGT(mVT)) { 14881 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14882 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14883 DAG.getConstant(Shift, dl, MVT::i32)); 14884 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14885 if (Op1VT == MVT::i64) 14886 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14887 } 14888 14889 SDValue Ops[] = { 14890 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14891 }; 14892 return 14893 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14894 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14895 cast<StoreSDNode>(N)->getMemOperand()); 14896 } 14897 14898 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14899 // So it can increase the chance of CSE constant construction. 14900 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14901 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14902 // Need to sign-extended to 64-bits to handle negative values. 14903 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14904 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14905 MemVT.getSizeInBits()); 14906 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14907 14908 // DAG.getTruncStore() can't be used here because it doesn't accept 14909 // the general (base + offset) addressing mode. 14910 // So we use UpdateNodeOperands and setTruncatingStore instead. 14911 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14912 N->getOperand(3)); 14913 cast<StoreSDNode>(N)->setTruncatingStore(true); 14914 return SDValue(N, 0); 14915 } 14916 14917 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14918 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14919 if (Op1VT.isSimple()) { 14920 MVT StoreVT = Op1VT.getSimpleVT(); 14921 if (Subtarget.needsSwapsForVSXMemOps() && 14922 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14923 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14924 return expandVSXStoreForLE(N, DCI); 14925 } 14926 break; 14927 } 14928 case ISD::LOAD: { 14929 LoadSDNode *LD = cast<LoadSDNode>(N); 14930 EVT VT = LD->getValueType(0); 14931 14932 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14933 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14934 if (VT.isSimple()) { 14935 MVT LoadVT = VT.getSimpleVT(); 14936 if (Subtarget.needsSwapsForVSXMemOps() && 14937 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14938 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14939 return expandVSXLoadForLE(N, DCI); 14940 } 14941 14942 // We sometimes end up with a 64-bit integer load, from which we extract 14943 // two single-precision floating-point numbers. This happens with 14944 // std::complex<float>, and other similar structures, because of the way we 14945 // canonicalize structure copies. However, if we lack direct moves, 14946 // then the final bitcasts from the extracted integer values to the 14947 // floating-point numbers turn into store/load pairs. Even with direct moves, 14948 // just loading the two floating-point numbers is likely better. 14949 auto ReplaceTwoFloatLoad = [&]() { 14950 if (VT != MVT::i64) 14951 return false; 14952 14953 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14954 LD->isVolatile()) 14955 return false; 14956 14957 // We're looking for a sequence like this: 14958 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14959 // t16: i64 = srl t13, Constant:i32<32> 14960 // t17: i32 = truncate t16 14961 // t18: f32 = bitcast t17 14962 // t19: i32 = truncate t13 14963 // t20: f32 = bitcast t19 14964 14965 if (!LD->hasNUsesOfValue(2, 0)) 14966 return false; 14967 14968 auto UI = LD->use_begin(); 14969 while (UI.getUse().getResNo() != 0) ++UI; 14970 SDNode *Trunc = *UI++; 14971 while (UI.getUse().getResNo() != 0) ++UI; 14972 SDNode *RightShift = *UI; 14973 if (Trunc->getOpcode() != ISD::TRUNCATE) 14974 std::swap(Trunc, RightShift); 14975 14976 if (Trunc->getOpcode() != ISD::TRUNCATE || 14977 Trunc->getValueType(0) != MVT::i32 || 14978 !Trunc->hasOneUse()) 14979 return false; 14980 if (RightShift->getOpcode() != ISD::SRL || 14981 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14982 RightShift->getConstantOperandVal(1) != 32 || 14983 !RightShift->hasOneUse()) 14984 return false; 14985 14986 SDNode *Trunc2 = *RightShift->use_begin(); 14987 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14988 Trunc2->getValueType(0) != MVT::i32 || 14989 !Trunc2->hasOneUse()) 14990 return false; 14991 14992 SDNode *Bitcast = *Trunc->use_begin(); 14993 SDNode *Bitcast2 = *Trunc2->use_begin(); 14994 14995 if (Bitcast->getOpcode() != ISD::BITCAST || 14996 Bitcast->getValueType(0) != MVT::f32) 14997 return false; 14998 if (Bitcast2->getOpcode() != ISD::BITCAST || 14999 Bitcast2->getValueType(0) != MVT::f32) 15000 return false; 15001 15002 if (Subtarget.isLittleEndian()) 15003 std::swap(Bitcast, Bitcast2); 15004 15005 // Bitcast has the second float (in memory-layout order) and Bitcast2 15006 // has the first one. 15007 15008 SDValue BasePtr = LD->getBasePtr(); 15009 if (LD->isIndexed()) { 15010 assert(LD->getAddressingMode() == ISD::PRE_INC && 15011 "Non-pre-inc AM on PPC?"); 15012 BasePtr = 15013 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15014 LD->getOffset()); 15015 } 15016 15017 auto MMOFlags = 15018 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15019 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15020 LD->getPointerInfo(), LD->getAlignment(), 15021 MMOFlags, LD->getAAInfo()); 15022 SDValue AddPtr = 15023 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15024 BasePtr, DAG.getIntPtrConstant(4, dl)); 15025 SDValue FloatLoad2 = DAG.getLoad( 15026 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15027 LD->getPointerInfo().getWithOffset(4), 15028 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 15029 15030 if (LD->isIndexed()) { 15031 // Note that DAGCombine should re-form any pre-increment load(s) from 15032 // what is produced here if that makes sense. 15033 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15034 } 15035 15036 DCI.CombineTo(Bitcast2, FloatLoad); 15037 DCI.CombineTo(Bitcast, FloatLoad2); 15038 15039 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15040 SDValue(FloatLoad2.getNode(), 1)); 15041 return true; 15042 }; 15043 15044 if (ReplaceTwoFloatLoad()) 15045 return SDValue(N, 0); 15046 15047 EVT MemVT = LD->getMemoryVT(); 15048 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15049 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15050 if (LD->isUnindexed() && VT.isVector() && 15051 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15052 // P8 and later hardware should just use LOAD. 15053 !Subtarget.hasP8Vector() && 15054 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15055 VT == MVT::v4f32))) && 15056 LD->getAlign() < ABIAlignment) { 15057 // This is a type-legal unaligned Altivec load. 15058 SDValue Chain = LD->getChain(); 15059 SDValue Ptr = LD->getBasePtr(); 15060 bool isLittleEndian = Subtarget.isLittleEndian(); 15061 15062 // This implements the loading of unaligned vectors as described in 15063 // the venerable Apple Velocity Engine overview. Specifically: 15064 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15065 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15066 // 15067 // The general idea is to expand a sequence of one or more unaligned 15068 // loads into an alignment-based permutation-control instruction (lvsl 15069 // or lvsr), a series of regular vector loads (which always truncate 15070 // their input address to an aligned address), and a series of 15071 // permutations. The results of these permutations are the requested 15072 // loaded values. The trick is that the last "extra" load is not taken 15073 // from the address you might suspect (sizeof(vector) bytes after the 15074 // last requested load), but rather sizeof(vector) - 1 bytes after the 15075 // last requested vector. The point of this is to avoid a page fault if 15076 // the base address happened to be aligned. This works because if the 15077 // base address is aligned, then adding less than a full vector length 15078 // will cause the last vector in the sequence to be (re)loaded. 15079 // Otherwise, the next vector will be fetched as you might suspect was 15080 // necessary. 15081 15082 // We might be able to reuse the permutation generation from 15083 // a different base address offset from this one by an aligned amount. 15084 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15085 // optimization later. 15086 Intrinsic::ID Intr, IntrLD, IntrPerm; 15087 MVT PermCntlTy, PermTy, LDTy; 15088 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15089 : Intrinsic::ppc_altivec_lvsl; 15090 IntrLD = Intrinsic::ppc_altivec_lvx; 15091 IntrPerm = Intrinsic::ppc_altivec_vperm; 15092 PermCntlTy = MVT::v16i8; 15093 PermTy = MVT::v4i32; 15094 LDTy = MVT::v4i32; 15095 15096 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15097 15098 // Create the new MMO for the new base load. It is like the original MMO, 15099 // but represents an area in memory almost twice the vector size centered 15100 // on the original address. If the address is unaligned, we might start 15101 // reading up to (sizeof(vector)-1) bytes below the address of the 15102 // original unaligned load. 15103 MachineFunction &MF = DAG.getMachineFunction(); 15104 MachineMemOperand *BaseMMO = 15105 MF.getMachineMemOperand(LD->getMemOperand(), 15106 -(long)MemVT.getStoreSize()+1, 15107 2*MemVT.getStoreSize()-1); 15108 15109 // Create the new base load. 15110 SDValue LDXIntID = 15111 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15112 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15113 SDValue BaseLoad = 15114 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15115 DAG.getVTList(PermTy, MVT::Other), 15116 BaseLoadOps, LDTy, BaseMMO); 15117 15118 // Note that the value of IncOffset (which is provided to the next 15119 // load's pointer info offset value, and thus used to calculate the 15120 // alignment), and the value of IncValue (which is actually used to 15121 // increment the pointer value) are different! This is because we 15122 // require the next load to appear to be aligned, even though it 15123 // is actually offset from the base pointer by a lesser amount. 15124 int IncOffset = VT.getSizeInBits() / 8; 15125 int IncValue = IncOffset; 15126 15127 // Walk (both up and down) the chain looking for another load at the real 15128 // (aligned) offset (the alignment of the other load does not matter in 15129 // this case). If found, then do not use the offset reduction trick, as 15130 // that will prevent the loads from being later combined (as they would 15131 // otherwise be duplicates). 15132 if (!findConsecutiveLoad(LD, DAG)) 15133 --IncValue; 15134 15135 SDValue Increment = 15136 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15137 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15138 15139 MachineMemOperand *ExtraMMO = 15140 MF.getMachineMemOperand(LD->getMemOperand(), 15141 1, 2*MemVT.getStoreSize()-1); 15142 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15143 SDValue ExtraLoad = 15144 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15145 DAG.getVTList(PermTy, MVT::Other), 15146 ExtraLoadOps, LDTy, ExtraMMO); 15147 15148 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15149 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15150 15151 // Because vperm has a big-endian bias, we must reverse the order 15152 // of the input vectors and complement the permute control vector 15153 // when generating little endian code. We have already handled the 15154 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15155 // and ExtraLoad here. 15156 SDValue Perm; 15157 if (isLittleEndian) 15158 Perm = BuildIntrinsicOp(IntrPerm, 15159 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15160 else 15161 Perm = BuildIntrinsicOp(IntrPerm, 15162 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15163 15164 if (VT != PermTy) 15165 Perm = Subtarget.hasAltivec() 15166 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15167 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15168 DAG.getTargetConstant(1, dl, MVT::i64)); 15169 // second argument is 1 because this rounding 15170 // is always exact. 15171 15172 // The output of the permutation is our loaded result, the TokenFactor is 15173 // our new chain. 15174 DCI.CombineTo(N, Perm, TF); 15175 return SDValue(N, 0); 15176 } 15177 } 15178 break; 15179 case ISD::INTRINSIC_WO_CHAIN: { 15180 bool isLittleEndian = Subtarget.isLittleEndian(); 15181 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15182 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15183 : Intrinsic::ppc_altivec_lvsl); 15184 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15185 SDValue Add = N->getOperand(1); 15186 15187 int Bits = 4 /* 16 byte alignment */; 15188 15189 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15190 APInt::getAllOnesValue(Bits /* alignment */) 15191 .zext(Add.getScalarValueSizeInBits()))) { 15192 SDNode *BasePtr = Add->getOperand(0).getNode(); 15193 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15194 UE = BasePtr->use_end(); 15195 UI != UE; ++UI) { 15196 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15197 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 15198 IID) { 15199 // We've found another LVSL/LVSR, and this address is an aligned 15200 // multiple of that one. The results will be the same, so use the 15201 // one we've just found instead. 15202 15203 return SDValue(*UI, 0); 15204 } 15205 } 15206 } 15207 15208 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15209 SDNode *BasePtr = Add->getOperand(0).getNode(); 15210 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15211 UE = BasePtr->use_end(); UI != UE; ++UI) { 15212 if (UI->getOpcode() == ISD::ADD && 15213 isa<ConstantSDNode>(UI->getOperand(1)) && 15214 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15215 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 15216 (1ULL << Bits) == 0) { 15217 SDNode *OtherAdd = *UI; 15218 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 15219 VE = OtherAdd->use_end(); VI != VE; ++VI) { 15220 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15221 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 15222 return SDValue(*VI, 0); 15223 } 15224 } 15225 } 15226 } 15227 } 15228 } 15229 15230 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15231 // Expose the vabsduw/h/b opportunity for down stream 15232 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15233 (IID == Intrinsic::ppc_altivec_vmaxsw || 15234 IID == Intrinsic::ppc_altivec_vmaxsh || 15235 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15236 SDValue V1 = N->getOperand(1); 15237 SDValue V2 = N->getOperand(2); 15238 if ((V1.getSimpleValueType() == MVT::v4i32 || 15239 V1.getSimpleValueType() == MVT::v8i16 || 15240 V1.getSimpleValueType() == MVT::v16i8) && 15241 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15242 // (0-a, a) 15243 if (V1.getOpcode() == ISD::SUB && 15244 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15245 V1.getOperand(1) == V2) { 15246 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15247 } 15248 // (a, 0-a) 15249 if (V2.getOpcode() == ISD::SUB && 15250 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15251 V2.getOperand(1) == V1) { 15252 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15253 } 15254 // (x-y, y-x) 15255 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15256 V1.getOperand(0) == V2.getOperand(1) && 15257 V1.getOperand(1) == V2.getOperand(0)) { 15258 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15259 } 15260 } 15261 } 15262 } 15263 15264 break; 15265 case ISD::INTRINSIC_W_CHAIN: 15266 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15267 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15268 if (Subtarget.needsSwapsForVSXMemOps()) { 15269 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15270 default: 15271 break; 15272 case Intrinsic::ppc_vsx_lxvw4x: 15273 case Intrinsic::ppc_vsx_lxvd2x: 15274 return expandVSXLoadForLE(N, DCI); 15275 } 15276 } 15277 break; 15278 case ISD::INTRINSIC_VOID: 15279 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15280 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15281 if (Subtarget.needsSwapsForVSXMemOps()) { 15282 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15283 default: 15284 break; 15285 case Intrinsic::ppc_vsx_stxvw4x: 15286 case Intrinsic::ppc_vsx_stxvd2x: 15287 return expandVSXStoreForLE(N, DCI); 15288 } 15289 } 15290 break; 15291 case ISD::BSWAP: 15292 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15293 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15294 N->getOperand(0).hasOneUse() && 15295 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15296 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15297 N->getValueType(0) == MVT::i64))) { 15298 SDValue Load = N->getOperand(0); 15299 LoadSDNode *LD = cast<LoadSDNode>(Load); 15300 // Create the byte-swapping load. 15301 SDValue Ops[] = { 15302 LD->getChain(), // Chain 15303 LD->getBasePtr(), // Ptr 15304 DAG.getValueType(N->getValueType(0)) // VT 15305 }; 15306 SDValue BSLoad = 15307 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15308 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15309 MVT::i64 : MVT::i32, MVT::Other), 15310 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15311 15312 // If this is an i16 load, insert the truncate. 15313 SDValue ResVal = BSLoad; 15314 if (N->getValueType(0) == MVT::i16) 15315 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15316 15317 // First, combine the bswap away. This makes the value produced by the 15318 // load dead. 15319 DCI.CombineTo(N, ResVal); 15320 15321 // Next, combine the load away, we give it a bogus result value but a real 15322 // chain result. The result value is dead because the bswap is dead. 15323 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15324 15325 // Return N so it doesn't get rechecked! 15326 return SDValue(N, 0); 15327 } 15328 break; 15329 case PPCISD::VCMP: 15330 // If a VCMP_rec node already exists with exactly the same operands as this 15331 // node, use its result instead of this node (VCMP_rec computes both a CR6 15332 // and a normal output). 15333 // 15334 if (!N->getOperand(0).hasOneUse() && 15335 !N->getOperand(1).hasOneUse() && 15336 !N->getOperand(2).hasOneUse()) { 15337 15338 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15339 SDNode *VCMPrecNode = nullptr; 15340 15341 SDNode *LHSN = N->getOperand(0).getNode(); 15342 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15343 UI != E; ++UI) 15344 if (UI->getOpcode() == PPCISD::VCMP_rec && 15345 UI->getOperand(1) == N->getOperand(1) && 15346 UI->getOperand(2) == N->getOperand(2) && 15347 UI->getOperand(0) == N->getOperand(0)) { 15348 VCMPrecNode = *UI; 15349 break; 15350 } 15351 15352 // If there is no VCMP_rec node, or if the flag value has a single use, 15353 // don't transform this. 15354 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15355 break; 15356 15357 // Look at the (necessarily single) use of the flag value. If it has a 15358 // chain, this transformation is more complex. Note that multiple things 15359 // could use the value result, which we should ignore. 15360 SDNode *FlagUser = nullptr; 15361 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15362 FlagUser == nullptr; ++UI) { 15363 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15364 SDNode *User = *UI; 15365 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15366 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15367 FlagUser = User; 15368 break; 15369 } 15370 } 15371 } 15372 15373 // If the user is a MFOCRF instruction, we know this is safe. 15374 // Otherwise we give up for right now. 15375 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15376 return SDValue(VCMPrecNode, 0); 15377 } 15378 break; 15379 case ISD::BRCOND: { 15380 SDValue Cond = N->getOperand(1); 15381 SDValue Target = N->getOperand(2); 15382 15383 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15384 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15385 Intrinsic::loop_decrement) { 15386 15387 // We now need to make the intrinsic dead (it cannot be instruction 15388 // selected). 15389 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15390 assert(Cond.getNode()->hasOneUse() && 15391 "Counter decrement has more than one use"); 15392 15393 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15394 N->getOperand(0), Target); 15395 } 15396 } 15397 break; 15398 case ISD::BR_CC: { 15399 // If this is a branch on an altivec predicate comparison, lower this so 15400 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15401 // lowering is done pre-legalize, because the legalizer lowers the predicate 15402 // compare down to code that is difficult to reassemble. 15403 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15404 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15405 15406 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15407 // value. If so, pass-through the AND to get to the intrinsic. 15408 if (LHS.getOpcode() == ISD::AND && 15409 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15410 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15411 Intrinsic::loop_decrement && 15412 isa<ConstantSDNode>(LHS.getOperand(1)) && 15413 !isNullConstant(LHS.getOperand(1))) 15414 LHS = LHS.getOperand(0); 15415 15416 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15417 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15418 Intrinsic::loop_decrement && 15419 isa<ConstantSDNode>(RHS)) { 15420 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15421 "Counter decrement comparison is not EQ or NE"); 15422 15423 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15424 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15425 (CC == ISD::SETNE && !Val); 15426 15427 // We now need to make the intrinsic dead (it cannot be instruction 15428 // selected). 15429 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15430 assert(LHS.getNode()->hasOneUse() && 15431 "Counter decrement has more than one use"); 15432 15433 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15434 N->getOperand(0), N->getOperand(4)); 15435 } 15436 15437 int CompareOpc; 15438 bool isDot; 15439 15440 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15441 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15442 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15443 assert(isDot && "Can't compare against a vector result!"); 15444 15445 // If this is a comparison against something other than 0/1, then we know 15446 // that the condition is never/always true. 15447 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15448 if (Val != 0 && Val != 1) { 15449 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15450 return N->getOperand(0); 15451 // Always !=, turn it into an unconditional branch. 15452 return DAG.getNode(ISD::BR, dl, MVT::Other, 15453 N->getOperand(0), N->getOperand(4)); 15454 } 15455 15456 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15457 15458 // Create the PPCISD altivec 'dot' comparison node. 15459 SDValue Ops[] = { 15460 LHS.getOperand(2), // LHS of compare 15461 LHS.getOperand(3), // RHS of compare 15462 DAG.getConstant(CompareOpc, dl, MVT::i32) 15463 }; 15464 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15465 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15466 15467 // Unpack the result based on how the target uses it. 15468 PPC::Predicate CompOpc; 15469 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15470 default: // Can't happen, don't crash on invalid number though. 15471 case 0: // Branch on the value of the EQ bit of CR6. 15472 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15473 break; 15474 case 1: // Branch on the inverted value of the EQ bit of CR6. 15475 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15476 break; 15477 case 2: // Branch on the value of the LT bit of CR6. 15478 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15479 break; 15480 case 3: // Branch on the inverted value of the LT bit of CR6. 15481 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15482 break; 15483 } 15484 15485 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15486 DAG.getConstant(CompOpc, dl, MVT::i32), 15487 DAG.getRegister(PPC::CR6, MVT::i32), 15488 N->getOperand(4), CompNode.getValue(1)); 15489 } 15490 break; 15491 } 15492 case ISD::BUILD_VECTOR: 15493 return DAGCombineBuildVector(N, DCI); 15494 case ISD::ABS: 15495 return combineABS(N, DCI); 15496 case ISD::VSELECT: 15497 return combineVSelect(N, DCI); 15498 } 15499 15500 return SDValue(); 15501 } 15502 15503 SDValue 15504 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15505 SelectionDAG &DAG, 15506 SmallVectorImpl<SDNode *> &Created) const { 15507 // fold (sdiv X, pow2) 15508 EVT VT = N->getValueType(0); 15509 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15510 return SDValue(); 15511 if ((VT != MVT::i32 && VT != MVT::i64) || 15512 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15513 return SDValue(); 15514 15515 SDLoc DL(N); 15516 SDValue N0 = N->getOperand(0); 15517 15518 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15519 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15520 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15521 15522 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15523 Created.push_back(Op.getNode()); 15524 15525 if (IsNegPow2) { 15526 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15527 Created.push_back(Op.getNode()); 15528 } 15529 15530 return Op; 15531 } 15532 15533 //===----------------------------------------------------------------------===// 15534 // Inline Assembly Support 15535 //===----------------------------------------------------------------------===// 15536 15537 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15538 KnownBits &Known, 15539 const APInt &DemandedElts, 15540 const SelectionDAG &DAG, 15541 unsigned Depth) const { 15542 Known.resetAll(); 15543 switch (Op.getOpcode()) { 15544 default: break; 15545 case PPCISD::LBRX: { 15546 // lhbrx is known to have the top bits cleared out. 15547 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15548 Known.Zero = 0xFFFF0000; 15549 break; 15550 } 15551 case ISD::INTRINSIC_WO_CHAIN: { 15552 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15553 default: break; 15554 case Intrinsic::ppc_altivec_vcmpbfp_p: 15555 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15556 case Intrinsic::ppc_altivec_vcmpequb_p: 15557 case Intrinsic::ppc_altivec_vcmpequh_p: 15558 case Intrinsic::ppc_altivec_vcmpequw_p: 15559 case Intrinsic::ppc_altivec_vcmpequd_p: 15560 case Intrinsic::ppc_altivec_vcmpequq_p: 15561 case Intrinsic::ppc_altivec_vcmpgefp_p: 15562 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15563 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15564 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15565 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15566 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15567 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15568 case Intrinsic::ppc_altivec_vcmpgtub_p: 15569 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15570 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15571 case Intrinsic::ppc_altivec_vcmpgtud_p: 15572 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15573 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15574 break; 15575 } 15576 } 15577 } 15578 } 15579 15580 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15581 switch (Subtarget.getCPUDirective()) { 15582 default: break; 15583 case PPC::DIR_970: 15584 case PPC::DIR_PWR4: 15585 case PPC::DIR_PWR5: 15586 case PPC::DIR_PWR5X: 15587 case PPC::DIR_PWR6: 15588 case PPC::DIR_PWR6X: 15589 case PPC::DIR_PWR7: 15590 case PPC::DIR_PWR8: 15591 case PPC::DIR_PWR9: 15592 case PPC::DIR_PWR10: 15593 case PPC::DIR_PWR_FUTURE: { 15594 if (!ML) 15595 break; 15596 15597 if (!DisableInnermostLoopAlign32) { 15598 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15599 // so that we can decrease cache misses and branch-prediction misses. 15600 // Actual alignment of the loop will depend on the hotness check and other 15601 // logic in alignBlocks. 15602 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15603 return Align(32); 15604 } 15605 15606 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15607 15608 // For small loops (between 5 and 8 instructions), align to a 32-byte 15609 // boundary so that the entire loop fits in one instruction-cache line. 15610 uint64_t LoopSize = 0; 15611 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15612 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15613 LoopSize += TII->getInstSizeInBytes(*J); 15614 if (LoopSize > 32) 15615 break; 15616 } 15617 15618 if (LoopSize > 16 && LoopSize <= 32) 15619 return Align(32); 15620 15621 break; 15622 } 15623 } 15624 15625 return TargetLowering::getPrefLoopAlignment(ML); 15626 } 15627 15628 /// getConstraintType - Given a constraint, return the type of 15629 /// constraint it is for this target. 15630 PPCTargetLowering::ConstraintType 15631 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15632 if (Constraint.size() == 1) { 15633 switch (Constraint[0]) { 15634 default: break; 15635 case 'b': 15636 case 'r': 15637 case 'f': 15638 case 'd': 15639 case 'v': 15640 case 'y': 15641 return C_RegisterClass; 15642 case 'Z': 15643 // FIXME: While Z does indicate a memory constraint, it specifically 15644 // indicates an r+r address (used in conjunction with the 'y' modifier 15645 // in the replacement string). Currently, we're forcing the base 15646 // register to be r0 in the asm printer (which is interpreted as zero) 15647 // and forming the complete address in the second register. This is 15648 // suboptimal. 15649 return C_Memory; 15650 } 15651 } else if (Constraint == "wc") { // individual CR bits. 15652 return C_RegisterClass; 15653 } else if (Constraint == "wa" || Constraint == "wd" || 15654 Constraint == "wf" || Constraint == "ws" || 15655 Constraint == "wi" || Constraint == "ww") { 15656 return C_RegisterClass; // VSX registers. 15657 } 15658 return TargetLowering::getConstraintType(Constraint); 15659 } 15660 15661 /// Examine constraint type and operand type and determine a weight value. 15662 /// This object must already have been set up with the operand type 15663 /// and the current alternative constraint selected. 15664 TargetLowering::ConstraintWeight 15665 PPCTargetLowering::getSingleConstraintMatchWeight( 15666 AsmOperandInfo &info, const char *constraint) const { 15667 ConstraintWeight weight = CW_Invalid; 15668 Value *CallOperandVal = info.CallOperandVal; 15669 // If we don't have a value, we can't do a match, 15670 // but allow it at the lowest weight. 15671 if (!CallOperandVal) 15672 return CW_Default; 15673 Type *type = CallOperandVal->getType(); 15674 15675 // Look at the constraint type. 15676 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15677 return CW_Register; // an individual CR bit. 15678 else if ((StringRef(constraint) == "wa" || 15679 StringRef(constraint) == "wd" || 15680 StringRef(constraint) == "wf") && 15681 type->isVectorTy()) 15682 return CW_Register; 15683 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15684 return CW_Register; // just hold 64-bit integers data. 15685 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15686 return CW_Register; 15687 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15688 return CW_Register; 15689 15690 switch (*constraint) { 15691 default: 15692 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15693 break; 15694 case 'b': 15695 if (type->isIntegerTy()) 15696 weight = CW_Register; 15697 break; 15698 case 'f': 15699 if (type->isFloatTy()) 15700 weight = CW_Register; 15701 break; 15702 case 'd': 15703 if (type->isDoubleTy()) 15704 weight = CW_Register; 15705 break; 15706 case 'v': 15707 if (type->isVectorTy()) 15708 weight = CW_Register; 15709 break; 15710 case 'y': 15711 weight = CW_Register; 15712 break; 15713 case 'Z': 15714 weight = CW_Memory; 15715 break; 15716 } 15717 return weight; 15718 } 15719 15720 std::pair<unsigned, const TargetRegisterClass *> 15721 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15722 StringRef Constraint, 15723 MVT VT) const { 15724 if (Constraint.size() == 1) { 15725 // GCC RS6000 Constraint Letters 15726 switch (Constraint[0]) { 15727 case 'b': // R1-R31 15728 if (VT == MVT::i64 && Subtarget.isPPC64()) 15729 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15730 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15731 case 'r': // R0-R31 15732 if (VT == MVT::i64 && Subtarget.isPPC64()) 15733 return std::make_pair(0U, &PPC::G8RCRegClass); 15734 return std::make_pair(0U, &PPC::GPRCRegClass); 15735 // 'd' and 'f' constraints are both defined to be "the floating point 15736 // registers", where one is for 32-bit and the other for 64-bit. We don't 15737 // really care overly much here so just give them all the same reg classes. 15738 case 'd': 15739 case 'f': 15740 if (Subtarget.hasSPE()) { 15741 if (VT == MVT::f32 || VT == MVT::i32) 15742 return std::make_pair(0U, &PPC::GPRCRegClass); 15743 if (VT == MVT::f64 || VT == MVT::i64) 15744 return std::make_pair(0U, &PPC::SPERCRegClass); 15745 } else { 15746 if (VT == MVT::f32 || VT == MVT::i32) 15747 return std::make_pair(0U, &PPC::F4RCRegClass); 15748 if (VT == MVT::f64 || VT == MVT::i64) 15749 return std::make_pair(0U, &PPC::F8RCRegClass); 15750 } 15751 break; 15752 case 'v': 15753 if (Subtarget.hasAltivec()) 15754 return std::make_pair(0U, &PPC::VRRCRegClass); 15755 break; 15756 case 'y': // crrc 15757 return std::make_pair(0U, &PPC::CRRCRegClass); 15758 } 15759 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15760 // An individual CR bit. 15761 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15762 } else if ((Constraint == "wa" || Constraint == "wd" || 15763 Constraint == "wf" || Constraint == "wi") && 15764 Subtarget.hasVSX()) { 15765 return std::make_pair(0U, &PPC::VSRCRegClass); 15766 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15767 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15768 return std::make_pair(0U, &PPC::VSSRCRegClass); 15769 else 15770 return std::make_pair(0U, &PPC::VSFRCRegClass); 15771 } 15772 15773 // If we name a VSX register, we can't defer to the base class because it 15774 // will not recognize the correct register (their names will be VSL{0-31} 15775 // and V{0-31} so they won't match). So we match them here. 15776 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15777 int VSNum = atoi(Constraint.data() + 3); 15778 assert(VSNum >= 0 && VSNum <= 63 && 15779 "Attempted to access a vsr out of range"); 15780 if (VSNum < 32) 15781 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15782 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15783 } 15784 std::pair<unsigned, const TargetRegisterClass *> R = 15785 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15786 15787 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15788 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15789 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15790 // register. 15791 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15792 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15793 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15794 PPC::GPRCRegClass.contains(R.first)) 15795 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15796 PPC::sub_32, &PPC::G8RCRegClass), 15797 &PPC::G8RCRegClass); 15798 15799 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15800 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15801 R.first = PPC::CR0; 15802 R.second = &PPC::CRRCRegClass; 15803 } 15804 15805 return R; 15806 } 15807 15808 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15809 /// vector. If it is invalid, don't add anything to Ops. 15810 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15811 std::string &Constraint, 15812 std::vector<SDValue>&Ops, 15813 SelectionDAG &DAG) const { 15814 SDValue Result; 15815 15816 // Only support length 1 constraints. 15817 if (Constraint.length() > 1) return; 15818 15819 char Letter = Constraint[0]; 15820 switch (Letter) { 15821 default: break; 15822 case 'I': 15823 case 'J': 15824 case 'K': 15825 case 'L': 15826 case 'M': 15827 case 'N': 15828 case 'O': 15829 case 'P': { 15830 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15831 if (!CST) return; // Must be an immediate to match. 15832 SDLoc dl(Op); 15833 int64_t Value = CST->getSExtValue(); 15834 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15835 // numbers are printed as such. 15836 switch (Letter) { 15837 default: llvm_unreachable("Unknown constraint letter!"); 15838 case 'I': // "I" is a signed 16-bit constant. 15839 if (isInt<16>(Value)) 15840 Result = DAG.getTargetConstant(Value, dl, TCVT); 15841 break; 15842 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15843 if (isShiftedUInt<16, 16>(Value)) 15844 Result = DAG.getTargetConstant(Value, dl, TCVT); 15845 break; 15846 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15847 if (isShiftedInt<16, 16>(Value)) 15848 Result = DAG.getTargetConstant(Value, dl, TCVT); 15849 break; 15850 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15851 if (isUInt<16>(Value)) 15852 Result = DAG.getTargetConstant(Value, dl, TCVT); 15853 break; 15854 case 'M': // "M" is a constant that is greater than 31. 15855 if (Value > 31) 15856 Result = DAG.getTargetConstant(Value, dl, TCVT); 15857 break; 15858 case 'N': // "N" is a positive constant that is an exact power of two. 15859 if (Value > 0 && isPowerOf2_64(Value)) 15860 Result = DAG.getTargetConstant(Value, dl, TCVT); 15861 break; 15862 case 'O': // "O" is the constant zero. 15863 if (Value == 0) 15864 Result = DAG.getTargetConstant(Value, dl, TCVT); 15865 break; 15866 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15867 if (isInt<16>(-Value)) 15868 Result = DAG.getTargetConstant(Value, dl, TCVT); 15869 break; 15870 } 15871 break; 15872 } 15873 } 15874 15875 if (Result.getNode()) { 15876 Ops.push_back(Result); 15877 return; 15878 } 15879 15880 // Handle standard constraint letters. 15881 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15882 } 15883 15884 // isLegalAddressingMode - Return true if the addressing mode represented 15885 // by AM is legal for this target, for a load/store of the specified type. 15886 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15887 const AddrMode &AM, Type *Ty, 15888 unsigned AS, 15889 Instruction *I) const { 15890 // Vector type r+i form is supported since power9 as DQ form. We don't check 15891 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15892 // imm form is preferred and the offset can be adjusted to use imm form later 15893 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15894 // max offset to check legal addressing mode, we should be a little aggressive 15895 // to contain other offsets for that LSRUse. 15896 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15897 return false; 15898 15899 // PPC allows a sign-extended 16-bit immediate field. 15900 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15901 return false; 15902 15903 // No global is ever allowed as a base. 15904 if (AM.BaseGV) 15905 return false; 15906 15907 // PPC only support r+r, 15908 switch (AM.Scale) { 15909 case 0: // "r+i" or just "i", depending on HasBaseReg. 15910 break; 15911 case 1: 15912 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15913 return false; 15914 // Otherwise we have r+r or r+i. 15915 break; 15916 case 2: 15917 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15918 return false; 15919 // Allow 2*r as r+r. 15920 break; 15921 default: 15922 // No other scales are supported. 15923 return false; 15924 } 15925 15926 return true; 15927 } 15928 15929 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15930 SelectionDAG &DAG) const { 15931 MachineFunction &MF = DAG.getMachineFunction(); 15932 MachineFrameInfo &MFI = MF.getFrameInfo(); 15933 MFI.setReturnAddressIsTaken(true); 15934 15935 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15936 return SDValue(); 15937 15938 SDLoc dl(Op); 15939 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15940 15941 // Make sure the function does not optimize away the store of the RA to 15942 // the stack. 15943 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15944 FuncInfo->setLRStoreRequired(); 15945 bool isPPC64 = Subtarget.isPPC64(); 15946 auto PtrVT = getPointerTy(MF.getDataLayout()); 15947 15948 if (Depth > 0) { 15949 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15950 SDValue Offset = 15951 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15952 isPPC64 ? MVT::i64 : MVT::i32); 15953 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15954 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15955 MachinePointerInfo()); 15956 } 15957 15958 // Just load the return address off the stack. 15959 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15960 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15961 MachinePointerInfo()); 15962 } 15963 15964 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15965 SelectionDAG &DAG) const { 15966 SDLoc dl(Op); 15967 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15968 15969 MachineFunction &MF = DAG.getMachineFunction(); 15970 MachineFrameInfo &MFI = MF.getFrameInfo(); 15971 MFI.setFrameAddressIsTaken(true); 15972 15973 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15974 bool isPPC64 = PtrVT == MVT::i64; 15975 15976 // Naked functions never have a frame pointer, and so we use r1. For all 15977 // other functions, this decision must be delayed until during PEI. 15978 unsigned FrameReg; 15979 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15980 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15981 else 15982 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15983 15984 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15985 PtrVT); 15986 while (Depth--) 15987 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15988 FrameAddr, MachinePointerInfo()); 15989 return FrameAddr; 15990 } 15991 15992 // FIXME? Maybe this could be a TableGen attribute on some registers and 15993 // this table could be generated automatically from RegInfo. 15994 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15995 const MachineFunction &MF) const { 15996 bool isPPC64 = Subtarget.isPPC64(); 15997 15998 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15999 if (!is64Bit && VT != LLT::scalar(32)) 16000 report_fatal_error("Invalid register global variable type"); 16001 16002 Register Reg = StringSwitch<Register>(RegName) 16003 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16004 .Case("r2", isPPC64 ? Register() : PPC::R2) 16005 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16006 .Default(Register()); 16007 16008 if (Reg) 16009 return Reg; 16010 report_fatal_error("Invalid register name global variable"); 16011 } 16012 16013 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16014 // 32-bit SVR4 ABI access everything as got-indirect. 16015 if (Subtarget.is32BitELFABI()) 16016 return true; 16017 16018 // AIX accesses everything indirectly through the TOC, which is similar to 16019 // the GOT. 16020 if (Subtarget.isAIXABI()) 16021 return true; 16022 16023 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16024 // If it is small or large code model, module locals are accessed 16025 // indirectly by loading their address from .toc/.got. 16026 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16027 return true; 16028 16029 // JumpTable and BlockAddress are accessed as got-indirect. 16030 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16031 return true; 16032 16033 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16034 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16035 16036 return false; 16037 } 16038 16039 bool 16040 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16041 // The PowerPC target isn't yet aware of offsets. 16042 return false; 16043 } 16044 16045 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16046 const CallInst &I, 16047 MachineFunction &MF, 16048 unsigned Intrinsic) const { 16049 switch (Intrinsic) { 16050 case Intrinsic::ppc_altivec_lvx: 16051 case Intrinsic::ppc_altivec_lvxl: 16052 case Intrinsic::ppc_altivec_lvebx: 16053 case Intrinsic::ppc_altivec_lvehx: 16054 case Intrinsic::ppc_altivec_lvewx: 16055 case Intrinsic::ppc_vsx_lxvd2x: 16056 case Intrinsic::ppc_vsx_lxvw4x: 16057 case Intrinsic::ppc_vsx_lxvd2x_be: 16058 case Intrinsic::ppc_vsx_lxvw4x_be: 16059 case Intrinsic::ppc_vsx_lxvl: 16060 case Intrinsic::ppc_vsx_lxvll: { 16061 EVT VT; 16062 switch (Intrinsic) { 16063 case Intrinsic::ppc_altivec_lvebx: 16064 VT = MVT::i8; 16065 break; 16066 case Intrinsic::ppc_altivec_lvehx: 16067 VT = MVT::i16; 16068 break; 16069 case Intrinsic::ppc_altivec_lvewx: 16070 VT = MVT::i32; 16071 break; 16072 case Intrinsic::ppc_vsx_lxvd2x: 16073 case Intrinsic::ppc_vsx_lxvd2x_be: 16074 VT = MVT::v2f64; 16075 break; 16076 default: 16077 VT = MVT::v4i32; 16078 break; 16079 } 16080 16081 Info.opc = ISD::INTRINSIC_W_CHAIN; 16082 Info.memVT = VT; 16083 Info.ptrVal = I.getArgOperand(0); 16084 Info.offset = -VT.getStoreSize()+1; 16085 Info.size = 2*VT.getStoreSize()-1; 16086 Info.align = Align(1); 16087 Info.flags = MachineMemOperand::MOLoad; 16088 return true; 16089 } 16090 case Intrinsic::ppc_altivec_stvx: 16091 case Intrinsic::ppc_altivec_stvxl: 16092 case Intrinsic::ppc_altivec_stvebx: 16093 case Intrinsic::ppc_altivec_stvehx: 16094 case Intrinsic::ppc_altivec_stvewx: 16095 case Intrinsic::ppc_vsx_stxvd2x: 16096 case Intrinsic::ppc_vsx_stxvw4x: 16097 case Intrinsic::ppc_vsx_stxvd2x_be: 16098 case Intrinsic::ppc_vsx_stxvw4x_be: 16099 case Intrinsic::ppc_vsx_stxvl: 16100 case Intrinsic::ppc_vsx_stxvll: { 16101 EVT VT; 16102 switch (Intrinsic) { 16103 case Intrinsic::ppc_altivec_stvebx: 16104 VT = MVT::i8; 16105 break; 16106 case Intrinsic::ppc_altivec_stvehx: 16107 VT = MVT::i16; 16108 break; 16109 case Intrinsic::ppc_altivec_stvewx: 16110 VT = MVT::i32; 16111 break; 16112 case Intrinsic::ppc_vsx_stxvd2x: 16113 case Intrinsic::ppc_vsx_stxvd2x_be: 16114 VT = MVT::v2f64; 16115 break; 16116 default: 16117 VT = MVT::v4i32; 16118 break; 16119 } 16120 16121 Info.opc = ISD::INTRINSIC_VOID; 16122 Info.memVT = VT; 16123 Info.ptrVal = I.getArgOperand(1); 16124 Info.offset = -VT.getStoreSize()+1; 16125 Info.size = 2*VT.getStoreSize()-1; 16126 Info.align = Align(1); 16127 Info.flags = MachineMemOperand::MOStore; 16128 return true; 16129 } 16130 default: 16131 break; 16132 } 16133 16134 return false; 16135 } 16136 16137 /// It returns EVT::Other if the type should be determined using generic 16138 /// target-independent logic. 16139 EVT PPCTargetLowering::getOptimalMemOpType( 16140 const MemOp &Op, const AttributeList &FuncAttributes) const { 16141 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16142 // We should use Altivec/VSX loads and stores when available. For unaligned 16143 // addresses, unaligned VSX loads are only fast starting with the P8. 16144 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16145 (Op.isAligned(Align(16)) || 16146 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16147 return MVT::v4i32; 16148 } 16149 16150 if (Subtarget.isPPC64()) { 16151 return MVT::i64; 16152 } 16153 16154 return MVT::i32; 16155 } 16156 16157 /// Returns true if it is beneficial to convert a load of a constant 16158 /// to just the constant itself. 16159 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16160 Type *Ty) const { 16161 assert(Ty->isIntegerTy()); 16162 16163 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16164 return !(BitSize == 0 || BitSize > 64); 16165 } 16166 16167 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16168 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16169 return false; 16170 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16171 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16172 return NumBits1 == 64 && NumBits2 == 32; 16173 } 16174 16175 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16176 if (!VT1.isInteger() || !VT2.isInteger()) 16177 return false; 16178 unsigned NumBits1 = VT1.getSizeInBits(); 16179 unsigned NumBits2 = VT2.getSizeInBits(); 16180 return NumBits1 == 64 && NumBits2 == 32; 16181 } 16182 16183 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16184 // Generally speaking, zexts are not free, but they are free when they can be 16185 // folded with other operations. 16186 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16187 EVT MemVT = LD->getMemoryVT(); 16188 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16189 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16190 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16191 LD->getExtensionType() == ISD::ZEXTLOAD)) 16192 return true; 16193 } 16194 16195 // FIXME: Add other cases... 16196 // - 32-bit shifts with a zext to i64 16197 // - zext after ctlz, bswap, etc. 16198 // - zext after and by a constant mask 16199 16200 return TargetLowering::isZExtFree(Val, VT2); 16201 } 16202 16203 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16204 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16205 "invalid fpext types"); 16206 // Extending to float128 is not free. 16207 if (DestVT == MVT::f128) 16208 return false; 16209 return true; 16210 } 16211 16212 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16213 return isInt<16>(Imm) || isUInt<16>(Imm); 16214 } 16215 16216 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16217 return isInt<16>(Imm) || isUInt<16>(Imm); 16218 } 16219 16220 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 16221 unsigned, 16222 unsigned, 16223 MachineMemOperand::Flags, 16224 bool *Fast) const { 16225 if (DisablePPCUnaligned) 16226 return false; 16227 16228 // PowerPC supports unaligned memory access for simple non-vector types. 16229 // Although accessing unaligned addresses is not as efficient as accessing 16230 // aligned addresses, it is generally more efficient than manual expansion, 16231 // and generally only traps for software emulation when crossing page 16232 // boundaries. 16233 16234 if (!VT.isSimple()) 16235 return false; 16236 16237 if (VT.isFloatingPoint() && !VT.isVector() && 16238 !Subtarget.allowsUnalignedFPAccess()) 16239 return false; 16240 16241 if (VT.getSimpleVT().isVector()) { 16242 if (Subtarget.hasVSX()) { 16243 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16244 VT != MVT::v4f32 && VT != MVT::v4i32) 16245 return false; 16246 } else { 16247 return false; 16248 } 16249 } 16250 16251 if (VT == MVT::ppcf128) 16252 return false; 16253 16254 if (Fast) 16255 *Fast = true; 16256 16257 return true; 16258 } 16259 16260 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16261 SDValue C) const { 16262 // Check integral scalar types. 16263 if (!VT.isScalarInteger()) 16264 return false; 16265 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16266 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16267 return false; 16268 // This transformation will generate >= 2 operations. But the following 16269 // cases will generate <= 2 instructions during ISEL. So exclude them. 16270 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16271 // HW instruction, ie. MULLI 16272 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16273 // instruction is needed than case 1, ie. MULLI and RLDICR 16274 int64_t Imm = ConstNode->getSExtValue(); 16275 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16276 Imm >>= Shift; 16277 if (isInt<16>(Imm)) 16278 return false; 16279 uint64_t UImm = static_cast<uint64_t>(Imm); 16280 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16281 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16282 return true; 16283 } 16284 return false; 16285 } 16286 16287 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16288 EVT VT) const { 16289 return isFMAFasterThanFMulAndFAdd( 16290 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16291 } 16292 16293 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16294 Type *Ty) const { 16295 switch (Ty->getScalarType()->getTypeID()) { 16296 case Type::FloatTyID: 16297 case Type::DoubleTyID: 16298 return true; 16299 case Type::FP128TyID: 16300 return Subtarget.hasP9Vector(); 16301 default: 16302 return false; 16303 } 16304 } 16305 16306 // FIXME: add more patterns which are not profitable to hoist. 16307 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16308 if (!I->hasOneUse()) 16309 return true; 16310 16311 Instruction *User = I->user_back(); 16312 assert(User && "A single use instruction with no uses."); 16313 16314 switch (I->getOpcode()) { 16315 case Instruction::FMul: { 16316 // Don't break FMA, PowerPC prefers FMA. 16317 if (User->getOpcode() != Instruction::FSub && 16318 User->getOpcode() != Instruction::FAdd) 16319 return true; 16320 16321 const TargetOptions &Options = getTargetMachine().Options; 16322 const Function *F = I->getFunction(); 16323 const DataLayout &DL = F->getParent()->getDataLayout(); 16324 Type *Ty = User->getOperand(0)->getType(); 16325 16326 return !( 16327 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16328 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16329 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16330 } 16331 case Instruction::Load: { 16332 // Don't break "store (load float*)" pattern, this pattern will be combined 16333 // to "store (load int32)" in later InstCombine pass. See function 16334 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16335 // cycles than loading a 32 bit integer. 16336 LoadInst *LI = cast<LoadInst>(I); 16337 // For the loads that combineLoadToOperationType does nothing, like 16338 // ordered load, it should be profitable to hoist them. 16339 // For swifterror load, it can only be used for pointer to pointer type, so 16340 // later type check should get rid of this case. 16341 if (!LI->isUnordered()) 16342 return true; 16343 16344 if (User->getOpcode() != Instruction::Store) 16345 return true; 16346 16347 if (I->getType()->getTypeID() != Type::FloatTyID) 16348 return true; 16349 16350 return false; 16351 } 16352 default: 16353 return true; 16354 } 16355 return true; 16356 } 16357 16358 const MCPhysReg * 16359 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16360 // LR is a callee-save register, but we must treat it as clobbered by any call 16361 // site. Hence we include LR in the scratch registers, which are in turn added 16362 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16363 // to CTR, which is used by any indirect call. 16364 static const MCPhysReg ScratchRegs[] = { 16365 PPC::X12, PPC::LR8, PPC::CTR8, 0 16366 }; 16367 16368 return ScratchRegs; 16369 } 16370 16371 Register PPCTargetLowering::getExceptionPointerRegister( 16372 const Constant *PersonalityFn) const { 16373 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16374 } 16375 16376 Register PPCTargetLowering::getExceptionSelectorRegister( 16377 const Constant *PersonalityFn) const { 16378 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16379 } 16380 16381 bool 16382 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16383 EVT VT , unsigned DefinedValues) const { 16384 if (VT == MVT::v2i64) 16385 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16386 16387 if (Subtarget.hasVSX()) 16388 return true; 16389 16390 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16391 } 16392 16393 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16394 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16395 return TargetLowering::getSchedulingPreference(N); 16396 16397 return Sched::ILP; 16398 } 16399 16400 // Create a fast isel object. 16401 FastISel * 16402 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16403 const TargetLibraryInfo *LibInfo) const { 16404 return PPC::createFastISel(FuncInfo, LibInfo); 16405 } 16406 16407 // 'Inverted' means the FMA opcode after negating one multiplicand. 16408 // For example, (fma -a b c) = (fnmsub a b c) 16409 static unsigned invertFMAOpcode(unsigned Opc) { 16410 switch (Opc) { 16411 default: 16412 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16413 case ISD::FMA: 16414 return PPCISD::FNMSUB; 16415 case PPCISD::FNMSUB: 16416 return ISD::FMA; 16417 } 16418 } 16419 16420 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16421 bool LegalOps, bool OptForSize, 16422 NegatibleCost &Cost, 16423 unsigned Depth) const { 16424 if (Depth > SelectionDAG::MaxRecursionDepth) 16425 return SDValue(); 16426 16427 unsigned Opc = Op.getOpcode(); 16428 EVT VT = Op.getValueType(); 16429 SDNodeFlags Flags = Op.getNode()->getFlags(); 16430 16431 switch (Opc) { 16432 case PPCISD::FNMSUB: 16433 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16434 break; 16435 16436 const TargetOptions &Options = getTargetMachine().Options; 16437 SDValue N0 = Op.getOperand(0); 16438 SDValue N1 = Op.getOperand(1); 16439 SDValue N2 = Op.getOperand(2); 16440 SDLoc Loc(Op); 16441 16442 NegatibleCost N2Cost = NegatibleCost::Expensive; 16443 SDValue NegN2 = 16444 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16445 16446 if (!NegN2) 16447 return SDValue(); 16448 16449 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16450 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16451 // These transformations may change sign of zeroes. For example, 16452 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16453 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16454 // Try and choose the cheaper one to negate. 16455 NegatibleCost N0Cost = NegatibleCost::Expensive; 16456 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16457 N0Cost, Depth + 1); 16458 16459 NegatibleCost N1Cost = NegatibleCost::Expensive; 16460 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16461 N1Cost, Depth + 1); 16462 16463 if (NegN0 && N0Cost <= N1Cost) { 16464 Cost = std::min(N0Cost, N2Cost); 16465 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16466 } else if (NegN1) { 16467 Cost = std::min(N1Cost, N2Cost); 16468 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16469 } 16470 } 16471 16472 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16473 if (isOperationLegal(ISD::FMA, VT)) { 16474 Cost = N2Cost; 16475 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16476 } 16477 16478 break; 16479 } 16480 16481 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16482 Cost, Depth); 16483 } 16484 16485 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16486 bool PPCTargetLowering::useLoadStackGuardNode() const { 16487 if (!Subtarget.isTargetLinux()) 16488 return TargetLowering::useLoadStackGuardNode(); 16489 return true; 16490 } 16491 16492 // Override to disable global variable loading on Linux. 16493 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16494 if (!Subtarget.isTargetLinux()) 16495 return TargetLowering::insertSSPDeclarations(M); 16496 } 16497 16498 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16499 bool ForCodeSize) const { 16500 if (!VT.isSimple() || !Subtarget.hasVSX()) 16501 return false; 16502 16503 switch(VT.getSimpleVT().SimpleTy) { 16504 default: 16505 // For FP types that are currently not supported by PPC backend, return 16506 // false. Examples: f16, f80. 16507 return false; 16508 case MVT::f32: 16509 case MVT::f64: 16510 if (Subtarget.hasPrefixInstrs()) { 16511 // With prefixed instructions, we can materialize anything that can be 16512 // represented with a 32-bit immediate, not just positive zero. 16513 APFloat APFloatOfImm = Imm; 16514 return convertToNonDenormSingle(APFloatOfImm); 16515 } 16516 LLVM_FALLTHROUGH; 16517 case MVT::ppcf128: 16518 return Imm.isPosZero(); 16519 } 16520 } 16521 16522 // For vector shift operation op, fold 16523 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16524 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16525 SelectionDAG &DAG) { 16526 SDValue N0 = N->getOperand(0); 16527 SDValue N1 = N->getOperand(1); 16528 EVT VT = N0.getValueType(); 16529 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16530 unsigned Opcode = N->getOpcode(); 16531 unsigned TargetOpcode; 16532 16533 switch (Opcode) { 16534 default: 16535 llvm_unreachable("Unexpected shift operation"); 16536 case ISD::SHL: 16537 TargetOpcode = PPCISD::SHL; 16538 break; 16539 case ISD::SRL: 16540 TargetOpcode = PPCISD::SRL; 16541 break; 16542 case ISD::SRA: 16543 TargetOpcode = PPCISD::SRA; 16544 break; 16545 } 16546 16547 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16548 N1->getOpcode() == ISD::AND) 16549 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16550 if (Mask->getZExtValue() == OpSizeInBits - 1) 16551 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16552 16553 return SDValue(); 16554 } 16555 16556 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16557 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16558 return Value; 16559 16560 SDValue N0 = N->getOperand(0); 16561 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16562 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16563 N0.getOpcode() != ISD::SIGN_EXTEND || 16564 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16565 N->getValueType(0) != MVT::i64) 16566 return SDValue(); 16567 16568 // We can't save an operation here if the value is already extended, and 16569 // the existing shift is easier to combine. 16570 SDValue ExtsSrc = N0.getOperand(0); 16571 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16572 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16573 return SDValue(); 16574 16575 SDLoc DL(N0); 16576 SDValue ShiftBy = SDValue(CN1, 0); 16577 // We want the shift amount to be i32 on the extswli, but the shift could 16578 // have an i64. 16579 if (ShiftBy.getValueType() == MVT::i64) 16580 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16581 16582 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16583 ShiftBy); 16584 } 16585 16586 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16587 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16588 return Value; 16589 16590 return SDValue(); 16591 } 16592 16593 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16594 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16595 return Value; 16596 16597 return SDValue(); 16598 } 16599 16600 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16601 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16602 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16603 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16604 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16605 const PPCSubtarget &Subtarget) { 16606 if (!Subtarget.isPPC64()) 16607 return SDValue(); 16608 16609 SDValue LHS = N->getOperand(0); 16610 SDValue RHS = N->getOperand(1); 16611 16612 auto isZextOfCompareWithConstant = [](SDValue Op) { 16613 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16614 Op.getValueType() != MVT::i64) 16615 return false; 16616 16617 SDValue Cmp = Op.getOperand(0); 16618 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16619 Cmp.getOperand(0).getValueType() != MVT::i64) 16620 return false; 16621 16622 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16623 int64_t NegConstant = 0 - Constant->getSExtValue(); 16624 // Due to the limitations of the addi instruction, 16625 // -C is required to be [-32768, 32767]. 16626 return isInt<16>(NegConstant); 16627 } 16628 16629 return false; 16630 }; 16631 16632 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16633 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16634 16635 // If there is a pattern, canonicalize a zext operand to the RHS. 16636 if (LHSHasPattern && !RHSHasPattern) 16637 std::swap(LHS, RHS); 16638 else if (!LHSHasPattern && !RHSHasPattern) 16639 return SDValue(); 16640 16641 SDLoc DL(N); 16642 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16643 SDValue Cmp = RHS.getOperand(0); 16644 SDValue Z = Cmp.getOperand(0); 16645 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16646 16647 assert(Constant && "Constant Should not be a null pointer."); 16648 int64_t NegConstant = 0 - Constant->getSExtValue(); 16649 16650 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16651 default: break; 16652 case ISD::SETNE: { 16653 // when C == 0 16654 // --> addze X, (addic Z, -1).carry 16655 // / 16656 // add X, (zext(setne Z, C))-- 16657 // \ when -32768 <= -C <= 32767 && C != 0 16658 // --> addze X, (addic (addi Z, -C), -1).carry 16659 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16660 DAG.getConstant(NegConstant, DL, MVT::i64)); 16661 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16662 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16663 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16664 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16665 SDValue(Addc.getNode(), 1)); 16666 } 16667 case ISD::SETEQ: { 16668 // when C == 0 16669 // --> addze X, (subfic Z, 0).carry 16670 // / 16671 // add X, (zext(sete Z, C))-- 16672 // \ when -32768 <= -C <= 32767 && C != 0 16673 // --> addze X, (subfic (addi Z, -C), 0).carry 16674 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16675 DAG.getConstant(NegConstant, DL, MVT::i64)); 16676 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16677 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16678 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16679 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16680 SDValue(Subc.getNode(), 1)); 16681 } 16682 } 16683 16684 return SDValue(); 16685 } 16686 16687 // Transform 16688 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16689 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16690 // In this case both C1 and C2 must be known constants. 16691 // C1+C2 must fit into a 34 bit signed integer. 16692 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16693 const PPCSubtarget &Subtarget) { 16694 if (!Subtarget.isUsingPCRelativeCalls()) 16695 return SDValue(); 16696 16697 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16698 // If we find that node try to cast the Global Address and the Constant. 16699 SDValue LHS = N->getOperand(0); 16700 SDValue RHS = N->getOperand(1); 16701 16702 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16703 std::swap(LHS, RHS); 16704 16705 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16706 return SDValue(); 16707 16708 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16709 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16710 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16711 16712 // Check that both casts succeeded. 16713 if (!GSDN || !ConstNode) 16714 return SDValue(); 16715 16716 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16717 SDLoc DL(GSDN); 16718 16719 // The signed int offset needs to fit in 34 bits. 16720 if (!isInt<34>(NewOffset)) 16721 return SDValue(); 16722 16723 // The new global address is a copy of the old global address except 16724 // that it has the updated Offset. 16725 SDValue GA = 16726 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16727 NewOffset, GSDN->getTargetFlags()); 16728 SDValue MatPCRel = 16729 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16730 return MatPCRel; 16731 } 16732 16733 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16734 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16735 return Value; 16736 16737 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16738 return Value; 16739 16740 return SDValue(); 16741 } 16742 16743 // Detect TRUNCATE operations on bitcasts of float128 values. 16744 // What we are looking for here is the situtation where we extract a subset 16745 // of bits from a 128 bit float. 16746 // This can be of two forms: 16747 // 1) BITCAST of f128 feeding TRUNCATE 16748 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16749 // The reason this is required is because we do not have a legal i128 type 16750 // and so we want to prevent having to store the f128 and then reload part 16751 // of it. 16752 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16753 DAGCombinerInfo &DCI) const { 16754 // If we are using CRBits then try that first. 16755 if (Subtarget.useCRBits()) { 16756 // Check if CRBits did anything and return that if it did. 16757 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16758 return CRTruncValue; 16759 } 16760 16761 SDLoc dl(N); 16762 SDValue Op0 = N->getOperand(0); 16763 16764 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16765 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16766 EVT VT = N->getValueType(0); 16767 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16768 return SDValue(); 16769 SDValue Sub = Op0.getOperand(0); 16770 if (Sub.getOpcode() == ISD::SUB) { 16771 SDValue SubOp0 = Sub.getOperand(0); 16772 SDValue SubOp1 = Sub.getOperand(1); 16773 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16774 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16775 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16776 SubOp1.getOperand(0), 16777 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16778 } 16779 } 16780 } 16781 16782 // Looking for a truncate of i128 to i64. 16783 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16784 return SDValue(); 16785 16786 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16787 16788 // SRL feeding TRUNCATE. 16789 if (Op0.getOpcode() == ISD::SRL) { 16790 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16791 // The right shift has to be by 64 bits. 16792 if (!ConstNode || ConstNode->getZExtValue() != 64) 16793 return SDValue(); 16794 16795 // Switch the element number to extract. 16796 EltToExtract = EltToExtract ? 0 : 1; 16797 // Update Op0 past the SRL. 16798 Op0 = Op0.getOperand(0); 16799 } 16800 16801 // BITCAST feeding a TRUNCATE possibly via SRL. 16802 if (Op0.getOpcode() == ISD::BITCAST && 16803 Op0.getValueType() == MVT::i128 && 16804 Op0.getOperand(0).getValueType() == MVT::f128) { 16805 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16806 return DCI.DAG.getNode( 16807 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16808 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16809 } 16810 return SDValue(); 16811 } 16812 16813 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16814 SelectionDAG &DAG = DCI.DAG; 16815 16816 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16817 if (!ConstOpOrElement) 16818 return SDValue(); 16819 16820 // An imul is usually smaller than the alternative sequence for legal type. 16821 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16822 isOperationLegal(ISD::MUL, N->getValueType(0))) 16823 return SDValue(); 16824 16825 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16826 switch (this->Subtarget.getCPUDirective()) { 16827 default: 16828 // TODO: enhance the condition for subtarget before pwr8 16829 return false; 16830 case PPC::DIR_PWR8: 16831 // type mul add shl 16832 // scalar 4 1 1 16833 // vector 7 2 2 16834 return true; 16835 case PPC::DIR_PWR9: 16836 case PPC::DIR_PWR10: 16837 case PPC::DIR_PWR_FUTURE: 16838 // type mul add shl 16839 // scalar 5 2 2 16840 // vector 7 2 2 16841 16842 // The cycle RATIO of related operations are showed as a table above. 16843 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16844 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16845 // are 4, it is always profitable; but for 3 instrs patterns 16846 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16847 // So we should only do it for vector type. 16848 return IsAddOne && IsNeg ? VT.isVector() : true; 16849 } 16850 }; 16851 16852 EVT VT = N->getValueType(0); 16853 SDLoc DL(N); 16854 16855 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16856 bool IsNeg = MulAmt.isNegative(); 16857 APInt MulAmtAbs = MulAmt.abs(); 16858 16859 if ((MulAmtAbs - 1).isPowerOf2()) { 16860 // (mul x, 2^N + 1) => (add (shl x, N), x) 16861 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16862 16863 if (!IsProfitable(IsNeg, true, VT)) 16864 return SDValue(); 16865 16866 SDValue Op0 = N->getOperand(0); 16867 SDValue Op1 = 16868 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16869 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16870 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16871 16872 if (!IsNeg) 16873 return Res; 16874 16875 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16876 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16877 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16878 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16879 16880 if (!IsProfitable(IsNeg, false, VT)) 16881 return SDValue(); 16882 16883 SDValue Op0 = N->getOperand(0); 16884 SDValue Op1 = 16885 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16886 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16887 16888 if (!IsNeg) 16889 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16890 else 16891 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16892 16893 } else { 16894 return SDValue(); 16895 } 16896 } 16897 16898 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16899 // in combiner since we need to check SD flags and other subtarget features. 16900 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16901 DAGCombinerInfo &DCI) const { 16902 SDValue N0 = N->getOperand(0); 16903 SDValue N1 = N->getOperand(1); 16904 SDValue N2 = N->getOperand(2); 16905 SDNodeFlags Flags = N->getFlags(); 16906 EVT VT = N->getValueType(0); 16907 SelectionDAG &DAG = DCI.DAG; 16908 const TargetOptions &Options = getTargetMachine().Options; 16909 unsigned Opc = N->getOpcode(); 16910 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16911 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16912 SDLoc Loc(N); 16913 16914 if (!isOperationLegal(ISD::FMA, VT)) 16915 return SDValue(); 16916 16917 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16918 // since (fnmsub a b c)=-0 while c-ab=+0. 16919 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16920 return SDValue(); 16921 16922 // (fma (fneg a) b c) => (fnmsub a b c) 16923 // (fnmsub (fneg a) b c) => (fma a b c) 16924 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16925 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16926 16927 // (fma a (fneg b) c) => (fnmsub a b c) 16928 // (fnmsub a (fneg b) c) => (fma a b c) 16929 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16930 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16931 16932 return SDValue(); 16933 } 16934 16935 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16936 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16937 if (!Subtarget.is64BitELFABI()) 16938 return false; 16939 16940 // If not a tail call then no need to proceed. 16941 if (!CI->isTailCall()) 16942 return false; 16943 16944 // If sibling calls have been disabled and tail-calls aren't guaranteed 16945 // there is no reason to duplicate. 16946 auto &TM = getTargetMachine(); 16947 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16948 return false; 16949 16950 // Can't tail call a function called indirectly, or if it has variadic args. 16951 const Function *Callee = CI->getCalledFunction(); 16952 if (!Callee || Callee->isVarArg()) 16953 return false; 16954 16955 // Make sure the callee and caller calling conventions are eligible for tco. 16956 const Function *Caller = CI->getParent()->getParent(); 16957 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16958 CI->getCallingConv())) 16959 return false; 16960 16961 // If the function is local then we have a good chance at tail-calling it 16962 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16963 } 16964 16965 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16966 if (!Subtarget.hasVSX()) 16967 return false; 16968 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16969 return true; 16970 return VT == MVT::f32 || VT == MVT::f64 || 16971 VT == MVT::v4f32 || VT == MVT::v2f64; 16972 } 16973 16974 bool PPCTargetLowering:: 16975 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16976 const Value *Mask = AndI.getOperand(1); 16977 // If the mask is suitable for andi. or andis. we should sink the and. 16978 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16979 // Can't handle constants wider than 64-bits. 16980 if (CI->getBitWidth() > 64) 16981 return false; 16982 int64_t ConstVal = CI->getZExtValue(); 16983 return isUInt<16>(ConstVal) || 16984 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16985 } 16986 16987 // For non-constant masks, we can always use the record-form and. 16988 return true; 16989 } 16990 16991 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16992 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16993 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16994 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16995 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16996 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16997 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16998 assert(Subtarget.hasP9Altivec() && 16999 "Only combine this when P9 altivec supported!"); 17000 EVT VT = N->getValueType(0); 17001 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17002 return SDValue(); 17003 17004 SelectionDAG &DAG = DCI.DAG; 17005 SDLoc dl(N); 17006 if (N->getOperand(0).getOpcode() == ISD::SUB) { 17007 // Even for signed integers, if it's known to be positive (as signed 17008 // integer) due to zero-extended inputs. 17009 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 17010 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 17011 if ((SubOpcd0 == ISD::ZERO_EXTEND || 17012 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 17013 (SubOpcd1 == ISD::ZERO_EXTEND || 17014 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 17015 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17016 N->getOperand(0)->getOperand(0), 17017 N->getOperand(0)->getOperand(1), 17018 DAG.getTargetConstant(0, dl, MVT::i32)); 17019 } 17020 17021 // For type v4i32, it can be optimized with xvnegsp + vabsduw 17022 if (N->getOperand(0).getValueType() == MVT::v4i32 && 17023 N->getOperand(0).hasOneUse()) { 17024 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17025 N->getOperand(0)->getOperand(0), 17026 N->getOperand(0)->getOperand(1), 17027 DAG.getTargetConstant(1, dl, MVT::i32)); 17028 } 17029 } 17030 17031 return SDValue(); 17032 } 17033 17034 // For type v4i32/v8ii16/v16i8, transform 17035 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 17036 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 17037 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 17038 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 17039 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17040 DAGCombinerInfo &DCI) const { 17041 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17042 assert(Subtarget.hasP9Altivec() && 17043 "Only combine this when P9 altivec supported!"); 17044 17045 SelectionDAG &DAG = DCI.DAG; 17046 SDLoc dl(N); 17047 SDValue Cond = N->getOperand(0); 17048 SDValue TrueOpnd = N->getOperand(1); 17049 SDValue FalseOpnd = N->getOperand(2); 17050 EVT VT = N->getOperand(1).getValueType(); 17051 17052 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17053 FalseOpnd.getOpcode() != ISD::SUB) 17054 return SDValue(); 17055 17056 // ABSD only available for type v4i32/v8i16/v16i8 17057 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17058 return SDValue(); 17059 17060 // At least to save one more dependent computation 17061 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17062 return SDValue(); 17063 17064 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17065 17066 // Can only handle unsigned comparison here 17067 switch (CC) { 17068 default: 17069 return SDValue(); 17070 case ISD::SETUGT: 17071 case ISD::SETUGE: 17072 break; 17073 case ISD::SETULT: 17074 case ISD::SETULE: 17075 std::swap(TrueOpnd, FalseOpnd); 17076 break; 17077 } 17078 17079 SDValue CmpOpnd1 = Cond.getOperand(0); 17080 SDValue CmpOpnd2 = Cond.getOperand(1); 17081 17082 // SETCC CmpOpnd1 CmpOpnd2 cond 17083 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17084 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17085 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17086 TrueOpnd.getOperand(1) == CmpOpnd2 && 17087 FalseOpnd.getOperand(0) == CmpOpnd2 && 17088 FalseOpnd.getOperand(1) == CmpOpnd1) { 17089 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17090 CmpOpnd1, CmpOpnd2, 17091 DAG.getTargetConstant(0, dl, MVT::i32)); 17092 } 17093 17094 return SDValue(); 17095 } 17096