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 static cl::opt<bool> EnablePPCPCRelTLS( 125 "enable-ppc-pcrel-tls", 126 cl::desc("enable the use of PC relative memops in TLS instructions on PPC"), 127 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 } else { 238 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 240 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 242 } 243 244 // PowerPC does not support direct load/store of condition registers. 245 setOperationAction(ISD::LOAD, MVT::i1, Custom); 246 setOperationAction(ISD::STORE, MVT::i1, Custom); 247 248 // FIXME: Remove this once the ANDI glue bug is fixed: 249 if (ANDIGlueBug) 250 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 251 252 for (MVT VT : MVT::integer_valuetypes()) { 253 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 254 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 255 setTruncStoreAction(VT, MVT::i1, Expand); 256 } 257 258 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 259 } 260 261 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 262 // PPC (the libcall is not available). 263 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 264 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 265 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 266 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 267 268 // We do not currently implement these libm ops for PowerPC. 269 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 270 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 271 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 272 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 273 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 274 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 275 276 // PowerPC has no SREM/UREM instructions unless we are on P9 277 // On P9 we may use a hardware instruction to compute the remainder. 278 // When the result of both the remainder and the division is required it is 279 // more efficient to compute the remainder from the result of the division 280 // rather than use the remainder instruction. The instructions are legalized 281 // directly because the DivRemPairsPass performs the transformation at the IR 282 // level. 283 if (Subtarget.isISA3_0()) { 284 setOperationAction(ISD::SREM, MVT::i32, Legal); 285 setOperationAction(ISD::UREM, MVT::i32, Legal); 286 setOperationAction(ISD::SREM, MVT::i64, Legal); 287 setOperationAction(ISD::UREM, MVT::i64, Legal); 288 } else { 289 setOperationAction(ISD::SREM, MVT::i32, Expand); 290 setOperationAction(ISD::UREM, MVT::i32, Expand); 291 setOperationAction(ISD::SREM, MVT::i64, Expand); 292 setOperationAction(ISD::UREM, MVT::i64, Expand); 293 } 294 295 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 296 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 297 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 298 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 299 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 300 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 301 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 302 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 303 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 304 305 // Handle constrained floating-point operations of scalar. 306 // TODO: Handle SPE specific operation. 307 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 309 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 310 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 311 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 312 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 313 314 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 315 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 316 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 317 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 318 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 319 if (Subtarget.hasVSX()) { 320 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 321 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 322 } 323 324 if (Subtarget.hasFSQRT()) { 325 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 326 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 327 } 328 329 if (Subtarget.hasFPRND()) { 330 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 331 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 332 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 333 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 334 335 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 336 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 337 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 338 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 339 } 340 341 // We don't support sin/cos/sqrt/fmod/pow 342 setOperationAction(ISD::FSIN , MVT::f64, Expand); 343 setOperationAction(ISD::FCOS , MVT::f64, Expand); 344 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 345 setOperationAction(ISD::FREM , MVT::f64, Expand); 346 setOperationAction(ISD::FPOW , MVT::f64, Expand); 347 setOperationAction(ISD::FSIN , MVT::f32, Expand); 348 setOperationAction(ISD::FCOS , MVT::f32, Expand); 349 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 350 setOperationAction(ISD::FREM , MVT::f32, Expand); 351 setOperationAction(ISD::FPOW , MVT::f32, Expand); 352 if (Subtarget.hasSPE()) { 353 setOperationAction(ISD::FMA , MVT::f64, Expand); 354 setOperationAction(ISD::FMA , MVT::f32, Expand); 355 } else { 356 setOperationAction(ISD::FMA , MVT::f64, Legal); 357 setOperationAction(ISD::FMA , MVT::f32, Legal); 358 } 359 360 if (Subtarget.hasSPE()) 361 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 362 363 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 364 365 // If we're enabling GP optimizations, use hardware square root 366 if (!Subtarget.hasFSQRT() && 367 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 368 Subtarget.hasFRE())) 369 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 370 371 if (!Subtarget.hasFSQRT() && 372 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 373 Subtarget.hasFRES())) 374 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 375 376 if (Subtarget.hasFCPSGN()) { 377 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 378 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 379 } else { 380 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 381 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 382 } 383 384 if (Subtarget.hasFPRND()) { 385 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 386 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 387 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 388 setOperationAction(ISD::FROUND, MVT::f64, Legal); 389 390 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 391 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 392 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 393 setOperationAction(ISD::FROUND, MVT::f32, Legal); 394 } 395 396 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 397 // to speed up scalar BSWAP64. 398 // CTPOP or CTTZ were introduced in P8/P9 respectively 399 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 400 if (Subtarget.hasP9Vector()) 401 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 402 else 403 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 404 if (Subtarget.isISA3_0()) { 405 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 406 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 407 } else { 408 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 409 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 410 } 411 412 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 413 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 414 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 415 } else { 416 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 417 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 418 } 419 420 // PowerPC does not have ROTR 421 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 422 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 423 424 if (!Subtarget.useCRBits()) { 425 // PowerPC does not have Select 426 setOperationAction(ISD::SELECT, MVT::i32, Expand); 427 setOperationAction(ISD::SELECT, MVT::i64, Expand); 428 setOperationAction(ISD::SELECT, MVT::f32, Expand); 429 setOperationAction(ISD::SELECT, MVT::f64, Expand); 430 } 431 432 // PowerPC wants to turn select_cc of FP into fsel when possible. 433 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 434 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 435 436 // PowerPC wants to optimize integer setcc a bit 437 if (!Subtarget.useCRBits()) 438 setOperationAction(ISD::SETCC, MVT::i32, Custom); 439 440 if (Subtarget.hasFPU()) { 441 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 442 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 443 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 444 445 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 446 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 447 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 448 } 449 450 // PowerPC does not have BRCOND which requires SetCC 451 if (!Subtarget.useCRBits()) 452 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 453 454 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 455 456 if (Subtarget.hasSPE()) { 457 // SPE has built-in conversions 458 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 459 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 460 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 461 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 462 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 463 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 464 } else { 465 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 466 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 467 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 468 469 // PowerPC does not have [U|S]INT_TO_FP 470 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 471 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 472 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 473 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 474 } 475 476 if (Subtarget.hasDirectMove() && isPPC64) { 477 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 478 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 479 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 480 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 481 if (TM.Options.UnsafeFPMath) { 482 setOperationAction(ISD::LRINT, MVT::f64, Legal); 483 setOperationAction(ISD::LRINT, MVT::f32, Legal); 484 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 485 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 486 setOperationAction(ISD::LROUND, MVT::f64, Legal); 487 setOperationAction(ISD::LROUND, MVT::f32, Legal); 488 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 489 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 490 } 491 } else { 492 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 493 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 494 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 495 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 496 } 497 498 // We cannot sextinreg(i1). Expand to shifts. 499 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 500 501 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 502 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 503 // support continuation, user-level threading, and etc.. As a result, no 504 // other SjLj exception interfaces are implemented and please don't build 505 // your own exception handling based on them. 506 // LLVM/Clang supports zero-cost DWARF exception handling. 507 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 508 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 509 510 // We want to legalize GlobalAddress and ConstantPool nodes into the 511 // appropriate instructions to materialize the address. 512 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 513 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 514 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 515 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 516 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 517 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 518 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 519 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 520 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 521 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 522 523 // TRAP is legal. 524 setOperationAction(ISD::TRAP, MVT::Other, Legal); 525 526 // TRAMPOLINE is custom lowered. 527 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 528 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 529 530 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 531 setOperationAction(ISD::VASTART , MVT::Other, Custom); 532 533 if (Subtarget.is64BitELFABI()) { 534 // VAARG always uses double-word chunks, so promote anything smaller. 535 setOperationAction(ISD::VAARG, MVT::i1, Promote); 536 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 537 setOperationAction(ISD::VAARG, MVT::i8, Promote); 538 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 539 setOperationAction(ISD::VAARG, MVT::i16, Promote); 540 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 541 setOperationAction(ISD::VAARG, MVT::i32, Promote); 542 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 543 setOperationAction(ISD::VAARG, MVT::Other, Expand); 544 } else if (Subtarget.is32BitELFABI()) { 545 // VAARG is custom lowered with the 32-bit SVR4 ABI. 546 setOperationAction(ISD::VAARG, MVT::Other, Custom); 547 setOperationAction(ISD::VAARG, MVT::i64, Custom); 548 } else 549 setOperationAction(ISD::VAARG, MVT::Other, Expand); 550 551 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 552 if (Subtarget.is32BitELFABI()) 553 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 554 else 555 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 556 557 // Use the default implementation. 558 setOperationAction(ISD::VAEND , MVT::Other, Expand); 559 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 560 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 561 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 562 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 563 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 564 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 565 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 566 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 567 568 // We want to custom lower some of our intrinsics. 569 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 570 571 // To handle counter-based loop conditions. 572 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 573 574 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 575 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 576 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 577 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 578 579 // Comparisons that require checking two conditions. 580 if (Subtarget.hasSPE()) { 581 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 582 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 583 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 584 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 585 } 586 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 587 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 588 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 589 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 590 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 591 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 592 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 593 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 594 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 595 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 596 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 597 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 598 599 if (Subtarget.has64BitSupport()) { 600 // They also have instructions for converting between i64 and fp. 601 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 602 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 603 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 604 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 605 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 606 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 607 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 608 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 609 // This is just the low 32 bits of a (signed) fp->i64 conversion. 610 // We cannot do this with Promote because i64 is not a legal type. 611 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 612 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 613 614 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 615 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 616 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 617 } 618 } else { 619 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 620 if (Subtarget.hasSPE()) { 621 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 622 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 623 } else { 624 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 625 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 626 } 627 } 628 629 // With the instructions enabled under FPCVT, we can do everything. 630 if (Subtarget.hasFPCVT()) { 631 if (Subtarget.has64BitSupport()) { 632 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 633 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 634 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 635 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 636 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 637 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 638 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 639 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 640 } 641 642 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 643 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 644 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 645 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 646 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 647 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 648 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 649 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 650 } 651 652 if (Subtarget.use64BitRegs()) { 653 // 64-bit PowerPC implementations can support i64 types directly 654 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 655 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 656 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 657 // 64-bit PowerPC wants to expand i128 shifts itself. 658 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 659 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 660 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 661 } else { 662 // 32-bit PowerPC wants to expand i64 shifts itself. 663 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 664 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 665 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 666 } 667 668 // PowerPC has better expansions for funnel shifts than the generic 669 // TargetLowering::expandFunnelShift. 670 if (Subtarget.has64BitSupport()) { 671 setOperationAction(ISD::FSHL, MVT::i64, Custom); 672 setOperationAction(ISD::FSHR, MVT::i64, Custom); 673 } 674 setOperationAction(ISD::FSHL, MVT::i32, Custom); 675 setOperationAction(ISD::FSHR, MVT::i32, Custom); 676 677 if (Subtarget.hasVSX()) { 678 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 679 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 680 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 681 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 682 } 683 684 if (Subtarget.hasAltivec()) { 685 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 686 setOperationAction(ISD::SADDSAT, VT, Legal); 687 setOperationAction(ISD::SSUBSAT, VT, Legal); 688 setOperationAction(ISD::UADDSAT, VT, Legal); 689 setOperationAction(ISD::USUBSAT, VT, Legal); 690 } 691 // First set operation action for all vector types to expand. Then we 692 // will selectively turn on ones that can be effectively codegen'd. 693 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 694 // add/sub are legal for all supported vector VT's. 695 setOperationAction(ISD::ADD, VT, Legal); 696 setOperationAction(ISD::SUB, VT, Legal); 697 698 // For v2i64, these are only valid with P8Vector. This is corrected after 699 // the loop. 700 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 701 setOperationAction(ISD::SMAX, VT, Legal); 702 setOperationAction(ISD::SMIN, VT, Legal); 703 setOperationAction(ISD::UMAX, VT, Legal); 704 setOperationAction(ISD::UMIN, VT, Legal); 705 } 706 else { 707 setOperationAction(ISD::SMAX, VT, Expand); 708 setOperationAction(ISD::SMIN, VT, Expand); 709 setOperationAction(ISD::UMAX, VT, Expand); 710 setOperationAction(ISD::UMIN, VT, Expand); 711 } 712 713 if (Subtarget.hasVSX()) { 714 setOperationAction(ISD::FMAXNUM, VT, Legal); 715 setOperationAction(ISD::FMINNUM, VT, Legal); 716 } 717 718 // Vector instructions introduced in P8 719 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 720 setOperationAction(ISD::CTPOP, VT, Legal); 721 setOperationAction(ISD::CTLZ, VT, Legal); 722 } 723 else { 724 setOperationAction(ISD::CTPOP, VT, Expand); 725 setOperationAction(ISD::CTLZ, VT, Expand); 726 } 727 728 // Vector instructions introduced in P9 729 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 730 setOperationAction(ISD::CTTZ, VT, Legal); 731 else 732 setOperationAction(ISD::CTTZ, VT, Expand); 733 734 // We promote all shuffles to v16i8. 735 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 736 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 737 738 // We promote all non-typed operations to v4i32. 739 setOperationAction(ISD::AND , VT, Promote); 740 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 741 setOperationAction(ISD::OR , VT, Promote); 742 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 743 setOperationAction(ISD::XOR , VT, Promote); 744 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 745 setOperationAction(ISD::LOAD , VT, Promote); 746 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 747 setOperationAction(ISD::SELECT, VT, Promote); 748 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 749 setOperationAction(ISD::VSELECT, VT, Legal); 750 setOperationAction(ISD::SELECT_CC, VT, Promote); 751 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 752 setOperationAction(ISD::STORE, VT, Promote); 753 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 754 755 // No other operations are legal. 756 setOperationAction(ISD::MUL , VT, Expand); 757 setOperationAction(ISD::SDIV, VT, Expand); 758 setOperationAction(ISD::SREM, VT, Expand); 759 setOperationAction(ISD::UDIV, VT, Expand); 760 setOperationAction(ISD::UREM, VT, Expand); 761 setOperationAction(ISD::FDIV, VT, Expand); 762 setOperationAction(ISD::FREM, VT, Expand); 763 setOperationAction(ISD::FNEG, VT, Expand); 764 setOperationAction(ISD::FSQRT, VT, Expand); 765 setOperationAction(ISD::FLOG, VT, Expand); 766 setOperationAction(ISD::FLOG10, VT, Expand); 767 setOperationAction(ISD::FLOG2, VT, Expand); 768 setOperationAction(ISD::FEXP, VT, Expand); 769 setOperationAction(ISD::FEXP2, VT, Expand); 770 setOperationAction(ISD::FSIN, VT, Expand); 771 setOperationAction(ISD::FCOS, VT, Expand); 772 setOperationAction(ISD::FABS, VT, Expand); 773 setOperationAction(ISD::FFLOOR, VT, Expand); 774 setOperationAction(ISD::FCEIL, VT, Expand); 775 setOperationAction(ISD::FTRUNC, VT, Expand); 776 setOperationAction(ISD::FRINT, VT, Expand); 777 setOperationAction(ISD::FNEARBYINT, VT, Expand); 778 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 779 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 780 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 781 setOperationAction(ISD::MULHU, VT, Expand); 782 setOperationAction(ISD::MULHS, VT, Expand); 783 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 784 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 785 setOperationAction(ISD::UDIVREM, VT, Expand); 786 setOperationAction(ISD::SDIVREM, VT, Expand); 787 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 788 setOperationAction(ISD::FPOW, VT, Expand); 789 setOperationAction(ISD::BSWAP, VT, Expand); 790 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 791 setOperationAction(ISD::ROTL, VT, Expand); 792 setOperationAction(ISD::ROTR, VT, Expand); 793 794 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 795 setTruncStoreAction(VT, InnerVT, Expand); 796 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 797 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 798 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 799 } 800 } 801 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 802 if (!Subtarget.hasP8Vector()) { 803 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 804 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 805 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 806 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 807 } 808 809 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 810 setOperationAction(ISD::ABS, VT, Custom); 811 812 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 813 // with merges, splats, etc. 814 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 815 816 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 817 // are cheap, so handle them before they get expanded to scalar. 818 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 819 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 820 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 821 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 822 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 823 824 setOperationAction(ISD::AND , MVT::v4i32, Legal); 825 setOperationAction(ISD::OR , MVT::v4i32, Legal); 826 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 827 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 828 setOperationAction(ISD::SELECT, MVT::v4i32, 829 Subtarget.useCRBits() ? Legal : Expand); 830 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 831 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 832 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 833 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 834 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 835 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 836 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 837 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 838 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 839 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 840 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 841 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 842 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 843 844 // Without hasP8Altivec set, v2i64 SMAX isn't available. 845 // But ABS custom lowering requires SMAX support. 846 if (!Subtarget.hasP8Altivec()) 847 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 848 849 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 850 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 851 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 852 if (Subtarget.hasAltivec()) 853 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 854 setOperationAction(ISD::ROTL, VT, Legal); 855 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 856 if (Subtarget.hasP8Altivec()) 857 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 858 859 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 860 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 861 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 862 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 863 864 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 865 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 866 867 if (Subtarget.hasVSX()) { 868 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 869 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 870 } 871 872 if (Subtarget.hasP8Altivec()) 873 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 874 else 875 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 876 877 if (Subtarget.isISA3_1()) { 878 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 879 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 880 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 881 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 882 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 883 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 884 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 885 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 886 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 887 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 888 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 889 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 890 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 891 } 892 893 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 894 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 895 896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 898 899 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 900 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 901 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 902 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 903 904 // Altivec does not contain unordered floating-point compare instructions 905 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 906 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 907 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 908 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 909 910 if (Subtarget.hasVSX()) { 911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 912 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 913 if (Subtarget.hasP8Vector()) { 914 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 915 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 916 } 917 if (Subtarget.hasDirectMove() && isPPC64) { 918 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 919 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 920 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 921 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 926 } 927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 928 929 // The nearbyint variants are not allowed to raise the inexact exception 930 // so we can only code-gen them with unsafe math. 931 if (TM.Options.UnsafeFPMath) { 932 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 933 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 934 } 935 936 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 937 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 938 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 939 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 940 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 941 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 942 setOperationAction(ISD::FROUND, MVT::f64, Legal); 943 setOperationAction(ISD::FRINT, MVT::f64, Legal); 944 945 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 946 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 947 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 948 setOperationAction(ISD::FROUND, MVT::f32, Legal); 949 setOperationAction(ISD::FRINT, MVT::f32, Legal); 950 951 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 952 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 953 954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 956 957 // Share the Altivec comparison restrictions. 958 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 959 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 960 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 961 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 962 963 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 964 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 965 966 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 967 968 if (Subtarget.hasP8Vector()) 969 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 970 971 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 972 973 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 974 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 975 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 976 977 if (Subtarget.hasP8Altivec()) { 978 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 979 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 980 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 981 982 // 128 bit shifts can be accomplished via 3 instructions for SHL and 983 // SRL, but not for SRA because of the instructions available: 984 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 985 // doing 986 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 987 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 988 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 989 990 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 991 } 992 else { 993 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 994 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 995 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 996 997 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 998 999 // VSX v2i64 only supports non-arithmetic operations. 1000 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1001 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1002 } 1003 1004 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1005 1006 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1007 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1008 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1009 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1010 1011 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1012 1013 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1014 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1015 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1016 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1017 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1018 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1019 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1020 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1021 1022 // Custom handling for partial vectors of integers converted to 1023 // floating point. We already have optimal handling for v2i32 through 1024 // the DAG combine, so those aren't necessary. 1025 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1026 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1027 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1028 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1029 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1030 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1031 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1032 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1036 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1037 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1038 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1039 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1040 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1041 1042 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1043 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1044 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1045 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1046 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1047 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1048 1049 if (Subtarget.hasDirectMove()) 1050 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1051 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1052 1053 // Handle constrained floating-point operations of vector. 1054 // The predictor is `hasVSX` because altivec instruction has 1055 // no exception but VSX vector instruction has. 1056 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1057 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1058 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1059 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1060 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1061 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1062 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1063 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1064 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1065 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1066 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1067 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1068 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1069 1070 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1071 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1072 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1073 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1074 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1075 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1076 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1077 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1078 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1079 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1080 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1081 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1082 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1083 1084 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1085 } 1086 1087 if (Subtarget.hasP8Altivec()) { 1088 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1089 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1090 } 1091 1092 if (Subtarget.hasP9Vector()) { 1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1095 1096 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1097 // SRL, but not for SRA because of the instructions available: 1098 // VS{RL} and VS{RL}O. 1099 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1100 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1101 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1102 1103 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1104 setOperationAction(ISD::FADD, MVT::f128, Legal); 1105 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1106 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1107 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1108 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1109 // No extending loads to f128 on PPC. 1110 for (MVT FPT : MVT::fp_valuetypes()) 1111 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1112 setOperationAction(ISD::FMA, MVT::f128, Legal); 1113 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1114 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1115 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1116 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1117 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1118 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1119 1120 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1121 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1122 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1123 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1124 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1125 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1126 1127 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1128 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1129 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1130 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1131 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1132 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1133 // No implementation for these ops for PowerPC. 1134 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1135 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1136 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1137 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1138 setOperationAction(ISD::FREM, MVT::f128, Expand); 1139 1140 // Handle constrained floating-point operations of fp128 1141 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1142 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1143 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1144 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1145 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1146 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1147 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1148 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1149 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1150 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1151 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1152 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1153 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1154 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1155 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1156 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1157 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1158 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1159 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1160 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1161 } 1162 1163 if (Subtarget.hasP9Altivec()) { 1164 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1165 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1166 1167 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1168 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1169 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1170 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1171 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1172 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1173 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1174 } 1175 } 1176 1177 if (Subtarget.has64BitSupport()) 1178 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1179 1180 if (Subtarget.isISA3_1()) 1181 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1182 1183 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1184 1185 if (!isPPC64) { 1186 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1187 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1188 } 1189 1190 setBooleanContents(ZeroOrOneBooleanContent); 1191 1192 if (Subtarget.hasAltivec()) { 1193 // Altivec instructions set fields to all zeros or all ones. 1194 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1195 } 1196 1197 if (!isPPC64) { 1198 // These libcalls are not available in 32-bit. 1199 setLibcallName(RTLIB::SHL_I128, nullptr); 1200 setLibcallName(RTLIB::SRL_I128, nullptr); 1201 setLibcallName(RTLIB::SRA_I128, nullptr); 1202 } 1203 1204 if (!isPPC64) 1205 setMaxAtomicSizeInBitsSupported(32); 1206 1207 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1208 1209 // We have target-specific dag combine patterns for the following nodes: 1210 setTargetDAGCombine(ISD::ADD); 1211 setTargetDAGCombine(ISD::SHL); 1212 setTargetDAGCombine(ISD::SRA); 1213 setTargetDAGCombine(ISD::SRL); 1214 setTargetDAGCombine(ISD::MUL); 1215 setTargetDAGCombine(ISD::FMA); 1216 setTargetDAGCombine(ISD::SINT_TO_FP); 1217 setTargetDAGCombine(ISD::BUILD_VECTOR); 1218 if (Subtarget.hasFPCVT()) 1219 setTargetDAGCombine(ISD::UINT_TO_FP); 1220 setTargetDAGCombine(ISD::LOAD); 1221 setTargetDAGCombine(ISD::STORE); 1222 setTargetDAGCombine(ISD::BR_CC); 1223 if (Subtarget.useCRBits()) 1224 setTargetDAGCombine(ISD::BRCOND); 1225 setTargetDAGCombine(ISD::BSWAP); 1226 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1227 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1228 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1229 1230 setTargetDAGCombine(ISD::SIGN_EXTEND); 1231 setTargetDAGCombine(ISD::ZERO_EXTEND); 1232 setTargetDAGCombine(ISD::ANY_EXTEND); 1233 1234 setTargetDAGCombine(ISD::TRUNCATE); 1235 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1236 1237 1238 if (Subtarget.useCRBits()) { 1239 setTargetDAGCombine(ISD::TRUNCATE); 1240 setTargetDAGCombine(ISD::SETCC); 1241 setTargetDAGCombine(ISD::SELECT_CC); 1242 } 1243 1244 if (Subtarget.hasP9Altivec()) { 1245 setTargetDAGCombine(ISD::ABS); 1246 setTargetDAGCombine(ISD::VSELECT); 1247 } 1248 1249 setLibcallName(RTLIB::LOG_F128, "logf128"); 1250 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1251 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1252 setLibcallName(RTLIB::EXP_F128, "expf128"); 1253 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1254 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1255 setLibcallName(RTLIB::COS_F128, "cosf128"); 1256 setLibcallName(RTLIB::POW_F128, "powf128"); 1257 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1258 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1259 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1260 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1261 1262 // With 32 condition bits, we don't need to sink (and duplicate) compares 1263 // aggressively in CodeGenPrep. 1264 if (Subtarget.useCRBits()) { 1265 setHasMultipleConditionRegisters(); 1266 setJumpIsExpensive(); 1267 } 1268 1269 setMinFunctionAlignment(Align(4)); 1270 1271 switch (Subtarget.getCPUDirective()) { 1272 default: break; 1273 case PPC::DIR_970: 1274 case PPC::DIR_A2: 1275 case PPC::DIR_E500: 1276 case PPC::DIR_E500mc: 1277 case PPC::DIR_E5500: 1278 case PPC::DIR_PWR4: 1279 case PPC::DIR_PWR5: 1280 case PPC::DIR_PWR5X: 1281 case PPC::DIR_PWR6: 1282 case PPC::DIR_PWR6X: 1283 case PPC::DIR_PWR7: 1284 case PPC::DIR_PWR8: 1285 case PPC::DIR_PWR9: 1286 case PPC::DIR_PWR10: 1287 case PPC::DIR_PWR_FUTURE: 1288 setPrefLoopAlignment(Align(16)); 1289 setPrefFunctionAlignment(Align(16)); 1290 break; 1291 } 1292 1293 if (Subtarget.enableMachineScheduler()) 1294 setSchedulingPreference(Sched::Source); 1295 else 1296 setSchedulingPreference(Sched::Hybrid); 1297 1298 computeRegisterProperties(STI.getRegisterInfo()); 1299 1300 // The Freescale cores do better with aggressive inlining of memcpy and 1301 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1302 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1303 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1304 MaxStoresPerMemset = 32; 1305 MaxStoresPerMemsetOptSize = 16; 1306 MaxStoresPerMemcpy = 32; 1307 MaxStoresPerMemcpyOptSize = 8; 1308 MaxStoresPerMemmove = 32; 1309 MaxStoresPerMemmoveOptSize = 8; 1310 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1311 // The A2 also benefits from (very) aggressive inlining of memcpy and 1312 // friends. The overhead of a the function call, even when warm, can be 1313 // over one hundred cycles. 1314 MaxStoresPerMemset = 128; 1315 MaxStoresPerMemcpy = 128; 1316 MaxStoresPerMemmove = 128; 1317 MaxLoadsPerMemcmp = 128; 1318 } else { 1319 MaxLoadsPerMemcmp = 8; 1320 MaxLoadsPerMemcmpOptSize = 4; 1321 } 1322 1323 IsStrictFPEnabled = true; 1324 1325 // Let the subtarget (CPU) decide if a predictable select is more expensive 1326 // than the corresponding branch. This information is used in CGP to decide 1327 // when to convert selects into branches. 1328 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1329 } 1330 1331 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1332 /// the desired ByVal argument alignment. 1333 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1334 if (MaxAlign == MaxMaxAlign) 1335 return; 1336 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1337 if (MaxMaxAlign >= 32 && 1338 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1339 MaxAlign = Align(32); 1340 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1341 MaxAlign < 16) 1342 MaxAlign = Align(16); 1343 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1344 Align EltAlign; 1345 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1346 if (EltAlign > MaxAlign) 1347 MaxAlign = EltAlign; 1348 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1349 for (auto *EltTy : STy->elements()) { 1350 Align EltAlign; 1351 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1352 if (EltAlign > MaxAlign) 1353 MaxAlign = EltAlign; 1354 if (MaxAlign == MaxMaxAlign) 1355 break; 1356 } 1357 } 1358 } 1359 1360 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1361 /// function arguments in the caller parameter area. 1362 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1363 const DataLayout &DL) const { 1364 // 16byte and wider vectors are passed on 16byte boundary. 1365 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1366 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1367 if (Subtarget.hasAltivec()) 1368 getMaxByValAlign(Ty, Alignment, Align(16)); 1369 return Alignment.value(); 1370 } 1371 1372 bool PPCTargetLowering::useSoftFloat() const { 1373 return Subtarget.useSoftFloat(); 1374 } 1375 1376 bool PPCTargetLowering::hasSPE() const { 1377 return Subtarget.hasSPE(); 1378 } 1379 1380 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1381 return VT.isScalarInteger(); 1382 } 1383 1384 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1385 /// type is cheaper than a multiply followed by a shift. 1386 /// This is true for words and doublewords on 64-bit PowerPC. 1387 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1388 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1389 isOperationLegal(ISD::MULHU, Type))) 1390 return true; 1391 return TargetLowering::isMulhCheaperThanMulShift(Type); 1392 } 1393 1394 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1395 switch ((PPCISD::NodeType)Opcode) { 1396 case PPCISD::FIRST_NUMBER: break; 1397 case PPCISD::FSEL: return "PPCISD::FSEL"; 1398 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1399 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1400 case PPCISD::FCFID: return "PPCISD::FCFID"; 1401 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1402 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1403 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1404 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1405 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1406 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1407 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1408 case PPCISD::FP_TO_UINT_IN_VSR: 1409 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1410 case PPCISD::FP_TO_SINT_IN_VSR: 1411 return "PPCISD::FP_TO_SINT_IN_VSR"; 1412 case PPCISD::FRE: return "PPCISD::FRE"; 1413 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1414 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1415 case PPCISD::VPERM: return "PPCISD::VPERM"; 1416 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1417 case PPCISD::XXSPLTI_SP_TO_DP: 1418 return "PPCISD::XXSPLTI_SP_TO_DP"; 1419 case PPCISD::XXSPLTI32DX: 1420 return "PPCISD::XXSPLTI32DX"; 1421 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1422 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1423 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1424 case PPCISD::CMPB: return "PPCISD::CMPB"; 1425 case PPCISD::Hi: return "PPCISD::Hi"; 1426 case PPCISD::Lo: return "PPCISD::Lo"; 1427 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1428 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1429 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1430 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1431 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1432 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1433 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1434 case PPCISD::SRL: return "PPCISD::SRL"; 1435 case PPCISD::SRA: return "PPCISD::SRA"; 1436 case PPCISD::SHL: return "PPCISD::SHL"; 1437 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1438 case PPCISD::CALL: return "PPCISD::CALL"; 1439 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1440 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1441 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1442 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1443 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1444 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1445 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1446 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1447 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1448 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1449 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1450 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1451 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1452 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1453 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1454 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1455 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1456 case PPCISD::ANDI_rec_1_EQ_BIT: 1457 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1458 case PPCISD::ANDI_rec_1_GT_BIT: 1459 return "PPCISD::ANDI_rec_1_GT_BIT"; 1460 case PPCISD::VCMP: return "PPCISD::VCMP"; 1461 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1462 case PPCISD::LBRX: return "PPCISD::LBRX"; 1463 case PPCISD::STBRX: return "PPCISD::STBRX"; 1464 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1465 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1466 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1467 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1468 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1469 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1470 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1471 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1472 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1473 case PPCISD::ST_VSR_SCAL_INT: 1474 return "PPCISD::ST_VSR_SCAL_INT"; 1475 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1476 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1477 case PPCISD::BDZ: return "PPCISD::BDZ"; 1478 case PPCISD::MFFS: return "PPCISD::MFFS"; 1479 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1480 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1481 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1482 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1483 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1484 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1485 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1486 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1487 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1488 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1489 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1490 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1491 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1492 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1493 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1494 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1495 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1496 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1497 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1498 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1499 case PPCISD::SC: return "PPCISD::SC"; 1500 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1501 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1502 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1503 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1504 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1505 case PPCISD::VABSD: return "PPCISD::VABSD"; 1506 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1507 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1508 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1509 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1510 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1511 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1512 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1513 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1514 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1515 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1516 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1517 case PPCISD::STRICT_FADDRTZ: 1518 return "PPCISD::STRICT_FADDRTZ"; 1519 case PPCISD::STRICT_FCTIDZ: 1520 return "PPCISD::STRICT_FCTIDZ"; 1521 case PPCISD::STRICT_FCTIWZ: 1522 return "PPCISD::STRICT_FCTIWZ"; 1523 case PPCISD::STRICT_FCTIDUZ: 1524 return "PPCISD::STRICT_FCTIDUZ"; 1525 case PPCISD::STRICT_FCTIWUZ: 1526 return "PPCISD::STRICT_FCTIWUZ"; 1527 case PPCISD::STRICT_FCFID: 1528 return "PPCISD::STRICT_FCFID"; 1529 case PPCISD::STRICT_FCFIDU: 1530 return "PPCISD::STRICT_FCFIDU"; 1531 case PPCISD::STRICT_FCFIDS: 1532 return "PPCISD::STRICT_FCFIDS"; 1533 case PPCISD::STRICT_FCFIDUS: 1534 return "PPCISD::STRICT_FCFIDUS"; 1535 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1536 } 1537 return nullptr; 1538 } 1539 1540 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1541 EVT VT) const { 1542 if (!VT.isVector()) 1543 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1544 1545 return VT.changeVectorElementTypeToInteger(); 1546 } 1547 1548 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1549 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1550 return true; 1551 } 1552 1553 //===----------------------------------------------------------------------===// 1554 // Node matching predicates, for use by the tblgen matching code. 1555 //===----------------------------------------------------------------------===// 1556 1557 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1558 static bool isFloatingPointZero(SDValue Op) { 1559 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1560 return CFP->getValueAPF().isZero(); 1561 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1562 // Maybe this has already been legalized into the constant pool? 1563 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1564 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1565 return CFP->getValueAPF().isZero(); 1566 } 1567 return false; 1568 } 1569 1570 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1571 /// true if Op is undef or if it matches the specified value. 1572 static bool isConstantOrUndef(int Op, int Val) { 1573 return Op < 0 || Op == Val; 1574 } 1575 1576 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1577 /// VPKUHUM instruction. 1578 /// The ShuffleKind distinguishes between big-endian operations with 1579 /// two different inputs (0), either-endian operations with two identical 1580 /// inputs (1), and little-endian operations with two different inputs (2). 1581 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1582 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1583 SelectionDAG &DAG) { 1584 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1585 if (ShuffleKind == 0) { 1586 if (IsLE) 1587 return false; 1588 for (unsigned i = 0; i != 16; ++i) 1589 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1590 return false; 1591 } else if (ShuffleKind == 2) { 1592 if (!IsLE) 1593 return false; 1594 for (unsigned i = 0; i != 16; ++i) 1595 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1596 return false; 1597 } else if (ShuffleKind == 1) { 1598 unsigned j = IsLE ? 0 : 1; 1599 for (unsigned i = 0; i != 8; ++i) 1600 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1601 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1602 return false; 1603 } 1604 return true; 1605 } 1606 1607 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1608 /// VPKUWUM instruction. 1609 /// The ShuffleKind distinguishes between big-endian operations with 1610 /// two different inputs (0), either-endian operations with two identical 1611 /// inputs (1), and little-endian operations with two different inputs (2). 1612 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1613 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1614 SelectionDAG &DAG) { 1615 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1616 if (ShuffleKind == 0) { 1617 if (IsLE) 1618 return false; 1619 for (unsigned i = 0; i != 16; i += 2) 1620 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1621 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1622 return false; 1623 } else if (ShuffleKind == 2) { 1624 if (!IsLE) 1625 return false; 1626 for (unsigned i = 0; i != 16; i += 2) 1627 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1628 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1629 return false; 1630 } else if (ShuffleKind == 1) { 1631 unsigned j = IsLE ? 0 : 2; 1632 for (unsigned i = 0; i != 8; i += 2) 1633 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1634 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1635 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1636 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1637 return false; 1638 } 1639 return true; 1640 } 1641 1642 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1643 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1644 /// current subtarget. 1645 /// 1646 /// The ShuffleKind distinguishes between big-endian operations with 1647 /// two different inputs (0), either-endian operations with two identical 1648 /// inputs (1), and little-endian operations with two different inputs (2). 1649 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1650 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1651 SelectionDAG &DAG) { 1652 const PPCSubtarget& Subtarget = 1653 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1654 if (!Subtarget.hasP8Vector()) 1655 return false; 1656 1657 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1658 if (ShuffleKind == 0) { 1659 if (IsLE) 1660 return false; 1661 for (unsigned i = 0; i != 16; i += 4) 1662 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1663 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1664 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1665 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1666 return false; 1667 } else if (ShuffleKind == 2) { 1668 if (!IsLE) 1669 return false; 1670 for (unsigned i = 0; i != 16; i += 4) 1671 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1672 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1673 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1674 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1675 return false; 1676 } else if (ShuffleKind == 1) { 1677 unsigned j = IsLE ? 0 : 4; 1678 for (unsigned i = 0; i != 8; i += 4) 1679 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1680 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1681 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1682 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1683 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1684 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1685 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1686 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1687 return false; 1688 } 1689 return true; 1690 } 1691 1692 /// isVMerge - Common function, used to match vmrg* shuffles. 1693 /// 1694 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1695 unsigned LHSStart, unsigned RHSStart) { 1696 if (N->getValueType(0) != MVT::v16i8) 1697 return false; 1698 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1699 "Unsupported merge size!"); 1700 1701 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1702 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1703 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1704 LHSStart+j+i*UnitSize) || 1705 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1706 RHSStart+j+i*UnitSize)) 1707 return false; 1708 } 1709 return true; 1710 } 1711 1712 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1713 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1714 /// The ShuffleKind distinguishes between big-endian merges with two 1715 /// different inputs (0), either-endian merges with two identical inputs (1), 1716 /// and little-endian merges with two different inputs (2). For the latter, 1717 /// the input operands are swapped (see PPCInstrAltivec.td). 1718 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1719 unsigned ShuffleKind, SelectionDAG &DAG) { 1720 if (DAG.getDataLayout().isLittleEndian()) { 1721 if (ShuffleKind == 1) // unary 1722 return isVMerge(N, UnitSize, 0, 0); 1723 else if (ShuffleKind == 2) // swapped 1724 return isVMerge(N, UnitSize, 0, 16); 1725 else 1726 return false; 1727 } else { 1728 if (ShuffleKind == 1) // unary 1729 return isVMerge(N, UnitSize, 8, 8); 1730 else if (ShuffleKind == 0) // normal 1731 return isVMerge(N, UnitSize, 8, 24); 1732 else 1733 return false; 1734 } 1735 } 1736 1737 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1738 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1739 /// The ShuffleKind distinguishes between big-endian merges with two 1740 /// different inputs (0), either-endian merges with two identical inputs (1), 1741 /// and little-endian merges with two different inputs (2). For the latter, 1742 /// the input operands are swapped (see PPCInstrAltivec.td). 1743 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1744 unsigned ShuffleKind, SelectionDAG &DAG) { 1745 if (DAG.getDataLayout().isLittleEndian()) { 1746 if (ShuffleKind == 1) // unary 1747 return isVMerge(N, UnitSize, 8, 8); 1748 else if (ShuffleKind == 2) // swapped 1749 return isVMerge(N, UnitSize, 8, 24); 1750 else 1751 return false; 1752 } else { 1753 if (ShuffleKind == 1) // unary 1754 return isVMerge(N, UnitSize, 0, 0); 1755 else if (ShuffleKind == 0) // normal 1756 return isVMerge(N, UnitSize, 0, 16); 1757 else 1758 return false; 1759 } 1760 } 1761 1762 /** 1763 * Common function used to match vmrgew and vmrgow shuffles 1764 * 1765 * The indexOffset determines whether to look for even or odd words in 1766 * the shuffle mask. This is based on the of the endianness of the target 1767 * machine. 1768 * - Little Endian: 1769 * - Use offset of 0 to check for odd elements 1770 * - Use offset of 4 to check for even elements 1771 * - Big Endian: 1772 * - Use offset of 0 to check for even elements 1773 * - Use offset of 4 to check for odd elements 1774 * A detailed description of the vector element ordering for little endian and 1775 * big endian can be found at 1776 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1777 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1778 * compiler differences mean to you 1779 * 1780 * The mask to the shuffle vector instruction specifies the indices of the 1781 * elements from the two input vectors to place in the result. The elements are 1782 * numbered in array-access order, starting with the first vector. These vectors 1783 * are always of type v16i8, thus each vector will contain 16 elements of size 1784 * 8. More info on the shuffle vector can be found in the 1785 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1786 * Language Reference. 1787 * 1788 * The RHSStartValue indicates whether the same input vectors are used (unary) 1789 * or two different input vectors are used, based on the following: 1790 * - If the instruction uses the same vector for both inputs, the range of the 1791 * indices will be 0 to 15. In this case, the RHSStart value passed should 1792 * be 0. 1793 * - If the instruction has two different vectors then the range of the 1794 * indices will be 0 to 31. In this case, the RHSStart value passed should 1795 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1796 * to 31 specify elements in the second vector). 1797 * 1798 * \param[in] N The shuffle vector SD Node to analyze 1799 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1800 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1801 * vector to the shuffle_vector instruction 1802 * \return true iff this shuffle vector represents an even or odd word merge 1803 */ 1804 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1805 unsigned RHSStartValue) { 1806 if (N->getValueType(0) != MVT::v16i8) 1807 return false; 1808 1809 for (unsigned i = 0; i < 2; ++i) 1810 for (unsigned j = 0; j < 4; ++j) 1811 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1812 i*RHSStartValue+j+IndexOffset) || 1813 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1814 i*RHSStartValue+j+IndexOffset+8)) 1815 return false; 1816 return true; 1817 } 1818 1819 /** 1820 * Determine if the specified shuffle mask is suitable for the vmrgew or 1821 * vmrgow instructions. 1822 * 1823 * \param[in] N The shuffle vector SD Node to analyze 1824 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1825 * \param[in] ShuffleKind Identify the type of merge: 1826 * - 0 = big-endian merge with two different inputs; 1827 * - 1 = either-endian merge with two identical inputs; 1828 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1829 * little-endian merges). 1830 * \param[in] DAG The current SelectionDAG 1831 * \return true iff this shuffle mask 1832 */ 1833 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1834 unsigned ShuffleKind, SelectionDAG &DAG) { 1835 if (DAG.getDataLayout().isLittleEndian()) { 1836 unsigned indexOffset = CheckEven ? 4 : 0; 1837 if (ShuffleKind == 1) // Unary 1838 return isVMerge(N, indexOffset, 0); 1839 else if (ShuffleKind == 2) // swapped 1840 return isVMerge(N, indexOffset, 16); 1841 else 1842 return false; 1843 } 1844 else { 1845 unsigned indexOffset = CheckEven ? 0 : 4; 1846 if (ShuffleKind == 1) // Unary 1847 return isVMerge(N, indexOffset, 0); 1848 else if (ShuffleKind == 0) // Normal 1849 return isVMerge(N, indexOffset, 16); 1850 else 1851 return false; 1852 } 1853 return false; 1854 } 1855 1856 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1857 /// amount, otherwise return -1. 1858 /// The ShuffleKind distinguishes between big-endian operations with two 1859 /// different inputs (0), either-endian operations with two identical inputs 1860 /// (1), and little-endian operations with two different inputs (2). For the 1861 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1862 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1863 SelectionDAG &DAG) { 1864 if (N->getValueType(0) != MVT::v16i8) 1865 return -1; 1866 1867 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1868 1869 // Find the first non-undef value in the shuffle mask. 1870 unsigned i; 1871 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1872 /*search*/; 1873 1874 if (i == 16) return -1; // all undef. 1875 1876 // Otherwise, check to see if the rest of the elements are consecutively 1877 // numbered from this value. 1878 unsigned ShiftAmt = SVOp->getMaskElt(i); 1879 if (ShiftAmt < i) return -1; 1880 1881 ShiftAmt -= i; 1882 bool isLE = DAG.getDataLayout().isLittleEndian(); 1883 1884 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1885 // Check the rest of the elements to see if they are consecutive. 1886 for (++i; i != 16; ++i) 1887 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1888 return -1; 1889 } else if (ShuffleKind == 1) { 1890 // Check the rest of the elements to see if they are consecutive. 1891 for (++i; i != 16; ++i) 1892 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1893 return -1; 1894 } else 1895 return -1; 1896 1897 if (isLE) 1898 ShiftAmt = 16 - ShiftAmt; 1899 1900 return ShiftAmt; 1901 } 1902 1903 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1904 /// specifies a splat of a single element that is suitable for input to 1905 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1906 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1907 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1908 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1909 1910 // The consecutive indices need to specify an element, not part of two 1911 // different elements. So abandon ship early if this isn't the case. 1912 if (N->getMaskElt(0) % EltSize != 0) 1913 return false; 1914 1915 // This is a splat operation if each element of the permute is the same, and 1916 // if the value doesn't reference the second vector. 1917 unsigned ElementBase = N->getMaskElt(0); 1918 1919 // FIXME: Handle UNDEF elements too! 1920 if (ElementBase >= 16) 1921 return false; 1922 1923 // Check that the indices are consecutive, in the case of a multi-byte element 1924 // splatted with a v16i8 mask. 1925 for (unsigned i = 1; i != EltSize; ++i) 1926 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1927 return false; 1928 1929 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1930 if (N->getMaskElt(i) < 0) continue; 1931 for (unsigned j = 0; j != EltSize; ++j) 1932 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1933 return false; 1934 } 1935 return true; 1936 } 1937 1938 /// Check that the mask is shuffling N byte elements. Within each N byte 1939 /// element of the mask, the indices could be either in increasing or 1940 /// decreasing order as long as they are consecutive. 1941 /// \param[in] N the shuffle vector SD Node to analyze 1942 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1943 /// Word/DoubleWord/QuadWord). 1944 /// \param[in] StepLen the delta indices number among the N byte element, if 1945 /// the mask is in increasing/decreasing order then it is 1/-1. 1946 /// \return true iff the mask is shuffling N byte elements. 1947 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1948 int StepLen) { 1949 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1950 "Unexpected element width."); 1951 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1952 1953 unsigned NumOfElem = 16 / Width; 1954 unsigned MaskVal[16]; // Width is never greater than 16 1955 for (unsigned i = 0; i < NumOfElem; ++i) { 1956 MaskVal[0] = N->getMaskElt(i * Width); 1957 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1958 return false; 1959 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1960 return false; 1961 } 1962 1963 for (unsigned int j = 1; j < Width; ++j) { 1964 MaskVal[j] = N->getMaskElt(i * Width + j); 1965 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1966 return false; 1967 } 1968 } 1969 } 1970 1971 return true; 1972 } 1973 1974 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1975 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1976 if (!isNByteElemShuffleMask(N, 4, 1)) 1977 return false; 1978 1979 // Now we look at mask elements 0,4,8,12 1980 unsigned M0 = N->getMaskElt(0) / 4; 1981 unsigned M1 = N->getMaskElt(4) / 4; 1982 unsigned M2 = N->getMaskElt(8) / 4; 1983 unsigned M3 = N->getMaskElt(12) / 4; 1984 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1985 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1986 1987 // Below, let H and L be arbitrary elements of the shuffle mask 1988 // where H is in the range [4,7] and L is in the range [0,3]. 1989 // H, 1, 2, 3 or L, 5, 6, 7 1990 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1991 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1992 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1993 InsertAtByte = IsLE ? 12 : 0; 1994 Swap = M0 < 4; 1995 return true; 1996 } 1997 // 0, H, 2, 3 or 4, L, 6, 7 1998 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1999 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2000 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2001 InsertAtByte = IsLE ? 8 : 4; 2002 Swap = M1 < 4; 2003 return true; 2004 } 2005 // 0, 1, H, 3 or 4, 5, L, 7 2006 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2007 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2008 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2009 InsertAtByte = IsLE ? 4 : 8; 2010 Swap = M2 < 4; 2011 return true; 2012 } 2013 // 0, 1, 2, H or 4, 5, 6, L 2014 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2015 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2016 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2017 InsertAtByte = IsLE ? 0 : 12; 2018 Swap = M3 < 4; 2019 return true; 2020 } 2021 2022 // If both vector operands for the shuffle are the same vector, the mask will 2023 // contain only elements from the first one and the second one will be undef. 2024 if (N->getOperand(1).isUndef()) { 2025 ShiftElts = 0; 2026 Swap = true; 2027 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2028 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2029 InsertAtByte = IsLE ? 12 : 0; 2030 return true; 2031 } 2032 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2033 InsertAtByte = IsLE ? 8 : 4; 2034 return true; 2035 } 2036 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2037 InsertAtByte = IsLE ? 4 : 8; 2038 return true; 2039 } 2040 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2041 InsertAtByte = IsLE ? 0 : 12; 2042 return true; 2043 } 2044 } 2045 2046 return false; 2047 } 2048 2049 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2050 bool &Swap, bool IsLE) { 2051 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2052 // Ensure each byte index of the word is consecutive. 2053 if (!isNByteElemShuffleMask(N, 4, 1)) 2054 return false; 2055 2056 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2057 unsigned M0 = N->getMaskElt(0) / 4; 2058 unsigned M1 = N->getMaskElt(4) / 4; 2059 unsigned M2 = N->getMaskElt(8) / 4; 2060 unsigned M3 = N->getMaskElt(12) / 4; 2061 2062 // If both vector operands for the shuffle are the same vector, the mask will 2063 // contain only elements from the first one and the second one will be undef. 2064 if (N->getOperand(1).isUndef()) { 2065 assert(M0 < 4 && "Indexing into an undef vector?"); 2066 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2067 return false; 2068 2069 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2070 Swap = false; 2071 return true; 2072 } 2073 2074 // Ensure each word index of the ShuffleVector Mask is consecutive. 2075 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2076 return false; 2077 2078 if (IsLE) { 2079 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2080 // Input vectors don't need to be swapped if the leading element 2081 // of the result is one of the 3 left elements of the second vector 2082 // (or if there is no shift to be done at all). 2083 Swap = false; 2084 ShiftElts = (8 - M0) % 8; 2085 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2086 // Input vectors need to be swapped if the leading element 2087 // of the result is one of the 3 left elements of the first vector 2088 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2089 Swap = true; 2090 ShiftElts = (4 - M0) % 4; 2091 } 2092 2093 return true; 2094 } else { // BE 2095 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2096 // Input vectors don't need to be swapped if the leading element 2097 // of the result is one of the 4 elements of the first vector. 2098 Swap = false; 2099 ShiftElts = M0; 2100 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2101 // Input vectors need to be swapped if the leading element 2102 // of the result is one of the 4 elements of the right vector. 2103 Swap = true; 2104 ShiftElts = M0 - 4; 2105 } 2106 2107 return true; 2108 } 2109 } 2110 2111 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2112 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2113 2114 if (!isNByteElemShuffleMask(N, Width, -1)) 2115 return false; 2116 2117 for (int i = 0; i < 16; i += Width) 2118 if (N->getMaskElt(i) != i + Width - 1) 2119 return false; 2120 2121 return true; 2122 } 2123 2124 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2125 return isXXBRShuffleMaskHelper(N, 2); 2126 } 2127 2128 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2129 return isXXBRShuffleMaskHelper(N, 4); 2130 } 2131 2132 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2133 return isXXBRShuffleMaskHelper(N, 8); 2134 } 2135 2136 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2137 return isXXBRShuffleMaskHelper(N, 16); 2138 } 2139 2140 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2141 /// if the inputs to the instruction should be swapped and set \p DM to the 2142 /// value for the immediate. 2143 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2144 /// AND element 0 of the result comes from the first input (LE) or second input 2145 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2146 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2147 /// mask. 2148 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2149 bool &Swap, bool IsLE) { 2150 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2151 2152 // Ensure each byte index of the double word is consecutive. 2153 if (!isNByteElemShuffleMask(N, 8, 1)) 2154 return false; 2155 2156 unsigned M0 = N->getMaskElt(0) / 8; 2157 unsigned M1 = N->getMaskElt(8) / 8; 2158 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2159 2160 // If both vector operands for the shuffle are the same vector, the mask will 2161 // contain only elements from the first one and the second one will be undef. 2162 if (N->getOperand(1).isUndef()) { 2163 if ((M0 | M1) < 2) { 2164 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2165 Swap = false; 2166 return true; 2167 } else 2168 return false; 2169 } 2170 2171 if (IsLE) { 2172 if (M0 > 1 && M1 < 2) { 2173 Swap = false; 2174 } else if (M0 < 2 && M1 > 1) { 2175 M0 = (M0 + 2) % 4; 2176 M1 = (M1 + 2) % 4; 2177 Swap = true; 2178 } else 2179 return false; 2180 2181 // Note: if control flow comes here that means Swap is already set above 2182 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2183 return true; 2184 } else { // BE 2185 if (M0 < 2 && M1 > 1) { 2186 Swap = false; 2187 } else if (M0 > 1 && M1 < 2) { 2188 M0 = (M0 + 2) % 4; 2189 M1 = (M1 + 2) % 4; 2190 Swap = true; 2191 } else 2192 return false; 2193 2194 // Note: if control flow comes here that means Swap is already set above 2195 DM = (M0 << 1) + (M1 & 1); 2196 return true; 2197 } 2198 } 2199 2200 2201 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2202 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2203 /// elements are counted from the left of the vector register). 2204 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2205 SelectionDAG &DAG) { 2206 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2207 assert(isSplatShuffleMask(SVOp, EltSize)); 2208 if (DAG.getDataLayout().isLittleEndian()) 2209 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2210 else 2211 return SVOp->getMaskElt(0) / EltSize; 2212 } 2213 2214 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2215 /// by using a vspltis[bhw] instruction of the specified element size, return 2216 /// the constant being splatted. The ByteSize field indicates the number of 2217 /// bytes of each element [124] -> [bhw]. 2218 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2219 SDValue OpVal(nullptr, 0); 2220 2221 // If ByteSize of the splat is bigger than the element size of the 2222 // build_vector, then we have a case where we are checking for a splat where 2223 // multiple elements of the buildvector are folded together into a single 2224 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2225 unsigned EltSize = 16/N->getNumOperands(); 2226 if (EltSize < ByteSize) { 2227 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2228 SDValue UniquedVals[4]; 2229 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2230 2231 // See if all of the elements in the buildvector agree across. 2232 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2233 if (N->getOperand(i).isUndef()) continue; 2234 // If the element isn't a constant, bail fully out. 2235 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2236 2237 if (!UniquedVals[i&(Multiple-1)].getNode()) 2238 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2239 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2240 return SDValue(); // no match. 2241 } 2242 2243 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2244 // either constant or undef values that are identical for each chunk. See 2245 // if these chunks can form into a larger vspltis*. 2246 2247 // Check to see if all of the leading entries are either 0 or -1. If 2248 // neither, then this won't fit into the immediate field. 2249 bool LeadingZero = true; 2250 bool LeadingOnes = true; 2251 for (unsigned i = 0; i != Multiple-1; ++i) { 2252 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2253 2254 LeadingZero &= isNullConstant(UniquedVals[i]); 2255 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2256 } 2257 // Finally, check the least significant entry. 2258 if (LeadingZero) { 2259 if (!UniquedVals[Multiple-1].getNode()) 2260 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2261 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2262 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2263 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2264 } 2265 if (LeadingOnes) { 2266 if (!UniquedVals[Multiple-1].getNode()) 2267 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2268 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2269 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2270 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2271 } 2272 2273 return SDValue(); 2274 } 2275 2276 // Check to see if this buildvec has a single non-undef value in its elements. 2277 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2278 if (N->getOperand(i).isUndef()) continue; 2279 if (!OpVal.getNode()) 2280 OpVal = N->getOperand(i); 2281 else if (OpVal != N->getOperand(i)) 2282 return SDValue(); 2283 } 2284 2285 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2286 2287 unsigned ValSizeInBytes = EltSize; 2288 uint64_t Value = 0; 2289 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2290 Value = CN->getZExtValue(); 2291 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2292 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2293 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2294 } 2295 2296 // If the splat value is larger than the element value, then we can never do 2297 // this splat. The only case that we could fit the replicated bits into our 2298 // immediate field for would be zero, and we prefer to use vxor for it. 2299 if (ValSizeInBytes < ByteSize) return SDValue(); 2300 2301 // If the element value is larger than the splat value, check if it consists 2302 // of a repeated bit pattern of size ByteSize. 2303 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2304 return SDValue(); 2305 2306 // Properly sign extend the value. 2307 int MaskVal = SignExtend32(Value, ByteSize * 8); 2308 2309 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2310 if (MaskVal == 0) return SDValue(); 2311 2312 // Finally, if this value fits in a 5 bit sext field, return it 2313 if (SignExtend32<5>(MaskVal) == MaskVal) 2314 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2315 return SDValue(); 2316 } 2317 2318 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2319 /// amount, otherwise return -1. 2320 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2321 EVT VT = N->getValueType(0); 2322 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2323 return -1; 2324 2325 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2326 2327 // Find the first non-undef value in the shuffle mask. 2328 unsigned i; 2329 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2330 /*search*/; 2331 2332 if (i == 4) return -1; // all undef. 2333 2334 // Otherwise, check to see if the rest of the elements are consecutively 2335 // numbered from this value. 2336 unsigned ShiftAmt = SVOp->getMaskElt(i); 2337 if (ShiftAmt < i) return -1; 2338 ShiftAmt -= i; 2339 2340 // Check the rest of the elements to see if they are consecutive. 2341 for (++i; i != 4; ++i) 2342 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2343 return -1; 2344 2345 return ShiftAmt; 2346 } 2347 2348 //===----------------------------------------------------------------------===// 2349 // Addressing Mode Selection 2350 //===----------------------------------------------------------------------===// 2351 2352 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2353 /// or 64-bit immediate, and if the value can be accurately represented as a 2354 /// sign extension from a 16-bit value. If so, this returns true and the 2355 /// immediate. 2356 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2357 if (!isa<ConstantSDNode>(N)) 2358 return false; 2359 2360 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2361 if (N->getValueType(0) == MVT::i32) 2362 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2363 else 2364 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2365 } 2366 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2367 return isIntS16Immediate(Op.getNode(), Imm); 2368 } 2369 2370 2371 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2372 /// be represented as an indexed [r+r] operation. 2373 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2374 SDValue &Index, 2375 SelectionDAG &DAG) const { 2376 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2377 UI != E; ++UI) { 2378 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2379 if (Memop->getMemoryVT() == MVT::f64) { 2380 Base = N.getOperand(0); 2381 Index = N.getOperand(1); 2382 return true; 2383 } 2384 } 2385 } 2386 return false; 2387 } 2388 2389 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2390 /// can be represented as an indexed [r+r] operation. Returns false if it 2391 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2392 /// non-zero and N can be represented by a base register plus a signed 16-bit 2393 /// displacement, make a more precise judgement by checking (displacement % \p 2394 /// EncodingAlignment). 2395 bool PPCTargetLowering::SelectAddressRegReg( 2396 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2397 MaybeAlign EncodingAlignment) const { 2398 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2399 // a [pc+imm]. 2400 if (SelectAddressPCRel(N, Base)) 2401 return false; 2402 2403 int16_t Imm = 0; 2404 if (N.getOpcode() == ISD::ADD) { 2405 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2406 // SPE load/store can only handle 8-bit offsets. 2407 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2408 return true; 2409 if (isIntS16Immediate(N.getOperand(1), Imm) && 2410 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2411 return false; // r+i 2412 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2413 return false; // r+i 2414 2415 Base = N.getOperand(0); 2416 Index = N.getOperand(1); 2417 return true; 2418 } else if (N.getOpcode() == ISD::OR) { 2419 if (isIntS16Immediate(N.getOperand(1), Imm) && 2420 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2421 return false; // r+i can fold it if we can. 2422 2423 // If this is an or of disjoint bitfields, we can codegen this as an add 2424 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2425 // disjoint. 2426 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2427 2428 if (LHSKnown.Zero.getBoolValue()) { 2429 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2430 // If all of the bits are known zero on the LHS or RHS, the add won't 2431 // carry. 2432 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2433 Base = N.getOperand(0); 2434 Index = N.getOperand(1); 2435 return true; 2436 } 2437 } 2438 } 2439 2440 return false; 2441 } 2442 2443 // If we happen to be doing an i64 load or store into a stack slot that has 2444 // less than a 4-byte alignment, then the frame-index elimination may need to 2445 // use an indexed load or store instruction (because the offset may not be a 2446 // multiple of 4). The extra register needed to hold the offset comes from the 2447 // register scavenger, and it is possible that the scavenger will need to use 2448 // an emergency spill slot. As a result, we need to make sure that a spill slot 2449 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2450 // stack slot. 2451 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2452 // FIXME: This does not handle the LWA case. 2453 if (VT != MVT::i64) 2454 return; 2455 2456 // NOTE: We'll exclude negative FIs here, which come from argument 2457 // lowering, because there are no known test cases triggering this problem 2458 // using packed structures (or similar). We can remove this exclusion if 2459 // we find such a test case. The reason why this is so test-case driven is 2460 // because this entire 'fixup' is only to prevent crashes (from the 2461 // register scavenger) on not-really-valid inputs. For example, if we have: 2462 // %a = alloca i1 2463 // %b = bitcast i1* %a to i64* 2464 // store i64* a, i64 b 2465 // then the store should really be marked as 'align 1', but is not. If it 2466 // were marked as 'align 1' then the indexed form would have been 2467 // instruction-selected initially, and the problem this 'fixup' is preventing 2468 // won't happen regardless. 2469 if (FrameIdx < 0) 2470 return; 2471 2472 MachineFunction &MF = DAG.getMachineFunction(); 2473 MachineFrameInfo &MFI = MF.getFrameInfo(); 2474 2475 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2476 return; 2477 2478 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2479 FuncInfo->setHasNonRISpills(); 2480 } 2481 2482 /// Returns true if the address N can be represented by a base register plus 2483 /// a signed 16-bit displacement [r+imm], and if it is not better 2484 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2485 /// displacements that are multiples of that value. 2486 bool PPCTargetLowering::SelectAddressRegImm( 2487 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2488 MaybeAlign EncodingAlignment) const { 2489 // FIXME dl should come from parent load or store, not from address 2490 SDLoc dl(N); 2491 2492 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2493 // a [pc+imm]. 2494 if (SelectAddressPCRel(N, Base)) 2495 return false; 2496 2497 // If this can be more profitably realized as r+r, fail. 2498 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2499 return false; 2500 2501 if (N.getOpcode() == ISD::ADD) { 2502 int16_t imm = 0; 2503 if (isIntS16Immediate(N.getOperand(1), imm) && 2504 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2505 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2506 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2507 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2508 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2509 } else { 2510 Base = N.getOperand(0); 2511 } 2512 return true; // [r+i] 2513 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2514 // Match LOAD (ADD (X, Lo(G))). 2515 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2516 && "Cannot handle constant offsets yet!"); 2517 Disp = N.getOperand(1).getOperand(0); // The global address. 2518 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2519 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2520 Disp.getOpcode() == ISD::TargetConstantPool || 2521 Disp.getOpcode() == ISD::TargetJumpTable); 2522 Base = N.getOperand(0); 2523 return true; // [&g+r] 2524 } 2525 } else if (N.getOpcode() == ISD::OR) { 2526 int16_t imm = 0; 2527 if (isIntS16Immediate(N.getOperand(1), imm) && 2528 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2529 // If this is an or of disjoint bitfields, we can codegen this as an add 2530 // (for better address arithmetic) if the LHS and RHS of the OR are 2531 // provably disjoint. 2532 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2533 2534 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2535 // If all of the bits are known zero on the LHS or RHS, the add won't 2536 // carry. 2537 if (FrameIndexSDNode *FI = 2538 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2539 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2540 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2541 } else { 2542 Base = N.getOperand(0); 2543 } 2544 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2545 return true; 2546 } 2547 } 2548 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2549 // Loading from a constant address. 2550 2551 // If this address fits entirely in a 16-bit sext immediate field, codegen 2552 // this as "d, 0" 2553 int16_t Imm; 2554 if (isIntS16Immediate(CN, Imm) && 2555 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2556 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2557 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2558 CN->getValueType(0)); 2559 return true; 2560 } 2561 2562 // Handle 32-bit sext immediates with LIS + addr mode. 2563 if ((CN->getValueType(0) == MVT::i32 || 2564 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2565 (!EncodingAlignment || 2566 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2567 int Addr = (int)CN->getZExtValue(); 2568 2569 // Otherwise, break this down into an LIS + disp. 2570 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2571 2572 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2573 MVT::i32); 2574 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2575 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2576 return true; 2577 } 2578 } 2579 2580 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2581 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2582 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2583 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2584 } else 2585 Base = N; 2586 return true; // [r+0] 2587 } 2588 2589 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2590 /// represented as an indexed [r+r] operation. 2591 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2592 SDValue &Index, 2593 SelectionDAG &DAG) const { 2594 // Check to see if we can easily represent this as an [r+r] address. This 2595 // will fail if it thinks that the address is more profitably represented as 2596 // reg+imm, e.g. where imm = 0. 2597 if (SelectAddressRegReg(N, Base, Index, DAG)) 2598 return true; 2599 2600 // If the address is the result of an add, we will utilize the fact that the 2601 // address calculation includes an implicit add. However, we can reduce 2602 // register pressure if we do not materialize a constant just for use as the 2603 // index register. We only get rid of the add if it is not an add of a 2604 // value and a 16-bit signed constant and both have a single use. 2605 int16_t imm = 0; 2606 if (N.getOpcode() == ISD::ADD && 2607 (!isIntS16Immediate(N.getOperand(1), imm) || 2608 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2609 Base = N.getOperand(0); 2610 Index = N.getOperand(1); 2611 return true; 2612 } 2613 2614 // Otherwise, do it the hard way, using R0 as the base register. 2615 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2616 N.getValueType()); 2617 Index = N; 2618 return true; 2619 } 2620 2621 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2622 Ty *PCRelCand = dyn_cast<Ty>(N); 2623 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2624 } 2625 2626 /// Returns true if this address is a PC Relative address. 2627 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2628 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2629 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2630 // This is a materialize PC Relative node. Always select this as PC Relative. 2631 Base = N; 2632 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2633 return true; 2634 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2635 isValidPCRelNode<GlobalAddressSDNode>(N) || 2636 isValidPCRelNode<JumpTableSDNode>(N) || 2637 isValidPCRelNode<BlockAddressSDNode>(N)) 2638 return true; 2639 return false; 2640 } 2641 2642 /// Returns true if we should use a direct load into vector instruction 2643 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2644 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2645 2646 // If there are any other uses other than scalar to vector, then we should 2647 // keep it as a scalar load -> direct move pattern to prevent multiple 2648 // loads. 2649 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2650 if (!LD) 2651 return false; 2652 2653 EVT MemVT = LD->getMemoryVT(); 2654 if (!MemVT.isSimple()) 2655 return false; 2656 switch(MemVT.getSimpleVT().SimpleTy) { 2657 case MVT::i64: 2658 break; 2659 case MVT::i32: 2660 if (!ST.hasP8Vector()) 2661 return false; 2662 break; 2663 case MVT::i16: 2664 case MVT::i8: 2665 if (!ST.hasP9Vector()) 2666 return false; 2667 break; 2668 default: 2669 return false; 2670 } 2671 2672 SDValue LoadedVal(N, 0); 2673 if (!LoadedVal.hasOneUse()) 2674 return false; 2675 2676 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2677 UI != UE; ++UI) 2678 if (UI.getUse().get().getResNo() == 0 && 2679 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2680 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2681 return false; 2682 2683 return true; 2684 } 2685 2686 /// getPreIndexedAddressParts - returns true by value, base pointer and 2687 /// offset pointer and addressing mode by reference if the node's address 2688 /// can be legally represented as pre-indexed load / store address. 2689 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2690 SDValue &Offset, 2691 ISD::MemIndexedMode &AM, 2692 SelectionDAG &DAG) const { 2693 if (DisablePPCPreinc) return false; 2694 2695 bool isLoad = true; 2696 SDValue Ptr; 2697 EVT VT; 2698 unsigned Alignment; 2699 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2700 Ptr = LD->getBasePtr(); 2701 VT = LD->getMemoryVT(); 2702 Alignment = LD->getAlignment(); 2703 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2704 Ptr = ST->getBasePtr(); 2705 VT = ST->getMemoryVT(); 2706 Alignment = ST->getAlignment(); 2707 isLoad = false; 2708 } else 2709 return false; 2710 2711 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2712 // instructions because we can fold these into a more efficient instruction 2713 // instead, (such as LXSD). 2714 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2715 return false; 2716 } 2717 2718 // PowerPC doesn't have preinc load/store instructions for vectors 2719 if (VT.isVector()) 2720 return false; 2721 2722 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2723 // Common code will reject creating a pre-inc form if the base pointer 2724 // is a frame index, or if N is a store and the base pointer is either 2725 // the same as or a predecessor of the value being stored. Check for 2726 // those situations here, and try with swapped Base/Offset instead. 2727 bool Swap = false; 2728 2729 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2730 Swap = true; 2731 else if (!isLoad) { 2732 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2733 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2734 Swap = true; 2735 } 2736 2737 if (Swap) 2738 std::swap(Base, Offset); 2739 2740 AM = ISD::PRE_INC; 2741 return true; 2742 } 2743 2744 // LDU/STU can only handle immediates that are a multiple of 4. 2745 if (VT != MVT::i64) { 2746 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2747 return false; 2748 } else { 2749 // LDU/STU need an address with at least 4-byte alignment. 2750 if (Alignment < 4) 2751 return false; 2752 2753 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2754 return false; 2755 } 2756 2757 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2758 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2759 // sext i32 to i64 when addr mode is r+i. 2760 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2761 LD->getExtensionType() == ISD::SEXTLOAD && 2762 isa<ConstantSDNode>(Offset)) 2763 return false; 2764 } 2765 2766 AM = ISD::PRE_INC; 2767 return true; 2768 } 2769 2770 //===----------------------------------------------------------------------===// 2771 // LowerOperation implementation 2772 //===----------------------------------------------------------------------===// 2773 2774 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2775 /// and LoOpFlags to the target MO flags. 2776 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2777 unsigned &HiOpFlags, unsigned &LoOpFlags, 2778 const GlobalValue *GV = nullptr) { 2779 HiOpFlags = PPCII::MO_HA; 2780 LoOpFlags = PPCII::MO_LO; 2781 2782 // Don't use the pic base if not in PIC relocation model. 2783 if (IsPIC) { 2784 HiOpFlags |= PPCII::MO_PIC_FLAG; 2785 LoOpFlags |= PPCII::MO_PIC_FLAG; 2786 } 2787 } 2788 2789 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2790 SelectionDAG &DAG) { 2791 SDLoc DL(HiPart); 2792 EVT PtrVT = HiPart.getValueType(); 2793 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2794 2795 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2796 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2797 2798 // With PIC, the first instruction is actually "GR+hi(&G)". 2799 if (isPIC) 2800 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2801 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2802 2803 // Generate non-pic code that has direct accesses to the constant pool. 2804 // The address of the global is just (hi(&g)+lo(&g)). 2805 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2806 } 2807 2808 static void setUsesTOCBasePtr(MachineFunction &MF) { 2809 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2810 FuncInfo->setUsesTOCBasePtr(); 2811 } 2812 2813 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2814 setUsesTOCBasePtr(DAG.getMachineFunction()); 2815 } 2816 2817 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2818 SDValue GA) const { 2819 const bool Is64Bit = Subtarget.isPPC64(); 2820 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2821 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2822 : Subtarget.isAIXABI() 2823 ? DAG.getRegister(PPC::R2, VT) 2824 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2825 SDValue Ops[] = { GA, Reg }; 2826 return DAG.getMemIntrinsicNode( 2827 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2828 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2829 MachineMemOperand::MOLoad); 2830 } 2831 2832 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2833 SelectionDAG &DAG) const { 2834 EVT PtrVT = Op.getValueType(); 2835 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2836 const Constant *C = CP->getConstVal(); 2837 2838 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2839 // The actual address of the GlobalValue is stored in the TOC. 2840 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2841 if (Subtarget.isUsingPCRelativeCalls()) { 2842 SDLoc DL(CP); 2843 EVT Ty = getPointerTy(DAG.getDataLayout()); 2844 SDValue ConstPool = DAG.getTargetConstantPool( 2845 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2846 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2847 } 2848 setUsesTOCBasePtr(DAG); 2849 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2850 return getTOCEntry(DAG, SDLoc(CP), GA); 2851 } 2852 2853 unsigned MOHiFlag, MOLoFlag; 2854 bool IsPIC = isPositionIndependent(); 2855 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2856 2857 if (IsPIC && Subtarget.isSVR4ABI()) { 2858 SDValue GA = 2859 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2860 return getTOCEntry(DAG, SDLoc(CP), GA); 2861 } 2862 2863 SDValue CPIHi = 2864 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2865 SDValue CPILo = 2866 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2867 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2868 } 2869 2870 // For 64-bit PowerPC, prefer the more compact relative encodings. 2871 // This trades 32 bits per jump table entry for one or two instructions 2872 // on the jump site. 2873 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2874 if (isJumpTableRelative()) 2875 return MachineJumpTableInfo::EK_LabelDifference32; 2876 2877 return TargetLowering::getJumpTableEncoding(); 2878 } 2879 2880 bool PPCTargetLowering::isJumpTableRelative() const { 2881 if (UseAbsoluteJumpTables) 2882 return false; 2883 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2884 return true; 2885 return TargetLowering::isJumpTableRelative(); 2886 } 2887 2888 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2889 SelectionDAG &DAG) const { 2890 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2891 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2892 2893 switch (getTargetMachine().getCodeModel()) { 2894 case CodeModel::Small: 2895 case CodeModel::Medium: 2896 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2897 default: 2898 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2899 getPointerTy(DAG.getDataLayout())); 2900 } 2901 } 2902 2903 const MCExpr * 2904 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2905 unsigned JTI, 2906 MCContext &Ctx) const { 2907 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2908 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2909 2910 switch (getTargetMachine().getCodeModel()) { 2911 case CodeModel::Small: 2912 case CodeModel::Medium: 2913 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2914 default: 2915 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2916 } 2917 } 2918 2919 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2920 EVT PtrVT = Op.getValueType(); 2921 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2922 2923 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2924 if (Subtarget.isUsingPCRelativeCalls()) { 2925 SDLoc DL(JT); 2926 EVT Ty = getPointerTy(DAG.getDataLayout()); 2927 SDValue GA = 2928 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2929 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2930 return MatAddr; 2931 } 2932 2933 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2934 // The actual address of the GlobalValue is stored in the TOC. 2935 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2936 setUsesTOCBasePtr(DAG); 2937 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2938 return getTOCEntry(DAG, SDLoc(JT), GA); 2939 } 2940 2941 unsigned MOHiFlag, MOLoFlag; 2942 bool IsPIC = isPositionIndependent(); 2943 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2944 2945 if (IsPIC && Subtarget.isSVR4ABI()) { 2946 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2947 PPCII::MO_PIC_FLAG); 2948 return getTOCEntry(DAG, SDLoc(GA), GA); 2949 } 2950 2951 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2952 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2953 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2954 } 2955 2956 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2957 SelectionDAG &DAG) const { 2958 EVT PtrVT = Op.getValueType(); 2959 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2960 const BlockAddress *BA = BASDN->getBlockAddress(); 2961 2962 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2963 if (Subtarget.isUsingPCRelativeCalls()) { 2964 SDLoc DL(BASDN); 2965 EVT Ty = getPointerTy(DAG.getDataLayout()); 2966 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2967 PPCII::MO_PCREL_FLAG); 2968 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2969 return MatAddr; 2970 } 2971 2972 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2973 // The actual BlockAddress is stored in the TOC. 2974 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2975 setUsesTOCBasePtr(DAG); 2976 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2977 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2978 } 2979 2980 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2981 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2982 return getTOCEntry( 2983 DAG, SDLoc(BASDN), 2984 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2985 2986 unsigned MOHiFlag, MOLoFlag; 2987 bool IsPIC = isPositionIndependent(); 2988 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2989 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2990 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2991 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2992 } 2993 2994 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2995 SelectionDAG &DAG) const { 2996 // FIXME: TLS addresses currently use medium model code sequences, 2997 // which is the most useful form. Eventually support for small and 2998 // large models could be added if users need it, at the cost of 2999 // additional complexity. 3000 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 3001 report_fatal_error("Thread local storage is not supported with pc-relative" 3002 " addressing - please compile with -mno-pcrel"); 3003 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3004 if (DAG.getTarget().useEmulatedTLS()) 3005 return LowerToTLSEmulatedModel(GA, DAG); 3006 3007 SDLoc dl(GA); 3008 const GlobalValue *GV = GA->getGlobal(); 3009 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3010 bool is64bit = Subtarget.isPPC64(); 3011 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3012 PICLevel::Level picLevel = M->getPICLevel(); 3013 3014 const TargetMachine &TM = getTargetMachine(); 3015 TLSModel::Model Model = TM.getTLSModel(GV); 3016 3017 if (Model == TLSModel::LocalExec) { 3018 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3019 PPCII::MO_TPREL_HA); 3020 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3021 PPCII::MO_TPREL_LO); 3022 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3023 : DAG.getRegister(PPC::R2, MVT::i32); 3024 3025 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3026 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3027 } 3028 3029 if (Model == TLSModel::InitialExec) { 3030 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3031 SDValue TGA = DAG.getTargetGlobalAddress( 3032 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3033 SDValue TGATLS = DAG.getTargetGlobalAddress( 3034 GV, dl, PtrVT, 0, 3035 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3036 SDValue TPOffset; 3037 if (IsPCRel) { 3038 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3039 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3040 MachinePointerInfo()); 3041 } else { 3042 SDValue GOTPtr; 3043 if (is64bit) { 3044 setUsesTOCBasePtr(DAG); 3045 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3046 GOTPtr = 3047 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3048 } else { 3049 if (!TM.isPositionIndependent()) 3050 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3051 else if (picLevel == PICLevel::SmallPIC) 3052 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3053 else 3054 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3055 } 3056 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3057 } 3058 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3059 } 3060 3061 if (Model == TLSModel::GeneralDynamic) { 3062 if (Subtarget.isUsingPCRelativeCalls()) { 3063 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3064 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3065 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3066 } 3067 3068 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3069 SDValue GOTPtr; 3070 if (is64bit) { 3071 setUsesTOCBasePtr(DAG); 3072 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3073 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3074 GOTReg, TGA); 3075 } else { 3076 if (picLevel == PICLevel::SmallPIC) 3077 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3078 else 3079 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3080 } 3081 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3082 GOTPtr, TGA, TGA); 3083 } 3084 3085 if (Model == TLSModel::LocalDynamic) { 3086 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3087 SDValue GOTPtr; 3088 if (is64bit) { 3089 setUsesTOCBasePtr(DAG); 3090 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3091 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3092 GOTReg, TGA); 3093 } else { 3094 if (picLevel == PICLevel::SmallPIC) 3095 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3096 else 3097 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3098 } 3099 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3100 PtrVT, GOTPtr, TGA, TGA); 3101 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3102 PtrVT, TLSAddr, TGA); 3103 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3104 } 3105 3106 llvm_unreachable("Unknown TLS model!"); 3107 } 3108 3109 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3110 SelectionDAG &DAG) const { 3111 EVT PtrVT = Op.getValueType(); 3112 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3113 SDLoc DL(GSDN); 3114 const GlobalValue *GV = GSDN->getGlobal(); 3115 3116 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3117 // The actual address of the GlobalValue is stored in the TOC. 3118 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3119 if (Subtarget.isUsingPCRelativeCalls()) { 3120 EVT Ty = getPointerTy(DAG.getDataLayout()); 3121 if (isAccessedAsGotIndirect(Op)) { 3122 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3123 PPCII::MO_PCREL_FLAG | 3124 PPCII::MO_GOT_FLAG); 3125 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3126 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3127 MachinePointerInfo()); 3128 return Load; 3129 } else { 3130 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3131 PPCII::MO_PCREL_FLAG); 3132 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3133 } 3134 } 3135 setUsesTOCBasePtr(DAG); 3136 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3137 return getTOCEntry(DAG, DL, GA); 3138 } 3139 3140 unsigned MOHiFlag, MOLoFlag; 3141 bool IsPIC = isPositionIndependent(); 3142 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3143 3144 if (IsPIC && Subtarget.isSVR4ABI()) { 3145 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3146 GSDN->getOffset(), 3147 PPCII::MO_PIC_FLAG); 3148 return getTOCEntry(DAG, DL, GA); 3149 } 3150 3151 SDValue GAHi = 3152 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3153 SDValue GALo = 3154 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3155 3156 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3157 } 3158 3159 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3160 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3161 SDLoc dl(Op); 3162 3163 if (Op.getValueType() == MVT::v2i64) { 3164 // When the operands themselves are v2i64 values, we need to do something 3165 // special because VSX has no underlying comparison operations for these. 3166 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3167 // Equality can be handled by casting to the legal type for Altivec 3168 // comparisons, everything else needs to be expanded. 3169 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3170 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3171 DAG.getSetCC(dl, MVT::v4i32, 3172 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3173 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3174 CC)); 3175 } 3176 3177 return SDValue(); 3178 } 3179 3180 // We handle most of these in the usual way. 3181 return Op; 3182 } 3183 3184 // If we're comparing for equality to zero, expose the fact that this is 3185 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3186 // fold the new nodes. 3187 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3188 return V; 3189 3190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3191 // Leave comparisons against 0 and -1 alone for now, since they're usually 3192 // optimized. FIXME: revisit this when we can custom lower all setcc 3193 // optimizations. 3194 if (C->isAllOnesValue() || C->isNullValue()) 3195 return SDValue(); 3196 } 3197 3198 // If we have an integer seteq/setne, turn it into a compare against zero 3199 // by xor'ing the rhs with the lhs, which is faster than setting a 3200 // condition register, reading it back out, and masking the correct bit. The 3201 // normal approach here uses sub to do this instead of xor. Using xor exposes 3202 // the result to other bit-twiddling opportunities. 3203 EVT LHSVT = Op.getOperand(0).getValueType(); 3204 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3205 EVT VT = Op.getValueType(); 3206 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3207 Op.getOperand(1)); 3208 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3209 } 3210 return SDValue(); 3211 } 3212 3213 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3214 SDNode *Node = Op.getNode(); 3215 EVT VT = Node->getValueType(0); 3216 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3217 SDValue InChain = Node->getOperand(0); 3218 SDValue VAListPtr = Node->getOperand(1); 3219 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3220 SDLoc dl(Node); 3221 3222 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3223 3224 // gpr_index 3225 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3226 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3227 InChain = GprIndex.getValue(1); 3228 3229 if (VT == MVT::i64) { 3230 // Check if GprIndex is even 3231 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3232 DAG.getConstant(1, dl, MVT::i32)); 3233 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3234 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3235 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3236 DAG.getConstant(1, dl, MVT::i32)); 3237 // Align GprIndex to be even if it isn't 3238 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3239 GprIndex); 3240 } 3241 3242 // fpr index is 1 byte after gpr 3243 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3244 DAG.getConstant(1, dl, MVT::i32)); 3245 3246 // fpr 3247 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3248 FprPtr, MachinePointerInfo(SV), MVT::i8); 3249 InChain = FprIndex.getValue(1); 3250 3251 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3252 DAG.getConstant(8, dl, MVT::i32)); 3253 3254 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3255 DAG.getConstant(4, dl, MVT::i32)); 3256 3257 // areas 3258 SDValue OverflowArea = 3259 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3260 InChain = OverflowArea.getValue(1); 3261 3262 SDValue RegSaveArea = 3263 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3264 InChain = RegSaveArea.getValue(1); 3265 3266 // select overflow_area if index > 8 3267 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3268 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3269 3270 // adjustment constant gpr_index * 4/8 3271 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3272 VT.isInteger() ? GprIndex : FprIndex, 3273 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3274 MVT::i32)); 3275 3276 // OurReg = RegSaveArea + RegConstant 3277 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3278 RegConstant); 3279 3280 // Floating types are 32 bytes into RegSaveArea 3281 if (VT.isFloatingPoint()) 3282 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3283 DAG.getConstant(32, dl, MVT::i32)); 3284 3285 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3286 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3287 VT.isInteger() ? GprIndex : FprIndex, 3288 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3289 MVT::i32)); 3290 3291 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3292 VT.isInteger() ? VAListPtr : FprPtr, 3293 MachinePointerInfo(SV), MVT::i8); 3294 3295 // determine if we should load from reg_save_area or overflow_area 3296 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3297 3298 // increase overflow_area by 4/8 if gpr/fpr > 8 3299 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3300 DAG.getConstant(VT.isInteger() ? 4 : 8, 3301 dl, MVT::i32)); 3302 3303 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3304 OverflowAreaPlusN); 3305 3306 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3307 MachinePointerInfo(), MVT::i32); 3308 3309 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3310 } 3311 3312 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3313 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3314 3315 // We have to copy the entire va_list struct: 3316 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3317 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3318 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3319 false, true, false, MachinePointerInfo(), 3320 MachinePointerInfo()); 3321 } 3322 3323 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3324 SelectionDAG &DAG) const { 3325 if (Subtarget.isAIXABI()) 3326 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3327 3328 return Op.getOperand(0); 3329 } 3330 3331 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3332 SelectionDAG &DAG) const { 3333 if (Subtarget.isAIXABI()) 3334 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3335 3336 SDValue Chain = Op.getOperand(0); 3337 SDValue Trmp = Op.getOperand(1); // trampoline 3338 SDValue FPtr = Op.getOperand(2); // nested function 3339 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3340 SDLoc dl(Op); 3341 3342 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3343 bool isPPC64 = (PtrVT == MVT::i64); 3344 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3345 3346 TargetLowering::ArgListTy Args; 3347 TargetLowering::ArgListEntry Entry; 3348 3349 Entry.Ty = IntPtrTy; 3350 Entry.Node = Trmp; Args.push_back(Entry); 3351 3352 // TrampSize == (isPPC64 ? 48 : 40); 3353 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3354 isPPC64 ? MVT::i64 : MVT::i32); 3355 Args.push_back(Entry); 3356 3357 Entry.Node = FPtr; Args.push_back(Entry); 3358 Entry.Node = Nest; Args.push_back(Entry); 3359 3360 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3361 TargetLowering::CallLoweringInfo CLI(DAG); 3362 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3363 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3364 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3365 3366 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3367 return CallResult.second; 3368 } 3369 3370 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3371 MachineFunction &MF = DAG.getMachineFunction(); 3372 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3373 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3374 3375 SDLoc dl(Op); 3376 3377 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3378 // vastart just stores the address of the VarArgsFrameIndex slot into the 3379 // memory location argument. 3380 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3381 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3382 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3383 MachinePointerInfo(SV)); 3384 } 3385 3386 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3387 // We suppose the given va_list is already allocated. 3388 // 3389 // typedef struct { 3390 // char gpr; /* index into the array of 8 GPRs 3391 // * stored in the register save area 3392 // * gpr=0 corresponds to r3, 3393 // * gpr=1 to r4, etc. 3394 // */ 3395 // char fpr; /* index into the array of 8 FPRs 3396 // * stored in the register save area 3397 // * fpr=0 corresponds to f1, 3398 // * fpr=1 to f2, etc. 3399 // */ 3400 // char *overflow_arg_area; 3401 // /* location on stack that holds 3402 // * the next overflow argument 3403 // */ 3404 // char *reg_save_area; 3405 // /* where r3:r10 and f1:f8 (if saved) 3406 // * are stored 3407 // */ 3408 // } va_list[1]; 3409 3410 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3411 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3412 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3413 PtrVT); 3414 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3415 PtrVT); 3416 3417 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3418 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3419 3420 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3421 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3422 3423 uint64_t FPROffset = 1; 3424 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3425 3426 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3427 3428 // Store first byte : number of int regs 3429 SDValue firstStore = 3430 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3431 MachinePointerInfo(SV), MVT::i8); 3432 uint64_t nextOffset = FPROffset; 3433 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3434 ConstFPROffset); 3435 3436 // Store second byte : number of float regs 3437 SDValue secondStore = 3438 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3439 MachinePointerInfo(SV, nextOffset), MVT::i8); 3440 nextOffset += StackOffset; 3441 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3442 3443 // Store second word : arguments given on stack 3444 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3445 MachinePointerInfo(SV, nextOffset)); 3446 nextOffset += FrameOffset; 3447 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3448 3449 // Store third word : arguments given in registers 3450 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3451 MachinePointerInfo(SV, nextOffset)); 3452 } 3453 3454 /// FPR - The set of FP registers that should be allocated for arguments 3455 /// on Darwin and AIX. 3456 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3457 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3458 PPC::F11, PPC::F12, PPC::F13}; 3459 3460 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3461 /// the stack. 3462 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3463 unsigned PtrByteSize) { 3464 unsigned ArgSize = ArgVT.getStoreSize(); 3465 if (Flags.isByVal()) 3466 ArgSize = Flags.getByValSize(); 3467 3468 // Round up to multiples of the pointer size, except for array members, 3469 // which are always packed. 3470 if (!Flags.isInConsecutiveRegs()) 3471 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3472 3473 return ArgSize; 3474 } 3475 3476 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3477 /// on the stack. 3478 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3479 ISD::ArgFlagsTy Flags, 3480 unsigned PtrByteSize) { 3481 Align Alignment(PtrByteSize); 3482 3483 // Altivec parameters are padded to a 16 byte boundary. 3484 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3485 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3486 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3487 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3488 Alignment = Align(16); 3489 3490 // ByVal parameters are aligned as requested. 3491 if (Flags.isByVal()) { 3492 auto BVAlign = Flags.getNonZeroByValAlign(); 3493 if (BVAlign > PtrByteSize) { 3494 if (BVAlign.value() % PtrByteSize != 0) 3495 llvm_unreachable( 3496 "ByVal alignment is not a multiple of the pointer size"); 3497 3498 Alignment = BVAlign; 3499 } 3500 } 3501 3502 // Array members are always packed to their original alignment. 3503 if (Flags.isInConsecutiveRegs()) { 3504 // If the array member was split into multiple registers, the first 3505 // needs to be aligned to the size of the full type. (Except for 3506 // ppcf128, which is only aligned as its f64 components.) 3507 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3508 Alignment = Align(OrigVT.getStoreSize()); 3509 else 3510 Alignment = Align(ArgVT.getStoreSize()); 3511 } 3512 3513 return Alignment; 3514 } 3515 3516 /// CalculateStackSlotUsed - Return whether this argument will use its 3517 /// stack slot (instead of being passed in registers). ArgOffset, 3518 /// AvailableFPRs, and AvailableVRs must hold the current argument 3519 /// position, and will be updated to account for this argument. 3520 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3521 unsigned PtrByteSize, unsigned LinkageSize, 3522 unsigned ParamAreaSize, unsigned &ArgOffset, 3523 unsigned &AvailableFPRs, 3524 unsigned &AvailableVRs) { 3525 bool UseMemory = false; 3526 3527 // Respect alignment of argument on the stack. 3528 Align Alignment = 3529 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3530 ArgOffset = alignTo(ArgOffset, Alignment); 3531 // If there's no space left in the argument save area, we must 3532 // use memory (this check also catches zero-sized arguments). 3533 if (ArgOffset >= LinkageSize + ParamAreaSize) 3534 UseMemory = true; 3535 3536 // Allocate argument on the stack. 3537 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3538 if (Flags.isInConsecutiveRegsLast()) 3539 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3540 // If we overran the argument save area, we must use memory 3541 // (this check catches arguments passed partially in memory) 3542 if (ArgOffset > LinkageSize + ParamAreaSize) 3543 UseMemory = true; 3544 3545 // However, if the argument is actually passed in an FPR or a VR, 3546 // we don't use memory after all. 3547 if (!Flags.isByVal()) { 3548 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3549 if (AvailableFPRs > 0) { 3550 --AvailableFPRs; 3551 return false; 3552 } 3553 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3554 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3555 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3556 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3557 if (AvailableVRs > 0) { 3558 --AvailableVRs; 3559 return false; 3560 } 3561 } 3562 3563 return UseMemory; 3564 } 3565 3566 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3567 /// ensure minimum alignment required for target. 3568 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3569 unsigned NumBytes) { 3570 return alignTo(NumBytes, Lowering->getStackAlign()); 3571 } 3572 3573 SDValue PPCTargetLowering::LowerFormalArguments( 3574 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3575 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3576 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3577 if (Subtarget.isAIXABI()) 3578 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3579 InVals); 3580 if (Subtarget.is64BitELFABI()) 3581 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3582 InVals); 3583 if (Subtarget.is32BitELFABI()) 3584 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3585 InVals); 3586 3587 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3588 InVals); 3589 } 3590 3591 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3592 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3593 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3594 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3595 3596 // 32-bit SVR4 ABI Stack Frame Layout: 3597 // +-----------------------------------+ 3598 // +--> | Back chain | 3599 // | +-----------------------------------+ 3600 // | | Floating-point register save area | 3601 // | +-----------------------------------+ 3602 // | | General register save area | 3603 // | +-----------------------------------+ 3604 // | | CR save word | 3605 // | +-----------------------------------+ 3606 // | | VRSAVE save word | 3607 // | +-----------------------------------+ 3608 // | | Alignment padding | 3609 // | +-----------------------------------+ 3610 // | | Vector register save area | 3611 // | +-----------------------------------+ 3612 // | | Local variable space | 3613 // | +-----------------------------------+ 3614 // | | Parameter list area | 3615 // | +-----------------------------------+ 3616 // | | LR save word | 3617 // | +-----------------------------------+ 3618 // SP--> +--- | Back chain | 3619 // +-----------------------------------+ 3620 // 3621 // Specifications: 3622 // System V Application Binary Interface PowerPC Processor Supplement 3623 // AltiVec Technology Programming Interface Manual 3624 3625 MachineFunction &MF = DAG.getMachineFunction(); 3626 MachineFrameInfo &MFI = MF.getFrameInfo(); 3627 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3628 3629 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3630 // Potential tail calls could cause overwriting of argument stack slots. 3631 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3632 (CallConv == CallingConv::Fast)); 3633 const Align PtrAlign(4); 3634 3635 // Assign locations to all of the incoming arguments. 3636 SmallVector<CCValAssign, 16> ArgLocs; 3637 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3638 *DAG.getContext()); 3639 3640 // Reserve space for the linkage area on the stack. 3641 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3642 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3643 if (useSoftFloat()) 3644 CCInfo.PreAnalyzeFormalArguments(Ins); 3645 3646 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3647 CCInfo.clearWasPPCF128(); 3648 3649 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3650 CCValAssign &VA = ArgLocs[i]; 3651 3652 // Arguments stored in registers. 3653 if (VA.isRegLoc()) { 3654 const TargetRegisterClass *RC; 3655 EVT ValVT = VA.getValVT(); 3656 3657 switch (ValVT.getSimpleVT().SimpleTy) { 3658 default: 3659 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3660 case MVT::i1: 3661 case MVT::i32: 3662 RC = &PPC::GPRCRegClass; 3663 break; 3664 case MVT::f32: 3665 if (Subtarget.hasP8Vector()) 3666 RC = &PPC::VSSRCRegClass; 3667 else if (Subtarget.hasSPE()) 3668 RC = &PPC::GPRCRegClass; 3669 else 3670 RC = &PPC::F4RCRegClass; 3671 break; 3672 case MVT::f64: 3673 if (Subtarget.hasVSX()) 3674 RC = &PPC::VSFRCRegClass; 3675 else if (Subtarget.hasSPE()) 3676 // SPE passes doubles in GPR pairs. 3677 RC = &PPC::GPRCRegClass; 3678 else 3679 RC = &PPC::F8RCRegClass; 3680 break; 3681 case MVT::v16i8: 3682 case MVT::v8i16: 3683 case MVT::v4i32: 3684 RC = &PPC::VRRCRegClass; 3685 break; 3686 case MVT::v4f32: 3687 RC = &PPC::VRRCRegClass; 3688 break; 3689 case MVT::v2f64: 3690 case MVT::v2i64: 3691 RC = &PPC::VRRCRegClass; 3692 break; 3693 } 3694 3695 SDValue ArgValue; 3696 // Transform the arguments stored in physical registers into 3697 // virtual ones. 3698 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3699 assert(i + 1 < e && "No second half of double precision argument"); 3700 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3701 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3702 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3703 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3704 if (!Subtarget.isLittleEndian()) 3705 std::swap (ArgValueLo, ArgValueHi); 3706 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3707 ArgValueHi); 3708 } else { 3709 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3710 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3711 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3712 if (ValVT == MVT::i1) 3713 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3714 } 3715 3716 InVals.push_back(ArgValue); 3717 } else { 3718 // Argument stored in memory. 3719 assert(VA.isMemLoc()); 3720 3721 // Get the extended size of the argument type in stack 3722 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3723 // Get the actual size of the argument type 3724 unsigned ObjSize = VA.getValVT().getStoreSize(); 3725 unsigned ArgOffset = VA.getLocMemOffset(); 3726 // Stack objects in PPC32 are right justified. 3727 ArgOffset += ArgSize - ObjSize; 3728 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3729 3730 // Create load nodes to retrieve arguments from the stack. 3731 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3732 InVals.push_back( 3733 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3734 } 3735 } 3736 3737 // Assign locations to all of the incoming aggregate by value arguments. 3738 // Aggregates passed by value are stored in the local variable space of the 3739 // caller's stack frame, right above the parameter list area. 3740 SmallVector<CCValAssign, 16> ByValArgLocs; 3741 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3742 ByValArgLocs, *DAG.getContext()); 3743 3744 // Reserve stack space for the allocations in CCInfo. 3745 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3746 3747 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3748 3749 // Area that is at least reserved in the caller of this function. 3750 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3751 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3752 3753 // Set the size that is at least reserved in caller of this function. Tail 3754 // call optimized function's reserved stack space needs to be aligned so that 3755 // taking the difference between two stack areas will result in an aligned 3756 // stack. 3757 MinReservedArea = 3758 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3759 FuncInfo->setMinReservedArea(MinReservedArea); 3760 3761 SmallVector<SDValue, 8> MemOps; 3762 3763 // If the function takes variable number of arguments, make a frame index for 3764 // the start of the first vararg value... for expansion of llvm.va_start. 3765 if (isVarArg) { 3766 static const MCPhysReg GPArgRegs[] = { 3767 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3768 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3769 }; 3770 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3771 3772 static const MCPhysReg FPArgRegs[] = { 3773 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3774 PPC::F8 3775 }; 3776 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3777 3778 if (useSoftFloat() || hasSPE()) 3779 NumFPArgRegs = 0; 3780 3781 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3782 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3783 3784 // Make room for NumGPArgRegs and NumFPArgRegs. 3785 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3786 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3787 3788 FuncInfo->setVarArgsStackOffset( 3789 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3790 CCInfo.getNextStackOffset(), true)); 3791 3792 FuncInfo->setVarArgsFrameIndex( 3793 MFI.CreateStackObject(Depth, Align(8), false)); 3794 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3795 3796 // The fixed integer arguments of a variadic function are stored to the 3797 // VarArgsFrameIndex on the stack so that they may be loaded by 3798 // dereferencing the result of va_next. 3799 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3800 // Get an existing live-in vreg, or add a new one. 3801 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3802 if (!VReg) 3803 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3804 3805 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3806 SDValue Store = 3807 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3808 MemOps.push_back(Store); 3809 // Increment the address by four for the next argument to store 3810 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3811 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3812 } 3813 3814 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3815 // is set. 3816 // The double arguments are stored to the VarArgsFrameIndex 3817 // on the stack. 3818 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3819 // Get an existing live-in vreg, or add a new one. 3820 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3821 if (!VReg) 3822 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3823 3824 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3825 SDValue Store = 3826 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3827 MemOps.push_back(Store); 3828 // Increment the address by eight for the next argument to store 3829 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3830 PtrVT); 3831 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3832 } 3833 } 3834 3835 if (!MemOps.empty()) 3836 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3837 3838 return Chain; 3839 } 3840 3841 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3842 // value to MVT::i64 and then truncate to the correct register size. 3843 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3844 EVT ObjectVT, SelectionDAG &DAG, 3845 SDValue ArgVal, 3846 const SDLoc &dl) const { 3847 if (Flags.isSExt()) 3848 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3849 DAG.getValueType(ObjectVT)); 3850 else if (Flags.isZExt()) 3851 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3852 DAG.getValueType(ObjectVT)); 3853 3854 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3855 } 3856 3857 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3858 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3859 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3860 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3861 // TODO: add description of PPC stack frame format, or at least some docs. 3862 // 3863 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3864 bool isLittleEndian = Subtarget.isLittleEndian(); 3865 MachineFunction &MF = DAG.getMachineFunction(); 3866 MachineFrameInfo &MFI = MF.getFrameInfo(); 3867 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3868 3869 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3870 "fastcc not supported on varargs functions"); 3871 3872 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3873 // Potential tail calls could cause overwriting of argument stack slots. 3874 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3875 (CallConv == CallingConv::Fast)); 3876 unsigned PtrByteSize = 8; 3877 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3878 3879 static const MCPhysReg GPR[] = { 3880 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3881 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3882 }; 3883 static const MCPhysReg VR[] = { 3884 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3885 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3886 }; 3887 3888 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3889 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3890 const unsigned Num_VR_Regs = array_lengthof(VR); 3891 3892 // Do a first pass over the arguments to determine whether the ABI 3893 // guarantees that our caller has allocated the parameter save area 3894 // on its stack frame. In the ELFv1 ABI, this is always the case; 3895 // in the ELFv2 ABI, it is true if this is a vararg function or if 3896 // any parameter is located in a stack slot. 3897 3898 bool HasParameterArea = !isELFv2ABI || isVarArg; 3899 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3900 unsigned NumBytes = LinkageSize; 3901 unsigned AvailableFPRs = Num_FPR_Regs; 3902 unsigned AvailableVRs = Num_VR_Regs; 3903 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3904 if (Ins[i].Flags.isNest()) 3905 continue; 3906 3907 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3908 PtrByteSize, LinkageSize, ParamAreaSize, 3909 NumBytes, AvailableFPRs, AvailableVRs)) 3910 HasParameterArea = true; 3911 } 3912 3913 // Add DAG nodes to load the arguments or copy them out of registers. On 3914 // entry to a function on PPC, the arguments start after the linkage area, 3915 // although the first ones are often in registers. 3916 3917 unsigned ArgOffset = LinkageSize; 3918 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3919 SmallVector<SDValue, 8> MemOps; 3920 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3921 unsigned CurArgIdx = 0; 3922 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3923 SDValue ArgVal; 3924 bool needsLoad = false; 3925 EVT ObjectVT = Ins[ArgNo].VT; 3926 EVT OrigVT = Ins[ArgNo].ArgVT; 3927 unsigned ObjSize = ObjectVT.getStoreSize(); 3928 unsigned ArgSize = ObjSize; 3929 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3930 if (Ins[ArgNo].isOrigArg()) { 3931 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3932 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3933 } 3934 // We re-align the argument offset for each argument, except when using the 3935 // fast calling convention, when we need to make sure we do that only when 3936 // we'll actually use a stack slot. 3937 unsigned CurArgOffset; 3938 Align Alignment; 3939 auto ComputeArgOffset = [&]() { 3940 /* Respect alignment of argument on the stack. */ 3941 Alignment = 3942 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3943 ArgOffset = alignTo(ArgOffset, Alignment); 3944 CurArgOffset = ArgOffset; 3945 }; 3946 3947 if (CallConv != CallingConv::Fast) { 3948 ComputeArgOffset(); 3949 3950 /* Compute GPR index associated with argument offset. */ 3951 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3952 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3953 } 3954 3955 // FIXME the codegen can be much improved in some cases. 3956 // We do not have to keep everything in memory. 3957 if (Flags.isByVal()) { 3958 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3959 3960 if (CallConv == CallingConv::Fast) 3961 ComputeArgOffset(); 3962 3963 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3964 ObjSize = Flags.getByValSize(); 3965 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3966 // Empty aggregate parameters do not take up registers. Examples: 3967 // struct { } a; 3968 // union { } b; 3969 // int c[0]; 3970 // etc. However, we have to provide a place-holder in InVals, so 3971 // pretend we have an 8-byte item at the current address for that 3972 // purpose. 3973 if (!ObjSize) { 3974 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3975 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3976 InVals.push_back(FIN); 3977 continue; 3978 } 3979 3980 // Create a stack object covering all stack doublewords occupied 3981 // by the argument. If the argument is (fully or partially) on 3982 // the stack, or if the argument is fully in registers but the 3983 // caller has allocated the parameter save anyway, we can refer 3984 // directly to the caller's stack frame. Otherwise, create a 3985 // local copy in our own frame. 3986 int FI; 3987 if (HasParameterArea || 3988 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3989 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3990 else 3991 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3992 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3993 3994 // Handle aggregates smaller than 8 bytes. 3995 if (ObjSize < PtrByteSize) { 3996 // The value of the object is its address, which differs from the 3997 // address of the enclosing doubleword on big-endian systems. 3998 SDValue Arg = FIN; 3999 if (!isLittleEndian) { 4000 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4001 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4002 } 4003 InVals.push_back(Arg); 4004 4005 if (GPR_idx != Num_GPR_Regs) { 4006 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4007 FuncInfo->addLiveInAttr(VReg, Flags); 4008 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4009 SDValue Store; 4010 4011 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4012 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4013 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4014 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4015 MachinePointerInfo(&*FuncArg), ObjType); 4016 } else { 4017 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4018 // store the whole register as-is to the parameter save area 4019 // slot. 4020 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4021 MachinePointerInfo(&*FuncArg)); 4022 } 4023 4024 MemOps.push_back(Store); 4025 } 4026 // Whether we copied from a register or not, advance the offset 4027 // into the parameter save area by a full doubleword. 4028 ArgOffset += PtrByteSize; 4029 continue; 4030 } 4031 4032 // The value of the object is its address, which is the address of 4033 // its first stack doubleword. 4034 InVals.push_back(FIN); 4035 4036 // Store whatever pieces of the object are in registers to memory. 4037 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4038 if (GPR_idx == Num_GPR_Regs) 4039 break; 4040 4041 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4042 FuncInfo->addLiveInAttr(VReg, Flags); 4043 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4044 SDValue Addr = FIN; 4045 if (j) { 4046 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4047 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4048 } 4049 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4050 MachinePointerInfo(&*FuncArg, j)); 4051 MemOps.push_back(Store); 4052 ++GPR_idx; 4053 } 4054 ArgOffset += ArgSize; 4055 continue; 4056 } 4057 4058 switch (ObjectVT.getSimpleVT().SimpleTy) { 4059 default: llvm_unreachable("Unhandled argument type!"); 4060 case MVT::i1: 4061 case MVT::i32: 4062 case MVT::i64: 4063 if (Flags.isNest()) { 4064 // The 'nest' parameter, if any, is passed in R11. 4065 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4066 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4067 4068 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4069 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4070 4071 break; 4072 } 4073 4074 // These can be scalar arguments or elements of an integer array type 4075 // passed directly. Clang may use those instead of "byval" aggregate 4076 // types to avoid forcing arguments to memory unnecessarily. 4077 if (GPR_idx != Num_GPR_Regs) { 4078 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4079 FuncInfo->addLiveInAttr(VReg, Flags); 4080 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4081 4082 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4083 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4084 // value to MVT::i64 and then truncate to the correct register size. 4085 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4086 } else { 4087 if (CallConv == CallingConv::Fast) 4088 ComputeArgOffset(); 4089 4090 needsLoad = true; 4091 ArgSize = PtrByteSize; 4092 } 4093 if (CallConv != CallingConv::Fast || needsLoad) 4094 ArgOffset += 8; 4095 break; 4096 4097 case MVT::f32: 4098 case MVT::f64: 4099 // These can be scalar arguments or elements of a float array type 4100 // passed directly. The latter are used to implement ELFv2 homogenous 4101 // float aggregates. 4102 if (FPR_idx != Num_FPR_Regs) { 4103 unsigned VReg; 4104 4105 if (ObjectVT == MVT::f32) 4106 VReg = MF.addLiveIn(FPR[FPR_idx], 4107 Subtarget.hasP8Vector() 4108 ? &PPC::VSSRCRegClass 4109 : &PPC::F4RCRegClass); 4110 else 4111 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4112 ? &PPC::VSFRCRegClass 4113 : &PPC::F8RCRegClass); 4114 4115 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4116 ++FPR_idx; 4117 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4118 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4119 // once we support fp <-> gpr moves. 4120 4121 // This can only ever happen in the presence of f32 array types, 4122 // since otherwise we never run out of FPRs before running out 4123 // of GPRs. 4124 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4125 FuncInfo->addLiveInAttr(VReg, Flags); 4126 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4127 4128 if (ObjectVT == MVT::f32) { 4129 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4130 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4131 DAG.getConstant(32, dl, MVT::i32)); 4132 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4133 } 4134 4135 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4136 } else { 4137 if (CallConv == CallingConv::Fast) 4138 ComputeArgOffset(); 4139 4140 needsLoad = true; 4141 } 4142 4143 // When passing an array of floats, the array occupies consecutive 4144 // space in the argument area; only round up to the next doubleword 4145 // at the end of the array. Otherwise, each float takes 8 bytes. 4146 if (CallConv != CallingConv::Fast || needsLoad) { 4147 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4148 ArgOffset += ArgSize; 4149 if (Flags.isInConsecutiveRegsLast()) 4150 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4151 } 4152 break; 4153 case MVT::v4f32: 4154 case MVT::v4i32: 4155 case MVT::v8i16: 4156 case MVT::v16i8: 4157 case MVT::v2f64: 4158 case MVT::v2i64: 4159 case MVT::v1i128: 4160 case MVT::f128: 4161 // These can be scalar arguments or elements of a vector array type 4162 // passed directly. The latter are used to implement ELFv2 homogenous 4163 // vector aggregates. 4164 if (VR_idx != Num_VR_Regs) { 4165 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4166 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4167 ++VR_idx; 4168 } else { 4169 if (CallConv == CallingConv::Fast) 4170 ComputeArgOffset(); 4171 needsLoad = true; 4172 } 4173 if (CallConv != CallingConv::Fast || needsLoad) 4174 ArgOffset += 16; 4175 break; 4176 } 4177 4178 // We need to load the argument to a virtual register if we determined 4179 // above that we ran out of physical registers of the appropriate type. 4180 if (needsLoad) { 4181 if (ObjSize < ArgSize && !isLittleEndian) 4182 CurArgOffset += ArgSize - ObjSize; 4183 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4184 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4185 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4186 } 4187 4188 InVals.push_back(ArgVal); 4189 } 4190 4191 // Area that is at least reserved in the caller of this function. 4192 unsigned MinReservedArea; 4193 if (HasParameterArea) 4194 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4195 else 4196 MinReservedArea = LinkageSize; 4197 4198 // Set the size that is at least reserved in caller of this function. Tail 4199 // call optimized functions' reserved stack space needs to be aligned so that 4200 // taking the difference between two stack areas will result in an aligned 4201 // stack. 4202 MinReservedArea = 4203 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4204 FuncInfo->setMinReservedArea(MinReservedArea); 4205 4206 // If the function takes variable number of arguments, make a frame index for 4207 // the start of the first vararg value... for expansion of llvm.va_start. 4208 // On ELFv2ABI spec, it writes: 4209 // C programs that are intended to be *portable* across different compilers 4210 // and architectures must use the header file <stdarg.h> to deal with variable 4211 // argument lists. 4212 if (isVarArg && MFI.hasVAStart()) { 4213 int Depth = ArgOffset; 4214 4215 FuncInfo->setVarArgsFrameIndex( 4216 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4217 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4218 4219 // If this function is vararg, store any remaining integer argument regs 4220 // to their spots on the stack so that they may be loaded by dereferencing 4221 // the result of va_next. 4222 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4223 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4224 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4225 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4226 SDValue Store = 4227 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4228 MemOps.push_back(Store); 4229 // Increment the address by four for the next argument to store 4230 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4231 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4232 } 4233 } 4234 4235 if (!MemOps.empty()) 4236 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4237 4238 return Chain; 4239 } 4240 4241 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4242 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4245 // TODO: add description of PPC stack frame format, or at least some docs. 4246 // 4247 MachineFunction &MF = DAG.getMachineFunction(); 4248 MachineFrameInfo &MFI = MF.getFrameInfo(); 4249 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4250 4251 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4252 bool isPPC64 = PtrVT == MVT::i64; 4253 // Potential tail calls could cause overwriting of argument stack slots. 4254 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4255 (CallConv == CallingConv::Fast)); 4256 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4257 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4258 unsigned ArgOffset = LinkageSize; 4259 // Area that is at least reserved in caller of this function. 4260 unsigned MinReservedArea = ArgOffset; 4261 4262 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4263 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4264 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4265 }; 4266 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4267 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4268 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4269 }; 4270 static const MCPhysReg VR[] = { 4271 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4272 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4273 }; 4274 4275 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4276 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4277 const unsigned Num_VR_Regs = array_lengthof( VR); 4278 4279 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4280 4281 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4282 4283 // In 32-bit non-varargs functions, the stack space for vectors is after the 4284 // stack space for non-vectors. We do not use this space unless we have 4285 // too many vectors to fit in registers, something that only occurs in 4286 // constructed examples:), but we have to walk the arglist to figure 4287 // that out...for the pathological case, compute VecArgOffset as the 4288 // start of the vector parameter area. Computing VecArgOffset is the 4289 // entire point of the following loop. 4290 unsigned VecArgOffset = ArgOffset; 4291 if (!isVarArg && !isPPC64) { 4292 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4293 ++ArgNo) { 4294 EVT ObjectVT = Ins[ArgNo].VT; 4295 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4296 4297 if (Flags.isByVal()) { 4298 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4299 unsigned ObjSize = Flags.getByValSize(); 4300 unsigned ArgSize = 4301 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4302 VecArgOffset += ArgSize; 4303 continue; 4304 } 4305 4306 switch(ObjectVT.getSimpleVT().SimpleTy) { 4307 default: llvm_unreachable("Unhandled argument type!"); 4308 case MVT::i1: 4309 case MVT::i32: 4310 case MVT::f32: 4311 VecArgOffset += 4; 4312 break; 4313 case MVT::i64: // PPC64 4314 case MVT::f64: 4315 // FIXME: We are guaranteed to be !isPPC64 at this point. 4316 // Does MVT::i64 apply? 4317 VecArgOffset += 8; 4318 break; 4319 case MVT::v4f32: 4320 case MVT::v4i32: 4321 case MVT::v8i16: 4322 case MVT::v16i8: 4323 // Nothing to do, we're only looking at Nonvector args here. 4324 break; 4325 } 4326 } 4327 } 4328 // We've found where the vector parameter area in memory is. Skip the 4329 // first 12 parameters; these don't use that memory. 4330 VecArgOffset = ((VecArgOffset+15)/16)*16; 4331 VecArgOffset += 12*16; 4332 4333 // Add DAG nodes to load the arguments or copy them out of registers. On 4334 // entry to a function on PPC, the arguments start after the linkage area, 4335 // although the first ones are often in registers. 4336 4337 SmallVector<SDValue, 8> MemOps; 4338 unsigned nAltivecParamsAtEnd = 0; 4339 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4340 unsigned CurArgIdx = 0; 4341 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4342 SDValue ArgVal; 4343 bool needsLoad = false; 4344 EVT ObjectVT = Ins[ArgNo].VT; 4345 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4346 unsigned ArgSize = ObjSize; 4347 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4348 if (Ins[ArgNo].isOrigArg()) { 4349 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4350 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4351 } 4352 unsigned CurArgOffset = ArgOffset; 4353 4354 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4355 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4356 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4357 if (isVarArg || isPPC64) { 4358 MinReservedArea = ((MinReservedArea+15)/16)*16; 4359 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4360 Flags, 4361 PtrByteSize); 4362 } else nAltivecParamsAtEnd++; 4363 } else 4364 // Calculate min reserved area. 4365 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4366 Flags, 4367 PtrByteSize); 4368 4369 // FIXME the codegen can be much improved in some cases. 4370 // We do not have to keep everything in memory. 4371 if (Flags.isByVal()) { 4372 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4373 4374 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4375 ObjSize = Flags.getByValSize(); 4376 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4377 // Objects of size 1 and 2 are right justified, everything else is 4378 // left justified. This means the memory address is adjusted forwards. 4379 if (ObjSize==1 || ObjSize==2) { 4380 CurArgOffset = CurArgOffset + (4 - ObjSize); 4381 } 4382 // The value of the object is its address. 4383 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4384 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4385 InVals.push_back(FIN); 4386 if (ObjSize==1 || ObjSize==2) { 4387 if (GPR_idx != Num_GPR_Regs) { 4388 unsigned VReg; 4389 if (isPPC64) 4390 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4391 else 4392 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4393 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4394 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4395 SDValue Store = 4396 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4397 MachinePointerInfo(&*FuncArg), ObjType); 4398 MemOps.push_back(Store); 4399 ++GPR_idx; 4400 } 4401 4402 ArgOffset += PtrByteSize; 4403 4404 continue; 4405 } 4406 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4407 // Store whatever pieces of the object are in registers 4408 // to memory. ArgOffset will be the address of the beginning 4409 // of the object. 4410 if (GPR_idx != Num_GPR_Regs) { 4411 unsigned VReg; 4412 if (isPPC64) 4413 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4414 else 4415 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4416 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4417 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4418 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4419 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4420 MachinePointerInfo(&*FuncArg, j)); 4421 MemOps.push_back(Store); 4422 ++GPR_idx; 4423 ArgOffset += PtrByteSize; 4424 } else { 4425 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4426 break; 4427 } 4428 } 4429 continue; 4430 } 4431 4432 switch (ObjectVT.getSimpleVT().SimpleTy) { 4433 default: llvm_unreachable("Unhandled argument type!"); 4434 case MVT::i1: 4435 case MVT::i32: 4436 if (!isPPC64) { 4437 if (GPR_idx != Num_GPR_Regs) { 4438 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4439 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4440 4441 if (ObjectVT == MVT::i1) 4442 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4443 4444 ++GPR_idx; 4445 } else { 4446 needsLoad = true; 4447 ArgSize = PtrByteSize; 4448 } 4449 // All int arguments reserve stack space in the Darwin ABI. 4450 ArgOffset += PtrByteSize; 4451 break; 4452 } 4453 LLVM_FALLTHROUGH; 4454 case MVT::i64: // PPC64 4455 if (GPR_idx != Num_GPR_Regs) { 4456 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4457 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4458 4459 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4460 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4461 // value to MVT::i64 and then truncate to the correct register size. 4462 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4463 4464 ++GPR_idx; 4465 } else { 4466 needsLoad = true; 4467 ArgSize = PtrByteSize; 4468 } 4469 // All int arguments reserve stack space in the Darwin ABI. 4470 ArgOffset += 8; 4471 break; 4472 4473 case MVT::f32: 4474 case MVT::f64: 4475 // Every 4 bytes of argument space consumes one of the GPRs available for 4476 // argument passing. 4477 if (GPR_idx != Num_GPR_Regs) { 4478 ++GPR_idx; 4479 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4480 ++GPR_idx; 4481 } 4482 if (FPR_idx != Num_FPR_Regs) { 4483 unsigned VReg; 4484 4485 if (ObjectVT == MVT::f32) 4486 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4487 else 4488 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4489 4490 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4491 ++FPR_idx; 4492 } else { 4493 needsLoad = true; 4494 } 4495 4496 // All FP arguments reserve stack space in the Darwin ABI. 4497 ArgOffset += isPPC64 ? 8 : ObjSize; 4498 break; 4499 case MVT::v4f32: 4500 case MVT::v4i32: 4501 case MVT::v8i16: 4502 case MVT::v16i8: 4503 // Note that vector arguments in registers don't reserve stack space, 4504 // except in varargs functions. 4505 if (VR_idx != Num_VR_Regs) { 4506 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4507 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4508 if (isVarArg) { 4509 while ((ArgOffset % 16) != 0) { 4510 ArgOffset += PtrByteSize; 4511 if (GPR_idx != Num_GPR_Regs) 4512 GPR_idx++; 4513 } 4514 ArgOffset += 16; 4515 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4516 } 4517 ++VR_idx; 4518 } else { 4519 if (!isVarArg && !isPPC64) { 4520 // Vectors go after all the nonvectors. 4521 CurArgOffset = VecArgOffset; 4522 VecArgOffset += 16; 4523 } else { 4524 // Vectors are aligned. 4525 ArgOffset = ((ArgOffset+15)/16)*16; 4526 CurArgOffset = ArgOffset; 4527 ArgOffset += 16; 4528 } 4529 needsLoad = true; 4530 } 4531 break; 4532 } 4533 4534 // We need to load the argument to a virtual register if we determined above 4535 // that we ran out of physical registers of the appropriate type. 4536 if (needsLoad) { 4537 int FI = MFI.CreateFixedObject(ObjSize, 4538 CurArgOffset + (ArgSize - ObjSize), 4539 isImmutable); 4540 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4541 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4542 } 4543 4544 InVals.push_back(ArgVal); 4545 } 4546 4547 // Allow for Altivec parameters at the end, if needed. 4548 if (nAltivecParamsAtEnd) { 4549 MinReservedArea = ((MinReservedArea+15)/16)*16; 4550 MinReservedArea += 16*nAltivecParamsAtEnd; 4551 } 4552 4553 // Area that is at least reserved in the caller of this function. 4554 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4555 4556 // Set the size that is at least reserved in caller of this function. Tail 4557 // call optimized functions' reserved stack space needs to be aligned so that 4558 // taking the difference between two stack areas will result in an aligned 4559 // stack. 4560 MinReservedArea = 4561 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4562 FuncInfo->setMinReservedArea(MinReservedArea); 4563 4564 // If the function takes variable number of arguments, make a frame index for 4565 // the start of the first vararg value... for expansion of llvm.va_start. 4566 if (isVarArg) { 4567 int Depth = ArgOffset; 4568 4569 FuncInfo->setVarArgsFrameIndex( 4570 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4571 Depth, true)); 4572 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4573 4574 // If this function is vararg, store any remaining integer argument regs 4575 // to their spots on the stack so that they may be loaded by dereferencing 4576 // the result of va_next. 4577 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4578 unsigned VReg; 4579 4580 if (isPPC64) 4581 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4582 else 4583 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4584 4585 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4586 SDValue Store = 4587 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4588 MemOps.push_back(Store); 4589 // Increment the address by four for the next argument to store 4590 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4591 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4592 } 4593 } 4594 4595 if (!MemOps.empty()) 4596 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4597 4598 return Chain; 4599 } 4600 4601 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4602 /// adjusted to accommodate the arguments for the tailcall. 4603 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4604 unsigned ParamSize) { 4605 4606 if (!isTailCall) return 0; 4607 4608 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4609 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4610 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4611 // Remember only if the new adjustment is bigger. 4612 if (SPDiff < FI->getTailCallSPDelta()) 4613 FI->setTailCallSPDelta(SPDiff); 4614 4615 return SPDiff; 4616 } 4617 4618 static bool isFunctionGlobalAddress(SDValue Callee); 4619 4620 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4621 const TargetMachine &TM) { 4622 // It does not make sense to call callsShareTOCBase() with a caller that 4623 // is PC Relative since PC Relative callers do not have a TOC. 4624 #ifndef NDEBUG 4625 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4626 assert(!STICaller->isUsingPCRelativeCalls() && 4627 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4628 #endif 4629 4630 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4631 // don't have enough information to determine if the caller and callee share 4632 // the same TOC base, so we have to pessimistically assume they don't for 4633 // correctness. 4634 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4635 if (!G) 4636 return false; 4637 4638 const GlobalValue *GV = G->getGlobal(); 4639 4640 // If the callee is preemptable, then the static linker will use a plt-stub 4641 // which saves the toc to the stack, and needs a nop after the call 4642 // instruction to convert to a toc-restore. 4643 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4644 return false; 4645 4646 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4647 // We may need a TOC restore in the situation where the caller requires a 4648 // valid TOC but the callee is PC Relative and does not. 4649 const Function *F = dyn_cast<Function>(GV); 4650 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4651 4652 // If we have an Alias we can try to get the function from there. 4653 if (Alias) { 4654 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4655 F = dyn_cast<Function>(GlobalObj); 4656 } 4657 4658 // If we still have no valid function pointer we do not have enough 4659 // information to determine if the callee uses PC Relative calls so we must 4660 // assume that it does. 4661 if (!F) 4662 return false; 4663 4664 // If the callee uses PC Relative we cannot guarantee that the callee won't 4665 // clobber the TOC of the caller and so we must assume that the two 4666 // functions do not share a TOC base. 4667 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4668 if (STICallee->isUsingPCRelativeCalls()) 4669 return false; 4670 4671 // The medium and large code models are expected to provide a sufficiently 4672 // large TOC to provide all data addressing needs of a module with a 4673 // single TOC. 4674 if (CodeModel::Medium == TM.getCodeModel() || 4675 CodeModel::Large == TM.getCodeModel()) 4676 return true; 4677 4678 // Otherwise we need to ensure callee and caller are in the same section, 4679 // since the linker may allocate multiple TOCs, and we don't know which 4680 // sections will belong to the same TOC base. 4681 if (!GV->isStrongDefinitionForLinker()) 4682 return false; 4683 4684 // Any explicitly-specified sections and section prefixes must also match. 4685 // Also, if we're using -ffunction-sections, then each function is always in 4686 // a different section (the same is true for COMDAT functions). 4687 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4688 GV->getSection() != Caller->getSection()) 4689 return false; 4690 if (const auto *F = dyn_cast<Function>(GV)) { 4691 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4692 return false; 4693 } 4694 4695 return true; 4696 } 4697 4698 static bool 4699 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4700 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4701 assert(Subtarget.is64BitELFABI()); 4702 4703 const unsigned PtrByteSize = 8; 4704 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4705 4706 static const MCPhysReg GPR[] = { 4707 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4708 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4709 }; 4710 static const MCPhysReg VR[] = { 4711 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4712 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4713 }; 4714 4715 const unsigned NumGPRs = array_lengthof(GPR); 4716 const unsigned NumFPRs = 13; 4717 const unsigned NumVRs = array_lengthof(VR); 4718 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4719 4720 unsigned NumBytes = LinkageSize; 4721 unsigned AvailableFPRs = NumFPRs; 4722 unsigned AvailableVRs = NumVRs; 4723 4724 for (const ISD::OutputArg& Param : Outs) { 4725 if (Param.Flags.isNest()) continue; 4726 4727 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4728 LinkageSize, ParamAreaSize, NumBytes, 4729 AvailableFPRs, AvailableVRs)) 4730 return true; 4731 } 4732 return false; 4733 } 4734 4735 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4736 if (CB.arg_size() != CallerFn->arg_size()) 4737 return false; 4738 4739 auto CalleeArgIter = CB.arg_begin(); 4740 auto CalleeArgEnd = CB.arg_end(); 4741 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4742 4743 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4744 const Value* CalleeArg = *CalleeArgIter; 4745 const Value* CallerArg = &(*CallerArgIter); 4746 if (CalleeArg == CallerArg) 4747 continue; 4748 4749 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4750 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4751 // } 4752 // 1st argument of callee is undef and has the same type as caller. 4753 if (CalleeArg->getType() == CallerArg->getType() && 4754 isa<UndefValue>(CalleeArg)) 4755 continue; 4756 4757 return false; 4758 } 4759 4760 return true; 4761 } 4762 4763 // Returns true if TCO is possible between the callers and callees 4764 // calling conventions. 4765 static bool 4766 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4767 CallingConv::ID CalleeCC) { 4768 // Tail calls are possible with fastcc and ccc. 4769 auto isTailCallableCC = [] (CallingConv::ID CC){ 4770 return CC == CallingConv::C || CC == CallingConv::Fast; 4771 }; 4772 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4773 return false; 4774 4775 // We can safely tail call both fastcc and ccc callees from a c calling 4776 // convention caller. If the caller is fastcc, we may have less stack space 4777 // than a non-fastcc caller with the same signature so disable tail-calls in 4778 // that case. 4779 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4780 } 4781 4782 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4783 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4784 const SmallVectorImpl<ISD::OutputArg> &Outs, 4785 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4786 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4787 4788 if (DisableSCO && !TailCallOpt) return false; 4789 4790 // Variadic argument functions are not supported. 4791 if (isVarArg) return false; 4792 4793 auto &Caller = DAG.getMachineFunction().getFunction(); 4794 // Check that the calling conventions are compatible for tco. 4795 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4796 return false; 4797 4798 // Caller contains any byval parameter is not supported. 4799 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4800 return false; 4801 4802 // Callee contains any byval parameter is not supported, too. 4803 // Note: This is a quick work around, because in some cases, e.g. 4804 // caller's stack size > callee's stack size, we are still able to apply 4805 // sibling call optimization. For example, gcc is able to do SCO for caller1 4806 // in the following example, but not for caller2. 4807 // struct test { 4808 // long int a; 4809 // char ary[56]; 4810 // } gTest; 4811 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4812 // b->a = v.a; 4813 // return 0; 4814 // } 4815 // void caller1(struct test a, struct test c, struct test *b) { 4816 // callee(gTest, b); } 4817 // void caller2(struct test *b) { callee(gTest, b); } 4818 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4819 return false; 4820 4821 // If callee and caller use different calling conventions, we cannot pass 4822 // parameters on stack since offsets for the parameter area may be different. 4823 if (Caller.getCallingConv() != CalleeCC && 4824 needStackSlotPassParameters(Subtarget, Outs)) 4825 return false; 4826 4827 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4828 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4829 // callee potentially have different TOC bases then we cannot tail call since 4830 // we need to restore the TOC pointer after the call. 4831 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4832 // We cannot guarantee this for indirect calls or calls to external functions. 4833 // When PC-Relative addressing is used, the concept of the TOC is no longer 4834 // applicable so this check is not required. 4835 // Check first for indirect calls. 4836 if (!Subtarget.isUsingPCRelativeCalls() && 4837 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4838 return false; 4839 4840 // Check if we share the TOC base. 4841 if (!Subtarget.isUsingPCRelativeCalls() && 4842 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4843 return false; 4844 4845 // TCO allows altering callee ABI, so we don't have to check further. 4846 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4847 return true; 4848 4849 if (DisableSCO) return false; 4850 4851 // If callee use the same argument list that caller is using, then we can 4852 // apply SCO on this case. If it is not, then we need to check if callee needs 4853 // stack for passing arguments. 4854 // PC Relative tail calls may not have a CallBase. 4855 // If there is no CallBase we cannot verify if we have the same argument 4856 // list so assume that we don't have the same argument list. 4857 if (CB && !hasSameArgumentList(&Caller, *CB) && 4858 needStackSlotPassParameters(Subtarget, Outs)) 4859 return false; 4860 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4861 return false; 4862 4863 return true; 4864 } 4865 4866 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4867 /// for tail call optimization. Targets which want to do tail call 4868 /// optimization should implement this function. 4869 bool 4870 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4871 CallingConv::ID CalleeCC, 4872 bool isVarArg, 4873 const SmallVectorImpl<ISD::InputArg> &Ins, 4874 SelectionDAG& DAG) const { 4875 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4876 return false; 4877 4878 // Variable argument functions are not supported. 4879 if (isVarArg) 4880 return false; 4881 4882 MachineFunction &MF = DAG.getMachineFunction(); 4883 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4884 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4885 // Functions containing by val parameters are not supported. 4886 for (unsigned i = 0; i != Ins.size(); i++) { 4887 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4888 if (Flags.isByVal()) return false; 4889 } 4890 4891 // Non-PIC/GOT tail calls are supported. 4892 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4893 return true; 4894 4895 // At the moment we can only do local tail calls (in same module, hidden 4896 // or protected) if we are generating PIC. 4897 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4898 return G->getGlobal()->hasHiddenVisibility() 4899 || G->getGlobal()->hasProtectedVisibility(); 4900 } 4901 4902 return false; 4903 } 4904 4905 /// isCallCompatibleAddress - Return the immediate to use if the specified 4906 /// 32-bit value is representable in the immediate field of a BxA instruction. 4907 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4908 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4909 if (!C) return nullptr; 4910 4911 int Addr = C->getZExtValue(); 4912 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4913 SignExtend32<26>(Addr) != Addr) 4914 return nullptr; // Top 6 bits have to be sext of immediate. 4915 4916 return DAG 4917 .getConstant( 4918 (int)C->getZExtValue() >> 2, SDLoc(Op), 4919 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4920 .getNode(); 4921 } 4922 4923 namespace { 4924 4925 struct TailCallArgumentInfo { 4926 SDValue Arg; 4927 SDValue FrameIdxOp; 4928 int FrameIdx = 0; 4929 4930 TailCallArgumentInfo() = default; 4931 }; 4932 4933 } // end anonymous namespace 4934 4935 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4936 static void StoreTailCallArgumentsToStackSlot( 4937 SelectionDAG &DAG, SDValue Chain, 4938 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4939 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4940 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4941 SDValue Arg = TailCallArgs[i].Arg; 4942 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4943 int FI = TailCallArgs[i].FrameIdx; 4944 // Store relative to framepointer. 4945 MemOpChains.push_back(DAG.getStore( 4946 Chain, dl, Arg, FIN, 4947 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4948 } 4949 } 4950 4951 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4952 /// the appropriate stack slot for the tail call optimized function call. 4953 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4954 SDValue OldRetAddr, SDValue OldFP, 4955 int SPDiff, const SDLoc &dl) { 4956 if (SPDiff) { 4957 // Calculate the new stack slot for the return address. 4958 MachineFunction &MF = DAG.getMachineFunction(); 4959 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4960 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4961 bool isPPC64 = Subtarget.isPPC64(); 4962 int SlotSize = isPPC64 ? 8 : 4; 4963 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4964 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4965 NewRetAddrLoc, true); 4966 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4967 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4968 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4969 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4970 } 4971 return Chain; 4972 } 4973 4974 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4975 /// the position of the argument. 4976 static void 4977 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4978 SDValue Arg, int SPDiff, unsigned ArgOffset, 4979 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4980 int Offset = ArgOffset + SPDiff; 4981 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4982 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4983 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4984 SDValue FIN = DAG.getFrameIndex(FI, VT); 4985 TailCallArgumentInfo Info; 4986 Info.Arg = Arg; 4987 Info.FrameIdxOp = FIN; 4988 Info.FrameIdx = FI; 4989 TailCallArguments.push_back(Info); 4990 } 4991 4992 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4993 /// stack slot. Returns the chain as result and the loaded frame pointers in 4994 /// LROpOut/FPOpout. Used when tail calling. 4995 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4996 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4997 SDValue &FPOpOut, const SDLoc &dl) const { 4998 if (SPDiff) { 4999 // Load the LR and FP stack slot for later adjusting. 5000 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5001 LROpOut = getReturnAddrFrameIndex(DAG); 5002 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5003 Chain = SDValue(LROpOut.getNode(), 1); 5004 } 5005 return Chain; 5006 } 5007 5008 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5009 /// by "Src" to address "Dst" of size "Size". Alignment information is 5010 /// specified by the specific parameter attribute. The copy will be passed as 5011 /// a byval function parameter. 5012 /// Sometimes what we are copying is the end of a larger object, the part that 5013 /// does not fit in registers. 5014 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5015 SDValue Chain, ISD::ArgFlagsTy Flags, 5016 SelectionDAG &DAG, const SDLoc &dl) { 5017 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5018 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5019 Flags.getNonZeroByValAlign(), false, false, false, 5020 MachinePointerInfo(), MachinePointerInfo()); 5021 } 5022 5023 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5024 /// tail calls. 5025 static void LowerMemOpCallTo( 5026 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5027 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5028 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5029 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5030 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5031 if (!isTailCall) { 5032 if (isVector) { 5033 SDValue StackPtr; 5034 if (isPPC64) 5035 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5036 else 5037 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5038 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5039 DAG.getConstant(ArgOffset, dl, PtrVT)); 5040 } 5041 MemOpChains.push_back( 5042 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5043 // Calculate and remember argument location. 5044 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5045 TailCallArguments); 5046 } 5047 5048 static void 5049 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5050 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5051 SDValue FPOp, 5052 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5053 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5054 // might overwrite each other in case of tail call optimization. 5055 SmallVector<SDValue, 8> MemOpChains2; 5056 // Do not flag preceding copytoreg stuff together with the following stuff. 5057 InFlag = SDValue(); 5058 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5059 MemOpChains2, dl); 5060 if (!MemOpChains2.empty()) 5061 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5062 5063 // Store the return address to the appropriate stack slot. 5064 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5065 5066 // Emit callseq_end just before tailcall node. 5067 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5068 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5069 InFlag = Chain.getValue(1); 5070 } 5071 5072 // Is this global address that of a function that can be called by name? (as 5073 // opposed to something that must hold a descriptor for an indirect call). 5074 static bool isFunctionGlobalAddress(SDValue Callee) { 5075 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5076 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5077 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5078 return false; 5079 5080 return G->getGlobal()->getValueType()->isFunctionTy(); 5081 } 5082 5083 return false; 5084 } 5085 5086 SDValue PPCTargetLowering::LowerCallResult( 5087 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5088 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5089 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5090 SmallVector<CCValAssign, 16> RVLocs; 5091 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5092 *DAG.getContext()); 5093 5094 CCRetInfo.AnalyzeCallResult( 5095 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5096 ? RetCC_PPC_Cold 5097 : RetCC_PPC); 5098 5099 // Copy all of the result registers out of their specified physreg. 5100 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5101 CCValAssign &VA = RVLocs[i]; 5102 assert(VA.isRegLoc() && "Can only return in registers!"); 5103 5104 SDValue Val; 5105 5106 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5107 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5108 InFlag); 5109 Chain = Lo.getValue(1); 5110 InFlag = Lo.getValue(2); 5111 VA = RVLocs[++i]; // skip ahead to next loc 5112 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5113 InFlag); 5114 Chain = Hi.getValue(1); 5115 InFlag = Hi.getValue(2); 5116 if (!Subtarget.isLittleEndian()) 5117 std::swap (Lo, Hi); 5118 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5119 } else { 5120 Val = DAG.getCopyFromReg(Chain, dl, 5121 VA.getLocReg(), VA.getLocVT(), InFlag); 5122 Chain = Val.getValue(1); 5123 InFlag = Val.getValue(2); 5124 } 5125 5126 switch (VA.getLocInfo()) { 5127 default: llvm_unreachable("Unknown loc info!"); 5128 case CCValAssign::Full: break; 5129 case CCValAssign::AExt: 5130 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5131 break; 5132 case CCValAssign::ZExt: 5133 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5134 DAG.getValueType(VA.getValVT())); 5135 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5136 break; 5137 case CCValAssign::SExt: 5138 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5139 DAG.getValueType(VA.getValVT())); 5140 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5141 break; 5142 } 5143 5144 InVals.push_back(Val); 5145 } 5146 5147 return Chain; 5148 } 5149 5150 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5151 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5152 // PatchPoint calls are not indirect. 5153 if (isPatchPoint) 5154 return false; 5155 5156 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5157 return false; 5158 5159 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5160 // becuase the immediate function pointer points to a descriptor instead of 5161 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5162 // pointer immediate points to the global entry point, while the BLA would 5163 // need to jump to the local entry point (see rL211174). 5164 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5165 isBLACompatibleAddress(Callee, DAG)) 5166 return false; 5167 5168 return true; 5169 } 5170 5171 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5172 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5173 return Subtarget.isAIXABI() || 5174 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5175 } 5176 5177 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5178 const Function &Caller, 5179 const SDValue &Callee, 5180 const PPCSubtarget &Subtarget, 5181 const TargetMachine &TM) { 5182 if (CFlags.IsTailCall) 5183 return PPCISD::TC_RETURN; 5184 5185 // This is a call through a function pointer. 5186 if (CFlags.IsIndirect) { 5187 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5188 // indirect calls. The save of the caller's TOC pointer to the stack will be 5189 // inserted into the DAG as part of call lowering. The restore of the TOC 5190 // pointer is modeled by using a pseudo instruction for the call opcode that 5191 // represents the 2 instruction sequence of an indirect branch and link, 5192 // immediately followed by a load of the TOC pointer from the the stack save 5193 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5194 // as it is not saved or used. 5195 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5196 : PPCISD::BCTRL; 5197 } 5198 5199 if (Subtarget.isUsingPCRelativeCalls()) { 5200 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5201 return PPCISD::CALL_NOTOC; 5202 } 5203 5204 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5205 // immediately following the call instruction if the caller and callee may 5206 // have different TOC bases. At link time if the linker determines the calls 5207 // may not share a TOC base, the call is redirected to a trampoline inserted 5208 // by the linker. The trampoline will (among other things) save the callers 5209 // TOC pointer at an ABI designated offset in the linkage area and the linker 5210 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5211 // into gpr2. 5212 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5213 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5214 : PPCISD::CALL_NOP; 5215 5216 return PPCISD::CALL; 5217 } 5218 5219 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5220 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5221 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5222 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5223 return SDValue(Dest, 0); 5224 5225 // Returns true if the callee is local, and false otherwise. 5226 auto isLocalCallee = [&]() { 5227 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5228 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5229 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5230 5231 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5232 !dyn_cast_or_null<GlobalIFunc>(GV); 5233 }; 5234 5235 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5236 // a static relocation model causes some versions of GNU LD (2.17.50, at 5237 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5238 // built with secure-PLT. 5239 bool UsePlt = 5240 Subtarget.is32BitELFABI() && !isLocalCallee() && 5241 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5242 5243 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5244 const TargetMachine &TM = Subtarget.getTargetMachine(); 5245 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5246 MCSymbolXCOFF *S = 5247 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5248 5249 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5250 return DAG.getMCSymbol(S, PtrVT); 5251 }; 5252 5253 if (isFunctionGlobalAddress(Callee)) { 5254 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5255 5256 if (Subtarget.isAIXABI()) { 5257 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5258 return getAIXFuncEntryPointSymbolSDNode(GV); 5259 } 5260 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5261 UsePlt ? PPCII::MO_PLT : 0); 5262 } 5263 5264 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5265 const char *SymName = S->getSymbol(); 5266 if (Subtarget.isAIXABI()) { 5267 // If there exists a user-declared function whose name is the same as the 5268 // ExternalSymbol's, then we pick up the user-declared version. 5269 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5270 if (const Function *F = 5271 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5272 return getAIXFuncEntryPointSymbolSDNode(F); 5273 5274 // On AIX, direct function calls reference the symbol for the function's 5275 // entry point, which is named by prepending a "." before the function's 5276 // C-linkage name. A Qualname is returned here because an external 5277 // function entry point is a csect with XTY_ER property. 5278 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5279 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5280 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5281 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5282 SectionKind::getMetadata()); 5283 return Sec->getQualNameSymbol(); 5284 }; 5285 5286 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5287 } 5288 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5289 UsePlt ? PPCII::MO_PLT : 0); 5290 } 5291 5292 // No transformation needed. 5293 assert(Callee.getNode() && "What no callee?"); 5294 return Callee; 5295 } 5296 5297 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5298 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5299 "Expected a CALLSEQ_STARTSDNode."); 5300 5301 // The last operand is the chain, except when the node has glue. If the node 5302 // has glue, then the last operand is the glue, and the chain is the second 5303 // last operand. 5304 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5305 if (LastValue.getValueType() != MVT::Glue) 5306 return LastValue; 5307 5308 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5309 } 5310 5311 // Creates the node that moves a functions address into the count register 5312 // to prepare for an indirect call instruction. 5313 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5314 SDValue &Glue, SDValue &Chain, 5315 const SDLoc &dl) { 5316 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5317 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5318 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5319 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5320 // The glue is the second value produced. 5321 Glue = Chain.getValue(1); 5322 } 5323 5324 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5325 SDValue &Glue, SDValue &Chain, 5326 SDValue CallSeqStart, 5327 const CallBase *CB, const SDLoc &dl, 5328 bool hasNest, 5329 const PPCSubtarget &Subtarget) { 5330 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5331 // entry point, but to the function descriptor (the function entry point 5332 // address is part of the function descriptor though). 5333 // The function descriptor is a three doubleword structure with the 5334 // following fields: function entry point, TOC base address and 5335 // environment pointer. 5336 // Thus for a call through a function pointer, the following actions need 5337 // to be performed: 5338 // 1. Save the TOC of the caller in the TOC save area of its stack 5339 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5340 // 2. Load the address of the function entry point from the function 5341 // descriptor. 5342 // 3. Load the TOC of the callee from the function descriptor into r2. 5343 // 4. Load the environment pointer from the function descriptor into 5344 // r11. 5345 // 5. Branch to the function entry point address. 5346 // 6. On return of the callee, the TOC of the caller needs to be 5347 // restored (this is done in FinishCall()). 5348 // 5349 // The loads are scheduled at the beginning of the call sequence, and the 5350 // register copies are flagged together to ensure that no other 5351 // operations can be scheduled in between. E.g. without flagging the 5352 // copies together, a TOC access in the caller could be scheduled between 5353 // the assignment of the callee TOC and the branch to the callee, which leads 5354 // to incorrect code. 5355 5356 // Start by loading the function address from the descriptor. 5357 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5358 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5359 ? (MachineMemOperand::MODereferenceable | 5360 MachineMemOperand::MOInvariant) 5361 : MachineMemOperand::MONone; 5362 5363 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5364 5365 // Registers used in building the DAG. 5366 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5367 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5368 5369 // Offsets of descriptor members. 5370 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5371 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5372 5373 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5374 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5375 5376 // One load for the functions entry point address. 5377 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5378 Alignment, MMOFlags); 5379 5380 // One for loading the TOC anchor for the module that contains the called 5381 // function. 5382 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5383 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5384 SDValue TOCPtr = 5385 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5386 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5387 5388 // One for loading the environment pointer. 5389 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5390 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5391 SDValue LoadEnvPtr = 5392 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5393 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5394 5395 5396 // Then copy the newly loaded TOC anchor to the TOC pointer. 5397 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5398 Chain = TOCVal.getValue(0); 5399 Glue = TOCVal.getValue(1); 5400 5401 // If the function call has an explicit 'nest' parameter, it takes the 5402 // place of the environment pointer. 5403 assert((!hasNest || !Subtarget.isAIXABI()) && 5404 "Nest parameter is not supported on AIX."); 5405 if (!hasNest) { 5406 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5407 Chain = EnvVal.getValue(0); 5408 Glue = EnvVal.getValue(1); 5409 } 5410 5411 // The rest of the indirect call sequence is the same as the non-descriptor 5412 // DAG. 5413 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5414 } 5415 5416 static void 5417 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5418 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5419 SelectionDAG &DAG, 5420 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5421 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5422 const PPCSubtarget &Subtarget) { 5423 const bool IsPPC64 = Subtarget.isPPC64(); 5424 // MVT for a general purpose register. 5425 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5426 5427 // First operand is always the chain. 5428 Ops.push_back(Chain); 5429 5430 // If it's a direct call pass the callee as the second operand. 5431 if (!CFlags.IsIndirect) 5432 Ops.push_back(Callee); 5433 else { 5434 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5435 5436 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5437 // on the stack (this would have been done in `LowerCall_64SVR4` or 5438 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5439 // represents both the indirect branch and a load that restores the TOC 5440 // pointer from the linkage area. The operand for the TOC restore is an add 5441 // of the TOC save offset to the stack pointer. This must be the second 5442 // operand: after the chain input but before any other variadic arguments. 5443 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5444 // saved or used. 5445 if (isTOCSaveRestoreRequired(Subtarget)) { 5446 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5447 5448 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5449 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5450 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5451 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5452 Ops.push_back(AddTOC); 5453 } 5454 5455 // Add the register used for the environment pointer. 5456 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5457 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5458 RegVT)); 5459 5460 5461 // Add CTR register as callee so a bctr can be emitted later. 5462 if (CFlags.IsTailCall) 5463 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5464 } 5465 5466 // If this is a tail call add stack pointer delta. 5467 if (CFlags.IsTailCall) 5468 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5469 5470 // Add argument registers to the end of the list so that they are known live 5471 // into the call. 5472 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5473 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5474 RegsToPass[i].second.getValueType())); 5475 5476 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5477 // no way to mark dependencies as implicit here. 5478 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5479 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5480 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5481 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5482 5483 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5484 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5485 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5486 5487 // Add a register mask operand representing the call-preserved registers. 5488 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5489 const uint32_t *Mask = 5490 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5491 assert(Mask && "Missing call preserved mask for calling convention"); 5492 Ops.push_back(DAG.getRegisterMask(Mask)); 5493 5494 // If the glue is valid, it is the last operand. 5495 if (Glue.getNode()) 5496 Ops.push_back(Glue); 5497 } 5498 5499 SDValue PPCTargetLowering::FinishCall( 5500 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5501 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5502 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5503 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5504 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5505 5506 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5507 Subtarget.isAIXABI()) 5508 setUsesTOCBasePtr(DAG); 5509 5510 unsigned CallOpc = 5511 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5512 Subtarget, DAG.getTarget()); 5513 5514 if (!CFlags.IsIndirect) 5515 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5516 else if (Subtarget.usesFunctionDescriptors()) 5517 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5518 dl, CFlags.HasNest, Subtarget); 5519 else 5520 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5521 5522 // Build the operand list for the call instruction. 5523 SmallVector<SDValue, 8> Ops; 5524 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5525 SPDiff, Subtarget); 5526 5527 // Emit tail call. 5528 if (CFlags.IsTailCall) { 5529 // Indirect tail call when using PC Relative calls do not have the same 5530 // constraints. 5531 assert(((Callee.getOpcode() == ISD::Register && 5532 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5533 Callee.getOpcode() == ISD::TargetExternalSymbol || 5534 Callee.getOpcode() == ISD::TargetGlobalAddress || 5535 isa<ConstantSDNode>(Callee) || 5536 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5537 "Expecting a global address, external symbol, absolute value, " 5538 "register or an indirect tail call when PC Relative calls are " 5539 "used."); 5540 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5541 assert(CallOpc == PPCISD::TC_RETURN && 5542 "Unexpected call opcode for a tail call."); 5543 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5544 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5545 } 5546 5547 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5548 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5549 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5550 Glue = Chain.getValue(1); 5551 5552 // When performing tail call optimization the callee pops its arguments off 5553 // the stack. Account for this here so these bytes can be pushed back on in 5554 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5555 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5556 getTargetMachine().Options.GuaranteedTailCallOpt) 5557 ? NumBytes 5558 : 0; 5559 5560 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5561 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5562 Glue, dl); 5563 Glue = Chain.getValue(1); 5564 5565 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5566 DAG, InVals); 5567 } 5568 5569 SDValue 5570 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5571 SmallVectorImpl<SDValue> &InVals) const { 5572 SelectionDAG &DAG = CLI.DAG; 5573 SDLoc &dl = CLI.DL; 5574 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5575 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5576 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5577 SDValue Chain = CLI.Chain; 5578 SDValue Callee = CLI.Callee; 5579 bool &isTailCall = CLI.IsTailCall; 5580 CallingConv::ID CallConv = CLI.CallConv; 5581 bool isVarArg = CLI.IsVarArg; 5582 bool isPatchPoint = CLI.IsPatchPoint; 5583 const CallBase *CB = CLI.CB; 5584 5585 if (isTailCall) { 5586 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5587 isTailCall = false; 5588 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5589 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5590 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5591 else 5592 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5593 Ins, DAG); 5594 if (isTailCall) { 5595 ++NumTailCalls; 5596 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5597 ++NumSiblingCalls; 5598 5599 // PC Relative calls no longer guarantee that the callee is a Global 5600 // Address Node. The callee could be an indirect tail call in which 5601 // case the SDValue for the callee could be a load (to load the address 5602 // of a function pointer) or it may be a register copy (to move the 5603 // address of the callee from a function parameter into a virtual 5604 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5605 assert((Subtarget.isUsingPCRelativeCalls() || 5606 isa<GlobalAddressSDNode>(Callee)) && 5607 "Callee should be an llvm::Function object."); 5608 5609 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5610 << "\nTCO callee: "); 5611 LLVM_DEBUG(Callee.dump()); 5612 } 5613 } 5614 5615 if (!isTailCall && CB && CB->isMustTailCall()) 5616 report_fatal_error("failed to perform tail call elimination on a call " 5617 "site marked musttail"); 5618 5619 // When long calls (i.e. indirect calls) are always used, calls are always 5620 // made via function pointer. If we have a function name, first translate it 5621 // into a pointer. 5622 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5623 !isTailCall) 5624 Callee = LowerGlobalAddress(Callee, DAG); 5625 5626 CallFlags CFlags( 5627 CallConv, isTailCall, isVarArg, isPatchPoint, 5628 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5629 // hasNest 5630 Subtarget.is64BitELFABI() && 5631 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5632 CLI.NoMerge); 5633 5634 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5635 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5636 InVals, CB); 5637 5638 if (Subtarget.isSVR4ABI()) 5639 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5640 InVals, CB); 5641 5642 if (Subtarget.isAIXABI()) 5643 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5644 InVals, CB); 5645 5646 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5647 InVals, CB); 5648 } 5649 5650 SDValue PPCTargetLowering::LowerCall_32SVR4( 5651 SDValue Chain, SDValue Callee, CallFlags CFlags, 5652 const SmallVectorImpl<ISD::OutputArg> &Outs, 5653 const SmallVectorImpl<SDValue> &OutVals, 5654 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5655 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5656 const CallBase *CB) const { 5657 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5658 // of the 32-bit SVR4 ABI stack frame layout. 5659 5660 const CallingConv::ID CallConv = CFlags.CallConv; 5661 const bool IsVarArg = CFlags.IsVarArg; 5662 const bool IsTailCall = CFlags.IsTailCall; 5663 5664 assert((CallConv == CallingConv::C || 5665 CallConv == CallingConv::Cold || 5666 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5667 5668 const Align PtrAlign(4); 5669 5670 MachineFunction &MF = DAG.getMachineFunction(); 5671 5672 // Mark this function as potentially containing a function that contains a 5673 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5674 // and restoring the callers stack pointer in this functions epilog. This is 5675 // done because by tail calling the called function might overwrite the value 5676 // in this function's (MF) stack pointer stack slot 0(SP). 5677 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5678 CallConv == CallingConv::Fast) 5679 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5680 5681 // Count how many bytes are to be pushed on the stack, including the linkage 5682 // area, parameter list area and the part of the local variable space which 5683 // contains copies of aggregates which are passed by value. 5684 5685 // Assign locations to all of the outgoing arguments. 5686 SmallVector<CCValAssign, 16> ArgLocs; 5687 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5688 5689 // Reserve space for the linkage area on the stack. 5690 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5691 PtrAlign); 5692 if (useSoftFloat()) 5693 CCInfo.PreAnalyzeCallOperands(Outs); 5694 5695 if (IsVarArg) { 5696 // Handle fixed and variable vector arguments differently. 5697 // Fixed vector arguments go into registers as long as registers are 5698 // available. Variable vector arguments always go into memory. 5699 unsigned NumArgs = Outs.size(); 5700 5701 for (unsigned i = 0; i != NumArgs; ++i) { 5702 MVT ArgVT = Outs[i].VT; 5703 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5704 bool Result; 5705 5706 if (Outs[i].IsFixed) { 5707 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5708 CCInfo); 5709 } else { 5710 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5711 ArgFlags, CCInfo); 5712 } 5713 5714 if (Result) { 5715 #ifndef NDEBUG 5716 errs() << "Call operand #" << i << " has unhandled type " 5717 << EVT(ArgVT).getEVTString() << "\n"; 5718 #endif 5719 llvm_unreachable(nullptr); 5720 } 5721 } 5722 } else { 5723 // All arguments are treated the same. 5724 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5725 } 5726 CCInfo.clearWasPPCF128(); 5727 5728 // Assign locations to all of the outgoing aggregate by value arguments. 5729 SmallVector<CCValAssign, 16> ByValArgLocs; 5730 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5731 5732 // Reserve stack space for the allocations in CCInfo. 5733 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5734 5735 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5736 5737 // Size of the linkage area, parameter list area and the part of the local 5738 // space variable where copies of aggregates which are passed by value are 5739 // stored. 5740 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5741 5742 // Calculate by how many bytes the stack has to be adjusted in case of tail 5743 // call optimization. 5744 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5745 5746 // Adjust the stack pointer for the new arguments... 5747 // These operations are automatically eliminated by the prolog/epilog pass 5748 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5749 SDValue CallSeqStart = Chain; 5750 5751 // Load the return address and frame pointer so it can be moved somewhere else 5752 // later. 5753 SDValue LROp, FPOp; 5754 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5755 5756 // Set up a copy of the stack pointer for use loading and storing any 5757 // arguments that may not fit in the registers available for argument 5758 // passing. 5759 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5760 5761 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5762 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5763 SmallVector<SDValue, 8> MemOpChains; 5764 5765 bool seenFloatArg = false; 5766 // Walk the register/memloc assignments, inserting copies/loads. 5767 // i - Tracks the index into the list of registers allocated for the call 5768 // RealArgIdx - Tracks the index into the list of actual function arguments 5769 // j - Tracks the index into the list of byval arguments 5770 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5771 i != e; 5772 ++i, ++RealArgIdx) { 5773 CCValAssign &VA = ArgLocs[i]; 5774 SDValue Arg = OutVals[RealArgIdx]; 5775 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5776 5777 if (Flags.isByVal()) { 5778 // Argument is an aggregate which is passed by value, thus we need to 5779 // create a copy of it in the local variable space of the current stack 5780 // frame (which is the stack frame of the caller) and pass the address of 5781 // this copy to the callee. 5782 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5783 CCValAssign &ByValVA = ByValArgLocs[j++]; 5784 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5785 5786 // Memory reserved in the local variable space of the callers stack frame. 5787 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5788 5789 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5790 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5791 StackPtr, PtrOff); 5792 5793 // Create a copy of the argument in the local area of the current 5794 // stack frame. 5795 SDValue MemcpyCall = 5796 CreateCopyOfByValArgument(Arg, PtrOff, 5797 CallSeqStart.getNode()->getOperand(0), 5798 Flags, DAG, dl); 5799 5800 // This must go outside the CALLSEQ_START..END. 5801 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5802 SDLoc(MemcpyCall)); 5803 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5804 NewCallSeqStart.getNode()); 5805 Chain = CallSeqStart = NewCallSeqStart; 5806 5807 // Pass the address of the aggregate copy on the stack either in a 5808 // physical register or in the parameter list area of the current stack 5809 // frame to the callee. 5810 Arg = PtrOff; 5811 } 5812 5813 // When useCRBits() is true, there can be i1 arguments. 5814 // It is because getRegisterType(MVT::i1) => MVT::i1, 5815 // and for other integer types getRegisterType() => MVT::i32. 5816 // Extend i1 and ensure callee will get i32. 5817 if (Arg.getValueType() == MVT::i1) 5818 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5819 dl, MVT::i32, Arg); 5820 5821 if (VA.isRegLoc()) { 5822 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5823 // Put argument in a physical register. 5824 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5825 bool IsLE = Subtarget.isLittleEndian(); 5826 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5827 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5828 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5829 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5830 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5831 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5832 SVal.getValue(0))); 5833 } else 5834 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5835 } else { 5836 // Put argument in the parameter list area of the current stack frame. 5837 assert(VA.isMemLoc()); 5838 unsigned LocMemOffset = VA.getLocMemOffset(); 5839 5840 if (!IsTailCall) { 5841 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5842 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5843 StackPtr, PtrOff); 5844 5845 MemOpChains.push_back( 5846 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5847 } else { 5848 // Calculate and remember argument location. 5849 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5850 TailCallArguments); 5851 } 5852 } 5853 } 5854 5855 if (!MemOpChains.empty()) 5856 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5857 5858 // Build a sequence of copy-to-reg nodes chained together with token chain 5859 // and flag operands which copy the outgoing args into the appropriate regs. 5860 SDValue InFlag; 5861 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5862 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5863 RegsToPass[i].second, InFlag); 5864 InFlag = Chain.getValue(1); 5865 } 5866 5867 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5868 // registers. 5869 if (IsVarArg) { 5870 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5871 SDValue Ops[] = { Chain, InFlag }; 5872 5873 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5874 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5875 5876 InFlag = Chain.getValue(1); 5877 } 5878 5879 if (IsTailCall) 5880 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5881 TailCallArguments); 5882 5883 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5884 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5885 } 5886 5887 // Copy an argument into memory, being careful to do this outside the 5888 // call sequence for the call to which the argument belongs. 5889 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5890 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5891 SelectionDAG &DAG, const SDLoc &dl) const { 5892 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5893 CallSeqStart.getNode()->getOperand(0), 5894 Flags, DAG, dl); 5895 // The MEMCPY must go outside the CALLSEQ_START..END. 5896 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5897 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5898 SDLoc(MemcpyCall)); 5899 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5900 NewCallSeqStart.getNode()); 5901 return NewCallSeqStart; 5902 } 5903 5904 SDValue PPCTargetLowering::LowerCall_64SVR4( 5905 SDValue Chain, SDValue Callee, CallFlags CFlags, 5906 const SmallVectorImpl<ISD::OutputArg> &Outs, 5907 const SmallVectorImpl<SDValue> &OutVals, 5908 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5909 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5910 const CallBase *CB) const { 5911 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5912 bool isLittleEndian = Subtarget.isLittleEndian(); 5913 unsigned NumOps = Outs.size(); 5914 bool IsSibCall = false; 5915 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5916 5917 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5918 unsigned PtrByteSize = 8; 5919 5920 MachineFunction &MF = DAG.getMachineFunction(); 5921 5922 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5923 IsSibCall = true; 5924 5925 // Mark this function as potentially containing a function that contains a 5926 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5927 // and restoring the callers stack pointer in this functions epilog. This is 5928 // done because by tail calling the called function might overwrite the value 5929 // in this function's (MF) stack pointer stack slot 0(SP). 5930 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5931 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5932 5933 assert(!(IsFastCall && CFlags.IsVarArg) && 5934 "fastcc not supported on varargs functions"); 5935 5936 // Count how many bytes are to be pushed on the stack, including the linkage 5937 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5938 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5939 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5940 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5941 unsigned NumBytes = LinkageSize; 5942 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5943 5944 static const MCPhysReg GPR[] = { 5945 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5946 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5947 }; 5948 static const MCPhysReg VR[] = { 5949 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5950 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5951 }; 5952 5953 const unsigned NumGPRs = array_lengthof(GPR); 5954 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5955 const unsigned NumVRs = array_lengthof(VR); 5956 5957 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5958 // can be passed to the callee in registers. 5959 // For the fast calling convention, there is another check below. 5960 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5961 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5962 if (!HasParameterArea) { 5963 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5964 unsigned AvailableFPRs = NumFPRs; 5965 unsigned AvailableVRs = NumVRs; 5966 unsigned NumBytesTmp = NumBytes; 5967 for (unsigned i = 0; i != NumOps; ++i) { 5968 if (Outs[i].Flags.isNest()) continue; 5969 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5970 PtrByteSize, LinkageSize, ParamAreaSize, 5971 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5972 HasParameterArea = true; 5973 } 5974 } 5975 5976 // When using the fast calling convention, we don't provide backing for 5977 // arguments that will be in registers. 5978 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5979 5980 // Avoid allocating parameter area for fastcc functions if all the arguments 5981 // can be passed in the registers. 5982 if (IsFastCall) 5983 HasParameterArea = false; 5984 5985 // Add up all the space actually used. 5986 for (unsigned i = 0; i != NumOps; ++i) { 5987 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5988 EVT ArgVT = Outs[i].VT; 5989 EVT OrigVT = Outs[i].ArgVT; 5990 5991 if (Flags.isNest()) 5992 continue; 5993 5994 if (IsFastCall) { 5995 if (Flags.isByVal()) { 5996 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5997 if (NumGPRsUsed > NumGPRs) 5998 HasParameterArea = true; 5999 } else { 6000 switch (ArgVT.getSimpleVT().SimpleTy) { 6001 default: llvm_unreachable("Unexpected ValueType for argument!"); 6002 case MVT::i1: 6003 case MVT::i32: 6004 case MVT::i64: 6005 if (++NumGPRsUsed <= NumGPRs) 6006 continue; 6007 break; 6008 case MVT::v4i32: 6009 case MVT::v8i16: 6010 case MVT::v16i8: 6011 case MVT::v2f64: 6012 case MVT::v2i64: 6013 case MVT::v1i128: 6014 case MVT::f128: 6015 if (++NumVRsUsed <= NumVRs) 6016 continue; 6017 break; 6018 case MVT::v4f32: 6019 if (++NumVRsUsed <= NumVRs) 6020 continue; 6021 break; 6022 case MVT::f32: 6023 case MVT::f64: 6024 if (++NumFPRsUsed <= NumFPRs) 6025 continue; 6026 break; 6027 } 6028 HasParameterArea = true; 6029 } 6030 } 6031 6032 /* Respect alignment of argument on the stack. */ 6033 auto Alignement = 6034 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6035 NumBytes = alignTo(NumBytes, Alignement); 6036 6037 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6038 if (Flags.isInConsecutiveRegsLast()) 6039 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6040 } 6041 6042 unsigned NumBytesActuallyUsed = NumBytes; 6043 6044 // In the old ELFv1 ABI, 6045 // the prolog code of the callee may store up to 8 GPR argument registers to 6046 // the stack, allowing va_start to index over them in memory if its varargs. 6047 // Because we cannot tell if this is needed on the caller side, we have to 6048 // conservatively assume that it is needed. As such, make sure we have at 6049 // least enough stack space for the caller to store the 8 GPRs. 6050 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6051 // really requires memory operands, e.g. a vararg function. 6052 if (HasParameterArea) 6053 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6054 else 6055 NumBytes = LinkageSize; 6056 6057 // Tail call needs the stack to be aligned. 6058 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6059 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6060 6061 int SPDiff = 0; 6062 6063 // Calculate by how many bytes the stack has to be adjusted in case of tail 6064 // call optimization. 6065 if (!IsSibCall) 6066 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6067 6068 // To protect arguments on the stack from being clobbered in a tail call, 6069 // force all the loads to happen before doing any other lowering. 6070 if (CFlags.IsTailCall) 6071 Chain = DAG.getStackArgumentTokenFactor(Chain); 6072 6073 // Adjust the stack pointer for the new arguments... 6074 // These operations are automatically eliminated by the prolog/epilog pass 6075 if (!IsSibCall) 6076 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6077 SDValue CallSeqStart = Chain; 6078 6079 // Load the return address and frame pointer so it can be move somewhere else 6080 // later. 6081 SDValue LROp, FPOp; 6082 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6083 6084 // Set up a copy of the stack pointer for use loading and storing any 6085 // arguments that may not fit in the registers available for argument 6086 // passing. 6087 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6088 6089 // Figure out which arguments are going to go in registers, and which in 6090 // memory. Also, if this is a vararg function, floating point operations 6091 // must be stored to our stack, and loaded into integer regs as well, if 6092 // any integer regs are available for argument passing. 6093 unsigned ArgOffset = LinkageSize; 6094 6095 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6096 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6097 6098 SmallVector<SDValue, 8> MemOpChains; 6099 for (unsigned i = 0; i != NumOps; ++i) { 6100 SDValue Arg = OutVals[i]; 6101 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6102 EVT ArgVT = Outs[i].VT; 6103 EVT OrigVT = Outs[i].ArgVT; 6104 6105 // PtrOff will be used to store the current argument to the stack if a 6106 // register cannot be found for it. 6107 SDValue PtrOff; 6108 6109 // We re-align the argument offset for each argument, except when using the 6110 // fast calling convention, when we need to make sure we do that only when 6111 // we'll actually use a stack slot. 6112 auto ComputePtrOff = [&]() { 6113 /* Respect alignment of argument on the stack. */ 6114 auto Alignment = 6115 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6116 ArgOffset = alignTo(ArgOffset, Alignment); 6117 6118 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6119 6120 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6121 }; 6122 6123 if (!IsFastCall) { 6124 ComputePtrOff(); 6125 6126 /* Compute GPR index associated with argument offset. */ 6127 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6128 GPR_idx = std::min(GPR_idx, NumGPRs); 6129 } 6130 6131 // Promote integers to 64-bit values. 6132 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6133 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6134 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6135 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6136 } 6137 6138 // FIXME memcpy is used way more than necessary. Correctness first. 6139 // Note: "by value" is code for passing a structure by value, not 6140 // basic types. 6141 if (Flags.isByVal()) { 6142 // Note: Size includes alignment padding, so 6143 // struct x { short a; char b; } 6144 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6145 // These are the proper values we need for right-justifying the 6146 // aggregate in a parameter register. 6147 unsigned Size = Flags.getByValSize(); 6148 6149 // An empty aggregate parameter takes up no storage and no 6150 // registers. 6151 if (Size == 0) 6152 continue; 6153 6154 if (IsFastCall) 6155 ComputePtrOff(); 6156 6157 // All aggregates smaller than 8 bytes must be passed right-justified. 6158 if (Size==1 || Size==2 || Size==4) { 6159 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6160 if (GPR_idx != NumGPRs) { 6161 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6162 MachinePointerInfo(), VT); 6163 MemOpChains.push_back(Load.getValue(1)); 6164 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6165 6166 ArgOffset += PtrByteSize; 6167 continue; 6168 } 6169 } 6170 6171 if (GPR_idx == NumGPRs && Size < 8) { 6172 SDValue AddPtr = PtrOff; 6173 if (!isLittleEndian) { 6174 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6175 PtrOff.getValueType()); 6176 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6177 } 6178 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6179 CallSeqStart, 6180 Flags, DAG, dl); 6181 ArgOffset += PtrByteSize; 6182 continue; 6183 } 6184 // Copy entire object into memory. There are cases where gcc-generated 6185 // code assumes it is there, even if it could be put entirely into 6186 // registers. (This is not what the doc says.) 6187 6188 // FIXME: The above statement is likely due to a misunderstanding of the 6189 // documents. All arguments must be copied into the parameter area BY 6190 // THE CALLEE in the event that the callee takes the address of any 6191 // formal argument. That has not yet been implemented. However, it is 6192 // reasonable to use the stack area as a staging area for the register 6193 // load. 6194 6195 // Skip this for small aggregates, as we will use the same slot for a 6196 // right-justified copy, below. 6197 if (Size >= 8) 6198 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6199 CallSeqStart, 6200 Flags, DAG, dl); 6201 6202 // When a register is available, pass a small aggregate right-justified. 6203 if (Size < 8 && GPR_idx != NumGPRs) { 6204 // The easiest way to get this right-justified in a register 6205 // is to copy the structure into the rightmost portion of a 6206 // local variable slot, then load the whole slot into the 6207 // register. 6208 // FIXME: The memcpy seems to produce pretty awful code for 6209 // small aggregates, particularly for packed ones. 6210 // FIXME: It would be preferable to use the slot in the 6211 // parameter save area instead of a new local variable. 6212 SDValue AddPtr = PtrOff; 6213 if (!isLittleEndian) { 6214 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6215 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6216 } 6217 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6218 CallSeqStart, 6219 Flags, DAG, dl); 6220 6221 // Load the slot into the register. 6222 SDValue Load = 6223 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6224 MemOpChains.push_back(Load.getValue(1)); 6225 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6226 6227 // Done with this argument. 6228 ArgOffset += PtrByteSize; 6229 continue; 6230 } 6231 6232 // For aggregates larger than PtrByteSize, copy the pieces of the 6233 // object that fit into registers from the parameter save area. 6234 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6235 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6236 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6237 if (GPR_idx != NumGPRs) { 6238 SDValue Load = 6239 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6240 MemOpChains.push_back(Load.getValue(1)); 6241 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6242 ArgOffset += PtrByteSize; 6243 } else { 6244 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6245 break; 6246 } 6247 } 6248 continue; 6249 } 6250 6251 switch (Arg.getSimpleValueType().SimpleTy) { 6252 default: llvm_unreachable("Unexpected ValueType for argument!"); 6253 case MVT::i1: 6254 case MVT::i32: 6255 case MVT::i64: 6256 if (Flags.isNest()) { 6257 // The 'nest' parameter, if any, is passed in R11. 6258 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6259 break; 6260 } 6261 6262 // These can be scalar arguments or elements of an integer array type 6263 // passed directly. Clang may use those instead of "byval" aggregate 6264 // types to avoid forcing arguments to memory unnecessarily. 6265 if (GPR_idx != NumGPRs) { 6266 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6267 } else { 6268 if (IsFastCall) 6269 ComputePtrOff(); 6270 6271 assert(HasParameterArea && 6272 "Parameter area must exist to pass an argument in memory."); 6273 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6274 true, CFlags.IsTailCall, false, MemOpChains, 6275 TailCallArguments, dl); 6276 if (IsFastCall) 6277 ArgOffset += PtrByteSize; 6278 } 6279 if (!IsFastCall) 6280 ArgOffset += PtrByteSize; 6281 break; 6282 case MVT::f32: 6283 case MVT::f64: { 6284 // These can be scalar arguments or elements of a float array type 6285 // passed directly. The latter are used to implement ELFv2 homogenous 6286 // float aggregates. 6287 6288 // Named arguments go into FPRs first, and once they overflow, the 6289 // remaining arguments go into GPRs and then the parameter save area. 6290 // Unnamed arguments for vararg functions always go to GPRs and 6291 // then the parameter save area. For now, put all arguments to vararg 6292 // routines always in both locations (FPR *and* GPR or stack slot). 6293 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6294 bool NeededLoad = false; 6295 6296 // First load the argument into the next available FPR. 6297 if (FPR_idx != NumFPRs) 6298 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6299 6300 // Next, load the argument into GPR or stack slot if needed. 6301 if (!NeedGPROrStack) 6302 ; 6303 else if (GPR_idx != NumGPRs && !IsFastCall) { 6304 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6305 // once we support fp <-> gpr moves. 6306 6307 // In the non-vararg case, this can only ever happen in the 6308 // presence of f32 array types, since otherwise we never run 6309 // out of FPRs before running out of GPRs. 6310 SDValue ArgVal; 6311 6312 // Double values are always passed in a single GPR. 6313 if (Arg.getValueType() != MVT::f32) { 6314 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6315 6316 // Non-array float values are extended and passed in a GPR. 6317 } else if (!Flags.isInConsecutiveRegs()) { 6318 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6319 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6320 6321 // If we have an array of floats, we collect every odd element 6322 // together with its predecessor into one GPR. 6323 } else if (ArgOffset % PtrByteSize != 0) { 6324 SDValue Lo, Hi; 6325 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6326 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6327 if (!isLittleEndian) 6328 std::swap(Lo, Hi); 6329 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6330 6331 // The final element, if even, goes into the first half of a GPR. 6332 } else if (Flags.isInConsecutiveRegsLast()) { 6333 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6334 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6335 if (!isLittleEndian) 6336 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6337 DAG.getConstant(32, dl, MVT::i32)); 6338 6339 // Non-final even elements are skipped; they will be handled 6340 // together the with subsequent argument on the next go-around. 6341 } else 6342 ArgVal = SDValue(); 6343 6344 if (ArgVal.getNode()) 6345 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6346 } else { 6347 if (IsFastCall) 6348 ComputePtrOff(); 6349 6350 // Single-precision floating-point values are mapped to the 6351 // second (rightmost) word of the stack doubleword. 6352 if (Arg.getValueType() == MVT::f32 && 6353 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6354 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6355 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6356 } 6357 6358 assert(HasParameterArea && 6359 "Parameter area must exist to pass an argument in memory."); 6360 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6361 true, CFlags.IsTailCall, false, MemOpChains, 6362 TailCallArguments, dl); 6363 6364 NeededLoad = true; 6365 } 6366 // When passing an array of floats, the array occupies consecutive 6367 // space in the argument area; only round up to the next doubleword 6368 // at the end of the array. Otherwise, each float takes 8 bytes. 6369 if (!IsFastCall || NeededLoad) { 6370 ArgOffset += (Arg.getValueType() == MVT::f32 && 6371 Flags.isInConsecutiveRegs()) ? 4 : 8; 6372 if (Flags.isInConsecutiveRegsLast()) 6373 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6374 } 6375 break; 6376 } 6377 case MVT::v4f32: 6378 case MVT::v4i32: 6379 case MVT::v8i16: 6380 case MVT::v16i8: 6381 case MVT::v2f64: 6382 case MVT::v2i64: 6383 case MVT::v1i128: 6384 case MVT::f128: 6385 // These can be scalar arguments or elements of a vector array type 6386 // passed directly. The latter are used to implement ELFv2 homogenous 6387 // vector aggregates. 6388 6389 // For a varargs call, named arguments go into VRs or on the stack as 6390 // usual; unnamed arguments always go to the stack or the corresponding 6391 // GPRs when within range. For now, we always put the value in both 6392 // locations (or even all three). 6393 if (CFlags.IsVarArg) { 6394 assert(HasParameterArea && 6395 "Parameter area must exist if we have a varargs call."); 6396 // We could elide this store in the case where the object fits 6397 // entirely in R registers. Maybe later. 6398 SDValue Store = 6399 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6400 MemOpChains.push_back(Store); 6401 if (VR_idx != NumVRs) { 6402 SDValue Load = 6403 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6404 MemOpChains.push_back(Load.getValue(1)); 6405 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6406 } 6407 ArgOffset += 16; 6408 for (unsigned i=0; i<16; i+=PtrByteSize) { 6409 if (GPR_idx == NumGPRs) 6410 break; 6411 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6412 DAG.getConstant(i, dl, PtrVT)); 6413 SDValue Load = 6414 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6415 MemOpChains.push_back(Load.getValue(1)); 6416 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6417 } 6418 break; 6419 } 6420 6421 // Non-varargs Altivec params go into VRs or on the stack. 6422 if (VR_idx != NumVRs) { 6423 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6424 } else { 6425 if (IsFastCall) 6426 ComputePtrOff(); 6427 6428 assert(HasParameterArea && 6429 "Parameter area must exist to pass an argument in memory."); 6430 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6431 true, CFlags.IsTailCall, true, MemOpChains, 6432 TailCallArguments, dl); 6433 if (IsFastCall) 6434 ArgOffset += 16; 6435 } 6436 6437 if (!IsFastCall) 6438 ArgOffset += 16; 6439 break; 6440 } 6441 } 6442 6443 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6444 "mismatch in size of parameter area"); 6445 (void)NumBytesActuallyUsed; 6446 6447 if (!MemOpChains.empty()) 6448 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6449 6450 // Check if this is an indirect call (MTCTR/BCTRL). 6451 // See prepareDescriptorIndirectCall and buildCallOperands for more 6452 // information about calls through function pointers in the 64-bit SVR4 ABI. 6453 if (CFlags.IsIndirect) { 6454 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6455 // caller in the TOC save area. 6456 if (isTOCSaveRestoreRequired(Subtarget)) { 6457 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6458 // Load r2 into a virtual register and store it to the TOC save area. 6459 setUsesTOCBasePtr(DAG); 6460 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6461 // TOC save area offset. 6462 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6463 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6464 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6465 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6466 MachinePointerInfo::getStack( 6467 DAG.getMachineFunction(), TOCSaveOffset)); 6468 } 6469 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6470 // This does not mean the MTCTR instruction must use R12; it's easier 6471 // to model this as an extra parameter, so do that. 6472 if (isELFv2ABI && !CFlags.IsPatchPoint) 6473 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6474 } 6475 6476 // Build a sequence of copy-to-reg nodes chained together with token chain 6477 // and flag operands which copy the outgoing args into the appropriate regs. 6478 SDValue InFlag; 6479 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6480 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6481 RegsToPass[i].second, InFlag); 6482 InFlag = Chain.getValue(1); 6483 } 6484 6485 if (CFlags.IsTailCall && !IsSibCall) 6486 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6487 TailCallArguments); 6488 6489 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6490 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6491 } 6492 6493 SDValue PPCTargetLowering::LowerCall_Darwin( 6494 SDValue Chain, SDValue Callee, CallFlags CFlags, 6495 const SmallVectorImpl<ISD::OutputArg> &Outs, 6496 const SmallVectorImpl<SDValue> &OutVals, 6497 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6498 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6499 const CallBase *CB) const { 6500 unsigned NumOps = Outs.size(); 6501 6502 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6503 bool isPPC64 = PtrVT == MVT::i64; 6504 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6505 6506 MachineFunction &MF = DAG.getMachineFunction(); 6507 6508 // Mark this function as potentially containing a function that contains a 6509 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6510 // and restoring the callers stack pointer in this functions epilog. This is 6511 // done because by tail calling the called function might overwrite the value 6512 // in this function's (MF) stack pointer stack slot 0(SP). 6513 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6514 CFlags.CallConv == CallingConv::Fast) 6515 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6516 6517 // Count how many bytes are to be pushed on the stack, including the linkage 6518 // area, and parameter passing area. We start with 24/48 bytes, which is 6519 // prereserved space for [SP][CR][LR][3 x unused]. 6520 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6521 unsigned NumBytes = LinkageSize; 6522 6523 // Add up all the space actually used. 6524 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6525 // they all go in registers, but we must reserve stack space for them for 6526 // possible use by the caller. In varargs or 64-bit calls, parameters are 6527 // assigned stack space in order, with padding so Altivec parameters are 6528 // 16-byte aligned. 6529 unsigned nAltivecParamsAtEnd = 0; 6530 for (unsigned i = 0; i != NumOps; ++i) { 6531 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6532 EVT ArgVT = Outs[i].VT; 6533 // Varargs Altivec parameters are padded to a 16 byte boundary. 6534 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6535 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6536 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6537 if (!CFlags.IsVarArg && !isPPC64) { 6538 // Non-varargs Altivec parameters go after all the non-Altivec 6539 // parameters; handle those later so we know how much padding we need. 6540 nAltivecParamsAtEnd++; 6541 continue; 6542 } 6543 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6544 NumBytes = ((NumBytes+15)/16)*16; 6545 } 6546 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6547 } 6548 6549 // Allow for Altivec parameters at the end, if needed. 6550 if (nAltivecParamsAtEnd) { 6551 NumBytes = ((NumBytes+15)/16)*16; 6552 NumBytes += 16*nAltivecParamsAtEnd; 6553 } 6554 6555 // The prolog code of the callee may store up to 8 GPR argument registers to 6556 // the stack, allowing va_start to index over them in memory if its varargs. 6557 // Because we cannot tell if this is needed on the caller side, we have to 6558 // conservatively assume that it is needed. As such, make sure we have at 6559 // least enough stack space for the caller to store the 8 GPRs. 6560 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6561 6562 // Tail call needs the stack to be aligned. 6563 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6564 CFlags.CallConv == CallingConv::Fast) 6565 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6566 6567 // Calculate by how many bytes the stack has to be adjusted in case of tail 6568 // call optimization. 6569 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6570 6571 // To protect arguments on the stack from being clobbered in a tail call, 6572 // force all the loads to happen before doing any other lowering. 6573 if (CFlags.IsTailCall) 6574 Chain = DAG.getStackArgumentTokenFactor(Chain); 6575 6576 // Adjust the stack pointer for the new arguments... 6577 // These operations are automatically eliminated by the prolog/epilog pass 6578 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6579 SDValue CallSeqStart = Chain; 6580 6581 // Load the return address and frame pointer so it can be move somewhere else 6582 // later. 6583 SDValue LROp, FPOp; 6584 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6585 6586 // Set up a copy of the stack pointer for use loading and storing any 6587 // arguments that may not fit in the registers available for argument 6588 // passing. 6589 SDValue StackPtr; 6590 if (isPPC64) 6591 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6592 else 6593 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6594 6595 // Figure out which arguments are going to go in registers, and which in 6596 // memory. Also, if this is a vararg function, floating point operations 6597 // must be stored to our stack, and loaded into integer regs as well, if 6598 // any integer regs are available for argument passing. 6599 unsigned ArgOffset = LinkageSize; 6600 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6601 6602 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6603 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6604 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6605 }; 6606 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6607 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6608 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6609 }; 6610 static const MCPhysReg VR[] = { 6611 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6612 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6613 }; 6614 const unsigned NumGPRs = array_lengthof(GPR_32); 6615 const unsigned NumFPRs = 13; 6616 const unsigned NumVRs = array_lengthof(VR); 6617 6618 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6619 6620 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6621 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6622 6623 SmallVector<SDValue, 8> MemOpChains; 6624 for (unsigned i = 0; i != NumOps; ++i) { 6625 SDValue Arg = OutVals[i]; 6626 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6627 6628 // PtrOff will be used to store the current argument to the stack if a 6629 // register cannot be found for it. 6630 SDValue PtrOff; 6631 6632 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6633 6634 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6635 6636 // On PPC64, promote integers to 64-bit values. 6637 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6638 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6639 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6640 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6641 } 6642 6643 // FIXME memcpy is used way more than necessary. Correctness first. 6644 // Note: "by value" is code for passing a structure by value, not 6645 // basic types. 6646 if (Flags.isByVal()) { 6647 unsigned Size = Flags.getByValSize(); 6648 // Very small objects are passed right-justified. Everything else is 6649 // passed left-justified. 6650 if (Size==1 || Size==2) { 6651 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6652 if (GPR_idx != NumGPRs) { 6653 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6654 MachinePointerInfo(), VT); 6655 MemOpChains.push_back(Load.getValue(1)); 6656 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6657 6658 ArgOffset += PtrByteSize; 6659 } else { 6660 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6661 PtrOff.getValueType()); 6662 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6663 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6664 CallSeqStart, 6665 Flags, DAG, dl); 6666 ArgOffset += PtrByteSize; 6667 } 6668 continue; 6669 } 6670 // Copy entire object into memory. There are cases where gcc-generated 6671 // code assumes it is there, even if it could be put entirely into 6672 // registers. (This is not what the doc says.) 6673 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6674 CallSeqStart, 6675 Flags, DAG, dl); 6676 6677 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6678 // copy the pieces of the object that fit into registers from the 6679 // parameter save area. 6680 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6681 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6682 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6683 if (GPR_idx != NumGPRs) { 6684 SDValue Load = 6685 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6686 MemOpChains.push_back(Load.getValue(1)); 6687 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6688 ArgOffset += PtrByteSize; 6689 } else { 6690 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6691 break; 6692 } 6693 } 6694 continue; 6695 } 6696 6697 switch (Arg.getSimpleValueType().SimpleTy) { 6698 default: llvm_unreachable("Unexpected ValueType for argument!"); 6699 case MVT::i1: 6700 case MVT::i32: 6701 case MVT::i64: 6702 if (GPR_idx != NumGPRs) { 6703 if (Arg.getValueType() == MVT::i1) 6704 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6705 6706 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6707 } else { 6708 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6709 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6710 TailCallArguments, dl); 6711 } 6712 ArgOffset += PtrByteSize; 6713 break; 6714 case MVT::f32: 6715 case MVT::f64: 6716 if (FPR_idx != NumFPRs) { 6717 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6718 6719 if (CFlags.IsVarArg) { 6720 SDValue Store = 6721 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6722 MemOpChains.push_back(Store); 6723 6724 // Float varargs are always shadowed in available integer registers 6725 if (GPR_idx != NumGPRs) { 6726 SDValue Load = 6727 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6728 MemOpChains.push_back(Load.getValue(1)); 6729 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6730 } 6731 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6732 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6733 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6734 SDValue Load = 6735 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6736 MemOpChains.push_back(Load.getValue(1)); 6737 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6738 } 6739 } else { 6740 // If we have any FPRs remaining, we may also have GPRs remaining. 6741 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6742 // GPRs. 6743 if (GPR_idx != NumGPRs) 6744 ++GPR_idx; 6745 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6746 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6747 ++GPR_idx; 6748 } 6749 } else 6750 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6751 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6752 TailCallArguments, dl); 6753 if (isPPC64) 6754 ArgOffset += 8; 6755 else 6756 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6757 break; 6758 case MVT::v4f32: 6759 case MVT::v4i32: 6760 case MVT::v8i16: 6761 case MVT::v16i8: 6762 if (CFlags.IsVarArg) { 6763 // These go aligned on the stack, or in the corresponding R registers 6764 // when within range. The Darwin PPC ABI doc claims they also go in 6765 // V registers; in fact gcc does this only for arguments that are 6766 // prototyped, not for those that match the ... We do it for all 6767 // arguments, seems to work. 6768 while (ArgOffset % 16 !=0) { 6769 ArgOffset += PtrByteSize; 6770 if (GPR_idx != NumGPRs) 6771 GPR_idx++; 6772 } 6773 // We could elide this store in the case where the object fits 6774 // entirely in R registers. Maybe later. 6775 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6776 DAG.getConstant(ArgOffset, dl, PtrVT)); 6777 SDValue Store = 6778 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6779 MemOpChains.push_back(Store); 6780 if (VR_idx != NumVRs) { 6781 SDValue Load = 6782 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6783 MemOpChains.push_back(Load.getValue(1)); 6784 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6785 } 6786 ArgOffset += 16; 6787 for (unsigned i=0; i<16; i+=PtrByteSize) { 6788 if (GPR_idx == NumGPRs) 6789 break; 6790 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6791 DAG.getConstant(i, dl, PtrVT)); 6792 SDValue Load = 6793 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6794 MemOpChains.push_back(Load.getValue(1)); 6795 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6796 } 6797 break; 6798 } 6799 6800 // Non-varargs Altivec params generally go in registers, but have 6801 // stack space allocated at the end. 6802 if (VR_idx != NumVRs) { 6803 // Doesn't have GPR space allocated. 6804 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6805 } else if (nAltivecParamsAtEnd==0) { 6806 // We are emitting Altivec params in order. 6807 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6808 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6809 TailCallArguments, dl); 6810 ArgOffset += 16; 6811 } 6812 break; 6813 } 6814 } 6815 // If all Altivec parameters fit in registers, as they usually do, 6816 // they get stack space following the non-Altivec parameters. We 6817 // don't track this here because nobody below needs it. 6818 // If there are more Altivec parameters than fit in registers emit 6819 // the stores here. 6820 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6821 unsigned j = 0; 6822 // Offset is aligned; skip 1st 12 params which go in V registers. 6823 ArgOffset = ((ArgOffset+15)/16)*16; 6824 ArgOffset += 12*16; 6825 for (unsigned i = 0; i != NumOps; ++i) { 6826 SDValue Arg = OutVals[i]; 6827 EVT ArgType = Outs[i].VT; 6828 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6829 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6830 if (++j > NumVRs) { 6831 SDValue PtrOff; 6832 // We are emitting Altivec params in order. 6833 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6834 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6835 TailCallArguments, dl); 6836 ArgOffset += 16; 6837 } 6838 } 6839 } 6840 } 6841 6842 if (!MemOpChains.empty()) 6843 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6844 6845 // On Darwin, R12 must contain the address of an indirect callee. This does 6846 // not mean the MTCTR instruction must use R12; it's easier to model this as 6847 // an extra parameter, so do that. 6848 if (CFlags.IsIndirect) { 6849 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6850 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6851 PPC::R12), Callee)); 6852 } 6853 6854 // Build a sequence of copy-to-reg nodes chained together with token chain 6855 // and flag operands which copy the outgoing args into the appropriate regs. 6856 SDValue InFlag; 6857 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6858 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6859 RegsToPass[i].second, InFlag); 6860 InFlag = Chain.getValue(1); 6861 } 6862 6863 if (CFlags.IsTailCall) 6864 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6865 TailCallArguments); 6866 6867 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6868 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6869 } 6870 6871 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6872 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6873 CCState &State) { 6874 6875 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6876 State.getMachineFunction().getSubtarget()); 6877 const bool IsPPC64 = Subtarget.isPPC64(); 6878 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6879 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6880 6881 assert((!ValVT.isInteger() || 6882 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6883 "Integer argument exceeds register size: should have been legalized"); 6884 6885 if (ValVT == MVT::f128) 6886 report_fatal_error("f128 is unimplemented on AIX."); 6887 6888 if (ArgFlags.isNest()) 6889 report_fatal_error("Nest arguments are unimplemented."); 6890 6891 if (ValVT.isVector() || LocVT.isVector()) 6892 report_fatal_error("Vector arguments are unimplemented on AIX."); 6893 6894 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6895 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6896 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6897 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6898 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6899 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6900 6901 if (ArgFlags.isByVal()) { 6902 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6903 report_fatal_error("Pass-by-value arguments with alignment greater than " 6904 "register width are not supported."); 6905 6906 const unsigned ByValSize = ArgFlags.getByValSize(); 6907 6908 // An empty aggregate parameter takes up no storage and no registers, 6909 // but needs a MemLoc for a stack slot for the formal arguments side. 6910 if (ByValSize == 0) { 6911 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6912 State.getNextStackOffset(), RegVT, 6913 LocInfo)); 6914 return false; 6915 } 6916 6917 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6918 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6919 for (const unsigned E = Offset + StackSize; Offset < E; 6920 Offset += PtrAlign.value()) { 6921 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6922 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6923 else { 6924 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6925 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6926 LocInfo)); 6927 break; 6928 } 6929 } 6930 return false; 6931 } 6932 6933 // Arguments always reserve parameter save area. 6934 switch (ValVT.SimpleTy) { 6935 default: 6936 report_fatal_error("Unhandled value type for argument."); 6937 case MVT::i64: 6938 // i64 arguments should have been split to i32 for PPC32. 6939 assert(IsPPC64 && "PPC32 should have split i64 values."); 6940 LLVM_FALLTHROUGH; 6941 case MVT::i1: 6942 case MVT::i32: { 6943 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6944 // AIX integer arguments are always passed in register width. 6945 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6946 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6947 : CCValAssign::LocInfo::ZExt; 6948 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6949 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6950 else 6951 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6952 6953 return false; 6954 } 6955 case MVT::f32: 6956 case MVT::f64: { 6957 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6958 const unsigned StoreSize = LocVT.getStoreSize(); 6959 // Floats are always 4-byte aligned in the PSA on AIX. 6960 // This includes f64 in 64-bit mode for ABI compatibility. 6961 const unsigned Offset = 6962 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6963 unsigned FReg = State.AllocateReg(FPR); 6964 if (FReg) 6965 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6966 6967 // Reserve and initialize GPRs or initialize the PSA as required. 6968 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6969 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6970 assert(FReg && "An FPR should be available when a GPR is reserved."); 6971 if (State.isVarArg()) { 6972 // Successfully reserved GPRs are only initialized for vararg calls. 6973 // Custom handling is required for: 6974 // f64 in PPC32 needs to be split into 2 GPRs. 6975 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6976 State.addLoc( 6977 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6978 } 6979 } else { 6980 // If there are insufficient GPRs, the PSA needs to be initialized. 6981 // Initialization occurs even if an FPR was initialized for 6982 // compatibility with the AIX XL compiler. The full memory for the 6983 // argument will be initialized even if a prior word is saved in GPR. 6984 // A custom memLoc is used when the argument also passes in FPR so 6985 // that the callee handling can skip over it easily. 6986 State.addLoc( 6987 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6988 LocInfo) 6989 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6990 break; 6991 } 6992 } 6993 6994 return false; 6995 } 6996 } 6997 return true; 6998 } 6999 7000 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7001 bool IsPPC64) { 7002 assert((IsPPC64 || SVT != MVT::i64) && 7003 "i64 should have been split for 32-bit codegen."); 7004 7005 switch (SVT) { 7006 default: 7007 report_fatal_error("Unexpected value type for formal argument"); 7008 case MVT::i1: 7009 case MVT::i32: 7010 case MVT::i64: 7011 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7012 case MVT::f32: 7013 return &PPC::F4RCRegClass; 7014 case MVT::f64: 7015 return &PPC::F8RCRegClass; 7016 } 7017 } 7018 7019 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7020 SelectionDAG &DAG, SDValue ArgValue, 7021 MVT LocVT, const SDLoc &dl) { 7022 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7023 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7024 7025 if (Flags.isSExt()) 7026 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7027 DAG.getValueType(ValVT)); 7028 else if (Flags.isZExt()) 7029 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7030 DAG.getValueType(ValVT)); 7031 7032 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7033 } 7034 7035 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7036 const unsigned LASize = FL->getLinkageSize(); 7037 7038 if (PPC::GPRCRegClass.contains(Reg)) { 7039 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7040 "Reg must be a valid argument register!"); 7041 return LASize + 4 * (Reg - PPC::R3); 7042 } 7043 7044 if (PPC::G8RCRegClass.contains(Reg)) { 7045 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7046 "Reg must be a valid argument register!"); 7047 return LASize + 8 * (Reg - PPC::X3); 7048 } 7049 7050 llvm_unreachable("Only general purpose registers expected."); 7051 } 7052 7053 // AIX ABI Stack Frame Layout: 7054 // 7055 // Low Memory +--------------------------------------------+ 7056 // SP +---> | Back chain | ---+ 7057 // | +--------------------------------------------+ | 7058 // | | Saved Condition Register | | 7059 // | +--------------------------------------------+ | 7060 // | | Saved Linkage Register | | 7061 // | +--------------------------------------------+ | Linkage Area 7062 // | | Reserved for compilers | | 7063 // | +--------------------------------------------+ | 7064 // | | Reserved for binders | | 7065 // | +--------------------------------------------+ | 7066 // | | Saved TOC pointer | ---+ 7067 // | +--------------------------------------------+ 7068 // | | Parameter save area | 7069 // | +--------------------------------------------+ 7070 // | | Alloca space | 7071 // | +--------------------------------------------+ 7072 // | | Local variable space | 7073 // | +--------------------------------------------+ 7074 // | | Float/int conversion temporary | 7075 // | +--------------------------------------------+ 7076 // | | Save area for AltiVec registers | 7077 // | +--------------------------------------------+ 7078 // | | AltiVec alignment padding | 7079 // | +--------------------------------------------+ 7080 // | | Save area for VRSAVE register | 7081 // | +--------------------------------------------+ 7082 // | | Save area for General Purpose registers | 7083 // | +--------------------------------------------+ 7084 // | | Save area for Floating Point registers | 7085 // | +--------------------------------------------+ 7086 // +---- | Back chain | 7087 // High Memory +--------------------------------------------+ 7088 // 7089 // Specifications: 7090 // AIX 7.2 Assembler Language Reference 7091 // Subroutine linkage convention 7092 7093 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7094 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7095 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7096 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7097 7098 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7099 CallConv == CallingConv::Fast) && 7100 "Unexpected calling convention!"); 7101 7102 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7103 report_fatal_error("Tail call support is unimplemented on AIX."); 7104 7105 if (useSoftFloat()) 7106 report_fatal_error("Soft float support is unimplemented on AIX."); 7107 7108 const PPCSubtarget &Subtarget = 7109 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7110 7111 const bool IsPPC64 = Subtarget.isPPC64(); 7112 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7113 7114 // Assign locations to all of the incoming arguments. 7115 SmallVector<CCValAssign, 16> ArgLocs; 7116 MachineFunction &MF = DAG.getMachineFunction(); 7117 MachineFrameInfo &MFI = MF.getFrameInfo(); 7118 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7119 7120 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7121 // Reserve space for the linkage area on the stack. 7122 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7123 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7124 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7125 7126 SmallVector<SDValue, 8> MemOps; 7127 7128 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7129 CCValAssign &VA = ArgLocs[I++]; 7130 MVT LocVT = VA.getLocVT(); 7131 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7132 7133 // For compatibility with the AIX XL compiler, the float args in the 7134 // parameter save area are initialized even if the argument is available 7135 // in register. The caller is required to initialize both the register 7136 // and memory, however, the callee can choose to expect it in either. 7137 // The memloc is dismissed here because the argument is retrieved from 7138 // the register. 7139 if (VA.isMemLoc() && VA.needsCustom()) 7140 continue; 7141 7142 if (Flags.isByVal() && VA.isMemLoc()) { 7143 const unsigned Size = 7144 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7145 PtrByteSize); 7146 const int FI = MF.getFrameInfo().CreateFixedObject( 7147 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7148 /* IsAliased */ true); 7149 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7150 InVals.push_back(FIN); 7151 7152 continue; 7153 } 7154 7155 if (Flags.isByVal()) { 7156 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7157 7158 const MCPhysReg ArgReg = VA.getLocReg(); 7159 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7160 7161 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7162 report_fatal_error("Over aligned byvals not supported yet."); 7163 7164 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7165 const int FI = MF.getFrameInfo().CreateFixedObject( 7166 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7167 /* IsAliased */ true); 7168 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7169 InVals.push_back(FIN); 7170 7171 // Add live ins for all the RegLocs for the same ByVal. 7172 const TargetRegisterClass *RegClass = 7173 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7174 7175 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7176 unsigned Offset) { 7177 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7178 // Since the callers side has left justified the aggregate in the 7179 // register, we can simply store the entire register into the stack 7180 // slot. 7181 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7182 // The store to the fixedstack object is needed becuase accessing a 7183 // field of the ByVal will use a gep and load. Ideally we will optimize 7184 // to extracting the value from the register directly, and elide the 7185 // stores when the arguments address is not taken, but that will need to 7186 // be future work. 7187 SDValue Store = DAG.getStore( 7188 CopyFrom.getValue(1), dl, CopyFrom, 7189 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7190 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7191 7192 MemOps.push_back(Store); 7193 }; 7194 7195 unsigned Offset = 0; 7196 HandleRegLoc(VA.getLocReg(), Offset); 7197 Offset += PtrByteSize; 7198 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7199 Offset += PtrByteSize) { 7200 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7201 "RegLocs should be for ByVal argument."); 7202 7203 const CCValAssign RL = ArgLocs[I++]; 7204 HandleRegLoc(RL.getLocReg(), Offset); 7205 } 7206 7207 if (Offset != StackSize) { 7208 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7209 "Expected MemLoc for remaining bytes."); 7210 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7211 // Consume the MemLoc.The InVal has already been emitted, so nothing 7212 // more needs to be done. 7213 ++I; 7214 } 7215 7216 continue; 7217 } 7218 7219 EVT ValVT = VA.getValVT(); 7220 if (VA.isRegLoc() && !VA.needsCustom()) { 7221 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7222 unsigned VReg = 7223 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7224 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7225 if (ValVT.isScalarInteger() && 7226 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7227 ArgValue = 7228 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7229 } 7230 InVals.push_back(ArgValue); 7231 continue; 7232 } 7233 if (VA.isMemLoc()) { 7234 const unsigned LocSize = LocVT.getStoreSize(); 7235 const unsigned ValSize = ValVT.getStoreSize(); 7236 assert((ValSize <= LocSize) && 7237 "Object size is larger than size of MemLoc"); 7238 int CurArgOffset = VA.getLocMemOffset(); 7239 // Objects are right-justified because AIX is big-endian. 7240 if (LocSize > ValSize) 7241 CurArgOffset += LocSize - ValSize; 7242 // Potential tail calls could cause overwriting of argument stack slots. 7243 const bool IsImmutable = 7244 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7245 (CallConv == CallingConv::Fast)); 7246 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7248 SDValue ArgValue = 7249 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7250 InVals.push_back(ArgValue); 7251 continue; 7252 } 7253 } 7254 7255 // On AIX a minimum of 8 words is saved to the parameter save area. 7256 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7257 // Area that is at least reserved in the caller of this function. 7258 unsigned CallerReservedArea = 7259 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7260 7261 // Set the size that is at least reserved in caller of this function. Tail 7262 // call optimized function's reserved stack space needs to be aligned so 7263 // that taking the difference between two stack areas will result in an 7264 // aligned stack. 7265 CallerReservedArea = 7266 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7267 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7268 FuncInfo->setMinReservedArea(CallerReservedArea); 7269 7270 if (isVarArg) { 7271 FuncInfo->setVarArgsFrameIndex( 7272 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7273 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7274 7275 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7276 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7277 7278 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7279 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7280 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7281 7282 // The fixed integer arguments of a variadic function are stored to the 7283 // VarArgsFrameIndex on the stack so that they may be loaded by 7284 // dereferencing the result of va_next. 7285 for (unsigned GPRIndex = 7286 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7287 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7288 7289 const unsigned VReg = 7290 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7291 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7292 7293 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7294 SDValue Store = 7295 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7296 MemOps.push_back(Store); 7297 // Increment the address for the next argument to store. 7298 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7299 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7300 } 7301 } 7302 7303 if (!MemOps.empty()) 7304 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7305 7306 return Chain; 7307 } 7308 7309 SDValue PPCTargetLowering::LowerCall_AIX( 7310 SDValue Chain, SDValue Callee, CallFlags CFlags, 7311 const SmallVectorImpl<ISD::OutputArg> &Outs, 7312 const SmallVectorImpl<SDValue> &OutVals, 7313 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7314 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7315 const CallBase *CB) const { 7316 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7317 // AIX ABI stack frame layout. 7318 7319 assert((CFlags.CallConv == CallingConv::C || 7320 CFlags.CallConv == CallingConv::Cold || 7321 CFlags.CallConv == CallingConv::Fast) && 7322 "Unexpected calling convention!"); 7323 7324 if (CFlags.IsPatchPoint) 7325 report_fatal_error("This call type is unimplemented on AIX."); 7326 7327 const PPCSubtarget& Subtarget = 7328 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7329 if (Subtarget.hasAltivec()) 7330 report_fatal_error("Altivec support is unimplemented on AIX."); 7331 7332 MachineFunction &MF = DAG.getMachineFunction(); 7333 SmallVector<CCValAssign, 16> ArgLocs; 7334 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7335 *DAG.getContext()); 7336 7337 // Reserve space for the linkage save area (LSA) on the stack. 7338 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7339 // [SP][CR][LR][2 x reserved][TOC]. 7340 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7341 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7342 const bool IsPPC64 = Subtarget.isPPC64(); 7343 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7344 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7345 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7346 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7347 7348 // The prolog code of the callee may store up to 8 GPR argument registers to 7349 // the stack, allowing va_start to index over them in memory if the callee 7350 // is variadic. 7351 // Because we cannot tell if this is needed on the caller side, we have to 7352 // conservatively assume that it is needed. As such, make sure we have at 7353 // least enough stack space for the caller to store the 8 GPRs. 7354 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7355 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7356 CCInfo.getNextStackOffset()); 7357 7358 // Adjust the stack pointer for the new arguments... 7359 // These operations are automatically eliminated by the prolog/epilog pass. 7360 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7361 SDValue CallSeqStart = Chain; 7362 7363 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7364 SmallVector<SDValue, 8> MemOpChains; 7365 7366 // Set up a copy of the stack pointer for loading and storing any 7367 // arguments that may not fit in the registers available for argument 7368 // passing. 7369 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7370 : DAG.getRegister(PPC::R1, MVT::i32); 7371 7372 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7373 const unsigned ValNo = ArgLocs[I].getValNo(); 7374 SDValue Arg = OutVals[ValNo]; 7375 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7376 7377 if (Flags.isByVal()) { 7378 const unsigned ByValSize = Flags.getByValSize(); 7379 7380 // Nothing to do for zero-sized ByVals on the caller side. 7381 if (!ByValSize) { 7382 ++I; 7383 continue; 7384 } 7385 7386 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7387 return DAG.getExtLoad( 7388 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7389 (LoadOffset != 0) 7390 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7391 : Arg, 7392 MachinePointerInfo(), VT); 7393 }; 7394 7395 unsigned LoadOffset = 0; 7396 7397 // Initialize registers, which are fully occupied by the by-val argument. 7398 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7399 SDValue Load = GetLoad(PtrVT, LoadOffset); 7400 MemOpChains.push_back(Load.getValue(1)); 7401 LoadOffset += PtrByteSize; 7402 const CCValAssign &ByValVA = ArgLocs[I++]; 7403 assert(ByValVA.getValNo() == ValNo && 7404 "Unexpected location for pass-by-value argument."); 7405 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7406 } 7407 7408 if (LoadOffset == ByValSize) 7409 continue; 7410 7411 // There must be one more loc to handle the remainder. 7412 assert(ArgLocs[I].getValNo() == ValNo && 7413 "Expected additional location for by-value argument."); 7414 7415 if (ArgLocs[I].isMemLoc()) { 7416 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7417 const CCValAssign &ByValVA = ArgLocs[I++]; 7418 ISD::ArgFlagsTy MemcpyFlags = Flags; 7419 // Only memcpy the bytes that don't pass in register. 7420 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7421 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7422 (LoadOffset != 0) 7423 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7424 : Arg, 7425 DAG.getObjectPtrOffset(dl, StackPtr, 7426 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7427 CallSeqStart, MemcpyFlags, DAG, dl); 7428 continue; 7429 } 7430 7431 // Initialize the final register residue. 7432 // Any residue that occupies the final by-val arg register must be 7433 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7434 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7435 // 2 and 1 byte loads. 7436 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7437 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7438 "Unexpected register residue for by-value argument."); 7439 SDValue ResidueVal; 7440 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7441 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7442 const MVT VT = 7443 N == 1 ? MVT::i8 7444 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7445 SDValue Load = GetLoad(VT, LoadOffset); 7446 MemOpChains.push_back(Load.getValue(1)); 7447 LoadOffset += N; 7448 Bytes += N; 7449 7450 // By-val arguments are passed left-justfied in register. 7451 // Every load here needs to be shifted, otherwise a full register load 7452 // should have been used. 7453 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7454 "Unexpected load emitted during handling of pass-by-value " 7455 "argument."); 7456 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7457 EVT ShiftAmountTy = 7458 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7459 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7460 SDValue ShiftedLoad = 7461 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7462 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7463 ShiftedLoad) 7464 : ShiftedLoad; 7465 } 7466 7467 const CCValAssign &ByValVA = ArgLocs[I++]; 7468 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7469 continue; 7470 } 7471 7472 CCValAssign &VA = ArgLocs[I++]; 7473 const MVT LocVT = VA.getLocVT(); 7474 const MVT ValVT = VA.getValVT(); 7475 7476 switch (VA.getLocInfo()) { 7477 default: 7478 report_fatal_error("Unexpected argument extension type."); 7479 case CCValAssign::Full: 7480 break; 7481 case CCValAssign::ZExt: 7482 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7483 break; 7484 case CCValAssign::SExt: 7485 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7486 break; 7487 } 7488 7489 if (VA.isRegLoc() && !VA.needsCustom()) { 7490 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7491 continue; 7492 } 7493 7494 if (VA.isMemLoc()) { 7495 SDValue PtrOff = 7496 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7497 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7498 MemOpChains.push_back( 7499 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7500 7501 continue; 7502 } 7503 7504 // Custom handling is used for GPR initializations for vararg float 7505 // arguments. 7506 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7507 ValVT.isFloatingPoint() && LocVT.isInteger() && 7508 "Unexpected register handling for calling convention."); 7509 7510 SDValue ArgAsInt = 7511 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7512 7513 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7514 // f32 in 32-bit GPR 7515 // f64 in 64-bit GPR 7516 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7517 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7518 // f32 in 64-bit GPR. 7519 RegsToPass.push_back(std::make_pair( 7520 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7521 else { 7522 // f64 in two 32-bit GPRs 7523 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7524 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7525 "Unexpected custom register for argument!"); 7526 CCValAssign &GPR1 = VA; 7527 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7528 DAG.getConstant(32, dl, MVT::i8)); 7529 RegsToPass.push_back(std::make_pair( 7530 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7531 7532 if (I != E) { 7533 // If only 1 GPR was available, there will only be one custom GPR and 7534 // the argument will also pass in memory. 7535 CCValAssign &PeekArg = ArgLocs[I]; 7536 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7537 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7538 CCValAssign &GPR2 = ArgLocs[I++]; 7539 RegsToPass.push_back(std::make_pair( 7540 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7541 } 7542 } 7543 } 7544 } 7545 7546 if (!MemOpChains.empty()) 7547 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7548 7549 // For indirect calls, we need to save the TOC base to the stack for 7550 // restoration after the call. 7551 if (CFlags.IsIndirect) { 7552 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7553 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7554 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7555 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7556 const unsigned TOCSaveOffset = 7557 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7558 7559 setUsesTOCBasePtr(DAG); 7560 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7561 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7562 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7563 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7564 Chain = DAG.getStore( 7565 Val.getValue(1), dl, Val, AddPtr, 7566 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7567 } 7568 7569 // Build a sequence of copy-to-reg nodes chained together with token chain 7570 // and flag operands which copy the outgoing args into the appropriate regs. 7571 SDValue InFlag; 7572 for (auto Reg : RegsToPass) { 7573 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7574 InFlag = Chain.getValue(1); 7575 } 7576 7577 const int SPDiff = 0; 7578 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7579 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7580 } 7581 7582 bool 7583 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7584 MachineFunction &MF, bool isVarArg, 7585 const SmallVectorImpl<ISD::OutputArg> &Outs, 7586 LLVMContext &Context) const { 7587 SmallVector<CCValAssign, 16> RVLocs; 7588 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7589 return CCInfo.CheckReturn( 7590 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7591 ? RetCC_PPC_Cold 7592 : RetCC_PPC); 7593 } 7594 7595 SDValue 7596 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7597 bool isVarArg, 7598 const SmallVectorImpl<ISD::OutputArg> &Outs, 7599 const SmallVectorImpl<SDValue> &OutVals, 7600 const SDLoc &dl, SelectionDAG &DAG) const { 7601 SmallVector<CCValAssign, 16> RVLocs; 7602 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7603 *DAG.getContext()); 7604 CCInfo.AnalyzeReturn(Outs, 7605 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7606 ? RetCC_PPC_Cold 7607 : RetCC_PPC); 7608 7609 SDValue Flag; 7610 SmallVector<SDValue, 4> RetOps(1, Chain); 7611 7612 // Copy the result values into the output registers. 7613 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7614 CCValAssign &VA = RVLocs[i]; 7615 assert(VA.isRegLoc() && "Can only return in registers!"); 7616 7617 SDValue Arg = OutVals[RealResIdx]; 7618 7619 switch (VA.getLocInfo()) { 7620 default: llvm_unreachable("Unknown loc info!"); 7621 case CCValAssign::Full: break; 7622 case CCValAssign::AExt: 7623 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7624 break; 7625 case CCValAssign::ZExt: 7626 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7627 break; 7628 case CCValAssign::SExt: 7629 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7630 break; 7631 } 7632 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7633 bool isLittleEndian = Subtarget.isLittleEndian(); 7634 // Legalize ret f64 -> ret 2 x i32. 7635 SDValue SVal = 7636 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7637 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7638 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7639 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7640 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7641 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7642 Flag = Chain.getValue(1); 7643 VA = RVLocs[++i]; // skip ahead to next loc 7644 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7645 } else 7646 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7647 Flag = Chain.getValue(1); 7648 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7649 } 7650 7651 RetOps[0] = Chain; // Update chain. 7652 7653 // Add the flag if we have it. 7654 if (Flag.getNode()) 7655 RetOps.push_back(Flag); 7656 7657 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7658 } 7659 7660 SDValue 7661 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7662 SelectionDAG &DAG) const { 7663 SDLoc dl(Op); 7664 7665 // Get the correct type for integers. 7666 EVT IntVT = Op.getValueType(); 7667 7668 // Get the inputs. 7669 SDValue Chain = Op.getOperand(0); 7670 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7671 // Build a DYNAREAOFFSET node. 7672 SDValue Ops[2] = {Chain, FPSIdx}; 7673 SDVTList VTs = DAG.getVTList(IntVT); 7674 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7675 } 7676 7677 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7678 SelectionDAG &DAG) const { 7679 // When we pop the dynamic allocation we need to restore the SP link. 7680 SDLoc dl(Op); 7681 7682 // Get the correct type for pointers. 7683 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7684 7685 // Construct the stack pointer operand. 7686 bool isPPC64 = Subtarget.isPPC64(); 7687 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7688 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7689 7690 // Get the operands for the STACKRESTORE. 7691 SDValue Chain = Op.getOperand(0); 7692 SDValue SaveSP = Op.getOperand(1); 7693 7694 // Load the old link SP. 7695 SDValue LoadLinkSP = 7696 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7697 7698 // Restore the stack pointer. 7699 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7700 7701 // Store the old link SP. 7702 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7703 } 7704 7705 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7706 MachineFunction &MF = DAG.getMachineFunction(); 7707 bool isPPC64 = Subtarget.isPPC64(); 7708 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7709 7710 // Get current frame pointer save index. The users of this index will be 7711 // primarily DYNALLOC instructions. 7712 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7713 int RASI = FI->getReturnAddrSaveIndex(); 7714 7715 // If the frame pointer save index hasn't been defined yet. 7716 if (!RASI) { 7717 // Find out what the fix offset of the frame pointer save area. 7718 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7719 // Allocate the frame index for frame pointer save area. 7720 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7721 // Save the result. 7722 FI->setReturnAddrSaveIndex(RASI); 7723 } 7724 return DAG.getFrameIndex(RASI, PtrVT); 7725 } 7726 7727 SDValue 7728 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7729 MachineFunction &MF = DAG.getMachineFunction(); 7730 bool isPPC64 = Subtarget.isPPC64(); 7731 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7732 7733 // Get current frame pointer save index. The users of this index will be 7734 // primarily DYNALLOC instructions. 7735 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7736 int FPSI = FI->getFramePointerSaveIndex(); 7737 7738 // If the frame pointer save index hasn't been defined yet. 7739 if (!FPSI) { 7740 // Find out what the fix offset of the frame pointer save area. 7741 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7742 // Allocate the frame index for frame pointer save area. 7743 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7744 // Save the result. 7745 FI->setFramePointerSaveIndex(FPSI); 7746 } 7747 return DAG.getFrameIndex(FPSI, PtrVT); 7748 } 7749 7750 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7751 SelectionDAG &DAG) const { 7752 MachineFunction &MF = DAG.getMachineFunction(); 7753 // Get the inputs. 7754 SDValue Chain = Op.getOperand(0); 7755 SDValue Size = Op.getOperand(1); 7756 SDLoc dl(Op); 7757 7758 // Get the correct type for pointers. 7759 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7760 // Negate the size. 7761 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7762 DAG.getConstant(0, dl, PtrVT), Size); 7763 // Construct a node for the frame pointer save index. 7764 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7765 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7766 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7767 if (hasInlineStackProbe(MF)) 7768 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7769 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7770 } 7771 7772 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7773 SelectionDAG &DAG) const { 7774 MachineFunction &MF = DAG.getMachineFunction(); 7775 7776 bool isPPC64 = Subtarget.isPPC64(); 7777 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7778 7779 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7780 return DAG.getFrameIndex(FI, PtrVT); 7781 } 7782 7783 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7784 SelectionDAG &DAG) const { 7785 SDLoc DL(Op); 7786 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7787 DAG.getVTList(MVT::i32, MVT::Other), 7788 Op.getOperand(0), Op.getOperand(1)); 7789 } 7790 7791 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7792 SelectionDAG &DAG) const { 7793 SDLoc DL(Op); 7794 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7795 Op.getOperand(0), Op.getOperand(1)); 7796 } 7797 7798 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7799 7800 assert(Op.getValueType() == MVT::i1 && 7801 "Custom lowering only for i1 loads"); 7802 7803 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7804 7805 SDLoc dl(Op); 7806 LoadSDNode *LD = cast<LoadSDNode>(Op); 7807 7808 SDValue Chain = LD->getChain(); 7809 SDValue BasePtr = LD->getBasePtr(); 7810 MachineMemOperand *MMO = LD->getMemOperand(); 7811 7812 SDValue NewLD = 7813 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7814 BasePtr, MVT::i8, MMO); 7815 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7816 7817 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7818 return DAG.getMergeValues(Ops, dl); 7819 } 7820 7821 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7822 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7823 "Custom lowering only for i1 stores"); 7824 7825 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7826 7827 SDLoc dl(Op); 7828 StoreSDNode *ST = cast<StoreSDNode>(Op); 7829 7830 SDValue Chain = ST->getChain(); 7831 SDValue BasePtr = ST->getBasePtr(); 7832 SDValue Value = ST->getValue(); 7833 MachineMemOperand *MMO = ST->getMemOperand(); 7834 7835 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7836 Value); 7837 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7838 } 7839 7840 // FIXME: Remove this once the ANDI glue bug is fixed: 7841 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7842 assert(Op.getValueType() == MVT::i1 && 7843 "Custom lowering only for i1 results"); 7844 7845 SDLoc DL(Op); 7846 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7847 } 7848 7849 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7850 SelectionDAG &DAG) const { 7851 7852 // Implements a vector truncate that fits in a vector register as a shuffle. 7853 // We want to legalize vector truncates down to where the source fits in 7854 // a vector register (and target is therefore smaller than vector register 7855 // size). At that point legalization will try to custom lower the sub-legal 7856 // result and get here - where we can contain the truncate as a single target 7857 // operation. 7858 7859 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7860 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7861 // 7862 // We will implement it for big-endian ordering as this (where x denotes 7863 // undefined): 7864 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7865 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7866 // 7867 // The same operation in little-endian ordering will be: 7868 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7869 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7870 7871 EVT TrgVT = Op.getValueType(); 7872 assert(TrgVT.isVector() && "Vector type expected."); 7873 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7874 EVT EltVT = TrgVT.getVectorElementType(); 7875 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7876 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7877 !isPowerOf2_32(EltVT.getSizeInBits())) 7878 return SDValue(); 7879 7880 SDValue N1 = Op.getOperand(0); 7881 EVT SrcVT = N1.getValueType(); 7882 unsigned SrcSize = SrcVT.getSizeInBits(); 7883 if (SrcSize > 256 || 7884 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7885 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7886 return SDValue(); 7887 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7888 return SDValue(); 7889 7890 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7891 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7892 7893 SDLoc DL(Op); 7894 SDValue Op1, Op2; 7895 if (SrcSize == 256) { 7896 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7897 EVT SplitVT = 7898 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7899 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7900 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7901 DAG.getConstant(0, DL, VecIdxTy)); 7902 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7903 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7904 } 7905 else { 7906 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7907 Op2 = DAG.getUNDEF(WideVT); 7908 } 7909 7910 // First list the elements we want to keep. 7911 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7912 SmallVector<int, 16> ShuffV; 7913 if (Subtarget.isLittleEndian()) 7914 for (unsigned i = 0; i < TrgNumElts; ++i) 7915 ShuffV.push_back(i * SizeMult); 7916 else 7917 for (unsigned i = 1; i <= TrgNumElts; ++i) 7918 ShuffV.push_back(i * SizeMult - 1); 7919 7920 // Populate the remaining elements with undefs. 7921 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7922 // ShuffV.push_back(i + WideNumElts); 7923 ShuffV.push_back(WideNumElts + 1); 7924 7925 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7926 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7927 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7928 } 7929 7930 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7931 /// possible. 7932 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7933 // Not FP, or using SPE? Not a fsel. 7934 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7935 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7936 return Op; 7937 7938 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7939 7940 EVT ResVT = Op.getValueType(); 7941 EVT CmpVT = Op.getOperand(0).getValueType(); 7942 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7943 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7944 SDLoc dl(Op); 7945 SDNodeFlags Flags = Op.getNode()->getFlags(); 7946 7947 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7948 // presence of infinities. 7949 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7950 switch (CC) { 7951 default: 7952 break; 7953 case ISD::SETOGT: 7954 case ISD::SETGT: 7955 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7956 case ISD::SETOLT: 7957 case ISD::SETLT: 7958 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7959 } 7960 } 7961 7962 // We might be able to do better than this under some circumstances, but in 7963 // general, fsel-based lowering of select is a finite-math-only optimization. 7964 // For more information, see section F.3 of the 2.06 ISA specification. 7965 // With ISA 3.0 7966 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7967 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7968 return Op; 7969 7970 // If the RHS of the comparison is a 0.0, we don't need to do the 7971 // subtraction at all. 7972 SDValue Sel1; 7973 if (isFloatingPointZero(RHS)) 7974 switch (CC) { 7975 default: break; // SETUO etc aren't handled by fsel. 7976 case ISD::SETNE: 7977 std::swap(TV, FV); 7978 LLVM_FALLTHROUGH; 7979 case ISD::SETEQ: 7980 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7981 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7982 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7983 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7984 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7985 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7986 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7987 case ISD::SETULT: 7988 case ISD::SETLT: 7989 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7990 LLVM_FALLTHROUGH; 7991 case ISD::SETOGE: 7992 case ISD::SETGE: 7993 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7994 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7995 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7996 case ISD::SETUGT: 7997 case ISD::SETGT: 7998 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7999 LLVM_FALLTHROUGH; 8000 case ISD::SETOLE: 8001 case ISD::SETLE: 8002 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8003 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8004 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8005 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8006 } 8007 8008 SDValue Cmp; 8009 switch (CC) { 8010 default: break; // SETUO etc aren't handled by fsel. 8011 case ISD::SETNE: 8012 std::swap(TV, FV); 8013 LLVM_FALLTHROUGH; 8014 case ISD::SETEQ: 8015 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8016 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8017 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8018 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8019 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8020 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8021 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8022 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8023 case ISD::SETULT: 8024 case ISD::SETLT: 8025 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8026 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8027 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8028 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8029 case ISD::SETOGE: 8030 case ISD::SETGE: 8031 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8032 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8033 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8034 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8035 case ISD::SETUGT: 8036 case ISD::SETGT: 8037 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8038 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8039 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8040 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8041 case ISD::SETOLE: 8042 case ISD::SETLE: 8043 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8044 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8045 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8046 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8047 } 8048 return Op; 8049 } 8050 8051 static unsigned getPPCStrictOpcode(unsigned Opc) { 8052 switch (Opc) { 8053 default: 8054 llvm_unreachable("No strict version of this opcode!"); 8055 case PPCISD::FCTIDZ: 8056 return PPCISD::STRICT_FCTIDZ; 8057 case PPCISD::FCTIWZ: 8058 return PPCISD::STRICT_FCTIWZ; 8059 case PPCISD::FCTIDUZ: 8060 return PPCISD::STRICT_FCTIDUZ; 8061 case PPCISD::FCTIWUZ: 8062 return PPCISD::STRICT_FCTIWUZ; 8063 case PPCISD::FCFID: 8064 return PPCISD::STRICT_FCFID; 8065 case PPCISD::FCFIDU: 8066 return PPCISD::STRICT_FCFIDU; 8067 case PPCISD::FCFIDS: 8068 return PPCISD::STRICT_FCFIDS; 8069 case PPCISD::FCFIDUS: 8070 return PPCISD::STRICT_FCFIDUS; 8071 } 8072 } 8073 8074 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8075 const PPCSubtarget &Subtarget) { 8076 SDLoc dl(Op); 8077 bool IsStrict = Op->isStrictFPOpcode(); 8078 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8079 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8080 // For strict nodes, source is the second operand. 8081 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8082 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8083 assert(Src.getValueType().isFloatingPoint()); 8084 if (Src.getValueType() == MVT::f32) { 8085 if (IsStrict) { 8086 Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other}, 8087 {Chain, Src}); 8088 Chain = Src.getValue(1); 8089 } else 8090 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8091 } 8092 SDValue Conv; 8093 unsigned Opc = ISD::DELETED_NODE; 8094 switch (Op.getSimpleValueType().SimpleTy) { 8095 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8096 case MVT::i32: 8097 Opc = IsSigned ? PPCISD::FCTIWZ 8098 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8099 break; 8100 case MVT::i64: 8101 assert((IsSigned || Subtarget.hasFPCVT()) && 8102 "i64 FP_TO_UINT is supported only with FPCVT"); 8103 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8104 } 8105 if (IsStrict) { 8106 Opc = getPPCStrictOpcode(Opc); 8107 Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src}); 8108 } else { 8109 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8110 } 8111 return Conv; 8112 } 8113 8114 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8115 SelectionDAG &DAG, 8116 const SDLoc &dl) const { 8117 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8118 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8119 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8120 bool IsStrict = Op->isStrictFPOpcode(); 8121 8122 // Convert the FP value to an int value through memory. 8123 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8124 (IsSigned || Subtarget.hasFPCVT()); 8125 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8126 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8127 MachinePointerInfo MPI = 8128 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8129 8130 // Emit a store to the stack slot. 8131 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8132 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8133 if (i32Stack) { 8134 MachineFunction &MF = DAG.getMachineFunction(); 8135 Alignment = Align(4); 8136 MachineMemOperand *MMO = 8137 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8138 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8139 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8140 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8141 } else 8142 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8143 8144 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8145 // add in a bias on big endian. 8146 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8147 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8148 DAG.getConstant(4, dl, FIPtr.getValueType())); 8149 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8150 } 8151 8152 RLI.Chain = Chain; 8153 RLI.Ptr = FIPtr; 8154 RLI.MPI = MPI; 8155 RLI.Alignment = Alignment; 8156 } 8157 8158 /// Custom lowers floating point to integer conversions to use 8159 /// the direct move instructions available in ISA 2.07 to avoid the 8160 /// need for load/store combinations. 8161 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8162 SelectionDAG &DAG, 8163 const SDLoc &dl) const { 8164 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8165 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8166 if (Op->isStrictFPOpcode()) 8167 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8168 else 8169 return Mov; 8170 } 8171 8172 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8173 const SDLoc &dl) const { 8174 bool IsStrict = Op->isStrictFPOpcode(); 8175 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8176 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8177 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8178 EVT SrcVT = Src.getValueType(); 8179 EVT DstVT = Op.getValueType(); 8180 8181 // FP to INT conversions are legal for f128. 8182 if (SrcVT == MVT::f128) 8183 return Op; 8184 8185 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8186 // PPC (the libcall is not available). 8187 if (SrcVT == MVT::ppcf128) { 8188 if (DstVT == MVT::i32) { 8189 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8190 // set other fast-math flags to FP operations in both strict and 8191 // non-strict cases. (FP_TO_SINT, FSUB) 8192 SDNodeFlags Flags; 8193 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8194 8195 if (IsSigned) { 8196 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8197 DAG.getIntPtrConstant(0, dl)); 8198 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8199 DAG.getIntPtrConstant(1, dl)); 8200 8201 // Add the two halves of the long double in round-to-zero mode, and use 8202 // a smaller FP_TO_SINT. 8203 if (IsStrict) { 8204 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8205 DAG.getVTList(MVT::f64, MVT::Other), 8206 {Op.getOperand(0), Lo, Hi}, Flags); 8207 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8208 DAG.getVTList(MVT::i32, MVT::Other), 8209 {Res.getValue(1), Res}, Flags); 8210 } else { 8211 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8212 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8213 } 8214 } else { 8215 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8216 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8217 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8218 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8219 if (IsStrict) { 8220 // Sel = Src < 0x80000000 8221 // FltOfs = select Sel, 0.0, 0x80000000 8222 // IntOfs = select Sel, 0, 0x80000000 8223 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8224 SDValue Chain = Op.getOperand(0); 8225 EVT SetCCVT = 8226 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8227 EVT DstSetCCVT = 8228 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8229 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8230 SDNodeFlags(), Chain, true); 8231 Chain = Sel.getValue(1); 8232 8233 SDValue FltOfs = DAG.getSelect( 8234 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8235 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8236 8237 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8238 DAG.getVTList(SrcVT, MVT::Other), 8239 {Chain, Src, FltOfs}, Flags); 8240 Chain = Val.getValue(1); 8241 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8242 DAG.getVTList(DstVT, MVT::Other), 8243 {Chain, Val}, Flags); 8244 Chain = SInt.getValue(1); 8245 SDValue IntOfs = DAG.getSelect( 8246 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8247 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8248 return DAG.getMergeValues({Result, Chain}, dl); 8249 } else { 8250 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8251 // FIXME: generated code sucks. 8252 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8253 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8254 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8255 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8256 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8257 } 8258 } 8259 } 8260 8261 return SDValue(); 8262 } 8263 8264 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8265 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8266 8267 ReuseLoadInfo RLI; 8268 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8269 8270 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8271 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8272 } 8273 8274 // We're trying to insert a regular store, S, and then a load, L. If the 8275 // incoming value, O, is a load, we might just be able to have our load use the 8276 // address used by O. However, we don't know if anything else will store to 8277 // that address before we can load from it. To prevent this situation, we need 8278 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8279 // the same chain operand as O, we create a token factor from the chain results 8280 // of O and L, and we replace all uses of O's chain result with that token 8281 // factor (see spliceIntoChain below for this last part). 8282 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8283 ReuseLoadInfo &RLI, 8284 SelectionDAG &DAG, 8285 ISD::LoadExtType ET) const { 8286 // Conservatively skip reusing for constrained FP nodes. 8287 if (Op->isStrictFPOpcode()) 8288 return false; 8289 8290 SDLoc dl(Op); 8291 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8292 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8293 if (ET == ISD::NON_EXTLOAD && 8294 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8295 isOperationLegalOrCustom(Op.getOpcode(), 8296 Op.getOperand(0).getValueType())) { 8297 8298 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8299 return true; 8300 } 8301 8302 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8303 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8304 LD->isNonTemporal()) 8305 return false; 8306 if (LD->getMemoryVT() != MemVT) 8307 return false; 8308 8309 RLI.Ptr = LD->getBasePtr(); 8310 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8311 assert(LD->getAddressingMode() == ISD::PRE_INC && 8312 "Non-pre-inc AM on PPC?"); 8313 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8314 LD->getOffset()); 8315 } 8316 8317 RLI.Chain = LD->getChain(); 8318 RLI.MPI = LD->getPointerInfo(); 8319 RLI.IsDereferenceable = LD->isDereferenceable(); 8320 RLI.IsInvariant = LD->isInvariant(); 8321 RLI.Alignment = LD->getAlign(); 8322 RLI.AAInfo = LD->getAAInfo(); 8323 RLI.Ranges = LD->getRanges(); 8324 8325 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8326 return true; 8327 } 8328 8329 // Given the head of the old chain, ResChain, insert a token factor containing 8330 // it and NewResChain, and make users of ResChain now be users of that token 8331 // factor. 8332 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8333 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8334 SDValue NewResChain, 8335 SelectionDAG &DAG) const { 8336 if (!ResChain) 8337 return; 8338 8339 SDLoc dl(NewResChain); 8340 8341 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8342 NewResChain, DAG.getUNDEF(MVT::Other)); 8343 assert(TF.getNode() != NewResChain.getNode() && 8344 "A new TF really is required here"); 8345 8346 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8347 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8348 } 8349 8350 /// Analyze profitability of direct move 8351 /// prefer float load to int load plus direct move 8352 /// when there is no integer use of int load 8353 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8354 SDNode *Origin = Op.getOperand(0).getNode(); 8355 if (Origin->getOpcode() != ISD::LOAD) 8356 return true; 8357 8358 // If there is no LXSIBZX/LXSIHZX, like Power8, 8359 // prefer direct move if the memory size is 1 or 2 bytes. 8360 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8361 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8362 return true; 8363 8364 for (SDNode::use_iterator UI = Origin->use_begin(), 8365 UE = Origin->use_end(); 8366 UI != UE; ++UI) { 8367 8368 // Only look at the users of the loaded value. 8369 if (UI.getUse().get().getResNo() != 0) 8370 continue; 8371 8372 if (UI->getOpcode() != ISD::SINT_TO_FP && 8373 UI->getOpcode() != ISD::UINT_TO_FP && 8374 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8375 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8376 return true; 8377 } 8378 8379 return false; 8380 } 8381 8382 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8383 const PPCSubtarget &Subtarget, 8384 SDValue Chain = SDValue()) { 8385 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8386 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8387 SDLoc dl(Op); 8388 // If we have FCFIDS, then use it when converting to single-precision. 8389 // Otherwise, convert to double-precision and then round. 8390 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8391 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8392 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8393 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8394 if (Op->isStrictFPOpcode()) { 8395 if (!Chain) 8396 Chain = Op.getOperand(0); 8397 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, {ConvTy, MVT::Other}, 8398 {Chain, Src}); 8399 } else 8400 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8401 } 8402 8403 /// Custom lowers integer to floating point conversions to use 8404 /// the direct move instructions available in ISA 2.07 to avoid the 8405 /// need for load/store combinations. 8406 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8407 SelectionDAG &DAG, 8408 const SDLoc &dl) const { 8409 assert((Op.getValueType() == MVT::f32 || 8410 Op.getValueType() == MVT::f64) && 8411 "Invalid floating point type as target of conversion"); 8412 assert(Subtarget.hasFPCVT() && 8413 "Int to FP conversions with direct moves require FPCVT"); 8414 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8415 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8416 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8417 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8418 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8419 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8420 return convertIntToFP(Op, Mov, DAG, Subtarget); 8421 } 8422 8423 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8424 8425 EVT VecVT = Vec.getValueType(); 8426 assert(VecVT.isVector() && "Expected a vector type."); 8427 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8428 8429 EVT EltVT = VecVT.getVectorElementType(); 8430 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8431 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8432 8433 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8434 SmallVector<SDValue, 16> Ops(NumConcat); 8435 Ops[0] = Vec; 8436 SDValue UndefVec = DAG.getUNDEF(VecVT); 8437 for (unsigned i = 1; i < NumConcat; ++i) 8438 Ops[i] = UndefVec; 8439 8440 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8441 } 8442 8443 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8444 const SDLoc &dl) const { 8445 bool IsStrict = Op->isStrictFPOpcode(); 8446 unsigned Opc = Op.getOpcode(); 8447 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8448 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8449 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8450 "Unexpected conversion type"); 8451 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8452 "Supports conversions to v2f64/v4f32 only."); 8453 8454 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8455 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8456 8457 SDValue Wide = widenVec(DAG, Src, dl); 8458 EVT WideVT = Wide.getValueType(); 8459 unsigned WideNumElts = WideVT.getVectorNumElements(); 8460 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8461 8462 SmallVector<int, 16> ShuffV; 8463 for (unsigned i = 0; i < WideNumElts; ++i) 8464 ShuffV.push_back(i + WideNumElts); 8465 8466 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8467 int SaveElts = FourEltRes ? 4 : 2; 8468 if (Subtarget.isLittleEndian()) 8469 for (int i = 0; i < SaveElts; i++) 8470 ShuffV[i * Stride] = i; 8471 else 8472 for (int i = 1; i <= SaveElts; i++) 8473 ShuffV[i * Stride - 1] = i - 1; 8474 8475 SDValue ShuffleSrc2 = 8476 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8477 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8478 8479 SDValue Extend; 8480 if (SignedConv) { 8481 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8482 EVT ExtVT = Src.getValueType(); 8483 if (Subtarget.hasP9Altivec()) 8484 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8485 IntermediateVT.getVectorNumElements()); 8486 8487 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8488 DAG.getValueType(ExtVT)); 8489 } else 8490 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8491 8492 if (IsStrict) 8493 return DAG.getNode(Opc, dl, {Op.getValueType(), MVT::Other}, 8494 {Op.getOperand(0), Extend}); 8495 8496 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8497 } 8498 8499 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8500 SelectionDAG &DAG) const { 8501 SDLoc dl(Op); 8502 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8503 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8504 bool IsStrict = Op->isStrictFPOpcode(); 8505 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8506 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8507 8508 EVT InVT = Src.getValueType(); 8509 EVT OutVT = Op.getValueType(); 8510 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8511 isOperationCustom(Op.getOpcode(), InVT)) 8512 return LowerINT_TO_FPVector(Op, DAG, dl); 8513 8514 // Conversions to f128 are legal. 8515 if (Op.getValueType() == MVT::f128) 8516 return Op; 8517 8518 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8519 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8520 return SDValue(); 8521 8522 if (Src.getValueType() == MVT::i1) 8523 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8524 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8525 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8526 8527 // If we have direct moves, we can do all the conversion, skip the store/load 8528 // however, without FPCVT we can't do most conversions. 8529 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8530 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8531 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8532 8533 assert((IsSigned || Subtarget.hasFPCVT()) && 8534 "UINT_TO_FP is supported only with FPCVT"); 8535 8536 if (Src.getValueType() == MVT::i64) { 8537 SDValue SINT = Src; 8538 // When converting to single-precision, we actually need to convert 8539 // to double-precision first and then round to single-precision. 8540 // To avoid double-rounding effects during that operation, we have 8541 // to prepare the input operand. Bits that might be truncated when 8542 // converting to double-precision are replaced by a bit that won't 8543 // be lost at this stage, but is below the single-precision rounding 8544 // position. 8545 // 8546 // However, if -enable-unsafe-fp-math is in effect, accept double 8547 // rounding to avoid the extra overhead. 8548 if (Op.getValueType() == MVT::f32 && 8549 !Subtarget.hasFPCVT() && 8550 !DAG.getTarget().Options.UnsafeFPMath) { 8551 8552 // Twiddle input to make sure the low 11 bits are zero. (If this 8553 // is the case, we are guaranteed the value will fit into the 53 bit 8554 // mantissa of an IEEE double-precision value without rounding.) 8555 // If any of those low 11 bits were not zero originally, make sure 8556 // bit 12 (value 2048) is set instead, so that the final rounding 8557 // to single-precision gets the correct result. 8558 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8559 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8560 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8561 Round, DAG.getConstant(2047, dl, MVT::i64)); 8562 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8563 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8564 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8565 8566 // However, we cannot use that value unconditionally: if the magnitude 8567 // of the input value is small, the bit-twiddling we did above might 8568 // end up visibly changing the output. Fortunately, in that case, we 8569 // don't need to twiddle bits since the original input will convert 8570 // exactly to double-precision floating-point already. Therefore, 8571 // construct a conditional to use the original value if the top 11 8572 // bits are all sign-bit copies, and use the rounded value computed 8573 // above otherwise. 8574 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8575 SINT, DAG.getConstant(53, dl, MVT::i32)); 8576 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8577 Cond, DAG.getConstant(1, dl, MVT::i64)); 8578 Cond = DAG.getSetCC( 8579 dl, 8580 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8581 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8582 8583 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8584 } 8585 8586 ReuseLoadInfo RLI; 8587 SDValue Bits; 8588 8589 MachineFunction &MF = DAG.getMachineFunction(); 8590 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8591 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8592 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8593 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8594 } else if (Subtarget.hasLFIWAX() && 8595 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8596 MachineMemOperand *MMO = 8597 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8598 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8599 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8600 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8601 DAG.getVTList(MVT::f64, MVT::Other), 8602 Ops, MVT::i32, MMO); 8603 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8604 } else if (Subtarget.hasFPCVT() && 8605 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8606 MachineMemOperand *MMO = 8607 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8608 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8609 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8610 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8611 DAG.getVTList(MVT::f64, MVT::Other), 8612 Ops, MVT::i32, MMO); 8613 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8614 } else if (((Subtarget.hasLFIWAX() && 8615 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8616 (Subtarget.hasFPCVT() && 8617 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8618 SINT.getOperand(0).getValueType() == MVT::i32) { 8619 MachineFrameInfo &MFI = MF.getFrameInfo(); 8620 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8621 8622 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8623 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8624 8625 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8626 MachinePointerInfo::getFixedStack( 8627 DAG.getMachineFunction(), FrameIdx)); 8628 Chain = Store; 8629 8630 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8631 "Expected an i32 store"); 8632 8633 RLI.Ptr = FIdx; 8634 RLI.Chain = Chain; 8635 RLI.MPI = 8636 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8637 RLI.Alignment = Align(4); 8638 8639 MachineMemOperand *MMO = 8640 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8641 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8642 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8643 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8644 PPCISD::LFIWZX : PPCISD::LFIWAX, 8645 dl, DAG.getVTList(MVT::f64, MVT::Other), 8646 Ops, MVT::i32, MMO); 8647 Chain = Bits.getValue(1); 8648 } else 8649 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8650 8651 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8652 if (IsStrict) 8653 Chain = FP.getValue(1); 8654 8655 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8656 if (IsStrict) 8657 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8658 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8659 else 8660 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8661 DAG.getIntPtrConstant(0, dl)); 8662 } 8663 return FP; 8664 } 8665 8666 assert(Src.getValueType() == MVT::i32 && 8667 "Unhandled INT_TO_FP type in custom expander!"); 8668 // Since we only generate this in 64-bit mode, we can take advantage of 8669 // 64-bit registers. In particular, sign extend the input value into the 8670 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8671 // then lfd it and fcfid it. 8672 MachineFunction &MF = DAG.getMachineFunction(); 8673 MachineFrameInfo &MFI = MF.getFrameInfo(); 8674 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8675 8676 SDValue Ld; 8677 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8678 ReuseLoadInfo RLI; 8679 bool ReusingLoad; 8680 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8681 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8682 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8683 8684 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8685 MachinePointerInfo::getFixedStack( 8686 DAG.getMachineFunction(), FrameIdx)); 8687 Chain = Store; 8688 8689 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8690 "Expected an i32 store"); 8691 8692 RLI.Ptr = FIdx; 8693 RLI.Chain = Chain; 8694 RLI.MPI = 8695 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8696 RLI.Alignment = Align(4); 8697 } 8698 8699 MachineMemOperand *MMO = 8700 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8701 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8702 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8703 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8704 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8705 MVT::i32, MMO); 8706 Chain = Ld.getValue(1); 8707 if (ReusingLoad) 8708 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8709 } else { 8710 assert(Subtarget.isPPC64() && 8711 "i32->FP without LFIWAX supported only on PPC64"); 8712 8713 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8714 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8715 8716 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8717 8718 // STD the extended value into the stack slot. 8719 SDValue Store = DAG.getStore( 8720 Chain, dl, Ext64, FIdx, 8721 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8722 Chain = Store; 8723 8724 // Load the value as a double. 8725 Ld = DAG.getLoad( 8726 MVT::f64, dl, Chain, FIdx, 8727 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8728 Chain = Ld.getValue(1); 8729 } 8730 8731 // FCFID it and return it. 8732 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8733 if (IsStrict) 8734 Chain = FP.getValue(1); 8735 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8736 if (IsStrict) 8737 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8738 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8739 else 8740 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8741 DAG.getIntPtrConstant(0, dl)); 8742 } 8743 return FP; 8744 } 8745 8746 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8747 SelectionDAG &DAG) const { 8748 SDLoc dl(Op); 8749 /* 8750 The rounding mode is in bits 30:31 of FPSR, and has the following 8751 settings: 8752 00 Round to nearest 8753 01 Round to 0 8754 10 Round to +inf 8755 11 Round to -inf 8756 8757 FLT_ROUNDS, on the other hand, expects the following: 8758 -1 Undefined 8759 0 Round to 0 8760 1 Round to nearest 8761 2 Round to +inf 8762 3 Round to -inf 8763 8764 To perform the conversion, we do: 8765 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8766 */ 8767 8768 MachineFunction &MF = DAG.getMachineFunction(); 8769 EVT VT = Op.getValueType(); 8770 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8771 8772 // Save FP Control Word to register 8773 SDValue Chain = Op.getOperand(0); 8774 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8775 Chain = MFFS.getValue(1); 8776 8777 // Save FP register to stack slot 8778 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8779 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8780 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8781 8782 // Load FP Control Word from low 32 bits of stack slot. 8783 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8784 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8785 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8786 Chain = CWD.getValue(1); 8787 8788 // Transform as necessary 8789 SDValue CWD1 = 8790 DAG.getNode(ISD::AND, dl, MVT::i32, 8791 CWD, DAG.getConstant(3, dl, MVT::i32)); 8792 SDValue CWD2 = 8793 DAG.getNode(ISD::SRL, dl, MVT::i32, 8794 DAG.getNode(ISD::AND, dl, MVT::i32, 8795 DAG.getNode(ISD::XOR, dl, MVT::i32, 8796 CWD, DAG.getConstant(3, dl, MVT::i32)), 8797 DAG.getConstant(3, dl, MVT::i32)), 8798 DAG.getConstant(1, dl, MVT::i32)); 8799 8800 SDValue RetVal = 8801 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8802 8803 RetVal = 8804 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8805 dl, VT, RetVal); 8806 8807 return DAG.getMergeValues({RetVal, Chain}, dl); 8808 } 8809 8810 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8811 EVT VT = Op.getValueType(); 8812 unsigned BitWidth = VT.getSizeInBits(); 8813 SDLoc dl(Op); 8814 assert(Op.getNumOperands() == 3 && 8815 VT == Op.getOperand(1).getValueType() && 8816 "Unexpected SHL!"); 8817 8818 // Expand into a bunch of logical ops. Note that these ops 8819 // depend on the PPC behavior for oversized shift amounts. 8820 SDValue Lo = Op.getOperand(0); 8821 SDValue Hi = Op.getOperand(1); 8822 SDValue Amt = Op.getOperand(2); 8823 EVT AmtVT = Amt.getValueType(); 8824 8825 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8826 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8827 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8828 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8829 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8830 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8831 DAG.getConstant(-BitWidth, dl, AmtVT)); 8832 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8833 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8834 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8835 SDValue OutOps[] = { OutLo, OutHi }; 8836 return DAG.getMergeValues(OutOps, dl); 8837 } 8838 8839 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8840 EVT VT = Op.getValueType(); 8841 SDLoc dl(Op); 8842 unsigned BitWidth = VT.getSizeInBits(); 8843 assert(Op.getNumOperands() == 3 && 8844 VT == Op.getOperand(1).getValueType() && 8845 "Unexpected SRL!"); 8846 8847 // Expand into a bunch of logical ops. Note that these ops 8848 // depend on the PPC behavior for oversized shift amounts. 8849 SDValue Lo = Op.getOperand(0); 8850 SDValue Hi = Op.getOperand(1); 8851 SDValue Amt = Op.getOperand(2); 8852 EVT AmtVT = Amt.getValueType(); 8853 8854 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8855 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8856 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8857 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8858 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8859 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8860 DAG.getConstant(-BitWidth, dl, AmtVT)); 8861 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8862 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8863 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8864 SDValue OutOps[] = { OutLo, OutHi }; 8865 return DAG.getMergeValues(OutOps, dl); 8866 } 8867 8868 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8869 SDLoc dl(Op); 8870 EVT VT = Op.getValueType(); 8871 unsigned BitWidth = VT.getSizeInBits(); 8872 assert(Op.getNumOperands() == 3 && 8873 VT == Op.getOperand(1).getValueType() && 8874 "Unexpected SRA!"); 8875 8876 // Expand into a bunch of logical ops, followed by a select_cc. 8877 SDValue Lo = Op.getOperand(0); 8878 SDValue Hi = Op.getOperand(1); 8879 SDValue Amt = Op.getOperand(2); 8880 EVT AmtVT = Amt.getValueType(); 8881 8882 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8883 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8884 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8885 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8886 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8887 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8888 DAG.getConstant(-BitWidth, dl, AmtVT)); 8889 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8890 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8891 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8892 Tmp4, Tmp6, ISD::SETLE); 8893 SDValue OutOps[] = { OutLo, OutHi }; 8894 return DAG.getMergeValues(OutOps, dl); 8895 } 8896 8897 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8898 SelectionDAG &DAG) const { 8899 SDLoc dl(Op); 8900 EVT VT = Op.getValueType(); 8901 unsigned BitWidth = VT.getSizeInBits(); 8902 8903 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8904 SDValue X = Op.getOperand(0); 8905 SDValue Y = Op.getOperand(1); 8906 SDValue Z = Op.getOperand(2); 8907 EVT AmtVT = Z.getValueType(); 8908 8909 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8910 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8911 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8912 // on PowerPC shift by BW being well defined. 8913 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8914 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8915 SDValue SubZ = 8916 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8917 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8918 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8919 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8920 } 8921 8922 //===----------------------------------------------------------------------===// 8923 // Vector related lowering. 8924 // 8925 8926 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8927 /// element size of SplatSize. Cast the result to VT. 8928 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8929 SelectionDAG &DAG, const SDLoc &dl) { 8930 static const MVT VTys[] = { // canonical VT to use for each size. 8931 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8932 }; 8933 8934 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8935 8936 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8937 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8938 SplatSize = 1; 8939 Val = 0xFF; 8940 } 8941 8942 EVT CanonicalVT = VTys[SplatSize-1]; 8943 8944 // Build a canonical splat for this value. 8945 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8946 } 8947 8948 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8949 /// specified intrinsic ID. 8950 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8951 const SDLoc &dl, EVT DestVT = MVT::Other) { 8952 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8953 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8954 DAG.getConstant(IID, dl, MVT::i32), Op); 8955 } 8956 8957 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8958 /// specified intrinsic ID. 8959 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8960 SelectionDAG &DAG, const SDLoc &dl, 8961 EVT DestVT = MVT::Other) { 8962 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8963 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8964 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8965 } 8966 8967 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8968 /// specified intrinsic ID. 8969 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8970 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8971 EVT DestVT = MVT::Other) { 8972 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8973 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8974 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8975 } 8976 8977 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8978 /// amount. The result has the specified value type. 8979 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8980 SelectionDAG &DAG, const SDLoc &dl) { 8981 // Force LHS/RHS to be the right type. 8982 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8983 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8984 8985 int Ops[16]; 8986 for (unsigned i = 0; i != 16; ++i) 8987 Ops[i] = i + Amt; 8988 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8989 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8990 } 8991 8992 /// Do we have an efficient pattern in a .td file for this node? 8993 /// 8994 /// \param V - pointer to the BuildVectorSDNode being matched 8995 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8996 /// 8997 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8998 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8999 /// the opposite is true (expansion is beneficial) are: 9000 /// - The node builds a vector out of integers that are not 32 or 64-bits 9001 /// - The node builds a vector out of constants 9002 /// - The node is a "load-and-splat" 9003 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9004 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9005 bool HasDirectMove, 9006 bool HasP8Vector) { 9007 EVT VecVT = V->getValueType(0); 9008 bool RightType = VecVT == MVT::v2f64 || 9009 (HasP8Vector && VecVT == MVT::v4f32) || 9010 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9011 if (!RightType) 9012 return false; 9013 9014 bool IsSplat = true; 9015 bool IsLoad = false; 9016 SDValue Op0 = V->getOperand(0); 9017 9018 // This function is called in a block that confirms the node is not a constant 9019 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9020 // different constants. 9021 if (V->isConstant()) 9022 return false; 9023 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9024 if (V->getOperand(i).isUndef()) 9025 return false; 9026 // We want to expand nodes that represent load-and-splat even if the 9027 // loaded value is a floating point truncation or conversion to int. 9028 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9029 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9030 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9031 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9032 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9033 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9034 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9035 IsLoad = true; 9036 // If the operands are different or the input is not a load and has more 9037 // uses than just this BV node, then it isn't a splat. 9038 if (V->getOperand(i) != Op0 || 9039 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9040 IsSplat = false; 9041 } 9042 return !(IsSplat && IsLoad); 9043 } 9044 9045 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9046 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9047 9048 SDLoc dl(Op); 9049 SDValue Op0 = Op->getOperand(0); 9050 9051 if ((Op.getValueType() != MVT::f128) || 9052 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9053 (Op0.getOperand(0).getValueType() != MVT::i64) || 9054 (Op0.getOperand(1).getValueType() != MVT::i64)) 9055 return SDValue(); 9056 9057 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9058 Op0.getOperand(1)); 9059 } 9060 9061 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9062 const SDValue *InputLoad = &Op; 9063 if (InputLoad->getOpcode() == ISD::BITCAST) 9064 InputLoad = &InputLoad->getOperand(0); 9065 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9066 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9067 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9068 InputLoad = &InputLoad->getOperand(0); 9069 } 9070 if (InputLoad->getOpcode() != ISD::LOAD) 9071 return nullptr; 9072 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9073 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9074 } 9075 9076 // Convert the argument APFloat to a single precision APFloat if there is no 9077 // loss in information during the conversion to single precision APFloat and the 9078 // resulting number is not a denormal number. Return true if successful. 9079 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9080 APFloat APFloatToConvert = ArgAPFloat; 9081 bool LosesInfo = true; 9082 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9083 &LosesInfo); 9084 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9085 if (Success) 9086 ArgAPFloat = APFloatToConvert; 9087 return Success; 9088 } 9089 9090 // Bitcast the argument APInt to a double and convert it to a single precision 9091 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9092 // argument if there is no loss in information during the conversion from 9093 // double to single precision APFloat and the resulting number is not a denormal 9094 // number. Return true if successful. 9095 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9096 double DpValue = ArgAPInt.bitsToDouble(); 9097 APFloat APFloatDp(DpValue); 9098 bool Success = convertToNonDenormSingle(APFloatDp); 9099 if (Success) 9100 ArgAPInt = APFloatDp.bitcastToAPInt(); 9101 return Success; 9102 } 9103 9104 // If this is a case we can't handle, return null and let the default 9105 // expansion code take care of it. If we CAN select this case, and if it 9106 // selects to a single instruction, return Op. Otherwise, if we can codegen 9107 // this case more efficiently than a constant pool load, lower it to the 9108 // sequence of ops that should be used. 9109 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9110 SelectionDAG &DAG) const { 9111 SDLoc dl(Op); 9112 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9113 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9114 9115 // Check if this is a splat of a constant value. 9116 APInt APSplatBits, APSplatUndef; 9117 unsigned SplatBitSize; 9118 bool HasAnyUndefs; 9119 bool BVNIsConstantSplat = 9120 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9121 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9122 9123 // If it is a splat of a double, check if we can shrink it to a 32 bit 9124 // non-denormal float which when converted back to double gives us the same 9125 // double. This is to exploit the XXSPLTIDP instruction. 9126 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9127 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9128 convertToNonDenormSingle(APSplatBits)) { 9129 SDValue SplatNode = DAG.getNode( 9130 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9131 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9132 return DAG.getBitcast(Op.getValueType(), SplatNode); 9133 } 9134 9135 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9136 9137 bool IsPermutedLoad = false; 9138 const SDValue *InputLoad = 9139 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9140 // Handle load-and-splat patterns as we have instructions that will do this 9141 // in one go. 9142 if (InputLoad && DAG.isSplatValue(Op, true)) { 9143 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9144 9145 // We have handling for 4 and 8 byte elements. 9146 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9147 9148 // Checking for a single use of this load, we have to check for vector 9149 // width (128 bits) / ElementSize uses (since each operand of the 9150 // BUILD_VECTOR is a separate use of the value. 9151 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9152 ((Subtarget.hasVSX() && ElementSize == 64) || 9153 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9154 SDValue Ops[] = { 9155 LD->getChain(), // Chain 9156 LD->getBasePtr(), // Ptr 9157 DAG.getValueType(Op.getValueType()) // VT 9158 }; 9159 return 9160 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9161 DAG.getVTList(Op.getValueType(), MVT::Other), 9162 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9163 } 9164 } 9165 9166 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9167 // lowered to VSX instructions under certain conditions. 9168 // Without VSX, there is no pattern more efficient than expanding the node. 9169 if (Subtarget.hasVSX() && 9170 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9171 Subtarget.hasP8Vector())) 9172 return Op; 9173 return SDValue(); 9174 } 9175 9176 uint64_t SplatBits = APSplatBits.getZExtValue(); 9177 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9178 unsigned SplatSize = SplatBitSize / 8; 9179 9180 // First, handle single instruction cases. 9181 9182 // All zeros? 9183 if (SplatBits == 0) { 9184 // Canonicalize all zero vectors to be v4i32. 9185 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9186 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9187 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9188 } 9189 return Op; 9190 } 9191 9192 // We have XXSPLTIW for constant splats four bytes wide. 9193 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9194 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9195 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9196 // turned into a 4-byte splat of 0xABABABAB. 9197 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9198 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9199 Op.getValueType(), DAG, dl); 9200 9201 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9202 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9203 dl); 9204 9205 // We have XXSPLTIB for constant splats one byte wide. 9206 if (Subtarget.hasP9Vector() && SplatSize == 1) 9207 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9208 dl); 9209 9210 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9211 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9212 (32-SplatBitSize)); 9213 if (SextVal >= -16 && SextVal <= 15) 9214 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9215 dl); 9216 9217 // Two instruction sequences. 9218 9219 // If this value is in the range [-32,30] and is even, use: 9220 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9221 // If this value is in the range [17,31] and is odd, use: 9222 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9223 // If this value is in the range [-31,-17] and is odd, use: 9224 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9225 // Note the last two are three-instruction sequences. 9226 if (SextVal >= -32 && SextVal <= 31) { 9227 // To avoid having these optimizations undone by constant folding, 9228 // we convert to a pseudo that will be expanded later into one of 9229 // the above forms. 9230 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9231 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9232 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9233 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9234 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9235 if (VT == Op.getValueType()) 9236 return RetVal; 9237 else 9238 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9239 } 9240 9241 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9242 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9243 // for fneg/fabs. 9244 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9245 // Make -1 and vspltisw -1: 9246 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9247 9248 // Make the VSLW intrinsic, computing 0x8000_0000. 9249 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9250 OnesV, DAG, dl); 9251 9252 // xor by OnesV to invert it. 9253 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9254 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9255 } 9256 9257 // Check to see if this is a wide variety of vsplti*, binop self cases. 9258 static const signed char SplatCsts[] = { 9259 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9260 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9261 }; 9262 9263 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9264 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9265 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9266 int i = SplatCsts[idx]; 9267 9268 // Figure out what shift amount will be used by altivec if shifted by i in 9269 // this splat size. 9270 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9271 9272 // vsplti + shl self. 9273 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9274 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9275 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9276 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9277 Intrinsic::ppc_altivec_vslw 9278 }; 9279 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9280 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9281 } 9282 9283 // vsplti + srl self. 9284 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9285 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9286 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9287 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9288 Intrinsic::ppc_altivec_vsrw 9289 }; 9290 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9291 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9292 } 9293 9294 // vsplti + sra self. 9295 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9296 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9297 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9298 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9299 Intrinsic::ppc_altivec_vsraw 9300 }; 9301 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9302 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9303 } 9304 9305 // vsplti + rol self. 9306 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9307 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9308 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9309 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9310 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9311 Intrinsic::ppc_altivec_vrlw 9312 }; 9313 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9314 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9315 } 9316 9317 // t = vsplti c, result = vsldoi t, t, 1 9318 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9319 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9320 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9321 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9322 } 9323 // t = vsplti c, result = vsldoi t, t, 2 9324 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9325 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9326 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9327 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9328 } 9329 // t = vsplti c, result = vsldoi t, t, 3 9330 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9331 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9332 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9333 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9334 } 9335 } 9336 9337 return SDValue(); 9338 } 9339 9340 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9341 /// the specified operations to build the shuffle. 9342 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9343 SDValue RHS, SelectionDAG &DAG, 9344 const SDLoc &dl) { 9345 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9346 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9347 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9348 9349 enum { 9350 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9351 OP_VMRGHW, 9352 OP_VMRGLW, 9353 OP_VSPLTISW0, 9354 OP_VSPLTISW1, 9355 OP_VSPLTISW2, 9356 OP_VSPLTISW3, 9357 OP_VSLDOI4, 9358 OP_VSLDOI8, 9359 OP_VSLDOI12 9360 }; 9361 9362 if (OpNum == OP_COPY) { 9363 if (LHSID == (1*9+2)*9+3) return LHS; 9364 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9365 return RHS; 9366 } 9367 9368 SDValue OpLHS, OpRHS; 9369 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9370 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9371 9372 int ShufIdxs[16]; 9373 switch (OpNum) { 9374 default: llvm_unreachable("Unknown i32 permute!"); 9375 case OP_VMRGHW: 9376 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9377 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9378 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9379 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9380 break; 9381 case OP_VMRGLW: 9382 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9383 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9384 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9385 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9386 break; 9387 case OP_VSPLTISW0: 9388 for (unsigned i = 0; i != 16; ++i) 9389 ShufIdxs[i] = (i&3)+0; 9390 break; 9391 case OP_VSPLTISW1: 9392 for (unsigned i = 0; i != 16; ++i) 9393 ShufIdxs[i] = (i&3)+4; 9394 break; 9395 case OP_VSPLTISW2: 9396 for (unsigned i = 0; i != 16; ++i) 9397 ShufIdxs[i] = (i&3)+8; 9398 break; 9399 case OP_VSPLTISW3: 9400 for (unsigned i = 0; i != 16; ++i) 9401 ShufIdxs[i] = (i&3)+12; 9402 break; 9403 case OP_VSLDOI4: 9404 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9405 case OP_VSLDOI8: 9406 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9407 case OP_VSLDOI12: 9408 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9409 } 9410 EVT VT = OpLHS.getValueType(); 9411 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9412 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9413 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9414 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9415 } 9416 9417 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9418 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9419 /// SDValue. 9420 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9421 SelectionDAG &DAG) const { 9422 const unsigned BytesInVector = 16; 9423 bool IsLE = Subtarget.isLittleEndian(); 9424 SDLoc dl(N); 9425 SDValue V1 = N->getOperand(0); 9426 SDValue V2 = N->getOperand(1); 9427 unsigned ShiftElts = 0, InsertAtByte = 0; 9428 bool Swap = false; 9429 9430 // Shifts required to get the byte we want at element 7. 9431 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9432 0, 15, 14, 13, 12, 11, 10, 9}; 9433 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9434 1, 2, 3, 4, 5, 6, 7, 8}; 9435 9436 ArrayRef<int> Mask = N->getMask(); 9437 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9438 9439 // For each mask element, find out if we're just inserting something 9440 // from V2 into V1 or vice versa. 9441 // Possible permutations inserting an element from V2 into V1: 9442 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9443 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9444 // ... 9445 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9446 // Inserting from V1 into V2 will be similar, except mask range will be 9447 // [16,31]. 9448 9449 bool FoundCandidate = false; 9450 // If both vector operands for the shuffle are the same vector, the mask 9451 // will contain only elements from the first one and the second one will be 9452 // undef. 9453 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9454 // Go through the mask of half-words to find an element that's being moved 9455 // from one vector to the other. 9456 for (unsigned i = 0; i < BytesInVector; ++i) { 9457 unsigned CurrentElement = Mask[i]; 9458 // If 2nd operand is undefined, we should only look for element 7 in the 9459 // Mask. 9460 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9461 continue; 9462 9463 bool OtherElementsInOrder = true; 9464 // Examine the other elements in the Mask to see if they're in original 9465 // order. 9466 for (unsigned j = 0; j < BytesInVector; ++j) { 9467 if (j == i) 9468 continue; 9469 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9470 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9471 // in which we always assume we're always picking from the 1st operand. 9472 int MaskOffset = 9473 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9474 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9475 OtherElementsInOrder = false; 9476 break; 9477 } 9478 } 9479 // If other elements are in original order, we record the number of shifts 9480 // we need to get the element we want into element 7. Also record which byte 9481 // in the vector we should insert into. 9482 if (OtherElementsInOrder) { 9483 // If 2nd operand is undefined, we assume no shifts and no swapping. 9484 if (V2.isUndef()) { 9485 ShiftElts = 0; 9486 Swap = false; 9487 } else { 9488 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9489 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9490 : BigEndianShifts[CurrentElement & 0xF]; 9491 Swap = CurrentElement < BytesInVector; 9492 } 9493 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9494 FoundCandidate = true; 9495 break; 9496 } 9497 } 9498 9499 if (!FoundCandidate) 9500 return SDValue(); 9501 9502 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9503 // optionally with VECSHL if shift is required. 9504 if (Swap) 9505 std::swap(V1, V2); 9506 if (V2.isUndef()) 9507 V2 = V1; 9508 if (ShiftElts) { 9509 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9510 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9511 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9512 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9513 } 9514 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9515 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9516 } 9517 9518 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9519 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9520 /// SDValue. 9521 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9522 SelectionDAG &DAG) const { 9523 const unsigned NumHalfWords = 8; 9524 const unsigned BytesInVector = NumHalfWords * 2; 9525 // Check that the shuffle is on half-words. 9526 if (!isNByteElemShuffleMask(N, 2, 1)) 9527 return SDValue(); 9528 9529 bool IsLE = Subtarget.isLittleEndian(); 9530 SDLoc dl(N); 9531 SDValue V1 = N->getOperand(0); 9532 SDValue V2 = N->getOperand(1); 9533 unsigned ShiftElts = 0, InsertAtByte = 0; 9534 bool Swap = false; 9535 9536 // Shifts required to get the half-word we want at element 3. 9537 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9538 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9539 9540 uint32_t Mask = 0; 9541 uint32_t OriginalOrderLow = 0x1234567; 9542 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9543 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9544 // 32-bit space, only need 4-bit nibbles per element. 9545 for (unsigned i = 0; i < NumHalfWords; ++i) { 9546 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9547 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9548 } 9549 9550 // For each mask element, find out if we're just inserting something 9551 // from V2 into V1 or vice versa. Possible permutations inserting an element 9552 // from V2 into V1: 9553 // X, 1, 2, 3, 4, 5, 6, 7 9554 // 0, X, 2, 3, 4, 5, 6, 7 9555 // 0, 1, X, 3, 4, 5, 6, 7 9556 // 0, 1, 2, X, 4, 5, 6, 7 9557 // 0, 1, 2, 3, X, 5, 6, 7 9558 // 0, 1, 2, 3, 4, X, 6, 7 9559 // 0, 1, 2, 3, 4, 5, X, 7 9560 // 0, 1, 2, 3, 4, 5, 6, X 9561 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9562 9563 bool FoundCandidate = false; 9564 // Go through the mask of half-words to find an element that's being moved 9565 // from one vector to the other. 9566 for (unsigned i = 0; i < NumHalfWords; ++i) { 9567 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9568 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9569 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9570 uint32_t TargetOrder = 0x0; 9571 9572 // If both vector operands for the shuffle are the same vector, the mask 9573 // will contain only elements from the first one and the second one will be 9574 // undef. 9575 if (V2.isUndef()) { 9576 ShiftElts = 0; 9577 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9578 TargetOrder = OriginalOrderLow; 9579 Swap = false; 9580 // Skip if not the correct element or mask of other elements don't equal 9581 // to our expected order. 9582 if (MaskOneElt == VINSERTHSrcElem && 9583 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9584 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9585 FoundCandidate = true; 9586 break; 9587 } 9588 } else { // If both operands are defined. 9589 // Target order is [8,15] if the current mask is between [0,7]. 9590 TargetOrder = 9591 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9592 // Skip if mask of other elements don't equal our expected order. 9593 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9594 // We only need the last 3 bits for the number of shifts. 9595 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9596 : BigEndianShifts[MaskOneElt & 0x7]; 9597 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9598 Swap = MaskOneElt < NumHalfWords; 9599 FoundCandidate = true; 9600 break; 9601 } 9602 } 9603 } 9604 9605 if (!FoundCandidate) 9606 return SDValue(); 9607 9608 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9609 // optionally with VECSHL if shift is required. 9610 if (Swap) 9611 std::swap(V1, V2); 9612 if (V2.isUndef()) 9613 V2 = V1; 9614 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9615 if (ShiftElts) { 9616 // Double ShiftElts because we're left shifting on v16i8 type. 9617 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9618 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9619 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9620 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9621 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9622 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9623 } 9624 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9625 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9626 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9627 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9628 } 9629 9630 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9631 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9632 /// return the default SDValue. 9633 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9634 SelectionDAG &DAG) const { 9635 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9636 // to v16i8. Peek through the bitcasts to get the actual operands. 9637 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9638 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9639 9640 auto ShuffleMask = SVN->getMask(); 9641 SDValue VecShuffle(SVN, 0); 9642 SDLoc DL(SVN); 9643 9644 // Check that we have a four byte shuffle. 9645 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9646 return SDValue(); 9647 9648 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9649 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9650 std::swap(LHS, RHS); 9651 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9652 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9653 } 9654 9655 // Ensure that the RHS is a vector of constants. 9656 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9657 if (!BVN) 9658 return SDValue(); 9659 9660 // Check if RHS is a splat of 4-bytes (or smaller). 9661 APInt APSplatValue, APSplatUndef; 9662 unsigned SplatBitSize; 9663 bool HasAnyUndefs; 9664 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9665 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9666 SplatBitSize > 32) 9667 return SDValue(); 9668 9669 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9670 // The instruction splats a constant C into two words of the source vector 9671 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9672 // Thus we check that the shuffle mask is the equivalent of 9673 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9674 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9675 // within each word are consecutive, so we only need to check the first byte. 9676 SDValue Index; 9677 bool IsLE = Subtarget.isLittleEndian(); 9678 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9679 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9680 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9681 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9682 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9683 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9684 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9685 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9686 else 9687 return SDValue(); 9688 9689 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9690 // for XXSPLTI32DX. 9691 unsigned SplatVal = APSplatValue.getZExtValue(); 9692 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9693 SplatVal |= (SplatVal << SplatBitSize); 9694 9695 SDValue SplatNode = DAG.getNode( 9696 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9697 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9698 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9699 } 9700 9701 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9702 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9703 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9704 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9705 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9706 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9707 assert(Op.getValueType() == MVT::v1i128 && 9708 "Only set v1i128 as custom, other type shouldn't reach here!"); 9709 SDLoc dl(Op); 9710 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9711 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9712 unsigned SHLAmt = N1.getConstantOperandVal(0); 9713 if (SHLAmt % 8 == 0) { 9714 SmallVector<int, 16> Mask(16, 0); 9715 std::iota(Mask.begin(), Mask.end(), 0); 9716 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9717 if (SDValue Shuffle = 9718 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9719 DAG.getUNDEF(MVT::v16i8), Mask)) 9720 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9721 } 9722 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9723 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9724 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9725 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9726 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9727 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9728 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9729 } 9730 9731 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9732 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9733 /// return the code it can be lowered into. Worst case, it can always be 9734 /// lowered into a vperm. 9735 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9736 SelectionDAG &DAG) const { 9737 SDLoc dl(Op); 9738 SDValue V1 = Op.getOperand(0); 9739 SDValue V2 = Op.getOperand(1); 9740 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9741 9742 // Any nodes that were combined in the target-independent combiner prior 9743 // to vector legalization will not be sent to the target combine. Try to 9744 // combine it here. 9745 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9746 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9747 return NewShuffle; 9748 Op = NewShuffle; 9749 SVOp = cast<ShuffleVectorSDNode>(Op); 9750 V1 = Op.getOperand(0); 9751 V2 = Op.getOperand(1); 9752 } 9753 EVT VT = Op.getValueType(); 9754 bool isLittleEndian = Subtarget.isLittleEndian(); 9755 9756 unsigned ShiftElts, InsertAtByte; 9757 bool Swap = false; 9758 9759 // If this is a load-and-splat, we can do that with a single instruction 9760 // in some cases. However if the load has multiple uses, we don't want to 9761 // combine it because that will just produce multiple loads. 9762 bool IsPermutedLoad = false; 9763 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9764 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9765 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9766 InputLoad->hasOneUse()) { 9767 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9768 int SplatIdx = 9769 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9770 9771 // The splat index for permuted loads will be in the left half of the vector 9772 // which is strictly wider than the loaded value by 8 bytes. So we need to 9773 // adjust the splat index to point to the correct address in memory. 9774 if (IsPermutedLoad) { 9775 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9776 SplatIdx += IsFourByte ? 2 : 1; 9777 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9778 "Splat of a value outside of the loaded memory"); 9779 } 9780 9781 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9782 // For 4-byte load-and-splat, we need Power9. 9783 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9784 uint64_t Offset = 0; 9785 if (IsFourByte) 9786 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9787 else 9788 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9789 9790 SDValue BasePtr = LD->getBasePtr(); 9791 if (Offset != 0) 9792 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9793 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9794 SDValue Ops[] = { 9795 LD->getChain(), // Chain 9796 BasePtr, // BasePtr 9797 DAG.getValueType(Op.getValueType()) // VT 9798 }; 9799 SDVTList VTL = 9800 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9801 SDValue LdSplt = 9802 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9803 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9804 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9805 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9806 return LdSplt; 9807 } 9808 } 9809 if (Subtarget.hasP9Vector() && 9810 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9811 isLittleEndian)) { 9812 if (Swap) 9813 std::swap(V1, V2); 9814 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9815 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9816 if (ShiftElts) { 9817 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9818 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9819 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9820 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9821 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9822 } 9823 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9824 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9825 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9826 } 9827 9828 if (Subtarget.hasPrefixInstrs()) { 9829 SDValue SplatInsertNode; 9830 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9831 return SplatInsertNode; 9832 } 9833 9834 if (Subtarget.hasP9Altivec()) { 9835 SDValue NewISDNode; 9836 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9837 return NewISDNode; 9838 9839 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9840 return NewISDNode; 9841 } 9842 9843 if (Subtarget.hasVSX() && 9844 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9845 if (Swap) 9846 std::swap(V1, V2); 9847 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9848 SDValue Conv2 = 9849 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9850 9851 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9852 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9853 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9854 } 9855 9856 if (Subtarget.hasVSX() && 9857 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9858 if (Swap) 9859 std::swap(V1, V2); 9860 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9861 SDValue Conv2 = 9862 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9863 9864 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9865 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9866 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9867 } 9868 9869 if (Subtarget.hasP9Vector()) { 9870 if (PPC::isXXBRHShuffleMask(SVOp)) { 9871 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9872 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9873 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9874 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9875 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9876 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9877 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9878 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9879 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9880 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9881 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9882 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9883 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9884 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9885 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9886 } 9887 } 9888 9889 if (Subtarget.hasVSX()) { 9890 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9891 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9892 9893 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9894 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9895 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9896 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9897 } 9898 9899 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9900 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9901 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9902 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9903 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9904 } 9905 } 9906 9907 // Cases that are handled by instructions that take permute immediates 9908 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9909 // selected by the instruction selector. 9910 if (V2.isUndef()) { 9911 if (PPC::isSplatShuffleMask(SVOp, 1) || 9912 PPC::isSplatShuffleMask(SVOp, 2) || 9913 PPC::isSplatShuffleMask(SVOp, 4) || 9914 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9915 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9916 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9917 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9918 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9919 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9920 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9921 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9922 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9923 (Subtarget.hasP8Altivec() && ( 9924 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9925 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9926 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9927 return Op; 9928 } 9929 } 9930 9931 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9932 // and produce a fixed permutation. If any of these match, do not lower to 9933 // VPERM. 9934 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9935 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9936 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9937 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9938 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9939 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9940 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9941 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9942 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9943 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9944 (Subtarget.hasP8Altivec() && ( 9945 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9946 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9947 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9948 return Op; 9949 9950 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9951 // perfect shuffle table to emit an optimal matching sequence. 9952 ArrayRef<int> PermMask = SVOp->getMask(); 9953 9954 unsigned PFIndexes[4]; 9955 bool isFourElementShuffle = true; 9956 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9957 unsigned EltNo = 8; // Start out undef. 9958 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9959 if (PermMask[i*4+j] < 0) 9960 continue; // Undef, ignore it. 9961 9962 unsigned ByteSource = PermMask[i*4+j]; 9963 if ((ByteSource & 3) != j) { 9964 isFourElementShuffle = false; 9965 break; 9966 } 9967 9968 if (EltNo == 8) { 9969 EltNo = ByteSource/4; 9970 } else if (EltNo != ByteSource/4) { 9971 isFourElementShuffle = false; 9972 break; 9973 } 9974 } 9975 PFIndexes[i] = EltNo; 9976 } 9977 9978 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9979 // perfect shuffle vector to determine if it is cost effective to do this as 9980 // discrete instructions, or whether we should use a vperm. 9981 // For now, we skip this for little endian until such time as we have a 9982 // little-endian perfect shuffle table. 9983 if (isFourElementShuffle && !isLittleEndian) { 9984 // Compute the index in the perfect shuffle table. 9985 unsigned PFTableIndex = 9986 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9987 9988 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9989 unsigned Cost = (PFEntry >> 30); 9990 9991 // Determining when to avoid vperm is tricky. Many things affect the cost 9992 // of vperm, particularly how many times the perm mask needs to be computed. 9993 // For example, if the perm mask can be hoisted out of a loop or is already 9994 // used (perhaps because there are multiple permutes with the same shuffle 9995 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9996 // the loop requires an extra register. 9997 // 9998 // As a compromise, we only emit discrete instructions if the shuffle can be 9999 // generated in 3 or fewer operations. When we have loop information 10000 // available, if this block is within a loop, we should avoid using vperm 10001 // for 3-operation perms and use a constant pool load instead. 10002 if (Cost < 3) 10003 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10004 } 10005 10006 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10007 // vector that will get spilled to the constant pool. 10008 if (V2.isUndef()) V2 = V1; 10009 10010 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10011 // that it is in input element units, not in bytes. Convert now. 10012 10013 // For little endian, the order of the input vectors is reversed, and 10014 // the permutation mask is complemented with respect to 31. This is 10015 // necessary to produce proper semantics with the big-endian-biased vperm 10016 // instruction. 10017 EVT EltVT = V1.getValueType().getVectorElementType(); 10018 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10019 10020 SmallVector<SDValue, 16> ResultMask; 10021 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10022 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10023 10024 for (unsigned j = 0; j != BytesPerElement; ++j) 10025 if (isLittleEndian) 10026 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10027 dl, MVT::i32)); 10028 else 10029 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10030 MVT::i32)); 10031 } 10032 10033 ShufflesHandledWithVPERM++; 10034 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10035 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10036 LLVM_DEBUG(SVOp->dump()); 10037 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10038 LLVM_DEBUG(VPermMask.dump()); 10039 10040 if (isLittleEndian) 10041 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10042 V2, V1, VPermMask); 10043 else 10044 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10045 V1, V2, VPermMask); 10046 } 10047 10048 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10049 /// vector comparison. If it is, return true and fill in Opc/isDot with 10050 /// information about the intrinsic. 10051 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10052 bool &isDot, const PPCSubtarget &Subtarget) { 10053 unsigned IntrinsicID = 10054 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10055 CompareOpc = -1; 10056 isDot = false; 10057 switch (IntrinsicID) { 10058 default: 10059 return false; 10060 // Comparison predicates. 10061 case Intrinsic::ppc_altivec_vcmpbfp_p: 10062 CompareOpc = 966; 10063 isDot = true; 10064 break; 10065 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10066 CompareOpc = 198; 10067 isDot = true; 10068 break; 10069 case Intrinsic::ppc_altivec_vcmpequb_p: 10070 CompareOpc = 6; 10071 isDot = true; 10072 break; 10073 case Intrinsic::ppc_altivec_vcmpequh_p: 10074 CompareOpc = 70; 10075 isDot = true; 10076 break; 10077 case Intrinsic::ppc_altivec_vcmpequw_p: 10078 CompareOpc = 134; 10079 isDot = true; 10080 break; 10081 case Intrinsic::ppc_altivec_vcmpequd_p: 10082 if (Subtarget.hasP8Altivec()) { 10083 CompareOpc = 199; 10084 isDot = true; 10085 } else 10086 return false; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpneb_p: 10089 case Intrinsic::ppc_altivec_vcmpneh_p: 10090 case Intrinsic::ppc_altivec_vcmpnew_p: 10091 case Intrinsic::ppc_altivec_vcmpnezb_p: 10092 case Intrinsic::ppc_altivec_vcmpnezh_p: 10093 case Intrinsic::ppc_altivec_vcmpnezw_p: 10094 if (Subtarget.hasP9Altivec()) { 10095 switch (IntrinsicID) { 10096 default: 10097 llvm_unreachable("Unknown comparison intrinsic."); 10098 case Intrinsic::ppc_altivec_vcmpneb_p: 10099 CompareOpc = 7; 10100 break; 10101 case Intrinsic::ppc_altivec_vcmpneh_p: 10102 CompareOpc = 71; 10103 break; 10104 case Intrinsic::ppc_altivec_vcmpnew_p: 10105 CompareOpc = 135; 10106 break; 10107 case Intrinsic::ppc_altivec_vcmpnezb_p: 10108 CompareOpc = 263; 10109 break; 10110 case Intrinsic::ppc_altivec_vcmpnezh_p: 10111 CompareOpc = 327; 10112 break; 10113 case Intrinsic::ppc_altivec_vcmpnezw_p: 10114 CompareOpc = 391; 10115 break; 10116 } 10117 isDot = true; 10118 } else 10119 return false; 10120 break; 10121 case Intrinsic::ppc_altivec_vcmpgefp_p: 10122 CompareOpc = 454; 10123 isDot = true; 10124 break; 10125 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10126 CompareOpc = 710; 10127 isDot = true; 10128 break; 10129 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10130 CompareOpc = 774; 10131 isDot = true; 10132 break; 10133 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10134 CompareOpc = 838; 10135 isDot = true; 10136 break; 10137 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10138 CompareOpc = 902; 10139 isDot = true; 10140 break; 10141 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10142 if (Subtarget.hasP8Altivec()) { 10143 CompareOpc = 967; 10144 isDot = true; 10145 } else 10146 return false; 10147 break; 10148 case Intrinsic::ppc_altivec_vcmpgtub_p: 10149 CompareOpc = 518; 10150 isDot = true; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10153 CompareOpc = 582; 10154 isDot = true; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10157 CompareOpc = 646; 10158 isDot = true; 10159 break; 10160 case Intrinsic::ppc_altivec_vcmpgtud_p: 10161 if (Subtarget.hasP8Altivec()) { 10162 CompareOpc = 711; 10163 isDot = true; 10164 } else 10165 return false; 10166 break; 10167 10168 // VSX predicate comparisons use the same infrastructure 10169 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10170 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10171 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10172 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10173 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10174 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10175 if (Subtarget.hasVSX()) { 10176 switch (IntrinsicID) { 10177 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10178 CompareOpc = 99; 10179 break; 10180 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10181 CompareOpc = 115; 10182 break; 10183 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10184 CompareOpc = 107; 10185 break; 10186 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10187 CompareOpc = 67; 10188 break; 10189 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10190 CompareOpc = 83; 10191 break; 10192 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10193 CompareOpc = 75; 10194 break; 10195 } 10196 isDot = true; 10197 } else 10198 return false; 10199 break; 10200 10201 // Normal Comparisons. 10202 case Intrinsic::ppc_altivec_vcmpbfp: 10203 CompareOpc = 966; 10204 break; 10205 case Intrinsic::ppc_altivec_vcmpeqfp: 10206 CompareOpc = 198; 10207 break; 10208 case Intrinsic::ppc_altivec_vcmpequb: 10209 CompareOpc = 6; 10210 break; 10211 case Intrinsic::ppc_altivec_vcmpequh: 10212 CompareOpc = 70; 10213 break; 10214 case Intrinsic::ppc_altivec_vcmpequw: 10215 CompareOpc = 134; 10216 break; 10217 case Intrinsic::ppc_altivec_vcmpequd: 10218 if (Subtarget.hasP8Altivec()) 10219 CompareOpc = 199; 10220 else 10221 return false; 10222 break; 10223 case Intrinsic::ppc_altivec_vcmpneb: 10224 case Intrinsic::ppc_altivec_vcmpneh: 10225 case Intrinsic::ppc_altivec_vcmpnew: 10226 case Intrinsic::ppc_altivec_vcmpnezb: 10227 case Intrinsic::ppc_altivec_vcmpnezh: 10228 case Intrinsic::ppc_altivec_vcmpnezw: 10229 if (Subtarget.hasP9Altivec()) 10230 switch (IntrinsicID) { 10231 default: 10232 llvm_unreachable("Unknown comparison intrinsic."); 10233 case Intrinsic::ppc_altivec_vcmpneb: 10234 CompareOpc = 7; 10235 break; 10236 case Intrinsic::ppc_altivec_vcmpneh: 10237 CompareOpc = 71; 10238 break; 10239 case Intrinsic::ppc_altivec_vcmpnew: 10240 CompareOpc = 135; 10241 break; 10242 case Intrinsic::ppc_altivec_vcmpnezb: 10243 CompareOpc = 263; 10244 break; 10245 case Intrinsic::ppc_altivec_vcmpnezh: 10246 CompareOpc = 327; 10247 break; 10248 case Intrinsic::ppc_altivec_vcmpnezw: 10249 CompareOpc = 391; 10250 break; 10251 } 10252 else 10253 return false; 10254 break; 10255 case Intrinsic::ppc_altivec_vcmpgefp: 10256 CompareOpc = 454; 10257 break; 10258 case Intrinsic::ppc_altivec_vcmpgtfp: 10259 CompareOpc = 710; 10260 break; 10261 case Intrinsic::ppc_altivec_vcmpgtsb: 10262 CompareOpc = 774; 10263 break; 10264 case Intrinsic::ppc_altivec_vcmpgtsh: 10265 CompareOpc = 838; 10266 break; 10267 case Intrinsic::ppc_altivec_vcmpgtsw: 10268 CompareOpc = 902; 10269 break; 10270 case Intrinsic::ppc_altivec_vcmpgtsd: 10271 if (Subtarget.hasP8Altivec()) 10272 CompareOpc = 967; 10273 else 10274 return false; 10275 break; 10276 case Intrinsic::ppc_altivec_vcmpgtub: 10277 CompareOpc = 518; 10278 break; 10279 case Intrinsic::ppc_altivec_vcmpgtuh: 10280 CompareOpc = 582; 10281 break; 10282 case Intrinsic::ppc_altivec_vcmpgtuw: 10283 CompareOpc = 646; 10284 break; 10285 case Intrinsic::ppc_altivec_vcmpgtud: 10286 if (Subtarget.hasP8Altivec()) 10287 CompareOpc = 711; 10288 else 10289 return false; 10290 break; 10291 } 10292 return true; 10293 } 10294 10295 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10296 /// lower, do it, otherwise return null. 10297 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10298 SelectionDAG &DAG) const { 10299 unsigned IntrinsicID = 10300 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10301 10302 SDLoc dl(Op); 10303 10304 if (IntrinsicID == Intrinsic::thread_pointer) { 10305 // Reads the thread pointer register, used for __builtin_thread_pointer. 10306 if (Subtarget.isPPC64()) 10307 return DAG.getRegister(PPC::X13, MVT::i64); 10308 return DAG.getRegister(PPC::R2, MVT::i32); 10309 } 10310 10311 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10312 // opcode number of the comparison. 10313 int CompareOpc; 10314 bool isDot; 10315 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10316 return SDValue(); // Don't custom lower most intrinsics. 10317 10318 // If this is a non-dot comparison, make the VCMP node and we are done. 10319 if (!isDot) { 10320 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10321 Op.getOperand(1), Op.getOperand(2), 10322 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10323 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10324 } 10325 10326 // Create the PPCISD altivec 'dot' comparison node. 10327 SDValue Ops[] = { 10328 Op.getOperand(2), // LHS 10329 Op.getOperand(3), // RHS 10330 DAG.getConstant(CompareOpc, dl, MVT::i32) 10331 }; 10332 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10333 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10334 10335 // Now that we have the comparison, emit a copy from the CR to a GPR. 10336 // This is flagged to the above dot comparison. 10337 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10338 DAG.getRegister(PPC::CR6, MVT::i32), 10339 CompNode.getValue(1)); 10340 10341 // Unpack the result based on how the target uses it. 10342 unsigned BitNo; // Bit # of CR6. 10343 bool InvertBit; // Invert result? 10344 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10345 default: // Can't happen, don't crash on invalid number though. 10346 case 0: // Return the value of the EQ bit of CR6. 10347 BitNo = 0; InvertBit = false; 10348 break; 10349 case 1: // Return the inverted value of the EQ bit of CR6. 10350 BitNo = 0; InvertBit = true; 10351 break; 10352 case 2: // Return the value of the LT bit of CR6. 10353 BitNo = 2; InvertBit = false; 10354 break; 10355 case 3: // Return the inverted value of the LT bit of CR6. 10356 BitNo = 2; InvertBit = true; 10357 break; 10358 } 10359 10360 // Shift the bit into the low position. 10361 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10362 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10363 // Isolate the bit. 10364 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10365 DAG.getConstant(1, dl, MVT::i32)); 10366 10367 // If we are supposed to, toggle the bit. 10368 if (InvertBit) 10369 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10370 DAG.getConstant(1, dl, MVT::i32)); 10371 return Flags; 10372 } 10373 10374 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10375 SelectionDAG &DAG) const { 10376 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10377 // the beginning of the argument list. 10378 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10379 SDLoc DL(Op); 10380 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10381 case Intrinsic::ppc_cfence: { 10382 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10383 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10384 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10385 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10386 Op.getOperand(ArgStart + 1)), 10387 Op.getOperand(0)), 10388 0); 10389 } 10390 default: 10391 break; 10392 } 10393 return SDValue(); 10394 } 10395 10396 // Lower scalar BSWAP64 to xxbrd. 10397 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10398 SDLoc dl(Op); 10399 // MTVSRDD 10400 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10401 Op.getOperand(0)); 10402 // XXBRD 10403 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10404 // MFVSRD 10405 int VectorIndex = 0; 10406 if (Subtarget.isLittleEndian()) 10407 VectorIndex = 1; 10408 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10409 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10410 return Op; 10411 } 10412 10413 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10414 // compared to a value that is atomically loaded (atomic loads zero-extend). 10415 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10416 SelectionDAG &DAG) const { 10417 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10418 "Expecting an atomic compare-and-swap here."); 10419 SDLoc dl(Op); 10420 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10421 EVT MemVT = AtomicNode->getMemoryVT(); 10422 if (MemVT.getSizeInBits() >= 32) 10423 return Op; 10424 10425 SDValue CmpOp = Op.getOperand(2); 10426 // If this is already correctly zero-extended, leave it alone. 10427 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10428 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10429 return Op; 10430 10431 // Clear the high bits of the compare operand. 10432 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10433 SDValue NewCmpOp = 10434 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10435 DAG.getConstant(MaskVal, dl, MVT::i32)); 10436 10437 // Replace the existing compare operand with the properly zero-extended one. 10438 SmallVector<SDValue, 4> Ops; 10439 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10440 Ops.push_back(AtomicNode->getOperand(i)); 10441 Ops[2] = NewCmpOp; 10442 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10443 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10444 auto NodeTy = 10445 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10446 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10447 } 10448 10449 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10450 SelectionDAG &DAG) const { 10451 SDLoc dl(Op); 10452 // Create a stack slot that is 16-byte aligned. 10453 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10454 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10455 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10456 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10457 10458 // Store the input value into Value#0 of the stack slot. 10459 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10460 MachinePointerInfo()); 10461 // Load it out. 10462 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10463 } 10464 10465 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10466 SelectionDAG &DAG) const { 10467 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10468 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10469 10470 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10471 // We have legal lowering for constant indices but not for variable ones. 10472 if (!C) 10473 return SDValue(); 10474 10475 EVT VT = Op.getValueType(); 10476 SDLoc dl(Op); 10477 SDValue V1 = Op.getOperand(0); 10478 SDValue V2 = Op.getOperand(1); 10479 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10480 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10481 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10482 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10483 unsigned InsertAtElement = C->getZExtValue(); 10484 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10485 if (Subtarget.isLittleEndian()) { 10486 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10487 } 10488 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10489 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10490 } 10491 return Op; 10492 } 10493 10494 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10495 SDLoc dl(Op); 10496 if (Op.getValueType() == MVT::v4i32) { 10497 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10498 10499 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10500 // +16 as shift amt. 10501 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10502 SDValue RHSSwap = // = vrlw RHS, 16 10503 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10504 10505 // Shrinkify inputs to v8i16. 10506 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10507 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10508 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10509 10510 // Low parts multiplied together, generating 32-bit results (we ignore the 10511 // top parts). 10512 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10513 LHS, RHS, DAG, dl, MVT::v4i32); 10514 10515 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10516 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10517 // Shift the high parts up 16 bits. 10518 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10519 Neg16, DAG, dl); 10520 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10521 } else if (Op.getValueType() == MVT::v16i8) { 10522 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10523 bool isLittleEndian = Subtarget.isLittleEndian(); 10524 10525 // Multiply the even 8-bit parts, producing 16-bit sums. 10526 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10527 LHS, RHS, DAG, dl, MVT::v8i16); 10528 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10529 10530 // Multiply the odd 8-bit parts, producing 16-bit sums. 10531 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10532 LHS, RHS, DAG, dl, MVT::v8i16); 10533 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10534 10535 // Merge the results together. Because vmuleub and vmuloub are 10536 // instructions with a big-endian bias, we must reverse the 10537 // element numbering and reverse the meaning of "odd" and "even" 10538 // when generating little endian code. 10539 int Ops[16]; 10540 for (unsigned i = 0; i != 8; ++i) { 10541 if (isLittleEndian) { 10542 Ops[i*2 ] = 2*i; 10543 Ops[i*2+1] = 2*i+16; 10544 } else { 10545 Ops[i*2 ] = 2*i+1; 10546 Ops[i*2+1] = 2*i+1+16; 10547 } 10548 } 10549 if (isLittleEndian) 10550 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10551 else 10552 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10553 } else { 10554 llvm_unreachable("Unknown mul to lower!"); 10555 } 10556 } 10557 10558 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10559 10560 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10561 10562 EVT VT = Op.getValueType(); 10563 assert(VT.isVector() && 10564 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10565 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10566 VT == MVT::v16i8) && 10567 "Unexpected vector element type!"); 10568 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10569 "Current subtarget doesn't support smax v2i64!"); 10570 10571 // For vector abs, it can be lowered to: 10572 // abs x 10573 // ==> 10574 // y = -x 10575 // smax(x, y) 10576 10577 SDLoc dl(Op); 10578 SDValue X = Op.getOperand(0); 10579 SDValue Zero = DAG.getConstant(0, dl, VT); 10580 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10581 10582 // SMAX patch https://reviews.llvm.org/D47332 10583 // hasn't landed yet, so use intrinsic first here. 10584 // TODO: Should use SMAX directly once SMAX patch landed 10585 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10586 if (VT == MVT::v2i64) 10587 BifID = Intrinsic::ppc_altivec_vmaxsd; 10588 else if (VT == MVT::v8i16) 10589 BifID = Intrinsic::ppc_altivec_vmaxsh; 10590 else if (VT == MVT::v16i8) 10591 BifID = Intrinsic::ppc_altivec_vmaxsb; 10592 10593 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10594 } 10595 10596 // Custom lowering for fpext vf32 to v2f64 10597 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10598 10599 assert(Op.getOpcode() == ISD::FP_EXTEND && 10600 "Should only be called for ISD::FP_EXTEND"); 10601 10602 // FIXME: handle extends from half precision float vectors on P9. 10603 // We only want to custom lower an extend from v2f32 to v2f64. 10604 if (Op.getValueType() != MVT::v2f64 || 10605 Op.getOperand(0).getValueType() != MVT::v2f32) 10606 return SDValue(); 10607 10608 SDLoc dl(Op); 10609 SDValue Op0 = Op.getOperand(0); 10610 10611 switch (Op0.getOpcode()) { 10612 default: 10613 return SDValue(); 10614 case ISD::EXTRACT_SUBVECTOR: { 10615 assert(Op0.getNumOperands() == 2 && 10616 isa<ConstantSDNode>(Op0->getOperand(1)) && 10617 "Node should have 2 operands with second one being a constant!"); 10618 10619 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10620 return SDValue(); 10621 10622 // Custom lower is only done for high or low doubleword. 10623 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10624 if (Idx % 2 != 0) 10625 return SDValue(); 10626 10627 // Since input is v4f32, at this point Idx is either 0 or 2. 10628 // Shift to get the doubleword position we want. 10629 int DWord = Idx >> 1; 10630 10631 // High and low word positions are different on little endian. 10632 if (Subtarget.isLittleEndian()) 10633 DWord ^= 0x1; 10634 10635 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10636 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10637 } 10638 case ISD::FADD: 10639 case ISD::FMUL: 10640 case ISD::FSUB: { 10641 SDValue NewLoad[2]; 10642 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10643 // Ensure both input are loads. 10644 SDValue LdOp = Op0.getOperand(i); 10645 if (LdOp.getOpcode() != ISD::LOAD) 10646 return SDValue(); 10647 // Generate new load node. 10648 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10649 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10650 NewLoad[i] = DAG.getMemIntrinsicNode( 10651 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10652 LD->getMemoryVT(), LD->getMemOperand()); 10653 } 10654 SDValue NewOp = 10655 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10656 NewLoad[1], Op0.getNode()->getFlags()); 10657 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10658 DAG.getConstant(0, dl, MVT::i32)); 10659 } 10660 case ISD::LOAD: { 10661 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10662 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10663 SDValue NewLd = DAG.getMemIntrinsicNode( 10664 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10665 LD->getMemoryVT(), LD->getMemOperand()); 10666 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10667 DAG.getConstant(0, dl, MVT::i32)); 10668 } 10669 } 10670 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10671 } 10672 10673 /// LowerOperation - Provide custom lowering hooks for some operations. 10674 /// 10675 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10676 switch (Op.getOpcode()) { 10677 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10678 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10679 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10680 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10681 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10682 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10683 case ISD::SETCC: return LowerSETCC(Op, DAG); 10684 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10685 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10686 10687 // Variable argument lowering. 10688 case ISD::VASTART: return LowerVASTART(Op, DAG); 10689 case ISD::VAARG: return LowerVAARG(Op, DAG); 10690 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10691 10692 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10693 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10694 case ISD::GET_DYNAMIC_AREA_OFFSET: 10695 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10696 10697 // Exception handling lowering. 10698 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10699 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10700 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10701 10702 case ISD::LOAD: return LowerLOAD(Op, DAG); 10703 case ISD::STORE: return LowerSTORE(Op, DAG); 10704 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10705 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10706 case ISD::STRICT_FP_TO_UINT: 10707 case ISD::STRICT_FP_TO_SINT: 10708 case ISD::FP_TO_UINT: 10709 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10710 case ISD::STRICT_UINT_TO_FP: 10711 case ISD::STRICT_SINT_TO_FP: 10712 case ISD::UINT_TO_FP: 10713 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10714 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10715 10716 // Lower 64-bit shifts. 10717 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10718 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10719 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10720 10721 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10722 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10723 10724 // Vector-related lowering. 10725 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10726 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10727 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10728 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10729 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10730 case ISD::MUL: return LowerMUL(Op, DAG); 10731 case ISD::ABS: return LowerABS(Op, DAG); 10732 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10733 case ISD::ROTL: return LowerROTL(Op, DAG); 10734 10735 // For counter-based loop handling. 10736 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10737 10738 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10739 10740 // Frame & Return address. 10741 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10742 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10743 10744 case ISD::INTRINSIC_VOID: 10745 return LowerINTRINSIC_VOID(Op, DAG); 10746 case ISD::BSWAP: 10747 return LowerBSWAP(Op, DAG); 10748 case ISD::ATOMIC_CMP_SWAP: 10749 return LowerATOMIC_CMP_SWAP(Op, DAG); 10750 } 10751 } 10752 10753 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10754 SmallVectorImpl<SDValue> &Results, 10755 SelectionDAG &DAG) const { 10756 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10757 10758 if (!Res.getNode()) 10759 return; 10760 10761 // Take the return value as-is if original node has only one result. 10762 if (N->getNumValues() == 1) { 10763 Results.push_back(Res); 10764 return; 10765 } 10766 10767 // New node should have the same number of results. 10768 assert((N->getNumValues() == Res->getNumValues()) && 10769 "Lowering returned the wrong number of results!"); 10770 10771 for (unsigned i = 0; i < N->getNumValues(); ++i) 10772 Results.push_back(Res.getValue(i)); 10773 } 10774 10775 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10776 SmallVectorImpl<SDValue>&Results, 10777 SelectionDAG &DAG) const { 10778 SDLoc dl(N); 10779 switch (N->getOpcode()) { 10780 default: 10781 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10782 case ISD::READCYCLECOUNTER: { 10783 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10784 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10785 10786 Results.push_back( 10787 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10788 Results.push_back(RTB.getValue(2)); 10789 break; 10790 } 10791 case ISD::INTRINSIC_W_CHAIN: { 10792 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10793 Intrinsic::loop_decrement) 10794 break; 10795 10796 assert(N->getValueType(0) == MVT::i1 && 10797 "Unexpected result type for CTR decrement intrinsic"); 10798 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10799 N->getValueType(0)); 10800 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10801 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10802 N->getOperand(1)); 10803 10804 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10805 Results.push_back(NewInt.getValue(1)); 10806 break; 10807 } 10808 case ISD::VAARG: { 10809 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10810 return; 10811 10812 EVT VT = N->getValueType(0); 10813 10814 if (VT == MVT::i64) { 10815 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10816 10817 Results.push_back(NewNode); 10818 Results.push_back(NewNode.getValue(1)); 10819 } 10820 return; 10821 } 10822 case ISD::STRICT_FP_TO_SINT: 10823 case ISD::STRICT_FP_TO_UINT: 10824 case ISD::FP_TO_SINT: 10825 case ISD::FP_TO_UINT: 10826 // LowerFP_TO_INT() can only handle f32 and f64. 10827 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10828 MVT::ppcf128) 10829 return; 10830 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10831 return; 10832 case ISD::TRUNCATE: { 10833 if (!N->getValueType(0).isVector()) 10834 return; 10835 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10836 if (Lowered) 10837 Results.push_back(Lowered); 10838 return; 10839 } 10840 case ISD::BITCAST: 10841 // Don't handle bitcast here. 10842 return; 10843 case ISD::FP_EXTEND: 10844 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10845 if (Lowered) 10846 Results.push_back(Lowered); 10847 return; 10848 } 10849 } 10850 10851 //===----------------------------------------------------------------------===// 10852 // Other Lowering Code 10853 //===----------------------------------------------------------------------===// 10854 10855 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10856 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10857 Function *Func = Intrinsic::getDeclaration(M, Id); 10858 return Builder.CreateCall(Func, {}); 10859 } 10860 10861 // The mappings for emitLeading/TrailingFence is taken from 10862 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10863 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10864 Instruction *Inst, 10865 AtomicOrdering Ord) const { 10866 if (Ord == AtomicOrdering::SequentiallyConsistent) 10867 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10868 if (isReleaseOrStronger(Ord)) 10869 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10870 return nullptr; 10871 } 10872 10873 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10874 Instruction *Inst, 10875 AtomicOrdering Ord) const { 10876 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10877 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10878 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10879 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10880 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10881 return Builder.CreateCall( 10882 Intrinsic::getDeclaration( 10883 Builder.GetInsertBlock()->getParent()->getParent(), 10884 Intrinsic::ppc_cfence, {Inst->getType()}), 10885 {Inst}); 10886 // FIXME: Can use isync for rmw operation. 10887 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10888 } 10889 return nullptr; 10890 } 10891 10892 MachineBasicBlock * 10893 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10894 unsigned AtomicSize, 10895 unsigned BinOpcode, 10896 unsigned CmpOpcode, 10897 unsigned CmpPred) const { 10898 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10899 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10900 10901 auto LoadMnemonic = PPC::LDARX; 10902 auto StoreMnemonic = PPC::STDCX; 10903 switch (AtomicSize) { 10904 default: 10905 llvm_unreachable("Unexpected size of atomic entity"); 10906 case 1: 10907 LoadMnemonic = PPC::LBARX; 10908 StoreMnemonic = PPC::STBCX; 10909 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10910 break; 10911 case 2: 10912 LoadMnemonic = PPC::LHARX; 10913 StoreMnemonic = PPC::STHCX; 10914 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10915 break; 10916 case 4: 10917 LoadMnemonic = PPC::LWARX; 10918 StoreMnemonic = PPC::STWCX; 10919 break; 10920 case 8: 10921 LoadMnemonic = PPC::LDARX; 10922 StoreMnemonic = PPC::STDCX; 10923 break; 10924 } 10925 10926 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10927 MachineFunction *F = BB->getParent(); 10928 MachineFunction::iterator It = ++BB->getIterator(); 10929 10930 Register dest = MI.getOperand(0).getReg(); 10931 Register ptrA = MI.getOperand(1).getReg(); 10932 Register ptrB = MI.getOperand(2).getReg(); 10933 Register incr = MI.getOperand(3).getReg(); 10934 DebugLoc dl = MI.getDebugLoc(); 10935 10936 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10937 MachineBasicBlock *loop2MBB = 10938 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10939 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10940 F->insert(It, loopMBB); 10941 if (CmpOpcode) 10942 F->insert(It, loop2MBB); 10943 F->insert(It, exitMBB); 10944 exitMBB->splice(exitMBB->begin(), BB, 10945 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10946 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10947 10948 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10949 Register TmpReg = (!BinOpcode) ? incr : 10950 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10951 : &PPC::GPRCRegClass); 10952 10953 // thisMBB: 10954 // ... 10955 // fallthrough --> loopMBB 10956 BB->addSuccessor(loopMBB); 10957 10958 // loopMBB: 10959 // l[wd]arx dest, ptr 10960 // add r0, dest, incr 10961 // st[wd]cx. r0, ptr 10962 // bne- loopMBB 10963 // fallthrough --> exitMBB 10964 10965 // For max/min... 10966 // loopMBB: 10967 // l[wd]arx dest, ptr 10968 // cmpl?[wd] incr, dest 10969 // bgt exitMBB 10970 // loop2MBB: 10971 // st[wd]cx. dest, ptr 10972 // bne- loopMBB 10973 // fallthrough --> exitMBB 10974 10975 BB = loopMBB; 10976 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10977 .addReg(ptrA).addReg(ptrB); 10978 if (BinOpcode) 10979 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10980 if (CmpOpcode) { 10981 // Signed comparisons of byte or halfword values must be sign-extended. 10982 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10983 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10984 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10985 ExtReg).addReg(dest); 10986 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10987 .addReg(incr).addReg(ExtReg); 10988 } else 10989 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10990 .addReg(incr).addReg(dest); 10991 10992 BuildMI(BB, dl, TII->get(PPC::BCC)) 10993 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10994 BB->addSuccessor(loop2MBB); 10995 BB->addSuccessor(exitMBB); 10996 BB = loop2MBB; 10997 } 10998 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10999 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11000 BuildMI(BB, dl, TII->get(PPC::BCC)) 11001 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11002 BB->addSuccessor(loopMBB); 11003 BB->addSuccessor(exitMBB); 11004 11005 // exitMBB: 11006 // ... 11007 BB = exitMBB; 11008 return BB; 11009 } 11010 11011 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11012 MachineInstr &MI, MachineBasicBlock *BB, 11013 bool is8bit, // operation 11014 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11015 // If we support part-word atomic mnemonics, just use them 11016 if (Subtarget.hasPartwordAtomics()) 11017 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11018 CmpPred); 11019 11020 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11021 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11022 // In 64 bit mode we have to use 64 bits for addresses, even though the 11023 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11024 // registers without caring whether they're 32 or 64, but here we're 11025 // doing actual arithmetic on the addresses. 11026 bool is64bit = Subtarget.isPPC64(); 11027 bool isLittleEndian = Subtarget.isLittleEndian(); 11028 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11029 11030 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11031 MachineFunction *F = BB->getParent(); 11032 MachineFunction::iterator It = ++BB->getIterator(); 11033 11034 Register dest = MI.getOperand(0).getReg(); 11035 Register ptrA = MI.getOperand(1).getReg(); 11036 Register ptrB = MI.getOperand(2).getReg(); 11037 Register incr = MI.getOperand(3).getReg(); 11038 DebugLoc dl = MI.getDebugLoc(); 11039 11040 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11041 MachineBasicBlock *loop2MBB = 11042 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11043 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11044 F->insert(It, loopMBB); 11045 if (CmpOpcode) 11046 F->insert(It, loop2MBB); 11047 F->insert(It, exitMBB); 11048 exitMBB->splice(exitMBB->begin(), BB, 11049 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11050 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11051 11052 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11053 const TargetRegisterClass *RC = 11054 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11055 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11056 11057 Register PtrReg = RegInfo.createVirtualRegister(RC); 11058 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11059 Register ShiftReg = 11060 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11061 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11062 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11063 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11064 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11065 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11066 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11067 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11068 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11069 Register Ptr1Reg; 11070 Register TmpReg = 11071 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11072 11073 // thisMBB: 11074 // ... 11075 // fallthrough --> loopMBB 11076 BB->addSuccessor(loopMBB); 11077 11078 // The 4-byte load must be aligned, while a char or short may be 11079 // anywhere in the word. Hence all this nasty bookkeeping code. 11080 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11081 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11082 // xori shift, shift1, 24 [16] 11083 // rlwinm ptr, ptr1, 0, 0, 29 11084 // slw incr2, incr, shift 11085 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11086 // slw mask, mask2, shift 11087 // loopMBB: 11088 // lwarx tmpDest, ptr 11089 // add tmp, tmpDest, incr2 11090 // andc tmp2, tmpDest, mask 11091 // and tmp3, tmp, mask 11092 // or tmp4, tmp3, tmp2 11093 // stwcx. tmp4, ptr 11094 // bne- loopMBB 11095 // fallthrough --> exitMBB 11096 // srw dest, tmpDest, shift 11097 if (ptrA != ZeroReg) { 11098 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11099 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11100 .addReg(ptrA) 11101 .addReg(ptrB); 11102 } else { 11103 Ptr1Reg = ptrB; 11104 } 11105 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11106 // mode. 11107 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11108 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11109 .addImm(3) 11110 .addImm(27) 11111 .addImm(is8bit ? 28 : 27); 11112 if (!isLittleEndian) 11113 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11114 .addReg(Shift1Reg) 11115 .addImm(is8bit ? 24 : 16); 11116 if (is64bit) 11117 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11118 .addReg(Ptr1Reg) 11119 .addImm(0) 11120 .addImm(61); 11121 else 11122 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11123 .addReg(Ptr1Reg) 11124 .addImm(0) 11125 .addImm(0) 11126 .addImm(29); 11127 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11128 if (is8bit) 11129 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11130 else { 11131 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11132 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11133 .addReg(Mask3Reg) 11134 .addImm(65535); 11135 } 11136 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11137 .addReg(Mask2Reg) 11138 .addReg(ShiftReg); 11139 11140 BB = loopMBB; 11141 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11142 .addReg(ZeroReg) 11143 .addReg(PtrReg); 11144 if (BinOpcode) 11145 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11146 .addReg(Incr2Reg) 11147 .addReg(TmpDestReg); 11148 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11149 .addReg(TmpDestReg) 11150 .addReg(MaskReg); 11151 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11152 if (CmpOpcode) { 11153 // For unsigned comparisons, we can directly compare the shifted values. 11154 // For signed comparisons we shift and sign extend. 11155 Register SReg = RegInfo.createVirtualRegister(GPRC); 11156 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11157 .addReg(TmpDestReg) 11158 .addReg(MaskReg); 11159 unsigned ValueReg = SReg; 11160 unsigned CmpReg = Incr2Reg; 11161 if (CmpOpcode == PPC::CMPW) { 11162 ValueReg = RegInfo.createVirtualRegister(GPRC); 11163 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11164 .addReg(SReg) 11165 .addReg(ShiftReg); 11166 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11167 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11168 .addReg(ValueReg); 11169 ValueReg = ValueSReg; 11170 CmpReg = incr; 11171 } 11172 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11173 .addReg(CmpReg) 11174 .addReg(ValueReg); 11175 BuildMI(BB, dl, TII->get(PPC::BCC)) 11176 .addImm(CmpPred) 11177 .addReg(PPC::CR0) 11178 .addMBB(exitMBB); 11179 BB->addSuccessor(loop2MBB); 11180 BB->addSuccessor(exitMBB); 11181 BB = loop2MBB; 11182 } 11183 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11184 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11185 .addReg(Tmp4Reg) 11186 .addReg(ZeroReg) 11187 .addReg(PtrReg); 11188 BuildMI(BB, dl, TII->get(PPC::BCC)) 11189 .addImm(PPC::PRED_NE) 11190 .addReg(PPC::CR0) 11191 .addMBB(loopMBB); 11192 BB->addSuccessor(loopMBB); 11193 BB->addSuccessor(exitMBB); 11194 11195 // exitMBB: 11196 // ... 11197 BB = exitMBB; 11198 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11199 .addReg(TmpDestReg) 11200 .addReg(ShiftReg); 11201 return BB; 11202 } 11203 11204 llvm::MachineBasicBlock * 11205 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11206 MachineBasicBlock *MBB) const { 11207 DebugLoc DL = MI.getDebugLoc(); 11208 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11209 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11210 11211 MachineFunction *MF = MBB->getParent(); 11212 MachineRegisterInfo &MRI = MF->getRegInfo(); 11213 11214 const BasicBlock *BB = MBB->getBasicBlock(); 11215 MachineFunction::iterator I = ++MBB->getIterator(); 11216 11217 Register DstReg = MI.getOperand(0).getReg(); 11218 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11219 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11220 Register mainDstReg = MRI.createVirtualRegister(RC); 11221 Register restoreDstReg = MRI.createVirtualRegister(RC); 11222 11223 MVT PVT = getPointerTy(MF->getDataLayout()); 11224 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11225 "Invalid Pointer Size!"); 11226 // For v = setjmp(buf), we generate 11227 // 11228 // thisMBB: 11229 // SjLjSetup mainMBB 11230 // bl mainMBB 11231 // v_restore = 1 11232 // b sinkMBB 11233 // 11234 // mainMBB: 11235 // buf[LabelOffset] = LR 11236 // v_main = 0 11237 // 11238 // sinkMBB: 11239 // v = phi(main, restore) 11240 // 11241 11242 MachineBasicBlock *thisMBB = MBB; 11243 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11244 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11245 MF->insert(I, mainMBB); 11246 MF->insert(I, sinkMBB); 11247 11248 MachineInstrBuilder MIB; 11249 11250 // Transfer the remainder of BB and its successor edges to sinkMBB. 11251 sinkMBB->splice(sinkMBB->begin(), MBB, 11252 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11253 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11254 11255 // Note that the structure of the jmp_buf used here is not compatible 11256 // with that used by libc, and is not designed to be. Specifically, it 11257 // stores only those 'reserved' registers that LLVM does not otherwise 11258 // understand how to spill. Also, by convention, by the time this 11259 // intrinsic is called, Clang has already stored the frame address in the 11260 // first slot of the buffer and stack address in the third. Following the 11261 // X86 target code, we'll store the jump address in the second slot. We also 11262 // need to save the TOC pointer (R2) to handle jumps between shared 11263 // libraries, and that will be stored in the fourth slot. The thread 11264 // identifier (R13) is not affected. 11265 11266 // thisMBB: 11267 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11268 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11269 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11270 11271 // Prepare IP either in reg. 11272 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11273 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11274 Register BufReg = MI.getOperand(1).getReg(); 11275 11276 if (Subtarget.is64BitELFABI()) { 11277 setUsesTOCBasePtr(*MBB->getParent()); 11278 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11279 .addReg(PPC::X2) 11280 .addImm(TOCOffset) 11281 .addReg(BufReg) 11282 .cloneMemRefs(MI); 11283 } 11284 11285 // Naked functions never have a base pointer, and so we use r1. For all 11286 // other functions, this decision must be delayed until during PEI. 11287 unsigned BaseReg; 11288 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11289 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11290 else 11291 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11292 11293 MIB = BuildMI(*thisMBB, MI, DL, 11294 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11295 .addReg(BaseReg) 11296 .addImm(BPOffset) 11297 .addReg(BufReg) 11298 .cloneMemRefs(MI); 11299 11300 // Setup 11301 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11302 MIB.addRegMask(TRI->getNoPreservedMask()); 11303 11304 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11305 11306 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11307 .addMBB(mainMBB); 11308 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11309 11310 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11311 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11312 11313 // mainMBB: 11314 // mainDstReg = 0 11315 MIB = 11316 BuildMI(mainMBB, DL, 11317 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11318 11319 // Store IP 11320 if (Subtarget.isPPC64()) { 11321 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11322 .addReg(LabelReg) 11323 .addImm(LabelOffset) 11324 .addReg(BufReg); 11325 } else { 11326 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11327 .addReg(LabelReg) 11328 .addImm(LabelOffset) 11329 .addReg(BufReg); 11330 } 11331 MIB.cloneMemRefs(MI); 11332 11333 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11334 mainMBB->addSuccessor(sinkMBB); 11335 11336 // sinkMBB: 11337 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11338 TII->get(PPC::PHI), DstReg) 11339 .addReg(mainDstReg).addMBB(mainMBB) 11340 .addReg(restoreDstReg).addMBB(thisMBB); 11341 11342 MI.eraseFromParent(); 11343 return sinkMBB; 11344 } 11345 11346 MachineBasicBlock * 11347 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11348 MachineBasicBlock *MBB) const { 11349 DebugLoc DL = MI.getDebugLoc(); 11350 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11351 11352 MachineFunction *MF = MBB->getParent(); 11353 MachineRegisterInfo &MRI = MF->getRegInfo(); 11354 11355 MVT PVT = getPointerTy(MF->getDataLayout()); 11356 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11357 "Invalid Pointer Size!"); 11358 11359 const TargetRegisterClass *RC = 11360 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11361 Register Tmp = MRI.createVirtualRegister(RC); 11362 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11363 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11364 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11365 unsigned BP = 11366 (PVT == MVT::i64) 11367 ? PPC::X30 11368 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11369 : PPC::R30); 11370 11371 MachineInstrBuilder MIB; 11372 11373 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11374 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11375 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11376 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11377 11378 Register BufReg = MI.getOperand(0).getReg(); 11379 11380 // Reload FP (the jumped-to function may not have had a 11381 // frame pointer, and if so, then its r31 will be restored 11382 // as necessary). 11383 if (PVT == MVT::i64) { 11384 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11385 .addImm(0) 11386 .addReg(BufReg); 11387 } else { 11388 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11389 .addImm(0) 11390 .addReg(BufReg); 11391 } 11392 MIB.cloneMemRefs(MI); 11393 11394 // Reload IP 11395 if (PVT == MVT::i64) { 11396 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11397 .addImm(LabelOffset) 11398 .addReg(BufReg); 11399 } else { 11400 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11401 .addImm(LabelOffset) 11402 .addReg(BufReg); 11403 } 11404 MIB.cloneMemRefs(MI); 11405 11406 // Reload SP 11407 if (PVT == MVT::i64) { 11408 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11409 .addImm(SPOffset) 11410 .addReg(BufReg); 11411 } else { 11412 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11413 .addImm(SPOffset) 11414 .addReg(BufReg); 11415 } 11416 MIB.cloneMemRefs(MI); 11417 11418 // Reload BP 11419 if (PVT == MVT::i64) { 11420 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11421 .addImm(BPOffset) 11422 .addReg(BufReg); 11423 } else { 11424 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11425 .addImm(BPOffset) 11426 .addReg(BufReg); 11427 } 11428 MIB.cloneMemRefs(MI); 11429 11430 // Reload TOC 11431 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11432 setUsesTOCBasePtr(*MBB->getParent()); 11433 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11434 .addImm(TOCOffset) 11435 .addReg(BufReg) 11436 .cloneMemRefs(MI); 11437 } 11438 11439 // Jump 11440 BuildMI(*MBB, MI, DL, 11441 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11442 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11443 11444 MI.eraseFromParent(); 11445 return MBB; 11446 } 11447 11448 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11449 // If the function specifically requests inline stack probes, emit them. 11450 if (MF.getFunction().hasFnAttribute("probe-stack")) 11451 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11452 "inline-asm"; 11453 return false; 11454 } 11455 11456 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11457 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11458 unsigned StackAlign = TFI->getStackAlignment(); 11459 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11460 "Unexpected stack alignment"); 11461 // The default stack probe size is 4096 if the function has no 11462 // stack-probe-size attribute. 11463 unsigned StackProbeSize = 4096; 11464 const Function &Fn = MF.getFunction(); 11465 if (Fn.hasFnAttribute("stack-probe-size")) 11466 Fn.getFnAttribute("stack-probe-size") 11467 .getValueAsString() 11468 .getAsInteger(0, StackProbeSize); 11469 // Round down to the stack alignment. 11470 StackProbeSize &= ~(StackAlign - 1); 11471 return StackProbeSize ? StackProbeSize : StackAlign; 11472 } 11473 11474 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11475 // into three phases. In the first phase, it uses pseudo instruction 11476 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11477 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11478 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11479 // MaxCallFrameSize so that it can calculate correct data area pointer. 11480 MachineBasicBlock * 11481 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11482 MachineBasicBlock *MBB) const { 11483 const bool isPPC64 = Subtarget.isPPC64(); 11484 MachineFunction *MF = MBB->getParent(); 11485 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11486 DebugLoc DL = MI.getDebugLoc(); 11487 const unsigned ProbeSize = getStackProbeSize(*MF); 11488 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11489 MachineRegisterInfo &MRI = MF->getRegInfo(); 11490 // The CFG of probing stack looks as 11491 // +-----+ 11492 // | MBB | 11493 // +--+--+ 11494 // | 11495 // +----v----+ 11496 // +--->+ TestMBB +---+ 11497 // | +----+----+ | 11498 // | | | 11499 // | +-----v----+ | 11500 // +---+ BlockMBB | | 11501 // +----------+ | 11502 // | 11503 // +---------+ | 11504 // | TailMBB +<--+ 11505 // +---------+ 11506 // In MBB, calculate previous frame pointer and final stack pointer. 11507 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11508 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11509 // TailMBB is spliced via \p MI. 11510 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11511 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11512 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11513 11514 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11515 MF->insert(MBBIter, TestMBB); 11516 MF->insert(MBBIter, BlockMBB); 11517 MF->insert(MBBIter, TailMBB); 11518 11519 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11520 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11521 11522 Register DstReg = MI.getOperand(0).getReg(); 11523 Register NegSizeReg = MI.getOperand(1).getReg(); 11524 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11525 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11526 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11527 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11528 11529 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11530 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11531 // NegSize. 11532 unsigned ProbeOpc; 11533 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11534 ProbeOpc = 11535 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11536 else 11537 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11538 // and NegSizeReg will be allocated in the same phyreg to avoid 11539 // redundant copy when NegSizeReg has only one use which is current MI and 11540 // will be replaced by PREPARE_PROBED_ALLOCA then. 11541 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11542 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11543 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11544 .addDef(ActualNegSizeReg) 11545 .addReg(NegSizeReg) 11546 .add(MI.getOperand(2)) 11547 .add(MI.getOperand(3)); 11548 11549 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11550 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11551 FinalStackPtr) 11552 .addReg(SPReg) 11553 .addReg(ActualNegSizeReg); 11554 11555 // Materialize a scratch register for update. 11556 int64_t NegProbeSize = -(int64_t)ProbeSize; 11557 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11558 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11559 if (!isInt<16>(NegProbeSize)) { 11560 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11561 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11562 .addImm(NegProbeSize >> 16); 11563 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11564 ScratchReg) 11565 .addReg(TempReg) 11566 .addImm(NegProbeSize & 0xFFFF); 11567 } else 11568 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11569 .addImm(NegProbeSize); 11570 11571 { 11572 // Probing leading residual part. 11573 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11574 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11575 .addReg(ActualNegSizeReg) 11576 .addReg(ScratchReg); 11577 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11578 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11579 .addReg(Div) 11580 .addReg(ScratchReg); 11581 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11582 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11583 .addReg(Mul) 11584 .addReg(ActualNegSizeReg); 11585 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11586 .addReg(FramePointer) 11587 .addReg(SPReg) 11588 .addReg(NegMod); 11589 } 11590 11591 { 11592 // Remaining part should be multiple of ProbeSize. 11593 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11594 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11595 .addReg(SPReg) 11596 .addReg(FinalStackPtr); 11597 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11598 .addImm(PPC::PRED_EQ) 11599 .addReg(CmpResult) 11600 .addMBB(TailMBB); 11601 TestMBB->addSuccessor(BlockMBB); 11602 TestMBB->addSuccessor(TailMBB); 11603 } 11604 11605 { 11606 // Touch the block. 11607 // |P...|P...|P... 11608 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11609 .addReg(FramePointer) 11610 .addReg(SPReg) 11611 .addReg(ScratchReg); 11612 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11613 BlockMBB->addSuccessor(TestMBB); 11614 } 11615 11616 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11617 // DYNAREAOFFSET pseudo instruction to get the future result. 11618 Register MaxCallFrameSizeReg = 11619 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11620 BuildMI(TailMBB, DL, 11621 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11622 MaxCallFrameSizeReg) 11623 .add(MI.getOperand(2)) 11624 .add(MI.getOperand(3)); 11625 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11626 .addReg(SPReg) 11627 .addReg(MaxCallFrameSizeReg); 11628 11629 // Splice instructions after MI to TailMBB. 11630 TailMBB->splice(TailMBB->end(), MBB, 11631 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11632 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11633 MBB->addSuccessor(TestMBB); 11634 11635 // Delete the pseudo instruction. 11636 MI.eraseFromParent(); 11637 11638 ++NumDynamicAllocaProbed; 11639 return TailMBB; 11640 } 11641 11642 MachineBasicBlock * 11643 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11644 MachineBasicBlock *BB) const { 11645 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11646 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11647 if (Subtarget.is64BitELFABI() && 11648 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11649 !Subtarget.isUsingPCRelativeCalls()) { 11650 // Call lowering should have added an r2 operand to indicate a dependence 11651 // on the TOC base pointer value. It can't however, because there is no 11652 // way to mark the dependence as implicit there, and so the stackmap code 11653 // will confuse it with a regular operand. Instead, add the dependence 11654 // here. 11655 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11656 } 11657 11658 return emitPatchPoint(MI, BB); 11659 } 11660 11661 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11662 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11663 return emitEHSjLjSetJmp(MI, BB); 11664 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11665 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11666 return emitEHSjLjLongJmp(MI, BB); 11667 } 11668 11669 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11670 11671 // To "insert" these instructions we actually have to insert their 11672 // control-flow patterns. 11673 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11674 MachineFunction::iterator It = ++BB->getIterator(); 11675 11676 MachineFunction *F = BB->getParent(); 11677 11678 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11679 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11680 MI.getOpcode() == PPC::SELECT_I8) { 11681 SmallVector<MachineOperand, 2> Cond; 11682 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11683 MI.getOpcode() == PPC::SELECT_CC_I8) 11684 Cond.push_back(MI.getOperand(4)); 11685 else 11686 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11687 Cond.push_back(MI.getOperand(1)); 11688 11689 DebugLoc dl = MI.getDebugLoc(); 11690 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11691 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11692 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11693 MI.getOpcode() == PPC::SELECT_CC_F8 || 11694 MI.getOpcode() == PPC::SELECT_CC_F16 || 11695 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11696 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11697 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11698 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11699 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11700 MI.getOpcode() == PPC::SELECT_CC_SPE || 11701 MI.getOpcode() == PPC::SELECT_F4 || 11702 MI.getOpcode() == PPC::SELECT_F8 || 11703 MI.getOpcode() == PPC::SELECT_F16 || 11704 MI.getOpcode() == PPC::SELECT_SPE || 11705 MI.getOpcode() == PPC::SELECT_SPE4 || 11706 MI.getOpcode() == PPC::SELECT_VRRC || 11707 MI.getOpcode() == PPC::SELECT_VSFRC || 11708 MI.getOpcode() == PPC::SELECT_VSSRC || 11709 MI.getOpcode() == PPC::SELECT_VSRC) { 11710 // The incoming instruction knows the destination vreg to set, the 11711 // condition code register to branch on, the true/false values to 11712 // select between, and a branch opcode to use. 11713 11714 // thisMBB: 11715 // ... 11716 // TrueVal = ... 11717 // cmpTY ccX, r1, r2 11718 // bCC copy1MBB 11719 // fallthrough --> copy0MBB 11720 MachineBasicBlock *thisMBB = BB; 11721 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11722 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11723 DebugLoc dl = MI.getDebugLoc(); 11724 F->insert(It, copy0MBB); 11725 F->insert(It, sinkMBB); 11726 11727 // Transfer the remainder of BB and its successor edges to sinkMBB. 11728 sinkMBB->splice(sinkMBB->begin(), BB, 11729 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11730 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11731 11732 // Next, add the true and fallthrough blocks as its successors. 11733 BB->addSuccessor(copy0MBB); 11734 BB->addSuccessor(sinkMBB); 11735 11736 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11737 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11738 MI.getOpcode() == PPC::SELECT_F16 || 11739 MI.getOpcode() == PPC::SELECT_SPE4 || 11740 MI.getOpcode() == PPC::SELECT_SPE || 11741 MI.getOpcode() == PPC::SELECT_VRRC || 11742 MI.getOpcode() == PPC::SELECT_VSFRC || 11743 MI.getOpcode() == PPC::SELECT_VSSRC || 11744 MI.getOpcode() == PPC::SELECT_VSRC) { 11745 BuildMI(BB, dl, TII->get(PPC::BC)) 11746 .addReg(MI.getOperand(1).getReg()) 11747 .addMBB(sinkMBB); 11748 } else { 11749 unsigned SelectPred = MI.getOperand(4).getImm(); 11750 BuildMI(BB, dl, TII->get(PPC::BCC)) 11751 .addImm(SelectPred) 11752 .addReg(MI.getOperand(1).getReg()) 11753 .addMBB(sinkMBB); 11754 } 11755 11756 // copy0MBB: 11757 // %FalseValue = ... 11758 // # fallthrough to sinkMBB 11759 BB = copy0MBB; 11760 11761 // Update machine-CFG edges 11762 BB->addSuccessor(sinkMBB); 11763 11764 // sinkMBB: 11765 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11766 // ... 11767 BB = sinkMBB; 11768 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11769 .addReg(MI.getOperand(3).getReg()) 11770 .addMBB(copy0MBB) 11771 .addReg(MI.getOperand(2).getReg()) 11772 .addMBB(thisMBB); 11773 } else if (MI.getOpcode() == PPC::ReadTB) { 11774 // To read the 64-bit time-base register on a 32-bit target, we read the 11775 // two halves. Should the counter have wrapped while it was being read, we 11776 // need to try again. 11777 // ... 11778 // readLoop: 11779 // mfspr Rx,TBU # load from TBU 11780 // mfspr Ry,TB # load from TB 11781 // mfspr Rz,TBU # load from TBU 11782 // cmpw crX,Rx,Rz # check if 'old'='new' 11783 // bne readLoop # branch if they're not equal 11784 // ... 11785 11786 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11787 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11788 DebugLoc dl = MI.getDebugLoc(); 11789 F->insert(It, readMBB); 11790 F->insert(It, sinkMBB); 11791 11792 // Transfer the remainder of BB and its successor edges to sinkMBB. 11793 sinkMBB->splice(sinkMBB->begin(), BB, 11794 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11795 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11796 11797 BB->addSuccessor(readMBB); 11798 BB = readMBB; 11799 11800 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11801 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11802 Register LoReg = MI.getOperand(0).getReg(); 11803 Register HiReg = MI.getOperand(1).getReg(); 11804 11805 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11806 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11807 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11808 11809 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11810 11811 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11812 .addReg(HiReg) 11813 .addReg(ReadAgainReg); 11814 BuildMI(BB, dl, TII->get(PPC::BCC)) 11815 .addImm(PPC::PRED_NE) 11816 .addReg(CmpReg) 11817 .addMBB(readMBB); 11818 11819 BB->addSuccessor(readMBB); 11820 BB->addSuccessor(sinkMBB); 11821 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11822 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11824 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11826 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11828 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11829 11830 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11831 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11833 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11835 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11837 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11838 11839 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11840 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11842 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11844 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11846 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11847 11848 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11849 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11851 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11853 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11855 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11856 11857 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11858 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11859 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11860 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11861 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11862 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11863 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11864 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11865 11866 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11867 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11869 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11871 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11872 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11873 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11874 11875 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11876 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11878 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11880 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11881 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11882 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11883 11884 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11885 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11887 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11889 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11890 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11891 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11892 11893 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11894 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11896 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11898 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11899 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11900 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11901 11902 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11903 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11904 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11905 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11906 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11907 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11908 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11909 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11910 11911 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11912 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11913 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11914 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11915 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11916 BB = EmitAtomicBinary(MI, BB, 4, 0); 11917 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11918 BB = EmitAtomicBinary(MI, BB, 8, 0); 11919 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11920 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11921 (Subtarget.hasPartwordAtomics() && 11922 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11923 (Subtarget.hasPartwordAtomics() && 11924 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11925 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11926 11927 auto LoadMnemonic = PPC::LDARX; 11928 auto StoreMnemonic = PPC::STDCX; 11929 switch (MI.getOpcode()) { 11930 default: 11931 llvm_unreachable("Compare and swap of unknown size"); 11932 case PPC::ATOMIC_CMP_SWAP_I8: 11933 LoadMnemonic = PPC::LBARX; 11934 StoreMnemonic = PPC::STBCX; 11935 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11936 break; 11937 case PPC::ATOMIC_CMP_SWAP_I16: 11938 LoadMnemonic = PPC::LHARX; 11939 StoreMnemonic = PPC::STHCX; 11940 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11941 break; 11942 case PPC::ATOMIC_CMP_SWAP_I32: 11943 LoadMnemonic = PPC::LWARX; 11944 StoreMnemonic = PPC::STWCX; 11945 break; 11946 case PPC::ATOMIC_CMP_SWAP_I64: 11947 LoadMnemonic = PPC::LDARX; 11948 StoreMnemonic = PPC::STDCX; 11949 break; 11950 } 11951 Register dest = MI.getOperand(0).getReg(); 11952 Register ptrA = MI.getOperand(1).getReg(); 11953 Register ptrB = MI.getOperand(2).getReg(); 11954 Register oldval = MI.getOperand(3).getReg(); 11955 Register newval = MI.getOperand(4).getReg(); 11956 DebugLoc dl = MI.getDebugLoc(); 11957 11958 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11959 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11960 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11961 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11962 F->insert(It, loop1MBB); 11963 F->insert(It, loop2MBB); 11964 F->insert(It, midMBB); 11965 F->insert(It, exitMBB); 11966 exitMBB->splice(exitMBB->begin(), BB, 11967 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11968 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11969 11970 // thisMBB: 11971 // ... 11972 // fallthrough --> loopMBB 11973 BB->addSuccessor(loop1MBB); 11974 11975 // loop1MBB: 11976 // l[bhwd]arx dest, ptr 11977 // cmp[wd] dest, oldval 11978 // bne- midMBB 11979 // loop2MBB: 11980 // st[bhwd]cx. newval, ptr 11981 // bne- loopMBB 11982 // b exitBB 11983 // midMBB: 11984 // st[bhwd]cx. dest, ptr 11985 // exitBB: 11986 BB = loop1MBB; 11987 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11988 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11989 .addReg(oldval) 11990 .addReg(dest); 11991 BuildMI(BB, dl, TII->get(PPC::BCC)) 11992 .addImm(PPC::PRED_NE) 11993 .addReg(PPC::CR0) 11994 .addMBB(midMBB); 11995 BB->addSuccessor(loop2MBB); 11996 BB->addSuccessor(midMBB); 11997 11998 BB = loop2MBB; 11999 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12000 .addReg(newval) 12001 .addReg(ptrA) 12002 .addReg(ptrB); 12003 BuildMI(BB, dl, TII->get(PPC::BCC)) 12004 .addImm(PPC::PRED_NE) 12005 .addReg(PPC::CR0) 12006 .addMBB(loop1MBB); 12007 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12008 BB->addSuccessor(loop1MBB); 12009 BB->addSuccessor(exitMBB); 12010 12011 BB = midMBB; 12012 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12013 .addReg(dest) 12014 .addReg(ptrA) 12015 .addReg(ptrB); 12016 BB->addSuccessor(exitMBB); 12017 12018 // exitMBB: 12019 // ... 12020 BB = exitMBB; 12021 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12022 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12023 // We must use 64-bit registers for addresses when targeting 64-bit, 12024 // since we're actually doing arithmetic on them. Other registers 12025 // can be 32-bit. 12026 bool is64bit = Subtarget.isPPC64(); 12027 bool isLittleEndian = Subtarget.isLittleEndian(); 12028 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12029 12030 Register dest = MI.getOperand(0).getReg(); 12031 Register ptrA = MI.getOperand(1).getReg(); 12032 Register ptrB = MI.getOperand(2).getReg(); 12033 Register oldval = MI.getOperand(3).getReg(); 12034 Register newval = MI.getOperand(4).getReg(); 12035 DebugLoc dl = MI.getDebugLoc(); 12036 12037 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12038 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12039 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12040 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12041 F->insert(It, loop1MBB); 12042 F->insert(It, loop2MBB); 12043 F->insert(It, midMBB); 12044 F->insert(It, exitMBB); 12045 exitMBB->splice(exitMBB->begin(), BB, 12046 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12047 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12048 12049 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12050 const TargetRegisterClass *RC = 12051 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12052 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12053 12054 Register PtrReg = RegInfo.createVirtualRegister(RC); 12055 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12056 Register ShiftReg = 12057 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12058 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12059 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12060 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12061 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12062 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12063 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12064 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12065 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12066 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12067 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12068 Register Ptr1Reg; 12069 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12070 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12071 // thisMBB: 12072 // ... 12073 // fallthrough --> loopMBB 12074 BB->addSuccessor(loop1MBB); 12075 12076 // The 4-byte load must be aligned, while a char or short may be 12077 // anywhere in the word. Hence all this nasty bookkeeping code. 12078 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12079 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12080 // xori shift, shift1, 24 [16] 12081 // rlwinm ptr, ptr1, 0, 0, 29 12082 // slw newval2, newval, shift 12083 // slw oldval2, oldval,shift 12084 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12085 // slw mask, mask2, shift 12086 // and newval3, newval2, mask 12087 // and oldval3, oldval2, mask 12088 // loop1MBB: 12089 // lwarx tmpDest, ptr 12090 // and tmp, tmpDest, mask 12091 // cmpw tmp, oldval3 12092 // bne- midMBB 12093 // loop2MBB: 12094 // andc tmp2, tmpDest, mask 12095 // or tmp4, tmp2, newval3 12096 // stwcx. tmp4, ptr 12097 // bne- loop1MBB 12098 // b exitBB 12099 // midMBB: 12100 // stwcx. tmpDest, ptr 12101 // exitBB: 12102 // srw dest, tmpDest, shift 12103 if (ptrA != ZeroReg) { 12104 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12105 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12106 .addReg(ptrA) 12107 .addReg(ptrB); 12108 } else { 12109 Ptr1Reg = ptrB; 12110 } 12111 12112 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12113 // mode. 12114 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12115 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12116 .addImm(3) 12117 .addImm(27) 12118 .addImm(is8bit ? 28 : 27); 12119 if (!isLittleEndian) 12120 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12121 .addReg(Shift1Reg) 12122 .addImm(is8bit ? 24 : 16); 12123 if (is64bit) 12124 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12125 .addReg(Ptr1Reg) 12126 .addImm(0) 12127 .addImm(61); 12128 else 12129 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12130 .addReg(Ptr1Reg) 12131 .addImm(0) 12132 .addImm(0) 12133 .addImm(29); 12134 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12135 .addReg(newval) 12136 .addReg(ShiftReg); 12137 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12138 .addReg(oldval) 12139 .addReg(ShiftReg); 12140 if (is8bit) 12141 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12142 else { 12143 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12144 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12145 .addReg(Mask3Reg) 12146 .addImm(65535); 12147 } 12148 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12149 .addReg(Mask2Reg) 12150 .addReg(ShiftReg); 12151 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12152 .addReg(NewVal2Reg) 12153 .addReg(MaskReg); 12154 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12155 .addReg(OldVal2Reg) 12156 .addReg(MaskReg); 12157 12158 BB = loop1MBB; 12159 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12160 .addReg(ZeroReg) 12161 .addReg(PtrReg); 12162 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12163 .addReg(TmpDestReg) 12164 .addReg(MaskReg); 12165 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12166 .addReg(TmpReg) 12167 .addReg(OldVal3Reg); 12168 BuildMI(BB, dl, TII->get(PPC::BCC)) 12169 .addImm(PPC::PRED_NE) 12170 .addReg(PPC::CR0) 12171 .addMBB(midMBB); 12172 BB->addSuccessor(loop2MBB); 12173 BB->addSuccessor(midMBB); 12174 12175 BB = loop2MBB; 12176 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12177 .addReg(TmpDestReg) 12178 .addReg(MaskReg); 12179 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12180 .addReg(Tmp2Reg) 12181 .addReg(NewVal3Reg); 12182 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12183 .addReg(Tmp4Reg) 12184 .addReg(ZeroReg) 12185 .addReg(PtrReg); 12186 BuildMI(BB, dl, TII->get(PPC::BCC)) 12187 .addImm(PPC::PRED_NE) 12188 .addReg(PPC::CR0) 12189 .addMBB(loop1MBB); 12190 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12191 BB->addSuccessor(loop1MBB); 12192 BB->addSuccessor(exitMBB); 12193 12194 BB = midMBB; 12195 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12196 .addReg(TmpDestReg) 12197 .addReg(ZeroReg) 12198 .addReg(PtrReg); 12199 BB->addSuccessor(exitMBB); 12200 12201 // exitMBB: 12202 // ... 12203 BB = exitMBB; 12204 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12205 .addReg(TmpReg) 12206 .addReg(ShiftReg); 12207 } else if (MI.getOpcode() == PPC::FADDrtz) { 12208 // This pseudo performs an FADD with rounding mode temporarily forced 12209 // to round-to-zero. We emit this via custom inserter since the FPSCR 12210 // is not modeled at the SelectionDAG level. 12211 Register Dest = MI.getOperand(0).getReg(); 12212 Register Src1 = MI.getOperand(1).getReg(); 12213 Register Src2 = MI.getOperand(2).getReg(); 12214 DebugLoc dl = MI.getDebugLoc(); 12215 12216 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12217 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12218 12219 // Save FPSCR value. 12220 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12221 12222 // Set rounding mode to round-to-zero. 12223 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12224 .addImm(31) 12225 .addReg(PPC::RM, RegState::ImplicitDefine); 12226 12227 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12228 .addImm(30) 12229 .addReg(PPC::RM, RegState::ImplicitDefine); 12230 12231 // Perform addition. 12232 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12233 .addReg(Src1) 12234 .addReg(Src2); 12235 if (MI.getFlag(MachineInstr::NoFPExcept)) 12236 MIB.setMIFlag(MachineInstr::NoFPExcept); 12237 12238 // Restore FPSCR value. 12239 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12240 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12241 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12242 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12243 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12244 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12245 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12246 ? PPC::ANDI8_rec 12247 : PPC::ANDI_rec; 12248 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12249 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12250 12251 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12252 Register Dest = RegInfo.createVirtualRegister( 12253 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12254 12255 DebugLoc Dl = MI.getDebugLoc(); 12256 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12257 .addReg(MI.getOperand(1).getReg()) 12258 .addImm(1); 12259 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12260 MI.getOperand(0).getReg()) 12261 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12262 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12263 DebugLoc Dl = MI.getDebugLoc(); 12264 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12265 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12266 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12267 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12268 MI.getOperand(0).getReg()) 12269 .addReg(CRReg); 12270 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12271 DebugLoc Dl = MI.getDebugLoc(); 12272 unsigned Imm = MI.getOperand(1).getImm(); 12273 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12274 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12275 MI.getOperand(0).getReg()) 12276 .addReg(PPC::CR0EQ); 12277 } else if (MI.getOpcode() == PPC::SETRNDi) { 12278 DebugLoc dl = MI.getDebugLoc(); 12279 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12280 12281 // Save FPSCR value. 12282 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12283 12284 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12285 // the following settings: 12286 // 00 Round to nearest 12287 // 01 Round to 0 12288 // 10 Round to +inf 12289 // 11 Round to -inf 12290 12291 // When the operand is immediate, using the two least significant bits of 12292 // the immediate to set the bits 62:63 of FPSCR. 12293 unsigned Mode = MI.getOperand(1).getImm(); 12294 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12295 .addImm(31) 12296 .addReg(PPC::RM, RegState::ImplicitDefine); 12297 12298 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12299 .addImm(30) 12300 .addReg(PPC::RM, RegState::ImplicitDefine); 12301 } else if (MI.getOpcode() == PPC::SETRND) { 12302 DebugLoc dl = MI.getDebugLoc(); 12303 12304 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12305 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12306 // If the target doesn't have DirectMove, we should use stack to do the 12307 // conversion, because the target doesn't have the instructions like mtvsrd 12308 // or mfvsrd to do this conversion directly. 12309 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12310 if (Subtarget.hasDirectMove()) { 12311 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12312 .addReg(SrcReg); 12313 } else { 12314 // Use stack to do the register copy. 12315 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12316 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12317 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12318 if (RC == &PPC::F8RCRegClass) { 12319 // Copy register from F8RCRegClass to G8RCRegclass. 12320 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12321 "Unsupported RegClass."); 12322 12323 StoreOp = PPC::STFD; 12324 LoadOp = PPC::LD; 12325 } else { 12326 // Copy register from G8RCRegClass to F8RCRegclass. 12327 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12328 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12329 "Unsupported RegClass."); 12330 } 12331 12332 MachineFrameInfo &MFI = F->getFrameInfo(); 12333 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12334 12335 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12336 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12337 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12338 MFI.getObjectAlign(FrameIdx)); 12339 12340 // Store the SrcReg into the stack. 12341 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12342 .addReg(SrcReg) 12343 .addImm(0) 12344 .addFrameIndex(FrameIdx) 12345 .addMemOperand(MMOStore); 12346 12347 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12348 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12349 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12350 MFI.getObjectAlign(FrameIdx)); 12351 12352 // Load from the stack where SrcReg is stored, and save to DestReg, 12353 // so we have done the RegClass conversion from RegClass::SrcReg to 12354 // RegClass::DestReg. 12355 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12356 .addImm(0) 12357 .addFrameIndex(FrameIdx) 12358 .addMemOperand(MMOLoad); 12359 } 12360 }; 12361 12362 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12363 12364 // Save FPSCR value. 12365 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12366 12367 // When the operand is gprc register, use two least significant bits of the 12368 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12369 // 12370 // copy OldFPSCRTmpReg, OldFPSCRReg 12371 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12372 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12373 // copy NewFPSCRReg, NewFPSCRTmpReg 12374 // mtfsf 255, NewFPSCRReg 12375 MachineOperand SrcOp = MI.getOperand(1); 12376 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12377 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12378 12379 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12380 12381 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12382 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12383 12384 // The first operand of INSERT_SUBREG should be a register which has 12385 // subregisters, we only care about its RegClass, so we should use an 12386 // IMPLICIT_DEF register. 12387 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12388 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12389 .addReg(ImDefReg) 12390 .add(SrcOp) 12391 .addImm(1); 12392 12393 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12394 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12395 .addReg(OldFPSCRTmpReg) 12396 .addReg(ExtSrcReg) 12397 .addImm(0) 12398 .addImm(62); 12399 12400 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12401 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12402 12403 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12404 // bits of FPSCR. 12405 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12406 .addImm(255) 12407 .addReg(NewFPSCRReg) 12408 .addImm(0) 12409 .addImm(0); 12410 } else if (MI.getOpcode() == PPC::SETFLM) { 12411 DebugLoc Dl = MI.getDebugLoc(); 12412 12413 // Result of setflm is previous FPSCR content, so we need to save it first. 12414 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12415 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12416 12417 // Put bits in 32:63 to FPSCR. 12418 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12419 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12420 .addImm(255) 12421 .addReg(NewFPSCRReg) 12422 .addImm(0) 12423 .addImm(0); 12424 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12425 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12426 return emitProbedAlloca(MI, BB); 12427 } else { 12428 llvm_unreachable("Unexpected instr type to insert"); 12429 } 12430 12431 MI.eraseFromParent(); // The pseudo instruction is gone now. 12432 return BB; 12433 } 12434 12435 //===----------------------------------------------------------------------===// 12436 // Target Optimization Hooks 12437 //===----------------------------------------------------------------------===// 12438 12439 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12440 // For the estimates, convergence is quadratic, so we essentially double the 12441 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12442 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12443 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12444 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12445 if (VT.getScalarType() == MVT::f64) 12446 RefinementSteps++; 12447 return RefinementSteps; 12448 } 12449 12450 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12451 int Enabled, int &RefinementSteps, 12452 bool &UseOneConstNR, 12453 bool Reciprocal) const { 12454 EVT VT = Operand.getValueType(); 12455 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12456 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12457 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12458 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12459 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12460 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12461 12462 // The Newton-Raphson computation with a single constant does not provide 12463 // enough accuracy on some CPUs. 12464 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12465 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12466 } 12467 return SDValue(); 12468 } 12469 12470 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12471 int Enabled, 12472 int &RefinementSteps) const { 12473 EVT VT = Operand.getValueType(); 12474 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12475 (VT == MVT::f64 && Subtarget.hasFRE()) || 12476 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12477 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12478 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12479 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12480 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12481 } 12482 return SDValue(); 12483 } 12484 12485 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12486 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12487 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12488 // enabled for division), this functionality is redundant with the default 12489 // combiner logic (once the division -> reciprocal/multiply transformation 12490 // has taken place). As a result, this matters more for older cores than for 12491 // newer ones. 12492 12493 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12494 // reciprocal if there are two or more FDIVs (for embedded cores with only 12495 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12496 switch (Subtarget.getCPUDirective()) { 12497 default: 12498 return 3; 12499 case PPC::DIR_440: 12500 case PPC::DIR_A2: 12501 case PPC::DIR_E500: 12502 case PPC::DIR_E500mc: 12503 case PPC::DIR_E5500: 12504 return 2; 12505 } 12506 } 12507 12508 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12509 // collapsed, and so we need to look through chains of them. 12510 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12511 int64_t& Offset, SelectionDAG &DAG) { 12512 if (DAG.isBaseWithConstantOffset(Loc)) { 12513 Base = Loc.getOperand(0); 12514 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12515 12516 // The base might itself be a base plus an offset, and if so, accumulate 12517 // that as well. 12518 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12519 } 12520 } 12521 12522 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12523 unsigned Bytes, int Dist, 12524 SelectionDAG &DAG) { 12525 if (VT.getSizeInBits() / 8 != Bytes) 12526 return false; 12527 12528 SDValue BaseLoc = Base->getBasePtr(); 12529 if (Loc.getOpcode() == ISD::FrameIndex) { 12530 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12531 return false; 12532 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12533 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12534 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12535 int FS = MFI.getObjectSize(FI); 12536 int BFS = MFI.getObjectSize(BFI); 12537 if (FS != BFS || FS != (int)Bytes) return false; 12538 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12539 } 12540 12541 SDValue Base1 = Loc, Base2 = BaseLoc; 12542 int64_t Offset1 = 0, Offset2 = 0; 12543 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12544 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12545 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12546 return true; 12547 12548 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12549 const GlobalValue *GV1 = nullptr; 12550 const GlobalValue *GV2 = nullptr; 12551 Offset1 = 0; 12552 Offset2 = 0; 12553 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12554 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12555 if (isGA1 && isGA2 && GV1 == GV2) 12556 return Offset1 == (Offset2 + Dist*Bytes); 12557 return false; 12558 } 12559 12560 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12561 // not enforce equality of the chain operands. 12562 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12563 unsigned Bytes, int Dist, 12564 SelectionDAG &DAG) { 12565 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12566 EVT VT = LS->getMemoryVT(); 12567 SDValue Loc = LS->getBasePtr(); 12568 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12569 } 12570 12571 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12572 EVT VT; 12573 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12574 default: return false; 12575 case Intrinsic::ppc_altivec_lvx: 12576 case Intrinsic::ppc_altivec_lvxl: 12577 case Intrinsic::ppc_vsx_lxvw4x: 12578 case Intrinsic::ppc_vsx_lxvw4x_be: 12579 VT = MVT::v4i32; 12580 break; 12581 case Intrinsic::ppc_vsx_lxvd2x: 12582 case Intrinsic::ppc_vsx_lxvd2x_be: 12583 VT = MVT::v2f64; 12584 break; 12585 case Intrinsic::ppc_altivec_lvebx: 12586 VT = MVT::i8; 12587 break; 12588 case Intrinsic::ppc_altivec_lvehx: 12589 VT = MVT::i16; 12590 break; 12591 case Intrinsic::ppc_altivec_lvewx: 12592 VT = MVT::i32; 12593 break; 12594 } 12595 12596 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12597 } 12598 12599 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12600 EVT VT; 12601 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12602 default: return false; 12603 case Intrinsic::ppc_altivec_stvx: 12604 case Intrinsic::ppc_altivec_stvxl: 12605 case Intrinsic::ppc_vsx_stxvw4x: 12606 VT = MVT::v4i32; 12607 break; 12608 case Intrinsic::ppc_vsx_stxvd2x: 12609 VT = MVT::v2f64; 12610 break; 12611 case Intrinsic::ppc_vsx_stxvw4x_be: 12612 VT = MVT::v4i32; 12613 break; 12614 case Intrinsic::ppc_vsx_stxvd2x_be: 12615 VT = MVT::v2f64; 12616 break; 12617 case Intrinsic::ppc_altivec_stvebx: 12618 VT = MVT::i8; 12619 break; 12620 case Intrinsic::ppc_altivec_stvehx: 12621 VT = MVT::i16; 12622 break; 12623 case Intrinsic::ppc_altivec_stvewx: 12624 VT = MVT::i32; 12625 break; 12626 } 12627 12628 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12629 } 12630 12631 return false; 12632 } 12633 12634 // Return true is there is a nearyby consecutive load to the one provided 12635 // (regardless of alignment). We search up and down the chain, looking though 12636 // token factors and other loads (but nothing else). As a result, a true result 12637 // indicates that it is safe to create a new consecutive load adjacent to the 12638 // load provided. 12639 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12640 SDValue Chain = LD->getChain(); 12641 EVT VT = LD->getMemoryVT(); 12642 12643 SmallSet<SDNode *, 16> LoadRoots; 12644 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12645 SmallSet<SDNode *, 16> Visited; 12646 12647 // First, search up the chain, branching to follow all token-factor operands. 12648 // If we find a consecutive load, then we're done, otherwise, record all 12649 // nodes just above the top-level loads and token factors. 12650 while (!Queue.empty()) { 12651 SDNode *ChainNext = Queue.pop_back_val(); 12652 if (!Visited.insert(ChainNext).second) 12653 continue; 12654 12655 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12656 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12657 return true; 12658 12659 if (!Visited.count(ChainLD->getChain().getNode())) 12660 Queue.push_back(ChainLD->getChain().getNode()); 12661 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12662 for (const SDUse &O : ChainNext->ops()) 12663 if (!Visited.count(O.getNode())) 12664 Queue.push_back(O.getNode()); 12665 } else 12666 LoadRoots.insert(ChainNext); 12667 } 12668 12669 // Second, search down the chain, starting from the top-level nodes recorded 12670 // in the first phase. These top-level nodes are the nodes just above all 12671 // loads and token factors. Starting with their uses, recursively look though 12672 // all loads (just the chain uses) and token factors to find a consecutive 12673 // load. 12674 Visited.clear(); 12675 Queue.clear(); 12676 12677 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12678 IE = LoadRoots.end(); I != IE; ++I) { 12679 Queue.push_back(*I); 12680 12681 while (!Queue.empty()) { 12682 SDNode *LoadRoot = Queue.pop_back_val(); 12683 if (!Visited.insert(LoadRoot).second) 12684 continue; 12685 12686 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12687 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12688 return true; 12689 12690 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12691 UE = LoadRoot->use_end(); UI != UE; ++UI) 12692 if (((isa<MemSDNode>(*UI) && 12693 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12694 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12695 Queue.push_back(*UI); 12696 } 12697 } 12698 12699 return false; 12700 } 12701 12702 /// This function is called when we have proved that a SETCC node can be replaced 12703 /// by subtraction (and other supporting instructions) so that the result of 12704 /// comparison is kept in a GPR instead of CR. This function is purely for 12705 /// codegen purposes and has some flags to guide the codegen process. 12706 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12707 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12708 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12709 12710 // Zero extend the operands to the largest legal integer. Originally, they 12711 // must be of a strictly smaller size. 12712 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12713 DAG.getConstant(Size, DL, MVT::i32)); 12714 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12715 DAG.getConstant(Size, DL, MVT::i32)); 12716 12717 // Swap if needed. Depends on the condition code. 12718 if (Swap) 12719 std::swap(Op0, Op1); 12720 12721 // Subtract extended integers. 12722 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12723 12724 // Move the sign bit to the least significant position and zero out the rest. 12725 // Now the least significant bit carries the result of original comparison. 12726 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12727 DAG.getConstant(Size - 1, DL, MVT::i32)); 12728 auto Final = Shifted; 12729 12730 // Complement the result if needed. Based on the condition code. 12731 if (Complement) 12732 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12733 DAG.getConstant(1, DL, MVT::i64)); 12734 12735 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12736 } 12737 12738 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12739 DAGCombinerInfo &DCI) const { 12740 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12741 12742 SelectionDAG &DAG = DCI.DAG; 12743 SDLoc DL(N); 12744 12745 // Size of integers being compared has a critical role in the following 12746 // analysis, so we prefer to do this when all types are legal. 12747 if (!DCI.isAfterLegalizeDAG()) 12748 return SDValue(); 12749 12750 // If all users of SETCC extend its value to a legal integer type 12751 // then we replace SETCC with a subtraction 12752 for (SDNode::use_iterator UI = N->use_begin(), 12753 UE = N->use_end(); UI != UE; ++UI) { 12754 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12755 return SDValue(); 12756 } 12757 12758 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12759 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12760 12761 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12762 12763 if (OpSize < Size) { 12764 switch (CC) { 12765 default: break; 12766 case ISD::SETULT: 12767 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12768 case ISD::SETULE: 12769 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12770 case ISD::SETUGT: 12771 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12772 case ISD::SETUGE: 12773 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12774 } 12775 } 12776 12777 return SDValue(); 12778 } 12779 12780 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12781 DAGCombinerInfo &DCI) const { 12782 SelectionDAG &DAG = DCI.DAG; 12783 SDLoc dl(N); 12784 12785 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12786 // If we're tracking CR bits, we need to be careful that we don't have: 12787 // trunc(binary-ops(zext(x), zext(y))) 12788 // or 12789 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12790 // such that we're unnecessarily moving things into GPRs when it would be 12791 // better to keep them in CR bits. 12792 12793 // Note that trunc here can be an actual i1 trunc, or can be the effective 12794 // truncation that comes from a setcc or select_cc. 12795 if (N->getOpcode() == ISD::TRUNCATE && 12796 N->getValueType(0) != MVT::i1) 12797 return SDValue(); 12798 12799 if (N->getOperand(0).getValueType() != MVT::i32 && 12800 N->getOperand(0).getValueType() != MVT::i64) 12801 return SDValue(); 12802 12803 if (N->getOpcode() == ISD::SETCC || 12804 N->getOpcode() == ISD::SELECT_CC) { 12805 // If we're looking at a comparison, then we need to make sure that the 12806 // high bits (all except for the first) don't matter the result. 12807 ISD::CondCode CC = 12808 cast<CondCodeSDNode>(N->getOperand( 12809 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12810 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12811 12812 if (ISD::isSignedIntSetCC(CC)) { 12813 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12814 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12815 return SDValue(); 12816 } else if (ISD::isUnsignedIntSetCC(CC)) { 12817 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12818 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12819 !DAG.MaskedValueIsZero(N->getOperand(1), 12820 APInt::getHighBitsSet(OpBits, OpBits-1))) 12821 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12822 : SDValue()); 12823 } else { 12824 // This is neither a signed nor an unsigned comparison, just make sure 12825 // that the high bits are equal. 12826 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12827 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12828 12829 // We don't really care about what is known about the first bit (if 12830 // anything), so clear it in all masks prior to comparing them. 12831 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12832 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12833 12834 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12835 return SDValue(); 12836 } 12837 } 12838 12839 // We now know that the higher-order bits are irrelevant, we just need to 12840 // make sure that all of the intermediate operations are bit operations, and 12841 // all inputs are extensions. 12842 if (N->getOperand(0).getOpcode() != ISD::AND && 12843 N->getOperand(0).getOpcode() != ISD::OR && 12844 N->getOperand(0).getOpcode() != ISD::XOR && 12845 N->getOperand(0).getOpcode() != ISD::SELECT && 12846 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12847 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12848 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12849 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12850 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12851 return SDValue(); 12852 12853 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12854 N->getOperand(1).getOpcode() != ISD::AND && 12855 N->getOperand(1).getOpcode() != ISD::OR && 12856 N->getOperand(1).getOpcode() != ISD::XOR && 12857 N->getOperand(1).getOpcode() != ISD::SELECT && 12858 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12859 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12860 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12861 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12862 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12863 return SDValue(); 12864 12865 SmallVector<SDValue, 4> Inputs; 12866 SmallVector<SDValue, 8> BinOps, PromOps; 12867 SmallPtrSet<SDNode *, 16> Visited; 12868 12869 for (unsigned i = 0; i < 2; ++i) { 12870 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12871 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12872 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12873 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12874 isa<ConstantSDNode>(N->getOperand(i))) 12875 Inputs.push_back(N->getOperand(i)); 12876 else 12877 BinOps.push_back(N->getOperand(i)); 12878 12879 if (N->getOpcode() == ISD::TRUNCATE) 12880 break; 12881 } 12882 12883 // Visit all inputs, collect all binary operations (and, or, xor and 12884 // select) that are all fed by extensions. 12885 while (!BinOps.empty()) { 12886 SDValue BinOp = BinOps.back(); 12887 BinOps.pop_back(); 12888 12889 if (!Visited.insert(BinOp.getNode()).second) 12890 continue; 12891 12892 PromOps.push_back(BinOp); 12893 12894 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12895 // The condition of the select is not promoted. 12896 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12897 continue; 12898 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12899 continue; 12900 12901 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12902 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12903 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12904 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12905 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12906 Inputs.push_back(BinOp.getOperand(i)); 12907 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12908 BinOp.getOperand(i).getOpcode() == ISD::OR || 12909 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12910 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12911 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12912 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12913 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12914 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12915 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12916 BinOps.push_back(BinOp.getOperand(i)); 12917 } else { 12918 // We have an input that is not an extension or another binary 12919 // operation; we'll abort this transformation. 12920 return SDValue(); 12921 } 12922 } 12923 } 12924 12925 // Make sure that this is a self-contained cluster of operations (which 12926 // is not quite the same thing as saying that everything has only one 12927 // use). 12928 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12929 if (isa<ConstantSDNode>(Inputs[i])) 12930 continue; 12931 12932 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12933 UE = Inputs[i].getNode()->use_end(); 12934 UI != UE; ++UI) { 12935 SDNode *User = *UI; 12936 if (User != N && !Visited.count(User)) 12937 return SDValue(); 12938 12939 // Make sure that we're not going to promote the non-output-value 12940 // operand(s) or SELECT or SELECT_CC. 12941 // FIXME: Although we could sometimes handle this, and it does occur in 12942 // practice that one of the condition inputs to the select is also one of 12943 // the outputs, we currently can't deal with this. 12944 if (User->getOpcode() == ISD::SELECT) { 12945 if (User->getOperand(0) == Inputs[i]) 12946 return SDValue(); 12947 } else if (User->getOpcode() == ISD::SELECT_CC) { 12948 if (User->getOperand(0) == Inputs[i] || 12949 User->getOperand(1) == Inputs[i]) 12950 return SDValue(); 12951 } 12952 } 12953 } 12954 12955 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12956 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12957 UE = PromOps[i].getNode()->use_end(); 12958 UI != UE; ++UI) { 12959 SDNode *User = *UI; 12960 if (User != N && !Visited.count(User)) 12961 return SDValue(); 12962 12963 // Make sure that we're not going to promote the non-output-value 12964 // operand(s) or SELECT or SELECT_CC. 12965 // FIXME: Although we could sometimes handle this, and it does occur in 12966 // practice that one of the condition inputs to the select is also one of 12967 // the outputs, we currently can't deal with this. 12968 if (User->getOpcode() == ISD::SELECT) { 12969 if (User->getOperand(0) == PromOps[i]) 12970 return SDValue(); 12971 } else if (User->getOpcode() == ISD::SELECT_CC) { 12972 if (User->getOperand(0) == PromOps[i] || 12973 User->getOperand(1) == PromOps[i]) 12974 return SDValue(); 12975 } 12976 } 12977 } 12978 12979 // Replace all inputs with the extension operand. 12980 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12981 // Constants may have users outside the cluster of to-be-promoted nodes, 12982 // and so we need to replace those as we do the promotions. 12983 if (isa<ConstantSDNode>(Inputs[i])) 12984 continue; 12985 else 12986 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12987 } 12988 12989 std::list<HandleSDNode> PromOpHandles; 12990 for (auto &PromOp : PromOps) 12991 PromOpHandles.emplace_back(PromOp); 12992 12993 // Replace all operations (these are all the same, but have a different 12994 // (i1) return type). DAG.getNode will validate that the types of 12995 // a binary operator match, so go through the list in reverse so that 12996 // we've likely promoted both operands first. Any intermediate truncations or 12997 // extensions disappear. 12998 while (!PromOpHandles.empty()) { 12999 SDValue PromOp = PromOpHandles.back().getValue(); 13000 PromOpHandles.pop_back(); 13001 13002 if (PromOp.getOpcode() == ISD::TRUNCATE || 13003 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13004 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13005 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13006 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13007 PromOp.getOperand(0).getValueType() != MVT::i1) { 13008 // The operand is not yet ready (see comment below). 13009 PromOpHandles.emplace_front(PromOp); 13010 continue; 13011 } 13012 13013 SDValue RepValue = PromOp.getOperand(0); 13014 if (isa<ConstantSDNode>(RepValue)) 13015 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13016 13017 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13018 continue; 13019 } 13020 13021 unsigned C; 13022 switch (PromOp.getOpcode()) { 13023 default: C = 0; break; 13024 case ISD::SELECT: C = 1; break; 13025 case ISD::SELECT_CC: C = 2; break; 13026 } 13027 13028 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13029 PromOp.getOperand(C).getValueType() != MVT::i1) || 13030 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13031 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13032 // The to-be-promoted operands of this node have not yet been 13033 // promoted (this should be rare because we're going through the 13034 // list backward, but if one of the operands has several users in 13035 // this cluster of to-be-promoted nodes, it is possible). 13036 PromOpHandles.emplace_front(PromOp); 13037 continue; 13038 } 13039 13040 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13041 PromOp.getNode()->op_end()); 13042 13043 // If there are any constant inputs, make sure they're replaced now. 13044 for (unsigned i = 0; i < 2; ++i) 13045 if (isa<ConstantSDNode>(Ops[C+i])) 13046 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13047 13048 DAG.ReplaceAllUsesOfValueWith(PromOp, 13049 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13050 } 13051 13052 // Now we're left with the initial truncation itself. 13053 if (N->getOpcode() == ISD::TRUNCATE) 13054 return N->getOperand(0); 13055 13056 // Otherwise, this is a comparison. The operands to be compared have just 13057 // changed type (to i1), but everything else is the same. 13058 return SDValue(N, 0); 13059 } 13060 13061 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13062 DAGCombinerInfo &DCI) const { 13063 SelectionDAG &DAG = DCI.DAG; 13064 SDLoc dl(N); 13065 13066 // If we're tracking CR bits, we need to be careful that we don't have: 13067 // zext(binary-ops(trunc(x), trunc(y))) 13068 // or 13069 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13070 // such that we're unnecessarily moving things into CR bits that can more 13071 // efficiently stay in GPRs. Note that if we're not certain that the high 13072 // bits are set as required by the final extension, we still may need to do 13073 // some masking to get the proper behavior. 13074 13075 // This same functionality is important on PPC64 when dealing with 13076 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13077 // the return values of functions. Because it is so similar, it is handled 13078 // here as well. 13079 13080 if (N->getValueType(0) != MVT::i32 && 13081 N->getValueType(0) != MVT::i64) 13082 return SDValue(); 13083 13084 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13085 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13086 return SDValue(); 13087 13088 if (N->getOperand(0).getOpcode() != ISD::AND && 13089 N->getOperand(0).getOpcode() != ISD::OR && 13090 N->getOperand(0).getOpcode() != ISD::XOR && 13091 N->getOperand(0).getOpcode() != ISD::SELECT && 13092 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13093 return SDValue(); 13094 13095 SmallVector<SDValue, 4> Inputs; 13096 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13097 SmallPtrSet<SDNode *, 16> Visited; 13098 13099 // Visit all inputs, collect all binary operations (and, or, xor and 13100 // select) that are all fed by truncations. 13101 while (!BinOps.empty()) { 13102 SDValue BinOp = BinOps.back(); 13103 BinOps.pop_back(); 13104 13105 if (!Visited.insert(BinOp.getNode()).second) 13106 continue; 13107 13108 PromOps.push_back(BinOp); 13109 13110 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13111 // The condition of the select is not promoted. 13112 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13113 continue; 13114 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13115 continue; 13116 13117 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13118 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13119 Inputs.push_back(BinOp.getOperand(i)); 13120 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13121 BinOp.getOperand(i).getOpcode() == ISD::OR || 13122 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13123 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13124 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13125 BinOps.push_back(BinOp.getOperand(i)); 13126 } else { 13127 // We have an input that is not a truncation or another binary 13128 // operation; we'll abort this transformation. 13129 return SDValue(); 13130 } 13131 } 13132 } 13133 13134 // The operands of a select that must be truncated when the select is 13135 // promoted because the operand is actually part of the to-be-promoted set. 13136 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13137 13138 // Make sure that this is a self-contained cluster of operations (which 13139 // is not quite the same thing as saying that everything has only one 13140 // use). 13141 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13142 if (isa<ConstantSDNode>(Inputs[i])) 13143 continue; 13144 13145 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13146 UE = Inputs[i].getNode()->use_end(); 13147 UI != UE; ++UI) { 13148 SDNode *User = *UI; 13149 if (User != N && !Visited.count(User)) 13150 return SDValue(); 13151 13152 // If we're going to promote the non-output-value operand(s) or SELECT or 13153 // SELECT_CC, record them for truncation. 13154 if (User->getOpcode() == ISD::SELECT) { 13155 if (User->getOperand(0) == Inputs[i]) 13156 SelectTruncOp[0].insert(std::make_pair(User, 13157 User->getOperand(0).getValueType())); 13158 } else if (User->getOpcode() == ISD::SELECT_CC) { 13159 if (User->getOperand(0) == Inputs[i]) 13160 SelectTruncOp[0].insert(std::make_pair(User, 13161 User->getOperand(0).getValueType())); 13162 if (User->getOperand(1) == Inputs[i]) 13163 SelectTruncOp[1].insert(std::make_pair(User, 13164 User->getOperand(1).getValueType())); 13165 } 13166 } 13167 } 13168 13169 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13170 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13171 UE = PromOps[i].getNode()->use_end(); 13172 UI != UE; ++UI) { 13173 SDNode *User = *UI; 13174 if (User != N && !Visited.count(User)) 13175 return SDValue(); 13176 13177 // If we're going to promote the non-output-value operand(s) or SELECT or 13178 // SELECT_CC, record them for truncation. 13179 if (User->getOpcode() == ISD::SELECT) { 13180 if (User->getOperand(0) == PromOps[i]) 13181 SelectTruncOp[0].insert(std::make_pair(User, 13182 User->getOperand(0).getValueType())); 13183 } else if (User->getOpcode() == ISD::SELECT_CC) { 13184 if (User->getOperand(0) == PromOps[i]) 13185 SelectTruncOp[0].insert(std::make_pair(User, 13186 User->getOperand(0).getValueType())); 13187 if (User->getOperand(1) == PromOps[i]) 13188 SelectTruncOp[1].insert(std::make_pair(User, 13189 User->getOperand(1).getValueType())); 13190 } 13191 } 13192 } 13193 13194 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13195 bool ReallyNeedsExt = false; 13196 if (N->getOpcode() != ISD::ANY_EXTEND) { 13197 // If all of the inputs are not already sign/zero extended, then 13198 // we'll still need to do that at the end. 13199 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13200 if (isa<ConstantSDNode>(Inputs[i])) 13201 continue; 13202 13203 unsigned OpBits = 13204 Inputs[i].getOperand(0).getValueSizeInBits(); 13205 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13206 13207 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13208 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13209 APInt::getHighBitsSet(OpBits, 13210 OpBits-PromBits))) || 13211 (N->getOpcode() == ISD::SIGN_EXTEND && 13212 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13213 (OpBits-(PromBits-1)))) { 13214 ReallyNeedsExt = true; 13215 break; 13216 } 13217 } 13218 } 13219 13220 // Replace all inputs, either with the truncation operand, or a 13221 // truncation or extension to the final output type. 13222 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13223 // Constant inputs need to be replaced with the to-be-promoted nodes that 13224 // use them because they might have users outside of the cluster of 13225 // promoted nodes. 13226 if (isa<ConstantSDNode>(Inputs[i])) 13227 continue; 13228 13229 SDValue InSrc = Inputs[i].getOperand(0); 13230 if (Inputs[i].getValueType() == N->getValueType(0)) 13231 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13232 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13233 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13234 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13235 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13236 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13237 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13238 else 13239 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13240 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13241 } 13242 13243 std::list<HandleSDNode> PromOpHandles; 13244 for (auto &PromOp : PromOps) 13245 PromOpHandles.emplace_back(PromOp); 13246 13247 // Replace all operations (these are all the same, but have a different 13248 // (promoted) return type). DAG.getNode will validate that the types of 13249 // a binary operator match, so go through the list in reverse so that 13250 // we've likely promoted both operands first. 13251 while (!PromOpHandles.empty()) { 13252 SDValue PromOp = PromOpHandles.back().getValue(); 13253 PromOpHandles.pop_back(); 13254 13255 unsigned C; 13256 switch (PromOp.getOpcode()) { 13257 default: C = 0; break; 13258 case ISD::SELECT: C = 1; break; 13259 case ISD::SELECT_CC: C = 2; break; 13260 } 13261 13262 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13263 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13264 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13265 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13266 // The to-be-promoted operands of this node have not yet been 13267 // promoted (this should be rare because we're going through the 13268 // list backward, but if one of the operands has several users in 13269 // this cluster of to-be-promoted nodes, it is possible). 13270 PromOpHandles.emplace_front(PromOp); 13271 continue; 13272 } 13273 13274 // For SELECT and SELECT_CC nodes, we do a similar check for any 13275 // to-be-promoted comparison inputs. 13276 if (PromOp.getOpcode() == ISD::SELECT || 13277 PromOp.getOpcode() == ISD::SELECT_CC) { 13278 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13279 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13280 (SelectTruncOp[1].count(PromOp.getNode()) && 13281 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13282 PromOpHandles.emplace_front(PromOp); 13283 continue; 13284 } 13285 } 13286 13287 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13288 PromOp.getNode()->op_end()); 13289 13290 // If this node has constant inputs, then they'll need to be promoted here. 13291 for (unsigned i = 0; i < 2; ++i) { 13292 if (!isa<ConstantSDNode>(Ops[C+i])) 13293 continue; 13294 if (Ops[C+i].getValueType() == N->getValueType(0)) 13295 continue; 13296 13297 if (N->getOpcode() == ISD::SIGN_EXTEND) 13298 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13299 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13300 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13301 else 13302 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13303 } 13304 13305 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13306 // truncate them again to the original value type. 13307 if (PromOp.getOpcode() == ISD::SELECT || 13308 PromOp.getOpcode() == ISD::SELECT_CC) { 13309 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13310 if (SI0 != SelectTruncOp[0].end()) 13311 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13312 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13313 if (SI1 != SelectTruncOp[1].end()) 13314 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13315 } 13316 13317 DAG.ReplaceAllUsesOfValueWith(PromOp, 13318 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13319 } 13320 13321 // Now we're left with the initial extension itself. 13322 if (!ReallyNeedsExt) 13323 return N->getOperand(0); 13324 13325 // To zero extend, just mask off everything except for the first bit (in the 13326 // i1 case). 13327 if (N->getOpcode() == ISD::ZERO_EXTEND) 13328 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13329 DAG.getConstant(APInt::getLowBitsSet( 13330 N->getValueSizeInBits(0), PromBits), 13331 dl, N->getValueType(0))); 13332 13333 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13334 "Invalid extension type"); 13335 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13336 SDValue ShiftCst = 13337 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13338 return DAG.getNode( 13339 ISD::SRA, dl, N->getValueType(0), 13340 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13341 ShiftCst); 13342 } 13343 13344 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13345 DAGCombinerInfo &DCI) const { 13346 assert(N->getOpcode() == ISD::SETCC && 13347 "Should be called with a SETCC node"); 13348 13349 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13350 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13351 SDValue LHS = N->getOperand(0); 13352 SDValue RHS = N->getOperand(1); 13353 13354 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13355 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13356 LHS.hasOneUse()) 13357 std::swap(LHS, RHS); 13358 13359 // x == 0-y --> x+y == 0 13360 // x != 0-y --> x+y != 0 13361 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13362 RHS.hasOneUse()) { 13363 SDLoc DL(N); 13364 SelectionDAG &DAG = DCI.DAG; 13365 EVT VT = N->getValueType(0); 13366 EVT OpVT = LHS.getValueType(); 13367 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13368 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13369 } 13370 } 13371 13372 return DAGCombineTruncBoolExt(N, DCI); 13373 } 13374 13375 // Is this an extending load from an f32 to an f64? 13376 static bool isFPExtLoad(SDValue Op) { 13377 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13378 return LD->getExtensionType() == ISD::EXTLOAD && 13379 Op.getValueType() == MVT::f64; 13380 return false; 13381 } 13382 13383 /// Reduces the number of fp-to-int conversion when building a vector. 13384 /// 13385 /// If this vector is built out of floating to integer conversions, 13386 /// transform it to a vector built out of floating point values followed by a 13387 /// single floating to integer conversion of the vector. 13388 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13389 /// becomes (fptosi (build_vector ($A, $B, ...))) 13390 SDValue PPCTargetLowering:: 13391 combineElementTruncationToVectorTruncation(SDNode *N, 13392 DAGCombinerInfo &DCI) const { 13393 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13394 "Should be called with a BUILD_VECTOR node"); 13395 13396 SelectionDAG &DAG = DCI.DAG; 13397 SDLoc dl(N); 13398 13399 SDValue FirstInput = N->getOperand(0); 13400 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13401 "The input operand must be an fp-to-int conversion."); 13402 13403 // This combine happens after legalization so the fp_to_[su]i nodes are 13404 // already converted to PPCSISD nodes. 13405 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13406 if (FirstConversion == PPCISD::FCTIDZ || 13407 FirstConversion == PPCISD::FCTIDUZ || 13408 FirstConversion == PPCISD::FCTIWZ || 13409 FirstConversion == PPCISD::FCTIWUZ) { 13410 bool IsSplat = true; 13411 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13412 FirstConversion == PPCISD::FCTIWUZ; 13413 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13414 SmallVector<SDValue, 4> Ops; 13415 EVT TargetVT = N->getValueType(0); 13416 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13417 SDValue NextOp = N->getOperand(i); 13418 if (NextOp.getOpcode() != PPCISD::MFVSR) 13419 return SDValue(); 13420 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13421 if (NextConversion != FirstConversion) 13422 return SDValue(); 13423 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13424 // This is not valid if the input was originally double precision. It is 13425 // also not profitable to do unless this is an extending load in which 13426 // case doing this combine will allow us to combine consecutive loads. 13427 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13428 return SDValue(); 13429 if (N->getOperand(i) != FirstInput) 13430 IsSplat = false; 13431 } 13432 13433 // If this is a splat, we leave it as-is since there will be only a single 13434 // fp-to-int conversion followed by a splat of the integer. This is better 13435 // for 32-bit and smaller ints and neutral for 64-bit ints. 13436 if (IsSplat) 13437 return SDValue(); 13438 13439 // Now that we know we have the right type of node, get its operands 13440 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13441 SDValue In = N->getOperand(i).getOperand(0); 13442 if (Is32Bit) { 13443 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13444 // here, we know that all inputs are extending loads so this is safe). 13445 if (In.isUndef()) 13446 Ops.push_back(DAG.getUNDEF(SrcVT)); 13447 else { 13448 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13449 MVT::f32, In.getOperand(0), 13450 DAG.getIntPtrConstant(1, dl)); 13451 Ops.push_back(Trunc); 13452 } 13453 } else 13454 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13455 } 13456 13457 unsigned Opcode; 13458 if (FirstConversion == PPCISD::FCTIDZ || 13459 FirstConversion == PPCISD::FCTIWZ) 13460 Opcode = ISD::FP_TO_SINT; 13461 else 13462 Opcode = ISD::FP_TO_UINT; 13463 13464 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13465 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13466 return DAG.getNode(Opcode, dl, TargetVT, BV); 13467 } 13468 return SDValue(); 13469 } 13470 13471 /// Reduce the number of loads when building a vector. 13472 /// 13473 /// Building a vector out of multiple loads can be converted to a load 13474 /// of the vector type if the loads are consecutive. If the loads are 13475 /// consecutive but in descending order, a shuffle is added at the end 13476 /// to reorder the vector. 13477 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13478 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13479 "Should be called with a BUILD_VECTOR node"); 13480 13481 SDLoc dl(N); 13482 13483 // Return early for non byte-sized type, as they can't be consecutive. 13484 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13485 return SDValue(); 13486 13487 bool InputsAreConsecutiveLoads = true; 13488 bool InputsAreReverseConsecutive = true; 13489 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13490 SDValue FirstInput = N->getOperand(0); 13491 bool IsRoundOfExtLoad = false; 13492 13493 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13494 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13495 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13496 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13497 } 13498 // Not a build vector of (possibly fp_rounded) loads. 13499 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13500 N->getNumOperands() == 1) 13501 return SDValue(); 13502 13503 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13504 // If any inputs are fp_round(extload), they all must be. 13505 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13506 return SDValue(); 13507 13508 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13509 N->getOperand(i); 13510 if (NextInput.getOpcode() != ISD::LOAD) 13511 return SDValue(); 13512 13513 SDValue PreviousInput = 13514 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13515 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13516 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13517 13518 // If any inputs are fp_round(extload), they all must be. 13519 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13520 return SDValue(); 13521 13522 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13523 InputsAreConsecutiveLoads = false; 13524 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13525 InputsAreReverseConsecutive = false; 13526 13527 // Exit early if the loads are neither consecutive nor reverse consecutive. 13528 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13529 return SDValue(); 13530 } 13531 13532 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13533 "The loads cannot be both consecutive and reverse consecutive."); 13534 13535 SDValue FirstLoadOp = 13536 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13537 SDValue LastLoadOp = 13538 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13539 N->getOperand(N->getNumOperands()-1); 13540 13541 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13542 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13543 if (InputsAreConsecutiveLoads) { 13544 assert(LD1 && "Input needs to be a LoadSDNode."); 13545 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13546 LD1->getBasePtr(), LD1->getPointerInfo(), 13547 LD1->getAlignment()); 13548 } 13549 if (InputsAreReverseConsecutive) { 13550 assert(LDL && "Input needs to be a LoadSDNode."); 13551 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13552 LDL->getBasePtr(), LDL->getPointerInfo(), 13553 LDL->getAlignment()); 13554 SmallVector<int, 16> Ops; 13555 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13556 Ops.push_back(i); 13557 13558 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13559 DAG.getUNDEF(N->getValueType(0)), Ops); 13560 } 13561 return SDValue(); 13562 } 13563 13564 // This function adds the required vector_shuffle needed to get 13565 // the elements of the vector extract in the correct position 13566 // as specified by the CorrectElems encoding. 13567 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13568 SDValue Input, uint64_t Elems, 13569 uint64_t CorrectElems) { 13570 SDLoc dl(N); 13571 13572 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13573 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13574 13575 // Knowing the element indices being extracted from the original 13576 // vector and the order in which they're being inserted, just put 13577 // them at element indices required for the instruction. 13578 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13579 if (DAG.getDataLayout().isLittleEndian()) 13580 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13581 else 13582 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13583 CorrectElems = CorrectElems >> 8; 13584 Elems = Elems >> 8; 13585 } 13586 13587 SDValue Shuffle = 13588 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13589 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13590 13591 EVT VT = N->getValueType(0); 13592 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13593 13594 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13595 Input.getValueType().getVectorElementType(), 13596 VT.getVectorNumElements()); 13597 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13598 DAG.getValueType(ExtVT)); 13599 } 13600 13601 // Look for build vector patterns where input operands come from sign 13602 // extended vector_extract elements of specific indices. If the correct indices 13603 // aren't used, add a vector shuffle to fix up the indices and create 13604 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13605 // during instruction selection. 13606 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13607 // This array encodes the indices that the vector sign extend instructions 13608 // extract from when extending from one type to another for both BE and LE. 13609 // The right nibble of each byte corresponds to the LE incides. 13610 // and the left nibble of each byte corresponds to the BE incides. 13611 // For example: 0x3074B8FC byte->word 13612 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13613 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13614 // For example: 0x000070F8 byte->double word 13615 // For LE: the allowed indices are: 0x0,0x8 13616 // For BE: the allowed indices are: 0x7,0xF 13617 uint64_t TargetElems[] = { 13618 0x3074B8FC, // b->w 13619 0x000070F8, // b->d 13620 0x10325476, // h->w 13621 0x00003074, // h->d 13622 0x00001032, // w->d 13623 }; 13624 13625 uint64_t Elems = 0; 13626 int Index; 13627 SDValue Input; 13628 13629 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13630 if (!Op) 13631 return false; 13632 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13633 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13634 return false; 13635 13636 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13637 // of the right width. 13638 SDValue Extract = Op.getOperand(0); 13639 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13640 Extract = Extract.getOperand(0); 13641 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13642 return false; 13643 13644 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13645 if (!ExtOp) 13646 return false; 13647 13648 Index = ExtOp->getZExtValue(); 13649 if (Input && Input != Extract.getOperand(0)) 13650 return false; 13651 13652 if (!Input) 13653 Input = Extract.getOperand(0); 13654 13655 Elems = Elems << 8; 13656 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13657 Elems |= Index; 13658 13659 return true; 13660 }; 13661 13662 // If the build vector operands aren't sign extended vector extracts, 13663 // of the same input vector, then return. 13664 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13665 if (!isSExtOfVecExtract(N->getOperand(i))) { 13666 return SDValue(); 13667 } 13668 } 13669 13670 // If the vector extract indicies are not correct, add the appropriate 13671 // vector_shuffle. 13672 int TgtElemArrayIdx; 13673 int InputSize = Input.getValueType().getScalarSizeInBits(); 13674 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13675 if (InputSize + OutputSize == 40) 13676 TgtElemArrayIdx = 0; 13677 else if (InputSize + OutputSize == 72) 13678 TgtElemArrayIdx = 1; 13679 else if (InputSize + OutputSize == 48) 13680 TgtElemArrayIdx = 2; 13681 else if (InputSize + OutputSize == 80) 13682 TgtElemArrayIdx = 3; 13683 else if (InputSize + OutputSize == 96) 13684 TgtElemArrayIdx = 4; 13685 else 13686 return SDValue(); 13687 13688 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13689 CorrectElems = DAG.getDataLayout().isLittleEndian() 13690 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13691 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13692 if (Elems != CorrectElems) { 13693 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13694 } 13695 13696 // Regular lowering will catch cases where a shuffle is not needed. 13697 return SDValue(); 13698 } 13699 13700 // Look for the pattern of a load from a narrow width to i128, feeding 13701 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13702 // (LXVRZX). This node represents a zero extending load that will be matched 13703 // to the Load VSX Vector Rightmost instructions. 13704 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13705 SDLoc DL(N); 13706 13707 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13708 if (N->getValueType(0) != MVT::v1i128) 13709 return SDValue(); 13710 13711 SDValue Operand = N->getOperand(0); 13712 // Proceed with the transformation if the operand to the BUILD_VECTOR 13713 // is a load instruction. 13714 if (Operand.getOpcode() != ISD::LOAD) 13715 return SDValue(); 13716 13717 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13718 EVT MemoryType = LD->getMemoryVT(); 13719 13720 // This transformation is only valid if the we are loading either a byte, 13721 // halfword, word, or doubleword. 13722 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13723 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13724 13725 // Ensure that the load from the narrow width is being zero extended to i128. 13726 if (!ValidLDType || 13727 (LD->getExtensionType() != ISD::ZEXTLOAD && 13728 LD->getExtensionType() != ISD::EXTLOAD)) 13729 return SDValue(); 13730 13731 SDValue LoadOps[] = { 13732 LD->getChain(), LD->getBasePtr(), 13733 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13734 13735 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13736 DAG.getVTList(MVT::v1i128, MVT::Other), 13737 LoadOps, MemoryType, LD->getMemOperand()); 13738 } 13739 13740 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13741 DAGCombinerInfo &DCI) const { 13742 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13743 "Should be called with a BUILD_VECTOR node"); 13744 13745 SelectionDAG &DAG = DCI.DAG; 13746 SDLoc dl(N); 13747 13748 if (!Subtarget.hasVSX()) 13749 return SDValue(); 13750 13751 // The target independent DAG combiner will leave a build_vector of 13752 // float-to-int conversions intact. We can generate MUCH better code for 13753 // a float-to-int conversion of a vector of floats. 13754 SDValue FirstInput = N->getOperand(0); 13755 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13756 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13757 if (Reduced) 13758 return Reduced; 13759 } 13760 13761 // If we're building a vector out of consecutive loads, just load that 13762 // vector type. 13763 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13764 if (Reduced) 13765 return Reduced; 13766 13767 // If we're building a vector out of extended elements from another vector 13768 // we have P9 vector integer extend instructions. The code assumes legal 13769 // input types (i.e. it can't handle things like v4i16) so do not run before 13770 // legalization. 13771 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13772 Reduced = combineBVOfVecSExt(N, DAG); 13773 if (Reduced) 13774 return Reduced; 13775 } 13776 13777 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13778 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13779 // is a load from <valid narrow width> to i128. 13780 if (Subtarget.isISA3_1()) { 13781 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13782 if (BVOfZLoad) 13783 return BVOfZLoad; 13784 } 13785 13786 if (N->getValueType(0) != MVT::v2f64) 13787 return SDValue(); 13788 13789 // Looking for: 13790 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13791 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13792 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13793 return SDValue(); 13794 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13795 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13796 return SDValue(); 13797 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13798 return SDValue(); 13799 13800 SDValue Ext1 = FirstInput.getOperand(0); 13801 SDValue Ext2 = N->getOperand(1).getOperand(0); 13802 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13803 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13804 return SDValue(); 13805 13806 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13807 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13808 if (!Ext1Op || !Ext2Op) 13809 return SDValue(); 13810 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13811 Ext1.getOperand(0) != Ext2.getOperand(0)) 13812 return SDValue(); 13813 13814 int FirstElem = Ext1Op->getZExtValue(); 13815 int SecondElem = Ext2Op->getZExtValue(); 13816 int SubvecIdx; 13817 if (FirstElem == 0 && SecondElem == 1) 13818 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13819 else if (FirstElem == 2 && SecondElem == 3) 13820 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13821 else 13822 return SDValue(); 13823 13824 SDValue SrcVec = Ext1.getOperand(0); 13825 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13826 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13827 return DAG.getNode(NodeType, dl, MVT::v2f64, 13828 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13829 } 13830 13831 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13832 DAGCombinerInfo &DCI) const { 13833 assert((N->getOpcode() == ISD::SINT_TO_FP || 13834 N->getOpcode() == ISD::UINT_TO_FP) && 13835 "Need an int -> FP conversion node here"); 13836 13837 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13838 return SDValue(); 13839 13840 SelectionDAG &DAG = DCI.DAG; 13841 SDLoc dl(N); 13842 SDValue Op(N, 0); 13843 13844 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13845 // from the hardware. 13846 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13847 return SDValue(); 13848 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13849 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13850 return SDValue(); 13851 13852 SDValue FirstOperand(Op.getOperand(0)); 13853 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13854 (FirstOperand.getValueType() == MVT::i8 || 13855 FirstOperand.getValueType() == MVT::i16); 13856 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13857 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13858 bool DstDouble = Op.getValueType() == MVT::f64; 13859 unsigned ConvOp = Signed ? 13860 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13861 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13862 SDValue WidthConst = 13863 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13864 dl, false); 13865 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13866 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13867 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13868 DAG.getVTList(MVT::f64, MVT::Other), 13869 Ops, MVT::i8, LDN->getMemOperand()); 13870 13871 // For signed conversion, we need to sign-extend the value in the VSR 13872 if (Signed) { 13873 SDValue ExtOps[] = { Ld, WidthConst }; 13874 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13875 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13876 } else 13877 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13878 } 13879 13880 13881 // For i32 intermediate values, unfortunately, the conversion functions 13882 // leave the upper 32 bits of the value are undefined. Within the set of 13883 // scalar instructions, we have no method for zero- or sign-extending the 13884 // value. Thus, we cannot handle i32 intermediate values here. 13885 if (Op.getOperand(0).getValueType() == MVT::i32) 13886 return SDValue(); 13887 13888 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13889 "UINT_TO_FP is supported only with FPCVT"); 13890 13891 // If we have FCFIDS, then use it when converting to single-precision. 13892 // Otherwise, convert to double-precision and then round. 13893 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13894 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13895 : PPCISD::FCFIDS) 13896 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13897 : PPCISD::FCFID); 13898 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13899 ? MVT::f32 13900 : MVT::f64; 13901 13902 // If we're converting from a float, to an int, and back to a float again, 13903 // then we don't need the store/load pair at all. 13904 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13905 Subtarget.hasFPCVT()) || 13906 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13907 SDValue Src = Op.getOperand(0).getOperand(0); 13908 if (Src.getValueType() == MVT::f32) { 13909 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13910 DCI.AddToWorklist(Src.getNode()); 13911 } else if (Src.getValueType() != MVT::f64) { 13912 // Make sure that we don't pick up a ppc_fp128 source value. 13913 return SDValue(); 13914 } 13915 13916 unsigned FCTOp = 13917 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13918 PPCISD::FCTIDUZ; 13919 13920 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13921 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13922 13923 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13924 FP = DAG.getNode(ISD::FP_ROUND, dl, 13925 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13926 DCI.AddToWorklist(FP.getNode()); 13927 } 13928 13929 return FP; 13930 } 13931 13932 return SDValue(); 13933 } 13934 13935 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13936 // builtins) into loads with swaps. 13937 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13938 DAGCombinerInfo &DCI) const { 13939 SelectionDAG &DAG = DCI.DAG; 13940 SDLoc dl(N); 13941 SDValue Chain; 13942 SDValue Base; 13943 MachineMemOperand *MMO; 13944 13945 switch (N->getOpcode()) { 13946 default: 13947 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13948 case ISD::LOAD: { 13949 LoadSDNode *LD = cast<LoadSDNode>(N); 13950 Chain = LD->getChain(); 13951 Base = LD->getBasePtr(); 13952 MMO = LD->getMemOperand(); 13953 // If the MMO suggests this isn't a load of a full vector, leave 13954 // things alone. For a built-in, we have to make the change for 13955 // correctness, so if there is a size problem that will be a bug. 13956 if (MMO->getSize() < 16) 13957 return SDValue(); 13958 break; 13959 } 13960 case ISD::INTRINSIC_W_CHAIN: { 13961 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13962 Chain = Intrin->getChain(); 13963 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13964 // us what we want. Get operand 2 instead. 13965 Base = Intrin->getOperand(2); 13966 MMO = Intrin->getMemOperand(); 13967 break; 13968 } 13969 } 13970 13971 MVT VecTy = N->getValueType(0).getSimpleVT(); 13972 13973 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13974 // aligned and the type is a vector with elements up to 4 bytes 13975 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13976 VecTy.getScalarSizeInBits() <= 32) { 13977 return SDValue(); 13978 } 13979 13980 SDValue LoadOps[] = { Chain, Base }; 13981 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13982 DAG.getVTList(MVT::v2f64, MVT::Other), 13983 LoadOps, MVT::v2f64, MMO); 13984 13985 DCI.AddToWorklist(Load.getNode()); 13986 Chain = Load.getValue(1); 13987 SDValue Swap = DAG.getNode( 13988 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13989 DCI.AddToWorklist(Swap.getNode()); 13990 13991 // Add a bitcast if the resulting load type doesn't match v2f64. 13992 if (VecTy != MVT::v2f64) { 13993 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13994 DCI.AddToWorklist(N.getNode()); 13995 // Package {bitcast value, swap's chain} to match Load's shape. 13996 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13997 N, Swap.getValue(1)); 13998 } 13999 14000 return Swap; 14001 } 14002 14003 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14004 // builtins) into stores with swaps. 14005 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14006 DAGCombinerInfo &DCI) const { 14007 SelectionDAG &DAG = DCI.DAG; 14008 SDLoc dl(N); 14009 SDValue Chain; 14010 SDValue Base; 14011 unsigned SrcOpnd; 14012 MachineMemOperand *MMO; 14013 14014 switch (N->getOpcode()) { 14015 default: 14016 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14017 case ISD::STORE: { 14018 StoreSDNode *ST = cast<StoreSDNode>(N); 14019 Chain = ST->getChain(); 14020 Base = ST->getBasePtr(); 14021 MMO = ST->getMemOperand(); 14022 SrcOpnd = 1; 14023 // If the MMO suggests this isn't a store of a full vector, leave 14024 // things alone. For a built-in, we have to make the change for 14025 // correctness, so if there is a size problem that will be a bug. 14026 if (MMO->getSize() < 16) 14027 return SDValue(); 14028 break; 14029 } 14030 case ISD::INTRINSIC_VOID: { 14031 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14032 Chain = Intrin->getChain(); 14033 // Intrin->getBasePtr() oddly does not get what we want. 14034 Base = Intrin->getOperand(3); 14035 MMO = Intrin->getMemOperand(); 14036 SrcOpnd = 2; 14037 break; 14038 } 14039 } 14040 14041 SDValue Src = N->getOperand(SrcOpnd); 14042 MVT VecTy = Src.getValueType().getSimpleVT(); 14043 14044 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14045 // aligned and the type is a vector with elements up to 4 bytes 14046 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14047 VecTy.getScalarSizeInBits() <= 32) { 14048 return SDValue(); 14049 } 14050 14051 // All stores are done as v2f64 and possible bit cast. 14052 if (VecTy != MVT::v2f64) { 14053 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14054 DCI.AddToWorklist(Src.getNode()); 14055 } 14056 14057 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14058 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14059 DCI.AddToWorklist(Swap.getNode()); 14060 Chain = Swap.getValue(1); 14061 SDValue StoreOps[] = { Chain, Swap, Base }; 14062 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14063 DAG.getVTList(MVT::Other), 14064 StoreOps, VecTy, MMO); 14065 DCI.AddToWorklist(Store.getNode()); 14066 return Store; 14067 } 14068 14069 // Handle DAG combine for STORE (FP_TO_INT F). 14070 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14071 DAGCombinerInfo &DCI) const { 14072 14073 SelectionDAG &DAG = DCI.DAG; 14074 SDLoc dl(N); 14075 unsigned Opcode = N->getOperand(1).getOpcode(); 14076 14077 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14078 && "Not a FP_TO_INT Instruction!"); 14079 14080 SDValue Val = N->getOperand(1).getOperand(0); 14081 EVT Op1VT = N->getOperand(1).getValueType(); 14082 EVT ResVT = Val.getValueType(); 14083 14084 // Floating point types smaller than 32 bits are not legal on Power. 14085 if (ResVT.getScalarSizeInBits() < 32) 14086 return SDValue(); 14087 14088 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14089 bool ValidTypeForStoreFltAsInt = 14090 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14091 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14092 14093 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14094 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14095 return SDValue(); 14096 14097 // Extend f32 values to f64 14098 if (ResVT.getScalarSizeInBits() == 32) { 14099 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14100 DCI.AddToWorklist(Val.getNode()); 14101 } 14102 14103 // Set signed or unsigned conversion opcode. 14104 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14105 PPCISD::FP_TO_SINT_IN_VSR : 14106 PPCISD::FP_TO_UINT_IN_VSR; 14107 14108 Val = DAG.getNode(ConvOpcode, 14109 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14110 DCI.AddToWorklist(Val.getNode()); 14111 14112 // Set number of bytes being converted. 14113 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14114 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14115 DAG.getIntPtrConstant(ByteSize, dl, false), 14116 DAG.getValueType(Op1VT) }; 14117 14118 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14119 DAG.getVTList(MVT::Other), Ops, 14120 cast<StoreSDNode>(N)->getMemoryVT(), 14121 cast<StoreSDNode>(N)->getMemOperand()); 14122 14123 DCI.AddToWorklist(Val.getNode()); 14124 return Val; 14125 } 14126 14127 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14128 // Check that the source of the element keeps flipping 14129 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14130 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14131 for (int i = 1, e = Mask.size(); i < e; i++) { 14132 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14133 return false; 14134 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14135 return false; 14136 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14137 } 14138 return true; 14139 } 14140 14141 static bool isSplatBV(SDValue Op) { 14142 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14143 return false; 14144 SDValue FirstOp; 14145 14146 // Find first non-undef input. 14147 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14148 FirstOp = Op.getOperand(i); 14149 if (!FirstOp.isUndef()) 14150 break; 14151 } 14152 14153 // All inputs are undef or the same as the first non-undef input. 14154 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14155 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14156 return false; 14157 return true; 14158 } 14159 14160 static SDValue isScalarToVec(SDValue Op) { 14161 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14162 return Op; 14163 if (Op.getOpcode() != ISD::BITCAST) 14164 return SDValue(); 14165 Op = Op.getOperand(0); 14166 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14167 return Op; 14168 return SDValue(); 14169 } 14170 14171 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14172 int LHSMaxIdx, int RHSMinIdx, 14173 int RHSMaxIdx, int HalfVec) { 14174 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14175 int Idx = ShuffV[i]; 14176 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14177 ShuffV[i] += HalfVec; 14178 } 14179 return; 14180 } 14181 14182 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14183 // the original is: 14184 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14185 // In such a case, just change the shuffle mask to extract the element 14186 // from the permuted index. 14187 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14188 SDLoc dl(OrigSToV); 14189 EVT VT = OrigSToV.getValueType(); 14190 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14191 "Expecting a SCALAR_TO_VECTOR here"); 14192 SDValue Input = OrigSToV.getOperand(0); 14193 14194 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14195 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14196 SDValue OrigVector = Input.getOperand(0); 14197 14198 // Can't handle non-const element indices or different vector types 14199 // for the input to the extract and the output of the scalar_to_vector. 14200 if (Idx && VT == OrigVector.getValueType()) { 14201 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14202 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14203 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14204 } 14205 } 14206 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14207 OrigSToV.getOperand(0)); 14208 } 14209 14210 // On little endian subtargets, combine shuffles such as: 14211 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14212 // into: 14213 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14214 // because the latter can be matched to a single instruction merge. 14215 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14216 // to put the value into element zero. Adjust the shuffle mask so that the 14217 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14218 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14219 SelectionDAG &DAG) const { 14220 SDValue LHS = SVN->getOperand(0); 14221 SDValue RHS = SVN->getOperand(1); 14222 auto Mask = SVN->getMask(); 14223 int NumElts = LHS.getValueType().getVectorNumElements(); 14224 SDValue Res(SVN, 0); 14225 SDLoc dl(SVN); 14226 14227 // None of these combines are useful on big endian systems since the ISA 14228 // already has a big endian bias. 14229 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14230 return Res; 14231 14232 // If this is not a shuffle of a shuffle and the first element comes from 14233 // the second vector, canonicalize to the commuted form. This will make it 14234 // more likely to match one of the single instruction patterns. 14235 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14236 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14237 std::swap(LHS, RHS); 14238 Res = DAG.getCommutedVectorShuffle(*SVN); 14239 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14240 } 14241 14242 // Adjust the shuffle mask if either input vector comes from a 14243 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14244 // form (to prevent the need for a swap). 14245 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14246 SDValue SToVLHS = isScalarToVec(LHS); 14247 SDValue SToVRHS = isScalarToVec(RHS); 14248 if (SToVLHS || SToVRHS) { 14249 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14250 : SToVRHS.getValueType().getVectorNumElements(); 14251 int NumEltsOut = ShuffV.size(); 14252 14253 // Initially assume that neither input is permuted. These will be adjusted 14254 // accordingly if either input is. 14255 int LHSMaxIdx = -1; 14256 int RHSMinIdx = -1; 14257 int RHSMaxIdx = -1; 14258 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14259 14260 // Get the permuted scalar to vector nodes for the source(s) that come from 14261 // ISD::SCALAR_TO_VECTOR. 14262 if (SToVLHS) { 14263 // Set up the values for the shuffle vector fixup. 14264 LHSMaxIdx = NumEltsOut / NumEltsIn; 14265 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14266 if (SToVLHS.getValueType() != LHS.getValueType()) 14267 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14268 LHS = SToVLHS; 14269 } 14270 if (SToVRHS) { 14271 RHSMinIdx = NumEltsOut; 14272 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14273 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14274 if (SToVRHS.getValueType() != RHS.getValueType()) 14275 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14276 RHS = SToVRHS; 14277 } 14278 14279 // Fix up the shuffle mask to reflect where the desired element actually is. 14280 // The minimum and maximum indices that correspond to element zero for both 14281 // the LHS and RHS are computed and will control which shuffle mask entries 14282 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14283 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14284 // HalfVec to refer to the corresponding element in the permuted vector. 14285 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14286 HalfVec); 14287 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14288 14289 // We may have simplified away the shuffle. We won't be able to do anything 14290 // further with it here. 14291 if (!isa<ShuffleVectorSDNode>(Res)) 14292 return Res; 14293 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14294 } 14295 14296 // The common case after we commuted the shuffle is that the RHS is a splat 14297 // and we have elements coming in from the splat at indices that are not 14298 // conducive to using a merge. 14299 // Example: 14300 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14301 if (!isSplatBV(RHS)) 14302 return Res; 14303 14304 // We are looking for a mask such that all even elements are from 14305 // one vector and all odd elements from the other. 14306 if (!isAlternatingShuffMask(Mask, NumElts)) 14307 return Res; 14308 14309 // Adjust the mask so we are pulling in the same index from the splat 14310 // as the index from the interesting vector in consecutive elements. 14311 // Example (even elements from first vector): 14312 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14313 if (Mask[0] < NumElts) 14314 for (int i = 1, e = Mask.size(); i < e; i += 2) 14315 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14316 // Example (odd elements from first vector): 14317 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14318 else 14319 for (int i = 0, e = Mask.size(); i < e; i += 2) 14320 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14321 14322 // If the RHS has undefs, we need to remove them since we may have created 14323 // a shuffle that adds those instead of the splat value. 14324 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14325 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14326 14327 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14328 return Res; 14329 } 14330 14331 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14332 LSBaseSDNode *LSBase, 14333 DAGCombinerInfo &DCI) const { 14334 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14335 "Not a reverse memop pattern!"); 14336 14337 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14338 auto Mask = SVN->getMask(); 14339 int i = 0; 14340 auto I = Mask.rbegin(); 14341 auto E = Mask.rend(); 14342 14343 for (; I != E; ++I) { 14344 if (*I != i) 14345 return false; 14346 i++; 14347 } 14348 return true; 14349 }; 14350 14351 SelectionDAG &DAG = DCI.DAG; 14352 EVT VT = SVN->getValueType(0); 14353 14354 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14355 return SDValue(); 14356 14357 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14358 // See comment in PPCVSXSwapRemoval.cpp. 14359 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14360 if (!Subtarget.hasP9Vector()) 14361 return SDValue(); 14362 14363 if(!IsElementReverse(SVN)) 14364 return SDValue(); 14365 14366 if (LSBase->getOpcode() == ISD::LOAD) { 14367 SDLoc dl(SVN); 14368 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14369 return DAG.getMemIntrinsicNode( 14370 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14371 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14372 } 14373 14374 if (LSBase->getOpcode() == ISD::STORE) { 14375 SDLoc dl(LSBase); 14376 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14377 LSBase->getBasePtr()}; 14378 return DAG.getMemIntrinsicNode( 14379 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14380 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14381 } 14382 14383 llvm_unreachable("Expected a load or store node here"); 14384 } 14385 14386 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14387 DAGCombinerInfo &DCI) const { 14388 SelectionDAG &DAG = DCI.DAG; 14389 SDLoc dl(N); 14390 switch (N->getOpcode()) { 14391 default: break; 14392 case ISD::ADD: 14393 return combineADD(N, DCI); 14394 case ISD::SHL: 14395 return combineSHL(N, DCI); 14396 case ISD::SRA: 14397 return combineSRA(N, DCI); 14398 case ISD::SRL: 14399 return combineSRL(N, DCI); 14400 case ISD::MUL: 14401 return combineMUL(N, DCI); 14402 case ISD::FMA: 14403 case PPCISD::FNMSUB: 14404 return combineFMALike(N, DCI); 14405 case PPCISD::SHL: 14406 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14407 return N->getOperand(0); 14408 break; 14409 case PPCISD::SRL: 14410 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14411 return N->getOperand(0); 14412 break; 14413 case PPCISD::SRA: 14414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14415 if (C->isNullValue() || // 0 >>s V -> 0. 14416 C->isAllOnesValue()) // -1 >>s V -> -1. 14417 return N->getOperand(0); 14418 } 14419 break; 14420 case ISD::SIGN_EXTEND: 14421 case ISD::ZERO_EXTEND: 14422 case ISD::ANY_EXTEND: 14423 return DAGCombineExtBoolTrunc(N, DCI); 14424 case ISD::TRUNCATE: 14425 return combineTRUNCATE(N, DCI); 14426 case ISD::SETCC: 14427 if (SDValue CSCC = combineSetCC(N, DCI)) 14428 return CSCC; 14429 LLVM_FALLTHROUGH; 14430 case ISD::SELECT_CC: 14431 return DAGCombineTruncBoolExt(N, DCI); 14432 case ISD::SINT_TO_FP: 14433 case ISD::UINT_TO_FP: 14434 return combineFPToIntToFP(N, DCI); 14435 case ISD::VECTOR_SHUFFLE: 14436 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14437 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14438 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14439 } 14440 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14441 case ISD::STORE: { 14442 14443 EVT Op1VT = N->getOperand(1).getValueType(); 14444 unsigned Opcode = N->getOperand(1).getOpcode(); 14445 14446 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14447 SDValue Val= combineStoreFPToInt(N, DCI); 14448 if (Val) 14449 return Val; 14450 } 14451 14452 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14453 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14454 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14455 if (Val) 14456 return Val; 14457 } 14458 14459 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14460 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14461 N->getOperand(1).getNode()->hasOneUse() && 14462 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14463 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14464 14465 // STBRX can only handle simple types and it makes no sense to store less 14466 // two bytes in byte-reversed order. 14467 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14468 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14469 break; 14470 14471 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14472 // Do an any-extend to 32-bits if this is a half-word input. 14473 if (BSwapOp.getValueType() == MVT::i16) 14474 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14475 14476 // If the type of BSWAP operand is wider than stored memory width 14477 // it need to be shifted to the right side before STBRX. 14478 if (Op1VT.bitsGT(mVT)) { 14479 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14480 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14481 DAG.getConstant(Shift, dl, MVT::i32)); 14482 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14483 if (Op1VT == MVT::i64) 14484 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14485 } 14486 14487 SDValue Ops[] = { 14488 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14489 }; 14490 return 14491 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14492 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14493 cast<StoreSDNode>(N)->getMemOperand()); 14494 } 14495 14496 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14497 // So it can increase the chance of CSE constant construction. 14498 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14499 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14500 // Need to sign-extended to 64-bits to handle negative values. 14501 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14502 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14503 MemVT.getSizeInBits()); 14504 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14505 14506 // DAG.getTruncStore() can't be used here because it doesn't accept 14507 // the general (base + offset) addressing mode. 14508 // So we use UpdateNodeOperands and setTruncatingStore instead. 14509 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14510 N->getOperand(3)); 14511 cast<StoreSDNode>(N)->setTruncatingStore(true); 14512 return SDValue(N, 0); 14513 } 14514 14515 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14516 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14517 if (Op1VT.isSimple()) { 14518 MVT StoreVT = Op1VT.getSimpleVT(); 14519 if (Subtarget.needsSwapsForVSXMemOps() && 14520 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14521 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14522 return expandVSXStoreForLE(N, DCI); 14523 } 14524 break; 14525 } 14526 case ISD::LOAD: { 14527 LoadSDNode *LD = cast<LoadSDNode>(N); 14528 EVT VT = LD->getValueType(0); 14529 14530 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14531 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14532 if (VT.isSimple()) { 14533 MVT LoadVT = VT.getSimpleVT(); 14534 if (Subtarget.needsSwapsForVSXMemOps() && 14535 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14536 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14537 return expandVSXLoadForLE(N, DCI); 14538 } 14539 14540 // We sometimes end up with a 64-bit integer load, from which we extract 14541 // two single-precision floating-point numbers. This happens with 14542 // std::complex<float>, and other similar structures, because of the way we 14543 // canonicalize structure copies. However, if we lack direct moves, 14544 // then the final bitcasts from the extracted integer values to the 14545 // floating-point numbers turn into store/load pairs. Even with direct moves, 14546 // just loading the two floating-point numbers is likely better. 14547 auto ReplaceTwoFloatLoad = [&]() { 14548 if (VT != MVT::i64) 14549 return false; 14550 14551 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14552 LD->isVolatile()) 14553 return false; 14554 14555 // We're looking for a sequence like this: 14556 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14557 // t16: i64 = srl t13, Constant:i32<32> 14558 // t17: i32 = truncate t16 14559 // t18: f32 = bitcast t17 14560 // t19: i32 = truncate t13 14561 // t20: f32 = bitcast t19 14562 14563 if (!LD->hasNUsesOfValue(2, 0)) 14564 return false; 14565 14566 auto UI = LD->use_begin(); 14567 while (UI.getUse().getResNo() != 0) ++UI; 14568 SDNode *Trunc = *UI++; 14569 while (UI.getUse().getResNo() != 0) ++UI; 14570 SDNode *RightShift = *UI; 14571 if (Trunc->getOpcode() != ISD::TRUNCATE) 14572 std::swap(Trunc, RightShift); 14573 14574 if (Trunc->getOpcode() != ISD::TRUNCATE || 14575 Trunc->getValueType(0) != MVT::i32 || 14576 !Trunc->hasOneUse()) 14577 return false; 14578 if (RightShift->getOpcode() != ISD::SRL || 14579 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14580 RightShift->getConstantOperandVal(1) != 32 || 14581 !RightShift->hasOneUse()) 14582 return false; 14583 14584 SDNode *Trunc2 = *RightShift->use_begin(); 14585 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14586 Trunc2->getValueType(0) != MVT::i32 || 14587 !Trunc2->hasOneUse()) 14588 return false; 14589 14590 SDNode *Bitcast = *Trunc->use_begin(); 14591 SDNode *Bitcast2 = *Trunc2->use_begin(); 14592 14593 if (Bitcast->getOpcode() != ISD::BITCAST || 14594 Bitcast->getValueType(0) != MVT::f32) 14595 return false; 14596 if (Bitcast2->getOpcode() != ISD::BITCAST || 14597 Bitcast2->getValueType(0) != MVT::f32) 14598 return false; 14599 14600 if (Subtarget.isLittleEndian()) 14601 std::swap(Bitcast, Bitcast2); 14602 14603 // Bitcast has the second float (in memory-layout order) and Bitcast2 14604 // has the first one. 14605 14606 SDValue BasePtr = LD->getBasePtr(); 14607 if (LD->isIndexed()) { 14608 assert(LD->getAddressingMode() == ISD::PRE_INC && 14609 "Non-pre-inc AM on PPC?"); 14610 BasePtr = 14611 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14612 LD->getOffset()); 14613 } 14614 14615 auto MMOFlags = 14616 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14617 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14618 LD->getPointerInfo(), LD->getAlignment(), 14619 MMOFlags, LD->getAAInfo()); 14620 SDValue AddPtr = 14621 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14622 BasePtr, DAG.getIntPtrConstant(4, dl)); 14623 SDValue FloatLoad2 = DAG.getLoad( 14624 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14625 LD->getPointerInfo().getWithOffset(4), 14626 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14627 14628 if (LD->isIndexed()) { 14629 // Note that DAGCombine should re-form any pre-increment load(s) from 14630 // what is produced here if that makes sense. 14631 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14632 } 14633 14634 DCI.CombineTo(Bitcast2, FloatLoad); 14635 DCI.CombineTo(Bitcast, FloatLoad2); 14636 14637 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14638 SDValue(FloatLoad2.getNode(), 1)); 14639 return true; 14640 }; 14641 14642 if (ReplaceTwoFloatLoad()) 14643 return SDValue(N, 0); 14644 14645 EVT MemVT = LD->getMemoryVT(); 14646 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14647 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14648 if (LD->isUnindexed() && VT.isVector() && 14649 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14650 // P8 and later hardware should just use LOAD. 14651 !Subtarget.hasP8Vector() && 14652 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14653 VT == MVT::v4f32))) && 14654 LD->getAlign() < ABIAlignment) { 14655 // This is a type-legal unaligned Altivec load. 14656 SDValue Chain = LD->getChain(); 14657 SDValue Ptr = LD->getBasePtr(); 14658 bool isLittleEndian = Subtarget.isLittleEndian(); 14659 14660 // This implements the loading of unaligned vectors as described in 14661 // the venerable Apple Velocity Engine overview. Specifically: 14662 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14663 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14664 // 14665 // The general idea is to expand a sequence of one or more unaligned 14666 // loads into an alignment-based permutation-control instruction (lvsl 14667 // or lvsr), a series of regular vector loads (which always truncate 14668 // their input address to an aligned address), and a series of 14669 // permutations. The results of these permutations are the requested 14670 // loaded values. The trick is that the last "extra" load is not taken 14671 // from the address you might suspect (sizeof(vector) bytes after the 14672 // last requested load), but rather sizeof(vector) - 1 bytes after the 14673 // last requested vector. The point of this is to avoid a page fault if 14674 // the base address happened to be aligned. This works because if the 14675 // base address is aligned, then adding less than a full vector length 14676 // will cause the last vector in the sequence to be (re)loaded. 14677 // Otherwise, the next vector will be fetched as you might suspect was 14678 // necessary. 14679 14680 // We might be able to reuse the permutation generation from 14681 // a different base address offset from this one by an aligned amount. 14682 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14683 // optimization later. 14684 Intrinsic::ID Intr, IntrLD, IntrPerm; 14685 MVT PermCntlTy, PermTy, LDTy; 14686 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14687 : Intrinsic::ppc_altivec_lvsl; 14688 IntrLD = Intrinsic::ppc_altivec_lvx; 14689 IntrPerm = Intrinsic::ppc_altivec_vperm; 14690 PermCntlTy = MVT::v16i8; 14691 PermTy = MVT::v4i32; 14692 LDTy = MVT::v4i32; 14693 14694 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14695 14696 // Create the new MMO for the new base load. It is like the original MMO, 14697 // but represents an area in memory almost twice the vector size centered 14698 // on the original address. If the address is unaligned, we might start 14699 // reading up to (sizeof(vector)-1) bytes below the address of the 14700 // original unaligned load. 14701 MachineFunction &MF = DAG.getMachineFunction(); 14702 MachineMemOperand *BaseMMO = 14703 MF.getMachineMemOperand(LD->getMemOperand(), 14704 -(long)MemVT.getStoreSize()+1, 14705 2*MemVT.getStoreSize()-1); 14706 14707 // Create the new base load. 14708 SDValue LDXIntID = 14709 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14710 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14711 SDValue BaseLoad = 14712 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14713 DAG.getVTList(PermTy, MVT::Other), 14714 BaseLoadOps, LDTy, BaseMMO); 14715 14716 // Note that the value of IncOffset (which is provided to the next 14717 // load's pointer info offset value, and thus used to calculate the 14718 // alignment), and the value of IncValue (which is actually used to 14719 // increment the pointer value) are different! This is because we 14720 // require the next load to appear to be aligned, even though it 14721 // is actually offset from the base pointer by a lesser amount. 14722 int IncOffset = VT.getSizeInBits() / 8; 14723 int IncValue = IncOffset; 14724 14725 // Walk (both up and down) the chain looking for another load at the real 14726 // (aligned) offset (the alignment of the other load does not matter in 14727 // this case). If found, then do not use the offset reduction trick, as 14728 // that will prevent the loads from being later combined (as they would 14729 // otherwise be duplicates). 14730 if (!findConsecutiveLoad(LD, DAG)) 14731 --IncValue; 14732 14733 SDValue Increment = 14734 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14735 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14736 14737 MachineMemOperand *ExtraMMO = 14738 MF.getMachineMemOperand(LD->getMemOperand(), 14739 1, 2*MemVT.getStoreSize()-1); 14740 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14741 SDValue ExtraLoad = 14742 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14743 DAG.getVTList(PermTy, MVT::Other), 14744 ExtraLoadOps, LDTy, ExtraMMO); 14745 14746 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14747 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14748 14749 // Because vperm has a big-endian bias, we must reverse the order 14750 // of the input vectors and complement the permute control vector 14751 // when generating little endian code. We have already handled the 14752 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14753 // and ExtraLoad here. 14754 SDValue Perm; 14755 if (isLittleEndian) 14756 Perm = BuildIntrinsicOp(IntrPerm, 14757 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14758 else 14759 Perm = BuildIntrinsicOp(IntrPerm, 14760 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14761 14762 if (VT != PermTy) 14763 Perm = Subtarget.hasAltivec() 14764 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14765 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14766 DAG.getTargetConstant(1, dl, MVT::i64)); 14767 // second argument is 1 because this rounding 14768 // is always exact. 14769 14770 // The output of the permutation is our loaded result, the TokenFactor is 14771 // our new chain. 14772 DCI.CombineTo(N, Perm, TF); 14773 return SDValue(N, 0); 14774 } 14775 } 14776 break; 14777 case ISD::INTRINSIC_WO_CHAIN: { 14778 bool isLittleEndian = Subtarget.isLittleEndian(); 14779 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14780 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14781 : Intrinsic::ppc_altivec_lvsl); 14782 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14783 SDValue Add = N->getOperand(1); 14784 14785 int Bits = 4 /* 16 byte alignment */; 14786 14787 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14788 APInt::getAllOnesValue(Bits /* alignment */) 14789 .zext(Add.getScalarValueSizeInBits()))) { 14790 SDNode *BasePtr = Add->getOperand(0).getNode(); 14791 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14792 UE = BasePtr->use_end(); 14793 UI != UE; ++UI) { 14794 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14795 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14796 IID) { 14797 // We've found another LVSL/LVSR, and this address is an aligned 14798 // multiple of that one. The results will be the same, so use the 14799 // one we've just found instead. 14800 14801 return SDValue(*UI, 0); 14802 } 14803 } 14804 } 14805 14806 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14807 SDNode *BasePtr = Add->getOperand(0).getNode(); 14808 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14809 UE = BasePtr->use_end(); UI != UE; ++UI) { 14810 if (UI->getOpcode() == ISD::ADD && 14811 isa<ConstantSDNode>(UI->getOperand(1)) && 14812 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14813 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14814 (1ULL << Bits) == 0) { 14815 SDNode *OtherAdd = *UI; 14816 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14817 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14818 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14819 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14820 return SDValue(*VI, 0); 14821 } 14822 } 14823 } 14824 } 14825 } 14826 } 14827 14828 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14829 // Expose the vabsduw/h/b opportunity for down stream 14830 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14831 (IID == Intrinsic::ppc_altivec_vmaxsw || 14832 IID == Intrinsic::ppc_altivec_vmaxsh || 14833 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14834 SDValue V1 = N->getOperand(1); 14835 SDValue V2 = N->getOperand(2); 14836 if ((V1.getSimpleValueType() == MVT::v4i32 || 14837 V1.getSimpleValueType() == MVT::v8i16 || 14838 V1.getSimpleValueType() == MVT::v16i8) && 14839 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14840 // (0-a, a) 14841 if (V1.getOpcode() == ISD::SUB && 14842 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14843 V1.getOperand(1) == V2) { 14844 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14845 } 14846 // (a, 0-a) 14847 if (V2.getOpcode() == ISD::SUB && 14848 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14849 V2.getOperand(1) == V1) { 14850 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14851 } 14852 // (x-y, y-x) 14853 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14854 V1.getOperand(0) == V2.getOperand(1) && 14855 V1.getOperand(1) == V2.getOperand(0)) { 14856 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14857 } 14858 } 14859 } 14860 } 14861 14862 break; 14863 case ISD::INTRINSIC_W_CHAIN: 14864 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14865 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14866 if (Subtarget.needsSwapsForVSXMemOps()) { 14867 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14868 default: 14869 break; 14870 case Intrinsic::ppc_vsx_lxvw4x: 14871 case Intrinsic::ppc_vsx_lxvd2x: 14872 return expandVSXLoadForLE(N, DCI); 14873 } 14874 } 14875 break; 14876 case ISD::INTRINSIC_VOID: 14877 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14878 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14879 if (Subtarget.needsSwapsForVSXMemOps()) { 14880 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14881 default: 14882 break; 14883 case Intrinsic::ppc_vsx_stxvw4x: 14884 case Intrinsic::ppc_vsx_stxvd2x: 14885 return expandVSXStoreForLE(N, DCI); 14886 } 14887 } 14888 break; 14889 case ISD::BSWAP: 14890 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14891 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14892 N->getOperand(0).hasOneUse() && 14893 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14894 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14895 N->getValueType(0) == MVT::i64))) { 14896 SDValue Load = N->getOperand(0); 14897 LoadSDNode *LD = cast<LoadSDNode>(Load); 14898 // Create the byte-swapping load. 14899 SDValue Ops[] = { 14900 LD->getChain(), // Chain 14901 LD->getBasePtr(), // Ptr 14902 DAG.getValueType(N->getValueType(0)) // VT 14903 }; 14904 SDValue BSLoad = 14905 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14906 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14907 MVT::i64 : MVT::i32, MVT::Other), 14908 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14909 14910 // If this is an i16 load, insert the truncate. 14911 SDValue ResVal = BSLoad; 14912 if (N->getValueType(0) == MVT::i16) 14913 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14914 14915 // First, combine the bswap away. This makes the value produced by the 14916 // load dead. 14917 DCI.CombineTo(N, ResVal); 14918 14919 // Next, combine the load away, we give it a bogus result value but a real 14920 // chain result. The result value is dead because the bswap is dead. 14921 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14922 14923 // Return N so it doesn't get rechecked! 14924 return SDValue(N, 0); 14925 } 14926 break; 14927 case PPCISD::VCMP: 14928 // If a VCMPo node already exists with exactly the same operands as this 14929 // node, use its result instead of this node (VCMPo computes both a CR6 and 14930 // a normal output). 14931 // 14932 if (!N->getOperand(0).hasOneUse() && 14933 !N->getOperand(1).hasOneUse() && 14934 !N->getOperand(2).hasOneUse()) { 14935 14936 // Scan all of the users of the LHS, looking for VCMPo's that match. 14937 SDNode *VCMPoNode = nullptr; 14938 14939 SDNode *LHSN = N->getOperand(0).getNode(); 14940 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14941 UI != E; ++UI) 14942 if (UI->getOpcode() == PPCISD::VCMPo && 14943 UI->getOperand(1) == N->getOperand(1) && 14944 UI->getOperand(2) == N->getOperand(2) && 14945 UI->getOperand(0) == N->getOperand(0)) { 14946 VCMPoNode = *UI; 14947 break; 14948 } 14949 14950 // If there is no VCMPo node, or if the flag value has a single use, don't 14951 // transform this. 14952 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14953 break; 14954 14955 // Look at the (necessarily single) use of the flag value. If it has a 14956 // chain, this transformation is more complex. Note that multiple things 14957 // could use the value result, which we should ignore. 14958 SDNode *FlagUser = nullptr; 14959 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14960 FlagUser == nullptr; ++UI) { 14961 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14962 SDNode *User = *UI; 14963 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14964 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14965 FlagUser = User; 14966 break; 14967 } 14968 } 14969 } 14970 14971 // If the user is a MFOCRF instruction, we know this is safe. 14972 // Otherwise we give up for right now. 14973 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14974 return SDValue(VCMPoNode, 0); 14975 } 14976 break; 14977 case ISD::BRCOND: { 14978 SDValue Cond = N->getOperand(1); 14979 SDValue Target = N->getOperand(2); 14980 14981 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14982 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14983 Intrinsic::loop_decrement) { 14984 14985 // We now need to make the intrinsic dead (it cannot be instruction 14986 // selected). 14987 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14988 assert(Cond.getNode()->hasOneUse() && 14989 "Counter decrement has more than one use"); 14990 14991 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14992 N->getOperand(0), Target); 14993 } 14994 } 14995 break; 14996 case ISD::BR_CC: { 14997 // If this is a branch on an altivec predicate comparison, lower this so 14998 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14999 // lowering is done pre-legalize, because the legalizer lowers the predicate 15000 // compare down to code that is difficult to reassemble. 15001 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15002 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15003 15004 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15005 // value. If so, pass-through the AND to get to the intrinsic. 15006 if (LHS.getOpcode() == ISD::AND && 15007 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15008 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15009 Intrinsic::loop_decrement && 15010 isa<ConstantSDNode>(LHS.getOperand(1)) && 15011 !isNullConstant(LHS.getOperand(1))) 15012 LHS = LHS.getOperand(0); 15013 15014 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15015 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15016 Intrinsic::loop_decrement && 15017 isa<ConstantSDNode>(RHS)) { 15018 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15019 "Counter decrement comparison is not EQ or NE"); 15020 15021 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15022 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15023 (CC == ISD::SETNE && !Val); 15024 15025 // We now need to make the intrinsic dead (it cannot be instruction 15026 // selected). 15027 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15028 assert(LHS.getNode()->hasOneUse() && 15029 "Counter decrement has more than one use"); 15030 15031 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15032 N->getOperand(0), N->getOperand(4)); 15033 } 15034 15035 int CompareOpc; 15036 bool isDot; 15037 15038 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15039 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15040 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15041 assert(isDot && "Can't compare against a vector result!"); 15042 15043 // If this is a comparison against something other than 0/1, then we know 15044 // that the condition is never/always true. 15045 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15046 if (Val != 0 && Val != 1) { 15047 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15048 return N->getOperand(0); 15049 // Always !=, turn it into an unconditional branch. 15050 return DAG.getNode(ISD::BR, dl, MVT::Other, 15051 N->getOperand(0), N->getOperand(4)); 15052 } 15053 15054 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15055 15056 // Create the PPCISD altivec 'dot' comparison node. 15057 SDValue Ops[] = { 15058 LHS.getOperand(2), // LHS of compare 15059 LHS.getOperand(3), // RHS of compare 15060 DAG.getConstant(CompareOpc, dl, MVT::i32) 15061 }; 15062 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15063 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15064 15065 // Unpack the result based on how the target uses it. 15066 PPC::Predicate CompOpc; 15067 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15068 default: // Can't happen, don't crash on invalid number though. 15069 case 0: // Branch on the value of the EQ bit of CR6. 15070 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15071 break; 15072 case 1: // Branch on the inverted value of the EQ bit of CR6. 15073 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15074 break; 15075 case 2: // Branch on the value of the LT bit of CR6. 15076 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15077 break; 15078 case 3: // Branch on the inverted value of the LT bit of CR6. 15079 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15080 break; 15081 } 15082 15083 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15084 DAG.getConstant(CompOpc, dl, MVT::i32), 15085 DAG.getRegister(PPC::CR6, MVT::i32), 15086 N->getOperand(4), CompNode.getValue(1)); 15087 } 15088 break; 15089 } 15090 case ISD::BUILD_VECTOR: 15091 return DAGCombineBuildVector(N, DCI); 15092 case ISD::ABS: 15093 return combineABS(N, DCI); 15094 case ISD::VSELECT: 15095 return combineVSelect(N, DCI); 15096 } 15097 15098 return SDValue(); 15099 } 15100 15101 SDValue 15102 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15103 SelectionDAG &DAG, 15104 SmallVectorImpl<SDNode *> &Created) const { 15105 // fold (sdiv X, pow2) 15106 EVT VT = N->getValueType(0); 15107 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15108 return SDValue(); 15109 if ((VT != MVT::i32 && VT != MVT::i64) || 15110 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15111 return SDValue(); 15112 15113 SDLoc DL(N); 15114 SDValue N0 = N->getOperand(0); 15115 15116 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15117 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15118 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15119 15120 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15121 Created.push_back(Op.getNode()); 15122 15123 if (IsNegPow2) { 15124 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15125 Created.push_back(Op.getNode()); 15126 } 15127 15128 return Op; 15129 } 15130 15131 //===----------------------------------------------------------------------===// 15132 // Inline Assembly Support 15133 //===----------------------------------------------------------------------===// 15134 15135 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15136 KnownBits &Known, 15137 const APInt &DemandedElts, 15138 const SelectionDAG &DAG, 15139 unsigned Depth) const { 15140 Known.resetAll(); 15141 switch (Op.getOpcode()) { 15142 default: break; 15143 case PPCISD::LBRX: { 15144 // lhbrx is known to have the top bits cleared out. 15145 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15146 Known.Zero = 0xFFFF0000; 15147 break; 15148 } 15149 case ISD::INTRINSIC_WO_CHAIN: { 15150 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15151 default: break; 15152 case Intrinsic::ppc_altivec_vcmpbfp_p: 15153 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15154 case Intrinsic::ppc_altivec_vcmpequb_p: 15155 case Intrinsic::ppc_altivec_vcmpequh_p: 15156 case Intrinsic::ppc_altivec_vcmpequw_p: 15157 case Intrinsic::ppc_altivec_vcmpequd_p: 15158 case Intrinsic::ppc_altivec_vcmpgefp_p: 15159 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15160 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15161 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15162 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15163 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15164 case Intrinsic::ppc_altivec_vcmpgtub_p: 15165 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15166 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15167 case Intrinsic::ppc_altivec_vcmpgtud_p: 15168 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15169 break; 15170 } 15171 } 15172 } 15173 } 15174 15175 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15176 switch (Subtarget.getCPUDirective()) { 15177 default: break; 15178 case PPC::DIR_970: 15179 case PPC::DIR_PWR4: 15180 case PPC::DIR_PWR5: 15181 case PPC::DIR_PWR5X: 15182 case PPC::DIR_PWR6: 15183 case PPC::DIR_PWR6X: 15184 case PPC::DIR_PWR7: 15185 case PPC::DIR_PWR8: 15186 case PPC::DIR_PWR9: 15187 case PPC::DIR_PWR10: 15188 case PPC::DIR_PWR_FUTURE: { 15189 if (!ML) 15190 break; 15191 15192 if (!DisableInnermostLoopAlign32) { 15193 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15194 // so that we can decrease cache misses and branch-prediction misses. 15195 // Actual alignment of the loop will depend on the hotness check and other 15196 // logic in alignBlocks. 15197 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15198 return Align(32); 15199 } 15200 15201 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15202 15203 // For small loops (between 5 and 8 instructions), align to a 32-byte 15204 // boundary so that the entire loop fits in one instruction-cache line. 15205 uint64_t LoopSize = 0; 15206 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15207 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15208 LoopSize += TII->getInstSizeInBytes(*J); 15209 if (LoopSize > 32) 15210 break; 15211 } 15212 15213 if (LoopSize > 16 && LoopSize <= 32) 15214 return Align(32); 15215 15216 break; 15217 } 15218 } 15219 15220 return TargetLowering::getPrefLoopAlignment(ML); 15221 } 15222 15223 /// getConstraintType - Given a constraint, return the type of 15224 /// constraint it is for this target. 15225 PPCTargetLowering::ConstraintType 15226 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15227 if (Constraint.size() == 1) { 15228 switch (Constraint[0]) { 15229 default: break; 15230 case 'b': 15231 case 'r': 15232 case 'f': 15233 case 'd': 15234 case 'v': 15235 case 'y': 15236 return C_RegisterClass; 15237 case 'Z': 15238 // FIXME: While Z does indicate a memory constraint, it specifically 15239 // indicates an r+r address (used in conjunction with the 'y' modifier 15240 // in the replacement string). Currently, we're forcing the base 15241 // register to be r0 in the asm printer (which is interpreted as zero) 15242 // and forming the complete address in the second register. This is 15243 // suboptimal. 15244 return C_Memory; 15245 } 15246 } else if (Constraint == "wc") { // individual CR bits. 15247 return C_RegisterClass; 15248 } else if (Constraint == "wa" || Constraint == "wd" || 15249 Constraint == "wf" || Constraint == "ws" || 15250 Constraint == "wi" || Constraint == "ww") { 15251 return C_RegisterClass; // VSX registers. 15252 } 15253 return TargetLowering::getConstraintType(Constraint); 15254 } 15255 15256 /// Examine constraint type and operand type and determine a weight value. 15257 /// This object must already have been set up with the operand type 15258 /// and the current alternative constraint selected. 15259 TargetLowering::ConstraintWeight 15260 PPCTargetLowering::getSingleConstraintMatchWeight( 15261 AsmOperandInfo &info, const char *constraint) const { 15262 ConstraintWeight weight = CW_Invalid; 15263 Value *CallOperandVal = info.CallOperandVal; 15264 // If we don't have a value, we can't do a match, 15265 // but allow it at the lowest weight. 15266 if (!CallOperandVal) 15267 return CW_Default; 15268 Type *type = CallOperandVal->getType(); 15269 15270 // Look at the constraint type. 15271 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15272 return CW_Register; // an individual CR bit. 15273 else if ((StringRef(constraint) == "wa" || 15274 StringRef(constraint) == "wd" || 15275 StringRef(constraint) == "wf") && 15276 type->isVectorTy()) 15277 return CW_Register; 15278 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15279 return CW_Register; // just hold 64-bit integers data. 15280 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15281 return CW_Register; 15282 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15283 return CW_Register; 15284 15285 switch (*constraint) { 15286 default: 15287 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15288 break; 15289 case 'b': 15290 if (type->isIntegerTy()) 15291 weight = CW_Register; 15292 break; 15293 case 'f': 15294 if (type->isFloatTy()) 15295 weight = CW_Register; 15296 break; 15297 case 'd': 15298 if (type->isDoubleTy()) 15299 weight = CW_Register; 15300 break; 15301 case 'v': 15302 if (type->isVectorTy()) 15303 weight = CW_Register; 15304 break; 15305 case 'y': 15306 weight = CW_Register; 15307 break; 15308 case 'Z': 15309 weight = CW_Memory; 15310 break; 15311 } 15312 return weight; 15313 } 15314 15315 std::pair<unsigned, const TargetRegisterClass *> 15316 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15317 StringRef Constraint, 15318 MVT VT) const { 15319 if (Constraint.size() == 1) { 15320 // GCC RS6000 Constraint Letters 15321 switch (Constraint[0]) { 15322 case 'b': // R1-R31 15323 if (VT == MVT::i64 && Subtarget.isPPC64()) 15324 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15325 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15326 case 'r': // R0-R31 15327 if (VT == MVT::i64 && Subtarget.isPPC64()) 15328 return std::make_pair(0U, &PPC::G8RCRegClass); 15329 return std::make_pair(0U, &PPC::GPRCRegClass); 15330 // 'd' and 'f' constraints are both defined to be "the floating point 15331 // registers", where one is for 32-bit and the other for 64-bit. We don't 15332 // really care overly much here so just give them all the same reg classes. 15333 case 'd': 15334 case 'f': 15335 if (Subtarget.hasSPE()) { 15336 if (VT == MVT::f32 || VT == MVT::i32) 15337 return std::make_pair(0U, &PPC::GPRCRegClass); 15338 if (VT == MVT::f64 || VT == MVT::i64) 15339 return std::make_pair(0U, &PPC::SPERCRegClass); 15340 } else { 15341 if (VT == MVT::f32 || VT == MVT::i32) 15342 return std::make_pair(0U, &PPC::F4RCRegClass); 15343 if (VT == MVT::f64 || VT == MVT::i64) 15344 return std::make_pair(0U, &PPC::F8RCRegClass); 15345 } 15346 break; 15347 case 'v': 15348 if (Subtarget.hasAltivec()) 15349 return std::make_pair(0U, &PPC::VRRCRegClass); 15350 break; 15351 case 'y': // crrc 15352 return std::make_pair(0U, &PPC::CRRCRegClass); 15353 } 15354 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15355 // An individual CR bit. 15356 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15357 } else if ((Constraint == "wa" || Constraint == "wd" || 15358 Constraint == "wf" || Constraint == "wi") && 15359 Subtarget.hasVSX()) { 15360 return std::make_pair(0U, &PPC::VSRCRegClass); 15361 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15362 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15363 return std::make_pair(0U, &PPC::VSSRCRegClass); 15364 else 15365 return std::make_pair(0U, &PPC::VSFRCRegClass); 15366 } 15367 15368 // If we name a VSX register, we can't defer to the base class because it 15369 // will not recognize the correct register (their names will be VSL{0-31} 15370 // and V{0-31} so they won't match). So we match them here. 15371 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15372 int VSNum = atoi(Constraint.data() + 3); 15373 assert(VSNum >= 0 && VSNum <= 63 && 15374 "Attempted to access a vsr out of range"); 15375 if (VSNum < 32) 15376 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15377 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15378 } 15379 std::pair<unsigned, const TargetRegisterClass *> R = 15380 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15381 15382 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15383 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15384 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15385 // register. 15386 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15387 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15388 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15389 PPC::GPRCRegClass.contains(R.first)) 15390 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15391 PPC::sub_32, &PPC::G8RCRegClass), 15392 &PPC::G8RCRegClass); 15393 15394 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15395 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15396 R.first = PPC::CR0; 15397 R.second = &PPC::CRRCRegClass; 15398 } 15399 15400 return R; 15401 } 15402 15403 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15404 /// vector. If it is invalid, don't add anything to Ops. 15405 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15406 std::string &Constraint, 15407 std::vector<SDValue>&Ops, 15408 SelectionDAG &DAG) const { 15409 SDValue Result; 15410 15411 // Only support length 1 constraints. 15412 if (Constraint.length() > 1) return; 15413 15414 char Letter = Constraint[0]; 15415 switch (Letter) { 15416 default: break; 15417 case 'I': 15418 case 'J': 15419 case 'K': 15420 case 'L': 15421 case 'M': 15422 case 'N': 15423 case 'O': 15424 case 'P': { 15425 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15426 if (!CST) return; // Must be an immediate to match. 15427 SDLoc dl(Op); 15428 int64_t Value = CST->getSExtValue(); 15429 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15430 // numbers are printed as such. 15431 switch (Letter) { 15432 default: llvm_unreachable("Unknown constraint letter!"); 15433 case 'I': // "I" is a signed 16-bit constant. 15434 if (isInt<16>(Value)) 15435 Result = DAG.getTargetConstant(Value, dl, TCVT); 15436 break; 15437 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15438 if (isShiftedUInt<16, 16>(Value)) 15439 Result = DAG.getTargetConstant(Value, dl, TCVT); 15440 break; 15441 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15442 if (isShiftedInt<16, 16>(Value)) 15443 Result = DAG.getTargetConstant(Value, dl, TCVT); 15444 break; 15445 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15446 if (isUInt<16>(Value)) 15447 Result = DAG.getTargetConstant(Value, dl, TCVT); 15448 break; 15449 case 'M': // "M" is a constant that is greater than 31. 15450 if (Value > 31) 15451 Result = DAG.getTargetConstant(Value, dl, TCVT); 15452 break; 15453 case 'N': // "N" is a positive constant that is an exact power of two. 15454 if (Value > 0 && isPowerOf2_64(Value)) 15455 Result = DAG.getTargetConstant(Value, dl, TCVT); 15456 break; 15457 case 'O': // "O" is the constant zero. 15458 if (Value == 0) 15459 Result = DAG.getTargetConstant(Value, dl, TCVT); 15460 break; 15461 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15462 if (isInt<16>(-Value)) 15463 Result = DAG.getTargetConstant(Value, dl, TCVT); 15464 break; 15465 } 15466 break; 15467 } 15468 } 15469 15470 if (Result.getNode()) { 15471 Ops.push_back(Result); 15472 return; 15473 } 15474 15475 // Handle standard constraint letters. 15476 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15477 } 15478 15479 // isLegalAddressingMode - Return true if the addressing mode represented 15480 // by AM is legal for this target, for a load/store of the specified type. 15481 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15482 const AddrMode &AM, Type *Ty, 15483 unsigned AS, 15484 Instruction *I) const { 15485 // Vector type r+i form is supported since power9 as DQ form. We don't check 15486 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15487 // imm form is preferred and the offset can be adjusted to use imm form later 15488 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15489 // max offset to check legal addressing mode, we should be a little aggressive 15490 // to contain other offsets for that LSRUse. 15491 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15492 return false; 15493 15494 // PPC allows a sign-extended 16-bit immediate field. 15495 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15496 return false; 15497 15498 // No global is ever allowed as a base. 15499 if (AM.BaseGV) 15500 return false; 15501 15502 // PPC only support r+r, 15503 switch (AM.Scale) { 15504 case 0: // "r+i" or just "i", depending on HasBaseReg. 15505 break; 15506 case 1: 15507 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15508 return false; 15509 // Otherwise we have r+r or r+i. 15510 break; 15511 case 2: 15512 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15513 return false; 15514 // Allow 2*r as r+r. 15515 break; 15516 default: 15517 // No other scales are supported. 15518 return false; 15519 } 15520 15521 return true; 15522 } 15523 15524 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15525 SelectionDAG &DAG) const { 15526 MachineFunction &MF = DAG.getMachineFunction(); 15527 MachineFrameInfo &MFI = MF.getFrameInfo(); 15528 MFI.setReturnAddressIsTaken(true); 15529 15530 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15531 return SDValue(); 15532 15533 SDLoc dl(Op); 15534 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15535 15536 // Make sure the function does not optimize away the store of the RA to 15537 // the stack. 15538 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15539 FuncInfo->setLRStoreRequired(); 15540 bool isPPC64 = Subtarget.isPPC64(); 15541 auto PtrVT = getPointerTy(MF.getDataLayout()); 15542 15543 if (Depth > 0) { 15544 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15545 SDValue Offset = 15546 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15547 isPPC64 ? MVT::i64 : MVT::i32); 15548 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15549 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15550 MachinePointerInfo()); 15551 } 15552 15553 // Just load the return address off the stack. 15554 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15555 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15556 MachinePointerInfo()); 15557 } 15558 15559 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15560 SelectionDAG &DAG) const { 15561 SDLoc dl(Op); 15562 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15563 15564 MachineFunction &MF = DAG.getMachineFunction(); 15565 MachineFrameInfo &MFI = MF.getFrameInfo(); 15566 MFI.setFrameAddressIsTaken(true); 15567 15568 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15569 bool isPPC64 = PtrVT == MVT::i64; 15570 15571 // Naked functions never have a frame pointer, and so we use r1. For all 15572 // other functions, this decision must be delayed until during PEI. 15573 unsigned FrameReg; 15574 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15575 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15576 else 15577 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15578 15579 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15580 PtrVT); 15581 while (Depth--) 15582 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15583 FrameAddr, MachinePointerInfo()); 15584 return FrameAddr; 15585 } 15586 15587 // FIXME? Maybe this could be a TableGen attribute on some registers and 15588 // this table could be generated automatically from RegInfo. 15589 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15590 const MachineFunction &MF) const { 15591 bool isPPC64 = Subtarget.isPPC64(); 15592 15593 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15594 if (!is64Bit && VT != LLT::scalar(32)) 15595 report_fatal_error("Invalid register global variable type"); 15596 15597 Register Reg = StringSwitch<Register>(RegName) 15598 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15599 .Case("r2", isPPC64 ? Register() : PPC::R2) 15600 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15601 .Default(Register()); 15602 15603 if (Reg) 15604 return Reg; 15605 report_fatal_error("Invalid register name global variable"); 15606 } 15607 15608 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15609 // 32-bit SVR4 ABI access everything as got-indirect. 15610 if (Subtarget.is32BitELFABI()) 15611 return true; 15612 15613 // AIX accesses everything indirectly through the TOC, which is similar to 15614 // the GOT. 15615 if (Subtarget.isAIXABI()) 15616 return true; 15617 15618 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15619 // If it is small or large code model, module locals are accessed 15620 // indirectly by loading their address from .toc/.got. 15621 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15622 return true; 15623 15624 // JumpTable and BlockAddress are accessed as got-indirect. 15625 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15626 return true; 15627 15628 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15629 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15630 15631 return false; 15632 } 15633 15634 bool 15635 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15636 // The PowerPC target isn't yet aware of offsets. 15637 return false; 15638 } 15639 15640 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15641 const CallInst &I, 15642 MachineFunction &MF, 15643 unsigned Intrinsic) const { 15644 switch (Intrinsic) { 15645 case Intrinsic::ppc_altivec_lvx: 15646 case Intrinsic::ppc_altivec_lvxl: 15647 case Intrinsic::ppc_altivec_lvebx: 15648 case Intrinsic::ppc_altivec_lvehx: 15649 case Intrinsic::ppc_altivec_lvewx: 15650 case Intrinsic::ppc_vsx_lxvd2x: 15651 case Intrinsic::ppc_vsx_lxvw4x: { 15652 EVT VT; 15653 switch (Intrinsic) { 15654 case Intrinsic::ppc_altivec_lvebx: 15655 VT = MVT::i8; 15656 break; 15657 case Intrinsic::ppc_altivec_lvehx: 15658 VT = MVT::i16; 15659 break; 15660 case Intrinsic::ppc_altivec_lvewx: 15661 VT = MVT::i32; 15662 break; 15663 case Intrinsic::ppc_vsx_lxvd2x: 15664 VT = MVT::v2f64; 15665 break; 15666 default: 15667 VT = MVT::v4i32; 15668 break; 15669 } 15670 15671 Info.opc = ISD::INTRINSIC_W_CHAIN; 15672 Info.memVT = VT; 15673 Info.ptrVal = I.getArgOperand(0); 15674 Info.offset = -VT.getStoreSize()+1; 15675 Info.size = 2*VT.getStoreSize()-1; 15676 Info.align = Align(1); 15677 Info.flags = MachineMemOperand::MOLoad; 15678 return true; 15679 } 15680 case Intrinsic::ppc_altivec_stvx: 15681 case Intrinsic::ppc_altivec_stvxl: 15682 case Intrinsic::ppc_altivec_stvebx: 15683 case Intrinsic::ppc_altivec_stvehx: 15684 case Intrinsic::ppc_altivec_stvewx: 15685 case Intrinsic::ppc_vsx_stxvd2x: 15686 case Intrinsic::ppc_vsx_stxvw4x: { 15687 EVT VT; 15688 switch (Intrinsic) { 15689 case Intrinsic::ppc_altivec_stvebx: 15690 VT = MVT::i8; 15691 break; 15692 case Intrinsic::ppc_altivec_stvehx: 15693 VT = MVT::i16; 15694 break; 15695 case Intrinsic::ppc_altivec_stvewx: 15696 VT = MVT::i32; 15697 break; 15698 case Intrinsic::ppc_vsx_stxvd2x: 15699 VT = MVT::v2f64; 15700 break; 15701 default: 15702 VT = MVT::v4i32; 15703 break; 15704 } 15705 15706 Info.opc = ISD::INTRINSIC_VOID; 15707 Info.memVT = VT; 15708 Info.ptrVal = I.getArgOperand(1); 15709 Info.offset = -VT.getStoreSize()+1; 15710 Info.size = 2*VT.getStoreSize()-1; 15711 Info.align = Align(1); 15712 Info.flags = MachineMemOperand::MOStore; 15713 return true; 15714 } 15715 default: 15716 break; 15717 } 15718 15719 return false; 15720 } 15721 15722 /// It returns EVT::Other if the type should be determined using generic 15723 /// target-independent logic. 15724 EVT PPCTargetLowering::getOptimalMemOpType( 15725 const MemOp &Op, const AttributeList &FuncAttributes) const { 15726 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15727 // We should use Altivec/VSX loads and stores when available. For unaligned 15728 // addresses, unaligned VSX loads are only fast starting with the P8. 15729 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15730 (Op.isAligned(Align(16)) || 15731 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15732 return MVT::v4i32; 15733 } 15734 15735 if (Subtarget.isPPC64()) { 15736 return MVT::i64; 15737 } 15738 15739 return MVT::i32; 15740 } 15741 15742 /// Returns true if it is beneficial to convert a load of a constant 15743 /// to just the constant itself. 15744 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15745 Type *Ty) const { 15746 assert(Ty->isIntegerTy()); 15747 15748 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15749 return !(BitSize == 0 || BitSize > 64); 15750 } 15751 15752 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15753 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15754 return false; 15755 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15756 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15757 return NumBits1 == 64 && NumBits2 == 32; 15758 } 15759 15760 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15761 if (!VT1.isInteger() || !VT2.isInteger()) 15762 return false; 15763 unsigned NumBits1 = VT1.getSizeInBits(); 15764 unsigned NumBits2 = VT2.getSizeInBits(); 15765 return NumBits1 == 64 && NumBits2 == 32; 15766 } 15767 15768 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15769 // Generally speaking, zexts are not free, but they are free when they can be 15770 // folded with other operations. 15771 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15772 EVT MemVT = LD->getMemoryVT(); 15773 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15774 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15775 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15776 LD->getExtensionType() == ISD::ZEXTLOAD)) 15777 return true; 15778 } 15779 15780 // FIXME: Add other cases... 15781 // - 32-bit shifts with a zext to i64 15782 // - zext after ctlz, bswap, etc. 15783 // - zext after and by a constant mask 15784 15785 return TargetLowering::isZExtFree(Val, VT2); 15786 } 15787 15788 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15789 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15790 "invalid fpext types"); 15791 // Extending to float128 is not free. 15792 if (DestVT == MVT::f128) 15793 return false; 15794 return true; 15795 } 15796 15797 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15798 return isInt<16>(Imm) || isUInt<16>(Imm); 15799 } 15800 15801 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15802 return isInt<16>(Imm) || isUInt<16>(Imm); 15803 } 15804 15805 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15806 unsigned, 15807 unsigned, 15808 MachineMemOperand::Flags, 15809 bool *Fast) const { 15810 if (DisablePPCUnaligned) 15811 return false; 15812 15813 // PowerPC supports unaligned memory access for simple non-vector types. 15814 // Although accessing unaligned addresses is not as efficient as accessing 15815 // aligned addresses, it is generally more efficient than manual expansion, 15816 // and generally only traps for software emulation when crossing page 15817 // boundaries. 15818 15819 if (!VT.isSimple()) 15820 return false; 15821 15822 if (VT.isFloatingPoint() && !VT.isVector() && 15823 !Subtarget.allowsUnalignedFPAccess()) 15824 return false; 15825 15826 if (VT.getSimpleVT().isVector()) { 15827 if (Subtarget.hasVSX()) { 15828 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15829 VT != MVT::v4f32 && VT != MVT::v4i32) 15830 return false; 15831 } else { 15832 return false; 15833 } 15834 } 15835 15836 if (VT == MVT::ppcf128) 15837 return false; 15838 15839 if (Fast) 15840 *Fast = true; 15841 15842 return true; 15843 } 15844 15845 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15846 EVT VT) const { 15847 return isFMAFasterThanFMulAndFAdd( 15848 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15849 } 15850 15851 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15852 Type *Ty) const { 15853 switch (Ty->getScalarType()->getTypeID()) { 15854 case Type::FloatTyID: 15855 case Type::DoubleTyID: 15856 return true; 15857 case Type::FP128TyID: 15858 return Subtarget.hasP9Vector(); 15859 default: 15860 return false; 15861 } 15862 } 15863 15864 // FIXME: add more patterns which are not profitable to hoist. 15865 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15866 if (!I->hasOneUse()) 15867 return true; 15868 15869 Instruction *User = I->user_back(); 15870 assert(User && "A single use instruction with no uses."); 15871 15872 switch (I->getOpcode()) { 15873 case Instruction::FMul: { 15874 // Don't break FMA, PowerPC prefers FMA. 15875 if (User->getOpcode() != Instruction::FSub && 15876 User->getOpcode() != Instruction::FAdd) 15877 return true; 15878 15879 const TargetOptions &Options = getTargetMachine().Options; 15880 const Function *F = I->getFunction(); 15881 const DataLayout &DL = F->getParent()->getDataLayout(); 15882 Type *Ty = User->getOperand(0)->getType(); 15883 15884 return !( 15885 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15886 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15887 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15888 } 15889 case Instruction::Load: { 15890 // Don't break "store (load float*)" pattern, this pattern will be combined 15891 // to "store (load int32)" in later InstCombine pass. See function 15892 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15893 // cycles than loading a 32 bit integer. 15894 LoadInst *LI = cast<LoadInst>(I); 15895 // For the loads that combineLoadToOperationType does nothing, like 15896 // ordered load, it should be profitable to hoist them. 15897 // For swifterror load, it can only be used for pointer to pointer type, so 15898 // later type check should get rid of this case. 15899 if (!LI->isUnordered()) 15900 return true; 15901 15902 if (User->getOpcode() != Instruction::Store) 15903 return true; 15904 15905 if (I->getType()->getTypeID() != Type::FloatTyID) 15906 return true; 15907 15908 return false; 15909 } 15910 default: 15911 return true; 15912 } 15913 return true; 15914 } 15915 15916 const MCPhysReg * 15917 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15918 // LR is a callee-save register, but we must treat it as clobbered by any call 15919 // site. Hence we include LR in the scratch registers, which are in turn added 15920 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15921 // to CTR, which is used by any indirect call. 15922 static const MCPhysReg ScratchRegs[] = { 15923 PPC::X12, PPC::LR8, PPC::CTR8, 0 15924 }; 15925 15926 return ScratchRegs; 15927 } 15928 15929 Register PPCTargetLowering::getExceptionPointerRegister( 15930 const Constant *PersonalityFn) const { 15931 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15932 } 15933 15934 Register PPCTargetLowering::getExceptionSelectorRegister( 15935 const Constant *PersonalityFn) const { 15936 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15937 } 15938 15939 bool 15940 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15941 EVT VT , unsigned DefinedValues) const { 15942 if (VT == MVT::v2i64) 15943 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15944 15945 if (Subtarget.hasVSX()) 15946 return true; 15947 15948 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15949 } 15950 15951 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15952 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15953 return TargetLowering::getSchedulingPreference(N); 15954 15955 return Sched::ILP; 15956 } 15957 15958 // Create a fast isel object. 15959 FastISel * 15960 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15961 const TargetLibraryInfo *LibInfo) const { 15962 return PPC::createFastISel(FuncInfo, LibInfo); 15963 } 15964 15965 // 'Inverted' means the FMA opcode after negating one multiplicand. 15966 // For example, (fma -a b c) = (fnmsub a b c) 15967 static unsigned invertFMAOpcode(unsigned Opc) { 15968 switch (Opc) { 15969 default: 15970 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15971 case ISD::FMA: 15972 return PPCISD::FNMSUB; 15973 case PPCISD::FNMSUB: 15974 return ISD::FMA; 15975 } 15976 } 15977 15978 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15979 bool LegalOps, bool OptForSize, 15980 NegatibleCost &Cost, 15981 unsigned Depth) const { 15982 if (Depth > SelectionDAG::MaxRecursionDepth) 15983 return SDValue(); 15984 15985 unsigned Opc = Op.getOpcode(); 15986 EVT VT = Op.getValueType(); 15987 SDNodeFlags Flags = Op.getNode()->getFlags(); 15988 15989 switch (Opc) { 15990 case PPCISD::FNMSUB: 15991 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15992 break; 15993 15994 const TargetOptions &Options = getTargetMachine().Options; 15995 SDValue N0 = Op.getOperand(0); 15996 SDValue N1 = Op.getOperand(1); 15997 SDValue N2 = Op.getOperand(2); 15998 SDLoc Loc(Op); 15999 16000 NegatibleCost N2Cost = NegatibleCost::Expensive; 16001 SDValue NegN2 = 16002 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16003 16004 if (!NegN2) 16005 return SDValue(); 16006 16007 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16008 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16009 // These transformations may change sign of zeroes. For example, 16010 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16011 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16012 // Try and choose the cheaper one to negate. 16013 NegatibleCost N0Cost = NegatibleCost::Expensive; 16014 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16015 N0Cost, Depth + 1); 16016 16017 NegatibleCost N1Cost = NegatibleCost::Expensive; 16018 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16019 N1Cost, Depth + 1); 16020 16021 if (NegN0 && N0Cost <= N1Cost) { 16022 Cost = std::min(N0Cost, N2Cost); 16023 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16024 } else if (NegN1) { 16025 Cost = std::min(N1Cost, N2Cost); 16026 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16027 } 16028 } 16029 16030 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16031 if (isOperationLegal(ISD::FMA, VT)) { 16032 Cost = N2Cost; 16033 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16034 } 16035 16036 break; 16037 } 16038 16039 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16040 Cost, Depth); 16041 } 16042 16043 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16044 bool PPCTargetLowering::useLoadStackGuardNode() const { 16045 if (!Subtarget.isTargetLinux()) 16046 return TargetLowering::useLoadStackGuardNode(); 16047 return true; 16048 } 16049 16050 // Override to disable global variable loading on Linux. 16051 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16052 if (!Subtarget.isTargetLinux()) 16053 return TargetLowering::insertSSPDeclarations(M); 16054 } 16055 16056 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16057 bool ForCodeSize) const { 16058 if (!VT.isSimple() || !Subtarget.hasVSX()) 16059 return false; 16060 16061 switch(VT.getSimpleVT().SimpleTy) { 16062 default: 16063 // For FP types that are currently not supported by PPC backend, return 16064 // false. Examples: f16, f80. 16065 return false; 16066 case MVT::f32: 16067 case MVT::f64: 16068 if (Subtarget.hasPrefixInstrs()) { 16069 // With prefixed instructions, we can materialize anything that can be 16070 // represented with a 32-bit immediate, not just positive zero. 16071 APFloat APFloatOfImm = Imm; 16072 return convertToNonDenormSingle(APFloatOfImm); 16073 } 16074 LLVM_FALLTHROUGH; 16075 case MVT::ppcf128: 16076 return Imm.isPosZero(); 16077 } 16078 } 16079 16080 // For vector shift operation op, fold 16081 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16082 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16083 SelectionDAG &DAG) { 16084 SDValue N0 = N->getOperand(0); 16085 SDValue N1 = N->getOperand(1); 16086 EVT VT = N0.getValueType(); 16087 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16088 unsigned Opcode = N->getOpcode(); 16089 unsigned TargetOpcode; 16090 16091 switch (Opcode) { 16092 default: 16093 llvm_unreachable("Unexpected shift operation"); 16094 case ISD::SHL: 16095 TargetOpcode = PPCISD::SHL; 16096 break; 16097 case ISD::SRL: 16098 TargetOpcode = PPCISD::SRL; 16099 break; 16100 case ISD::SRA: 16101 TargetOpcode = PPCISD::SRA; 16102 break; 16103 } 16104 16105 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16106 N1->getOpcode() == ISD::AND) 16107 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16108 if (Mask->getZExtValue() == OpSizeInBits - 1) 16109 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16110 16111 return SDValue(); 16112 } 16113 16114 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16115 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16116 return Value; 16117 16118 SDValue N0 = N->getOperand(0); 16119 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16120 if (!Subtarget.isISA3_0() || 16121 N0.getOpcode() != ISD::SIGN_EXTEND || 16122 N0.getOperand(0).getValueType() != MVT::i32 || 16123 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16124 return SDValue(); 16125 16126 // We can't save an operation here if the value is already extended, and 16127 // the existing shift is easier to combine. 16128 SDValue ExtsSrc = N0.getOperand(0); 16129 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16130 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16131 return SDValue(); 16132 16133 SDLoc DL(N0); 16134 SDValue ShiftBy = SDValue(CN1, 0); 16135 // We want the shift amount to be i32 on the extswli, but the shift could 16136 // have an i64. 16137 if (ShiftBy.getValueType() == MVT::i64) 16138 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16139 16140 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16141 ShiftBy); 16142 } 16143 16144 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16145 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16146 return Value; 16147 16148 return SDValue(); 16149 } 16150 16151 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16152 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16153 return Value; 16154 16155 return SDValue(); 16156 } 16157 16158 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16159 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16160 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16161 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16162 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16163 const PPCSubtarget &Subtarget) { 16164 if (!Subtarget.isPPC64()) 16165 return SDValue(); 16166 16167 SDValue LHS = N->getOperand(0); 16168 SDValue RHS = N->getOperand(1); 16169 16170 auto isZextOfCompareWithConstant = [](SDValue Op) { 16171 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16172 Op.getValueType() != MVT::i64) 16173 return false; 16174 16175 SDValue Cmp = Op.getOperand(0); 16176 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16177 Cmp.getOperand(0).getValueType() != MVT::i64) 16178 return false; 16179 16180 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16181 int64_t NegConstant = 0 - Constant->getSExtValue(); 16182 // Due to the limitations of the addi instruction, 16183 // -C is required to be [-32768, 32767]. 16184 return isInt<16>(NegConstant); 16185 } 16186 16187 return false; 16188 }; 16189 16190 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16191 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16192 16193 // If there is a pattern, canonicalize a zext operand to the RHS. 16194 if (LHSHasPattern && !RHSHasPattern) 16195 std::swap(LHS, RHS); 16196 else if (!LHSHasPattern && !RHSHasPattern) 16197 return SDValue(); 16198 16199 SDLoc DL(N); 16200 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16201 SDValue Cmp = RHS.getOperand(0); 16202 SDValue Z = Cmp.getOperand(0); 16203 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16204 16205 assert(Constant && "Constant Should not be a null pointer."); 16206 int64_t NegConstant = 0 - Constant->getSExtValue(); 16207 16208 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16209 default: break; 16210 case ISD::SETNE: { 16211 // when C == 0 16212 // --> addze X, (addic Z, -1).carry 16213 // / 16214 // add X, (zext(setne Z, C))-- 16215 // \ when -32768 <= -C <= 32767 && C != 0 16216 // --> addze X, (addic (addi Z, -C), -1).carry 16217 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16218 DAG.getConstant(NegConstant, DL, MVT::i64)); 16219 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16220 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16221 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16222 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16223 SDValue(Addc.getNode(), 1)); 16224 } 16225 case ISD::SETEQ: { 16226 // when C == 0 16227 // --> addze X, (subfic Z, 0).carry 16228 // / 16229 // add X, (zext(sete Z, C))-- 16230 // \ when -32768 <= -C <= 32767 && C != 0 16231 // --> addze X, (subfic (addi Z, -C), 0).carry 16232 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16233 DAG.getConstant(NegConstant, DL, MVT::i64)); 16234 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16235 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16236 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16237 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16238 SDValue(Subc.getNode(), 1)); 16239 } 16240 } 16241 16242 return SDValue(); 16243 } 16244 16245 // Transform 16246 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16247 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16248 // In this case both C1 and C2 must be known constants. 16249 // C1+C2 must fit into a 34 bit signed integer. 16250 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16251 const PPCSubtarget &Subtarget) { 16252 if (!Subtarget.isUsingPCRelativeCalls()) 16253 return SDValue(); 16254 16255 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16256 // If we find that node try to cast the Global Address and the Constant. 16257 SDValue LHS = N->getOperand(0); 16258 SDValue RHS = N->getOperand(1); 16259 16260 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16261 std::swap(LHS, RHS); 16262 16263 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16264 return SDValue(); 16265 16266 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16267 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16268 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16269 16270 // Check that both casts succeeded. 16271 if (!GSDN || !ConstNode) 16272 return SDValue(); 16273 16274 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16275 SDLoc DL(GSDN); 16276 16277 // The signed int offset needs to fit in 34 bits. 16278 if (!isInt<34>(NewOffset)) 16279 return SDValue(); 16280 16281 // The new global address is a copy of the old global address except 16282 // that it has the updated Offset. 16283 SDValue GA = 16284 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16285 NewOffset, GSDN->getTargetFlags()); 16286 SDValue MatPCRel = 16287 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16288 return MatPCRel; 16289 } 16290 16291 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16292 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16293 return Value; 16294 16295 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16296 return Value; 16297 16298 return SDValue(); 16299 } 16300 16301 // Detect TRUNCATE operations on bitcasts of float128 values. 16302 // What we are looking for here is the situtation where we extract a subset 16303 // of bits from a 128 bit float. 16304 // This can be of two forms: 16305 // 1) BITCAST of f128 feeding TRUNCATE 16306 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16307 // The reason this is required is because we do not have a legal i128 type 16308 // and so we want to prevent having to store the f128 and then reload part 16309 // of it. 16310 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16311 DAGCombinerInfo &DCI) const { 16312 // If we are using CRBits then try that first. 16313 if (Subtarget.useCRBits()) { 16314 // Check if CRBits did anything and return that if it did. 16315 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16316 return CRTruncValue; 16317 } 16318 16319 SDLoc dl(N); 16320 SDValue Op0 = N->getOperand(0); 16321 16322 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16323 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16324 EVT VT = N->getValueType(0); 16325 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16326 return SDValue(); 16327 SDValue Sub = Op0.getOperand(0); 16328 if (Sub.getOpcode() == ISD::SUB) { 16329 SDValue SubOp0 = Sub.getOperand(0); 16330 SDValue SubOp1 = Sub.getOperand(1); 16331 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16332 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16333 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16334 SubOp1.getOperand(0), 16335 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16336 } 16337 } 16338 } 16339 16340 // Looking for a truncate of i128 to i64. 16341 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16342 return SDValue(); 16343 16344 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16345 16346 // SRL feeding TRUNCATE. 16347 if (Op0.getOpcode() == ISD::SRL) { 16348 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16349 // The right shift has to be by 64 bits. 16350 if (!ConstNode || ConstNode->getZExtValue() != 64) 16351 return SDValue(); 16352 16353 // Switch the element number to extract. 16354 EltToExtract = EltToExtract ? 0 : 1; 16355 // Update Op0 past the SRL. 16356 Op0 = Op0.getOperand(0); 16357 } 16358 16359 // BITCAST feeding a TRUNCATE possibly via SRL. 16360 if (Op0.getOpcode() == ISD::BITCAST && 16361 Op0.getValueType() == MVT::i128 && 16362 Op0.getOperand(0).getValueType() == MVT::f128) { 16363 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16364 return DCI.DAG.getNode( 16365 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16366 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16367 } 16368 return SDValue(); 16369 } 16370 16371 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16372 SelectionDAG &DAG = DCI.DAG; 16373 16374 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16375 if (!ConstOpOrElement) 16376 return SDValue(); 16377 16378 // An imul is usually smaller than the alternative sequence for legal type. 16379 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16380 isOperationLegal(ISD::MUL, N->getValueType(0))) 16381 return SDValue(); 16382 16383 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16384 switch (this->Subtarget.getCPUDirective()) { 16385 default: 16386 // TODO: enhance the condition for subtarget before pwr8 16387 return false; 16388 case PPC::DIR_PWR8: 16389 // type mul add shl 16390 // scalar 4 1 1 16391 // vector 7 2 2 16392 return true; 16393 case PPC::DIR_PWR9: 16394 case PPC::DIR_PWR10: 16395 case PPC::DIR_PWR_FUTURE: 16396 // type mul add shl 16397 // scalar 5 2 2 16398 // vector 7 2 2 16399 16400 // The cycle RATIO of related operations are showed as a table above. 16401 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16402 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16403 // are 4, it is always profitable; but for 3 instrs patterns 16404 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16405 // So we should only do it for vector type. 16406 return IsAddOne && IsNeg ? VT.isVector() : true; 16407 } 16408 }; 16409 16410 EVT VT = N->getValueType(0); 16411 SDLoc DL(N); 16412 16413 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16414 bool IsNeg = MulAmt.isNegative(); 16415 APInt MulAmtAbs = MulAmt.abs(); 16416 16417 if ((MulAmtAbs - 1).isPowerOf2()) { 16418 // (mul x, 2^N + 1) => (add (shl x, N), x) 16419 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16420 16421 if (!IsProfitable(IsNeg, true, VT)) 16422 return SDValue(); 16423 16424 SDValue Op0 = N->getOperand(0); 16425 SDValue Op1 = 16426 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16427 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16428 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16429 16430 if (!IsNeg) 16431 return Res; 16432 16433 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16434 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16435 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16436 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16437 16438 if (!IsProfitable(IsNeg, false, VT)) 16439 return SDValue(); 16440 16441 SDValue Op0 = N->getOperand(0); 16442 SDValue Op1 = 16443 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16444 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16445 16446 if (!IsNeg) 16447 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16448 else 16449 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16450 16451 } else { 16452 return SDValue(); 16453 } 16454 } 16455 16456 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16457 // in combiner since we need to check SD flags and other subtarget features. 16458 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16459 DAGCombinerInfo &DCI) const { 16460 SDValue N0 = N->getOperand(0); 16461 SDValue N1 = N->getOperand(1); 16462 SDValue N2 = N->getOperand(2); 16463 SDNodeFlags Flags = N->getFlags(); 16464 EVT VT = N->getValueType(0); 16465 SelectionDAG &DAG = DCI.DAG; 16466 const TargetOptions &Options = getTargetMachine().Options; 16467 unsigned Opc = N->getOpcode(); 16468 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16469 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16470 SDLoc Loc(N); 16471 16472 if (!isOperationLegal(ISD::FMA, VT)) 16473 return SDValue(); 16474 16475 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16476 // since (fnmsub a b c)=-0 while c-ab=+0. 16477 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16478 return SDValue(); 16479 16480 // (fma (fneg a) b c) => (fnmsub a b c) 16481 // (fnmsub (fneg a) b c) => (fma a b c) 16482 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16483 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16484 16485 // (fma a (fneg b) c) => (fnmsub a b c) 16486 // (fnmsub a (fneg b) c) => (fma a b c) 16487 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16488 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16489 16490 return SDValue(); 16491 } 16492 16493 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16494 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16495 if (!Subtarget.is64BitELFABI()) 16496 return false; 16497 16498 // If not a tail call then no need to proceed. 16499 if (!CI->isTailCall()) 16500 return false; 16501 16502 // If sibling calls have been disabled and tail-calls aren't guaranteed 16503 // there is no reason to duplicate. 16504 auto &TM = getTargetMachine(); 16505 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16506 return false; 16507 16508 // Can't tail call a function called indirectly, or if it has variadic args. 16509 const Function *Callee = CI->getCalledFunction(); 16510 if (!Callee || Callee->isVarArg()) 16511 return false; 16512 16513 // Make sure the callee and caller calling conventions are eligible for tco. 16514 const Function *Caller = CI->getParent()->getParent(); 16515 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16516 CI->getCallingConv())) 16517 return false; 16518 16519 // If the function is local then we have a good chance at tail-calling it 16520 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16521 } 16522 16523 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16524 if (!Subtarget.hasVSX()) 16525 return false; 16526 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16527 return true; 16528 return VT == MVT::f32 || VT == MVT::f64 || 16529 VT == MVT::v4f32 || VT == MVT::v2f64; 16530 } 16531 16532 bool PPCTargetLowering:: 16533 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16534 const Value *Mask = AndI.getOperand(1); 16535 // If the mask is suitable for andi. or andis. we should sink the and. 16536 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16537 // Can't handle constants wider than 64-bits. 16538 if (CI->getBitWidth() > 64) 16539 return false; 16540 int64_t ConstVal = CI->getZExtValue(); 16541 return isUInt<16>(ConstVal) || 16542 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16543 } 16544 16545 // For non-constant masks, we can always use the record-form and. 16546 return true; 16547 } 16548 16549 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16550 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16551 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16552 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16553 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16554 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16555 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16556 assert(Subtarget.hasP9Altivec() && 16557 "Only combine this when P9 altivec supported!"); 16558 EVT VT = N->getValueType(0); 16559 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16560 return SDValue(); 16561 16562 SelectionDAG &DAG = DCI.DAG; 16563 SDLoc dl(N); 16564 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16565 // Even for signed integers, if it's known to be positive (as signed 16566 // integer) due to zero-extended inputs. 16567 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16568 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16569 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16570 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16571 (SubOpcd1 == ISD::ZERO_EXTEND || 16572 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16573 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16574 N->getOperand(0)->getOperand(0), 16575 N->getOperand(0)->getOperand(1), 16576 DAG.getTargetConstant(0, dl, MVT::i32)); 16577 } 16578 16579 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16580 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16581 N->getOperand(0).hasOneUse()) { 16582 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16583 N->getOperand(0)->getOperand(0), 16584 N->getOperand(0)->getOperand(1), 16585 DAG.getTargetConstant(1, dl, MVT::i32)); 16586 } 16587 } 16588 16589 return SDValue(); 16590 } 16591 16592 // For type v4i32/v8ii16/v16i8, transform 16593 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16594 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16595 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16596 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16597 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16598 DAGCombinerInfo &DCI) const { 16599 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16600 assert(Subtarget.hasP9Altivec() && 16601 "Only combine this when P9 altivec supported!"); 16602 16603 SelectionDAG &DAG = DCI.DAG; 16604 SDLoc dl(N); 16605 SDValue Cond = N->getOperand(0); 16606 SDValue TrueOpnd = N->getOperand(1); 16607 SDValue FalseOpnd = N->getOperand(2); 16608 EVT VT = N->getOperand(1).getValueType(); 16609 16610 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16611 FalseOpnd.getOpcode() != ISD::SUB) 16612 return SDValue(); 16613 16614 // ABSD only available for type v4i32/v8i16/v16i8 16615 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16616 return SDValue(); 16617 16618 // At least to save one more dependent computation 16619 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16620 return SDValue(); 16621 16622 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16623 16624 // Can only handle unsigned comparison here 16625 switch (CC) { 16626 default: 16627 return SDValue(); 16628 case ISD::SETUGT: 16629 case ISD::SETUGE: 16630 break; 16631 case ISD::SETULT: 16632 case ISD::SETULE: 16633 std::swap(TrueOpnd, FalseOpnd); 16634 break; 16635 } 16636 16637 SDValue CmpOpnd1 = Cond.getOperand(0); 16638 SDValue CmpOpnd2 = Cond.getOperand(1); 16639 16640 // SETCC CmpOpnd1 CmpOpnd2 cond 16641 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16642 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16643 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16644 TrueOpnd.getOperand(1) == CmpOpnd2 && 16645 FalseOpnd.getOperand(0) == CmpOpnd2 && 16646 FalseOpnd.getOperand(1) == CmpOpnd1) { 16647 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16648 CmpOpnd1, CmpOpnd2, 16649 DAG.getTargetConstant(0, dl, MVT::i32)); 16650 } 16651 16652 return SDValue(); 16653 } 16654