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/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetLowering.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/CallSite.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/Constant.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DerivedTypes.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/Intrinsics.h" 68 #include "llvm/IR/Module.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/MC/MCExpr.h" 73 #include "llvm/MC/MCRegisterInfo.h" 74 #include "llvm/Support/AtomicOrdering.h" 75 #include "llvm/Support/BranchProbability.h" 76 #include "llvm/Support/Casting.h" 77 #include "llvm/Support/CodeGen.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Compiler.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/ErrorHandling.h" 82 #include "llvm/Support/Format.h" 83 #include "llvm/Support/KnownBits.h" 84 #include "llvm/Support/MachineValueType.h" 85 #include "llvm/Support/MathExtras.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstdint> 92 #include <iterator> 93 #include <list> 94 #include <utility> 95 #include <vector> 96 97 using namespace llvm; 98 99 #define DEBUG_TYPE "ppc-lowering" 100 101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 103 104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisableSCO("disable-ppc-sco", 111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 112 113 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 114 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 115 116 STATISTIC(NumTailCalls, "Number of tail calls"); 117 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 118 119 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 120 121 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 122 123 // FIXME: Remove this once the bug has been fixed! 124 extern cl::opt<bool> ANDIGlueBug; 125 126 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 127 const PPCSubtarget &STI) 128 : TargetLowering(TM), Subtarget(STI) { 129 // Use _setjmp/_longjmp instead of setjmp/longjmp. 130 setUseUnderscoreSetJmp(true); 131 setUseUnderscoreLongJmp(true); 132 133 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 134 // arguments are at least 4/8 bytes aligned. 135 bool isPPC64 = Subtarget.isPPC64(); 136 setMinStackArgumentAlignment(isPPC64 ? 8:4); 137 138 // Set up the register classes. 139 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 140 if (!useSoftFloat()) { 141 if (hasSPE()) { 142 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 143 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 144 } else { 145 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 146 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 147 } 148 } 149 150 // Match BITREVERSE to customized fast code sequence in the td file. 151 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 152 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 153 154 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 155 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 156 157 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 158 for (MVT VT : MVT::integer_valuetypes()) { 159 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 160 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 161 } 162 163 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 164 165 // PowerPC has pre-inc load and store's. 166 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 167 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 168 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 169 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 170 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 171 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 172 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 173 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 174 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 175 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 176 if (!Subtarget.hasSPE()) { 177 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 178 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 181 } 182 183 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 184 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 185 for (MVT VT : ScalarIntVTs) { 186 setOperationAction(ISD::ADDC, VT, Legal); 187 setOperationAction(ISD::ADDE, VT, Legal); 188 setOperationAction(ISD::SUBC, VT, Legal); 189 setOperationAction(ISD::SUBE, VT, Legal); 190 } 191 192 if (Subtarget.useCRBits()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 194 195 if (isPPC64 || Subtarget.hasFPCVT()) { 196 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 197 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 198 isPPC64 ? MVT::i64 : MVT::i32); 199 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 200 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 201 isPPC64 ? MVT::i64 : MVT::i32); 202 } else { 203 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 204 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 205 } 206 207 // PowerPC does not support direct load/store of condition registers. 208 setOperationAction(ISD::LOAD, MVT::i1, Custom); 209 setOperationAction(ISD::STORE, MVT::i1, Custom); 210 211 // FIXME: Remove this once the ANDI glue bug is fixed: 212 if (ANDIGlueBug) 213 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 214 215 for (MVT VT : MVT::integer_valuetypes()) { 216 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 217 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 218 setTruncStoreAction(VT, MVT::i1, Expand); 219 } 220 221 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 222 } 223 224 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 225 // PPC (the libcall is not available). 226 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 227 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 228 229 // We do not currently implement these libm ops for PowerPC. 230 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 231 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 232 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 233 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 234 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 235 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 236 237 // PowerPC has no SREM/UREM instructions unless we are on P9 238 // On P9 we may use a hardware instruction to compute the remainder. 239 // The instructions are not legalized directly because in the cases where the 240 // result of both the remainder and the division is required it is more 241 // efficient to compute the remainder from the result of the division rather 242 // than use the remainder instruction. 243 if (Subtarget.isISA3_0()) { 244 setOperationAction(ISD::SREM, MVT::i32, Custom); 245 setOperationAction(ISD::UREM, MVT::i32, Custom); 246 setOperationAction(ISD::SREM, MVT::i64, Custom); 247 setOperationAction(ISD::UREM, MVT::i64, Custom); 248 } else { 249 setOperationAction(ISD::SREM, MVT::i32, Expand); 250 setOperationAction(ISD::UREM, MVT::i32, Expand); 251 setOperationAction(ISD::SREM, MVT::i64, Expand); 252 setOperationAction(ISD::UREM, MVT::i64, Expand); 253 } 254 255 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 256 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 257 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 258 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 259 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 260 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 261 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 262 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 263 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 264 265 // We don't support sin/cos/sqrt/fmod/pow 266 setOperationAction(ISD::FSIN , MVT::f64, Expand); 267 setOperationAction(ISD::FCOS , MVT::f64, Expand); 268 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 269 setOperationAction(ISD::FREM , MVT::f64, Expand); 270 setOperationAction(ISD::FPOW , MVT::f64, Expand); 271 setOperationAction(ISD::FSIN , MVT::f32, Expand); 272 setOperationAction(ISD::FCOS , MVT::f32, Expand); 273 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 274 setOperationAction(ISD::FREM , MVT::f32, Expand); 275 setOperationAction(ISD::FPOW , MVT::f32, Expand); 276 if (Subtarget.hasSPE()) { 277 setOperationAction(ISD::FMA , MVT::f64, Expand); 278 setOperationAction(ISD::FMA , MVT::f32, Expand); 279 } else { 280 setOperationAction(ISD::FMA , MVT::f64, Legal); 281 setOperationAction(ISD::FMA , MVT::f32, Legal); 282 } 283 284 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 285 286 // If we're enabling GP optimizations, use hardware square root 287 if (!Subtarget.hasFSQRT() && 288 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 289 Subtarget.hasFRE())) 290 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 291 292 if (!Subtarget.hasFSQRT() && 293 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 294 Subtarget.hasFRES())) 295 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 296 297 if (Subtarget.hasFCPSGN()) { 298 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 299 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 300 } else { 301 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 302 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 303 } 304 305 if (Subtarget.hasFPRND()) { 306 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 307 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 308 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 309 setOperationAction(ISD::FROUND, MVT::f64, Legal); 310 311 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 312 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 313 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 314 setOperationAction(ISD::FROUND, MVT::f32, Legal); 315 } 316 317 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 318 // to speed up scalar BSWAP64. 319 // CTPOP or CTTZ were introduced in P8/P9 respectively 320 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 321 if (Subtarget.hasP9Vector()) 322 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 323 else 324 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 325 if (Subtarget.isISA3_0()) { 326 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 327 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 328 } else { 329 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 330 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 331 } 332 333 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 334 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 335 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 336 } else { 337 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 338 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 339 } 340 341 // PowerPC does not have ROTR 342 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 343 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 344 345 if (!Subtarget.useCRBits()) { 346 // PowerPC does not have Select 347 setOperationAction(ISD::SELECT, MVT::i32, Expand); 348 setOperationAction(ISD::SELECT, MVT::i64, Expand); 349 setOperationAction(ISD::SELECT, MVT::f32, Expand); 350 setOperationAction(ISD::SELECT, MVT::f64, Expand); 351 } 352 353 // PowerPC wants to turn select_cc of FP into fsel when possible. 354 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 355 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 356 357 // PowerPC wants to optimize integer setcc a bit 358 if (!Subtarget.useCRBits()) 359 setOperationAction(ISD::SETCC, MVT::i32, Custom); 360 361 // PowerPC does not have BRCOND which requires SetCC 362 if (!Subtarget.useCRBits()) 363 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 364 365 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 366 367 if (Subtarget.hasSPE()) { 368 // SPE has built-in conversions 369 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 370 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 371 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 372 } else { 373 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 374 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 375 376 // PowerPC does not have [U|S]INT_TO_FP 377 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 378 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 379 } 380 381 if (Subtarget.hasDirectMove() && isPPC64) { 382 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 383 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 384 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 385 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 386 } else { 387 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 388 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 389 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 390 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 391 } 392 393 // We cannot sextinreg(i1). Expand to shifts. 394 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 395 396 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 397 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 398 // support continuation, user-level threading, and etc.. As a result, no 399 // other SjLj exception interfaces are implemented and please don't build 400 // your own exception handling based on them. 401 // LLVM/Clang supports zero-cost DWARF exception handling. 402 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 403 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 404 405 // We want to legalize GlobalAddress and ConstantPool nodes into the 406 // appropriate instructions to materialize the address. 407 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 408 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 409 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 410 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 411 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 412 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 413 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 414 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 415 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 416 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 417 418 // TRAP is legal. 419 setOperationAction(ISD::TRAP, MVT::Other, Legal); 420 421 // TRAMPOLINE is custom lowered. 422 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 423 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 424 425 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 426 setOperationAction(ISD::VASTART , MVT::Other, Custom); 427 428 if (Subtarget.isSVR4ABI()) { 429 if (isPPC64) { 430 // VAARG always uses double-word chunks, so promote anything smaller. 431 setOperationAction(ISD::VAARG, MVT::i1, Promote); 432 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 433 setOperationAction(ISD::VAARG, MVT::i8, Promote); 434 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 435 setOperationAction(ISD::VAARG, MVT::i16, Promote); 436 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 437 setOperationAction(ISD::VAARG, MVT::i32, Promote); 438 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 439 setOperationAction(ISD::VAARG, MVT::Other, Expand); 440 } else { 441 // VAARG is custom lowered with the 32-bit SVR4 ABI. 442 setOperationAction(ISD::VAARG, MVT::Other, Custom); 443 setOperationAction(ISD::VAARG, MVT::i64, Custom); 444 } 445 } else 446 setOperationAction(ISD::VAARG, MVT::Other, Expand); 447 448 if (Subtarget.isSVR4ABI() && !isPPC64) 449 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 450 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 451 else 452 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 453 454 // Use the default implementation. 455 setOperationAction(ISD::VAEND , MVT::Other, Expand); 456 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 457 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 458 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 459 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 460 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 461 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 462 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 463 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 464 465 // We want to custom lower some of our intrinsics. 466 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 467 468 // To handle counter-based loop conditions. 469 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 470 471 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 475 476 // Comparisons that require checking two conditions. 477 if (Subtarget.hasSPE()) { 478 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 479 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 480 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 481 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 482 } 483 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 484 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 485 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 486 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 487 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 488 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 489 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 495 496 if (Subtarget.has64BitSupport()) { 497 // They also have instructions for converting between i64 and fp. 498 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 499 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 500 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 501 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 502 // This is just the low 32 bits of a (signed) fp->i64 conversion. 503 // We cannot do this with Promote because i64 is not a legal type. 504 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 505 506 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 507 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 508 } else { 509 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 510 if (Subtarget.hasSPE()) 511 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 512 else 513 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 514 } 515 516 // With the instructions enabled under FPCVT, we can do everything. 517 if (Subtarget.hasFPCVT()) { 518 if (Subtarget.has64BitSupport()) { 519 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 520 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 521 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 522 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 523 } 524 525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 526 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 527 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 528 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 529 } 530 531 if (Subtarget.use64BitRegs()) { 532 // 64-bit PowerPC implementations can support i64 types directly 533 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 534 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 535 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 536 // 64-bit PowerPC wants to expand i128 shifts itself. 537 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 538 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 539 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 540 } else { 541 // 32-bit PowerPC wants to expand i64 shifts itself. 542 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 543 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 544 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 545 } 546 547 if (Subtarget.hasAltivec()) { 548 // First set operation action for all vector types to expand. Then we 549 // will selectively turn on ones that can be effectively codegen'd. 550 for (MVT VT : MVT::vector_valuetypes()) { 551 // add/sub are legal for all supported vector VT's. 552 setOperationAction(ISD::ADD, VT, Legal); 553 setOperationAction(ISD::SUB, VT, Legal); 554 555 // Vector instructions introduced in P8 556 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 557 setOperationAction(ISD::CTPOP, VT, Legal); 558 setOperationAction(ISD::CTLZ, VT, Legal); 559 } 560 else { 561 setOperationAction(ISD::CTPOP, VT, Expand); 562 setOperationAction(ISD::CTLZ, VT, Expand); 563 } 564 565 // Vector instructions introduced in P9 566 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 567 setOperationAction(ISD::CTTZ, VT, Legal); 568 else 569 setOperationAction(ISD::CTTZ, VT, Expand); 570 571 // We promote all shuffles to v16i8. 572 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 573 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 574 575 // We promote all non-typed operations to v4i32. 576 setOperationAction(ISD::AND , VT, Promote); 577 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 578 setOperationAction(ISD::OR , VT, Promote); 579 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 580 setOperationAction(ISD::XOR , VT, Promote); 581 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 582 setOperationAction(ISD::LOAD , VT, Promote); 583 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 584 setOperationAction(ISD::SELECT, VT, Promote); 585 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 586 setOperationAction(ISD::VSELECT, VT, Legal); 587 setOperationAction(ISD::SELECT_CC, VT, Promote); 588 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 589 setOperationAction(ISD::STORE, VT, Promote); 590 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 591 592 // No other operations are legal. 593 setOperationAction(ISD::MUL , VT, Expand); 594 setOperationAction(ISD::SDIV, VT, Expand); 595 setOperationAction(ISD::SREM, VT, Expand); 596 setOperationAction(ISD::UDIV, VT, Expand); 597 setOperationAction(ISD::UREM, VT, Expand); 598 setOperationAction(ISD::FDIV, VT, Expand); 599 setOperationAction(ISD::FREM, VT, Expand); 600 setOperationAction(ISD::FNEG, VT, Expand); 601 setOperationAction(ISD::FSQRT, VT, Expand); 602 setOperationAction(ISD::FLOG, VT, Expand); 603 setOperationAction(ISD::FLOG10, VT, Expand); 604 setOperationAction(ISD::FLOG2, VT, Expand); 605 setOperationAction(ISD::FEXP, VT, Expand); 606 setOperationAction(ISD::FEXP2, VT, Expand); 607 setOperationAction(ISD::FSIN, VT, Expand); 608 setOperationAction(ISD::FCOS, VT, Expand); 609 setOperationAction(ISD::FABS, VT, Expand); 610 setOperationAction(ISD::FFLOOR, VT, Expand); 611 setOperationAction(ISD::FCEIL, VT, Expand); 612 setOperationAction(ISD::FTRUNC, VT, Expand); 613 setOperationAction(ISD::FRINT, VT, Expand); 614 setOperationAction(ISD::FNEARBYINT, VT, Expand); 615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 616 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 617 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 618 setOperationAction(ISD::MULHU, VT, Expand); 619 setOperationAction(ISD::MULHS, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UDIVREM, VT, Expand); 623 setOperationAction(ISD::SDIVREM, VT, Expand); 624 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 625 setOperationAction(ISD::FPOW, VT, Expand); 626 setOperationAction(ISD::BSWAP, VT, Expand); 627 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 628 setOperationAction(ISD::ROTL, VT, Expand); 629 setOperationAction(ISD::ROTR, VT, Expand); 630 631 for (MVT InnerVT : MVT::vector_valuetypes()) { 632 setTruncStoreAction(VT, InnerVT, Expand); 633 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 634 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 635 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 636 } 637 } 638 639 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 640 setOperationAction(ISD::ABS, VT, Custom); 641 642 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 643 // with merges, splats, etc. 644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 645 646 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 647 // are cheap, so handle them before they get expanded to scalar. 648 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 649 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 650 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 651 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 652 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 653 654 setOperationAction(ISD::AND , MVT::v4i32, Legal); 655 setOperationAction(ISD::OR , MVT::v4i32, Legal); 656 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 657 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 658 setOperationAction(ISD::SELECT, MVT::v4i32, 659 Subtarget.useCRBits() ? Legal : Expand); 660 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 661 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 662 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 663 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 664 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 665 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 666 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 667 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 668 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 669 670 // Without hasP8Altivec set, v2i64 SMAX isn't available. 671 // But ABS custom lowering requires SMAX support. 672 if (!Subtarget.hasP8Altivec()) 673 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 674 675 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 676 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 677 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 678 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 679 680 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 681 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 682 683 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 684 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 685 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 686 } 687 688 if (Subtarget.hasP8Altivec()) 689 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 690 else 691 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 692 693 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 694 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 695 696 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 697 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 698 699 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 700 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 701 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 702 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 703 704 // Altivec does not contain unordered floating-point compare instructions 705 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 706 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 707 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 708 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 709 710 if (Subtarget.hasVSX()) { 711 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 713 if (Subtarget.hasP8Vector()) { 714 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 716 } 717 if (Subtarget.hasDirectMove() && isPPC64) { 718 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 719 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 720 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 722 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 724 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 725 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 726 } 727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 728 729 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 730 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 731 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 732 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 733 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 734 735 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 736 737 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 738 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 739 740 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 741 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 742 743 // Share the Altivec comparison restrictions. 744 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 745 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 746 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 747 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 748 749 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 750 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 751 752 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 753 754 if (Subtarget.hasP8Vector()) 755 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 756 757 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 758 759 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 760 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 761 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 762 763 if (Subtarget.hasP8Altivec()) { 764 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 765 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 766 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 767 768 // 128 bit shifts can be accomplished via 3 instructions for SHL and 769 // SRL, but not for SRA because of the instructions available: 770 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 771 // doing 772 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 773 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 774 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 775 776 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 777 } 778 else { 779 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 780 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 781 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 782 783 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 784 785 // VSX v2i64 only supports non-arithmetic operations. 786 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 787 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 788 } 789 790 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 791 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 792 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 793 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 794 795 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 796 797 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 798 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 799 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 800 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 801 802 // Custom handling for partial vectors of integers converted to 803 // floating point. We already have optimal handling for v2i32 through 804 // the DAG combine, so those aren't necessary. 805 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 806 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 807 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 808 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 809 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 810 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 811 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 812 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 813 814 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 815 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 816 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 817 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 818 819 if (Subtarget.hasDirectMove()) 820 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 821 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 822 823 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 824 } 825 826 if (Subtarget.hasP8Altivec()) { 827 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 828 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 829 } 830 831 if (Subtarget.hasP9Vector()) { 832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 834 835 // 128 bit shifts can be accomplished via 3 instructions for SHL and 836 // SRL, but not for SRA because of the instructions available: 837 // VS{RL} and VS{RL}O. 838 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 839 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 840 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 841 842 if (EnableQuadPrecision) { 843 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 844 setOperationAction(ISD::FADD, MVT::f128, Legal); 845 setOperationAction(ISD::FSUB, MVT::f128, Legal); 846 setOperationAction(ISD::FDIV, MVT::f128, Legal); 847 setOperationAction(ISD::FMUL, MVT::f128, Legal); 848 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 849 // No extending loads to f128 on PPC. 850 for (MVT FPT : MVT::fp_valuetypes()) 851 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 852 setOperationAction(ISD::FMA, MVT::f128, Legal); 853 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 854 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 855 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 856 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 857 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 858 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 859 860 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 861 setOperationAction(ISD::FRINT, MVT::f128, Legal); 862 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 863 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 864 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 865 setOperationAction(ISD::FROUND, MVT::f128, Legal); 866 867 setOperationAction(ISD::SELECT, MVT::f128, Expand); 868 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 869 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 870 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 871 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 872 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 873 // No implementation for these ops for PowerPC. 874 setOperationAction(ISD::FSIN , MVT::f128, Expand); 875 setOperationAction(ISD::FCOS , MVT::f128, Expand); 876 setOperationAction(ISD::FPOW, MVT::f128, Expand); 877 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 878 setOperationAction(ISD::FREM, MVT::f128, Expand); 879 } 880 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 881 882 } 883 884 if (Subtarget.hasP9Altivec()) { 885 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 887 } 888 } 889 890 if (Subtarget.hasQPX()) { 891 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 892 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 893 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 894 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 895 896 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 897 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 898 899 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 900 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 901 902 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 903 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 904 905 if (!Subtarget.useCRBits()) 906 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 907 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 908 909 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 910 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 911 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 912 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 913 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 914 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 915 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 916 917 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 918 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 919 920 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 921 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 922 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 923 924 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 925 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 926 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 927 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 928 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 929 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 930 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 931 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 932 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 933 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 934 935 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 936 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 937 938 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 939 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 940 941 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 942 943 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 944 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 945 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 946 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 947 948 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 949 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 950 951 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 952 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 953 954 if (!Subtarget.useCRBits()) 955 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 956 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 957 958 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 959 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 960 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 961 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 962 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 963 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 964 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 965 966 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 967 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 968 969 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 970 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 971 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 972 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 973 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 974 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 975 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 976 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 977 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 978 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 979 980 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 981 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 982 983 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 984 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 985 986 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 987 988 setOperationAction(ISD::AND , MVT::v4i1, Legal); 989 setOperationAction(ISD::OR , MVT::v4i1, Legal); 990 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 991 992 if (!Subtarget.useCRBits()) 993 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 994 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 995 996 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 997 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 998 999 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1000 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1001 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1002 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1003 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1004 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1005 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1006 1007 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1008 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1009 1010 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1011 1012 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1013 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1014 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1015 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1016 1017 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1018 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1021 1022 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1023 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1024 1025 // These need to set FE_INEXACT, and so cannot be vectorized here. 1026 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1027 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1028 1029 if (TM.Options.UnsafeFPMath) { 1030 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1031 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1032 1033 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1034 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1035 } else { 1036 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1037 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1038 1039 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1040 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1041 } 1042 } 1043 1044 if (Subtarget.has64BitSupport()) 1045 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1046 1047 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1048 1049 if (!isPPC64) { 1050 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1051 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1052 } 1053 1054 setBooleanContents(ZeroOrOneBooleanContent); 1055 1056 if (Subtarget.hasAltivec()) { 1057 // Altivec instructions set fields to all zeros or all ones. 1058 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1059 } 1060 1061 if (!isPPC64) { 1062 // These libcalls are not available in 32-bit. 1063 setLibcallName(RTLIB::SHL_I128, nullptr); 1064 setLibcallName(RTLIB::SRL_I128, nullptr); 1065 setLibcallName(RTLIB::SRA_I128, nullptr); 1066 } 1067 1068 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1069 1070 // We have target-specific dag combine patterns for the following nodes: 1071 setTargetDAGCombine(ISD::ADD); 1072 setTargetDAGCombine(ISD::SHL); 1073 setTargetDAGCombine(ISD::SRA); 1074 setTargetDAGCombine(ISD::SRL); 1075 setTargetDAGCombine(ISD::MUL); 1076 setTargetDAGCombine(ISD::SINT_TO_FP); 1077 setTargetDAGCombine(ISD::BUILD_VECTOR); 1078 if (Subtarget.hasFPCVT()) 1079 setTargetDAGCombine(ISD::UINT_TO_FP); 1080 setTargetDAGCombine(ISD::LOAD); 1081 setTargetDAGCombine(ISD::STORE); 1082 setTargetDAGCombine(ISD::BR_CC); 1083 if (Subtarget.useCRBits()) 1084 setTargetDAGCombine(ISD::BRCOND); 1085 setTargetDAGCombine(ISD::BSWAP); 1086 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1087 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1088 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1089 1090 setTargetDAGCombine(ISD::SIGN_EXTEND); 1091 setTargetDAGCombine(ISD::ZERO_EXTEND); 1092 setTargetDAGCombine(ISD::ANY_EXTEND); 1093 1094 setTargetDAGCombine(ISD::TRUNCATE); 1095 1096 if (Subtarget.useCRBits()) { 1097 setTargetDAGCombine(ISD::TRUNCATE); 1098 setTargetDAGCombine(ISD::SETCC); 1099 setTargetDAGCombine(ISD::SELECT_CC); 1100 } 1101 1102 // Use reciprocal estimates. 1103 if (TM.Options.UnsafeFPMath) { 1104 setTargetDAGCombine(ISD::FDIV); 1105 setTargetDAGCombine(ISD::FSQRT); 1106 } 1107 1108 if (Subtarget.hasP9Altivec()) { 1109 setTargetDAGCombine(ISD::ABS); 1110 setTargetDAGCombine(ISD::VSELECT); 1111 } 1112 1113 // Darwin long double math library functions have $LDBL128 appended. 1114 if (Subtarget.isDarwin()) { 1115 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1116 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1117 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1118 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1119 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1120 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1121 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1122 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1123 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1124 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1125 } 1126 1127 if (EnableQuadPrecision) { 1128 setLibcallName(RTLIB::LOG_F128, "logf128"); 1129 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1130 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1131 setLibcallName(RTLIB::EXP_F128, "expf128"); 1132 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1133 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1134 setLibcallName(RTLIB::COS_F128, "cosf128"); 1135 setLibcallName(RTLIB::POW_F128, "powf128"); 1136 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1137 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1138 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1139 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1140 } 1141 1142 // With 32 condition bits, we don't need to sink (and duplicate) compares 1143 // aggressively in CodeGenPrep. 1144 if (Subtarget.useCRBits()) { 1145 setHasMultipleConditionRegisters(); 1146 setJumpIsExpensive(); 1147 } 1148 1149 setMinFunctionAlignment(2); 1150 if (Subtarget.isDarwin()) 1151 setPrefFunctionAlignment(4); 1152 1153 switch (Subtarget.getDarwinDirective()) { 1154 default: break; 1155 case PPC::DIR_970: 1156 case PPC::DIR_A2: 1157 case PPC::DIR_E500: 1158 case PPC::DIR_E500mc: 1159 case PPC::DIR_E5500: 1160 case PPC::DIR_PWR4: 1161 case PPC::DIR_PWR5: 1162 case PPC::DIR_PWR5X: 1163 case PPC::DIR_PWR6: 1164 case PPC::DIR_PWR6X: 1165 case PPC::DIR_PWR7: 1166 case PPC::DIR_PWR8: 1167 case PPC::DIR_PWR9: 1168 setPrefFunctionAlignment(4); 1169 setPrefLoopAlignment(4); 1170 break; 1171 } 1172 1173 if (Subtarget.enableMachineScheduler()) 1174 setSchedulingPreference(Sched::Source); 1175 else 1176 setSchedulingPreference(Sched::Hybrid); 1177 1178 computeRegisterProperties(STI.getRegisterInfo()); 1179 1180 // The Freescale cores do better with aggressive inlining of memcpy and 1181 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1182 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1183 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1184 MaxStoresPerMemset = 32; 1185 MaxStoresPerMemsetOptSize = 16; 1186 MaxStoresPerMemcpy = 32; 1187 MaxStoresPerMemcpyOptSize = 8; 1188 MaxStoresPerMemmove = 32; 1189 MaxStoresPerMemmoveOptSize = 8; 1190 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1191 // The A2 also benefits from (very) aggressive inlining of memcpy and 1192 // friends. The overhead of a the function call, even when warm, can be 1193 // over one hundred cycles. 1194 MaxStoresPerMemset = 128; 1195 MaxStoresPerMemcpy = 128; 1196 MaxStoresPerMemmove = 128; 1197 MaxLoadsPerMemcmp = 128; 1198 } else { 1199 MaxLoadsPerMemcmp = 8; 1200 MaxLoadsPerMemcmpOptSize = 4; 1201 } 1202 } 1203 1204 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1205 /// the desired ByVal argument alignment. 1206 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1207 unsigned MaxMaxAlign) { 1208 if (MaxAlign == MaxMaxAlign) 1209 return; 1210 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1211 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1212 MaxAlign = 32; 1213 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1214 MaxAlign = 16; 1215 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1216 unsigned EltAlign = 0; 1217 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1218 if (EltAlign > MaxAlign) 1219 MaxAlign = EltAlign; 1220 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1221 for (auto *EltTy : STy->elements()) { 1222 unsigned EltAlign = 0; 1223 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1224 if (EltAlign > MaxAlign) 1225 MaxAlign = EltAlign; 1226 if (MaxAlign == MaxMaxAlign) 1227 break; 1228 } 1229 } 1230 } 1231 1232 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1233 /// function arguments in the caller parameter area. 1234 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1235 const DataLayout &DL) const { 1236 // Darwin passes everything on 4 byte boundary. 1237 if (Subtarget.isDarwin()) 1238 return 4; 1239 1240 // 16byte and wider vectors are passed on 16byte boundary. 1241 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1242 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1243 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1244 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1245 return Align; 1246 } 1247 1248 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1249 CallingConv:: ID CC, 1250 EVT VT) const { 1251 if (Subtarget.hasSPE() && VT == MVT::f64) 1252 return 2; 1253 return PPCTargetLowering::getNumRegisters(Context, VT); 1254 } 1255 1256 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1257 CallingConv:: ID CC, 1258 EVT VT) const { 1259 if (Subtarget.hasSPE() && VT == MVT::f64) 1260 return MVT::i32; 1261 return PPCTargetLowering::getRegisterType(Context, VT); 1262 } 1263 1264 bool PPCTargetLowering::useSoftFloat() const { 1265 return Subtarget.useSoftFloat(); 1266 } 1267 1268 bool PPCTargetLowering::hasSPE() const { 1269 return Subtarget.hasSPE(); 1270 } 1271 1272 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1273 switch ((PPCISD::NodeType)Opcode) { 1274 case PPCISD::FIRST_NUMBER: break; 1275 case PPCISD::FSEL: return "PPCISD::FSEL"; 1276 case PPCISD::FCFID: return "PPCISD::FCFID"; 1277 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1278 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1279 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1280 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1281 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1282 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1283 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1284 case PPCISD::FP_TO_UINT_IN_VSR: 1285 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1286 case PPCISD::FP_TO_SINT_IN_VSR: 1287 return "PPCISD::FP_TO_SINT_IN_VSR"; 1288 case PPCISD::FRE: return "PPCISD::FRE"; 1289 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1290 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1291 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1292 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1293 case PPCISD::VPERM: return "PPCISD::VPERM"; 1294 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1295 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1296 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1297 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1298 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1299 case PPCISD::CMPB: return "PPCISD::CMPB"; 1300 case PPCISD::Hi: return "PPCISD::Hi"; 1301 case PPCISD::Lo: return "PPCISD::Lo"; 1302 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1303 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1304 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1305 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1306 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1307 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1308 case PPCISD::SRL: return "PPCISD::SRL"; 1309 case PPCISD::SRA: return "PPCISD::SRA"; 1310 case PPCISD::SHL: return "PPCISD::SHL"; 1311 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1312 case PPCISD::CALL: return "PPCISD::CALL"; 1313 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1314 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1315 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1316 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1317 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1318 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1319 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1320 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1321 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1322 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1323 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1324 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1325 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1326 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1327 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1328 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1329 case PPCISD::VCMP: return "PPCISD::VCMP"; 1330 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1331 case PPCISD::LBRX: return "PPCISD::LBRX"; 1332 case PPCISD::STBRX: return "PPCISD::STBRX"; 1333 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1334 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1335 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1336 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1337 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1338 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1339 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1340 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1341 case PPCISD::ST_VSR_SCAL_INT: 1342 return "PPCISD::ST_VSR_SCAL_INT"; 1343 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1344 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1345 case PPCISD::BDZ: return "PPCISD::BDZ"; 1346 case PPCISD::MFFS: return "PPCISD::MFFS"; 1347 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1348 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1349 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1350 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1351 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1352 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1353 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1354 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1355 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1356 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1357 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1358 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1359 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1360 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1361 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1362 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1363 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1364 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1365 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1366 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1367 case PPCISD::SC: return "PPCISD::SC"; 1368 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1369 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1370 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1371 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1372 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1373 case PPCISD::VABSD: return "PPCISD::VABSD"; 1374 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1375 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1376 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1377 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1378 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1379 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1380 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1381 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1382 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1383 case PPCISD::FP_EXTEND_LH: return "PPCISD::FP_EXTEND_LH"; 1384 } 1385 return nullptr; 1386 } 1387 1388 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1389 EVT VT) const { 1390 if (!VT.isVector()) 1391 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1392 1393 if (Subtarget.hasQPX()) 1394 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1395 1396 return VT.changeVectorElementTypeToInteger(); 1397 } 1398 1399 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1400 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1401 return true; 1402 } 1403 1404 //===----------------------------------------------------------------------===// 1405 // Node matching predicates, for use by the tblgen matching code. 1406 //===----------------------------------------------------------------------===// 1407 1408 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1409 static bool isFloatingPointZero(SDValue Op) { 1410 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1411 return CFP->getValueAPF().isZero(); 1412 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1413 // Maybe this has already been legalized into the constant pool? 1414 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1415 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1416 return CFP->getValueAPF().isZero(); 1417 } 1418 return false; 1419 } 1420 1421 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1422 /// true if Op is undef or if it matches the specified value. 1423 static bool isConstantOrUndef(int Op, int Val) { 1424 return Op < 0 || Op == Val; 1425 } 1426 1427 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1428 /// VPKUHUM instruction. 1429 /// The ShuffleKind distinguishes between big-endian operations with 1430 /// two different inputs (0), either-endian operations with two identical 1431 /// inputs (1), and little-endian operations with two different inputs (2). 1432 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1433 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1434 SelectionDAG &DAG) { 1435 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1436 if (ShuffleKind == 0) { 1437 if (IsLE) 1438 return false; 1439 for (unsigned i = 0; i != 16; ++i) 1440 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1441 return false; 1442 } else if (ShuffleKind == 2) { 1443 if (!IsLE) 1444 return false; 1445 for (unsigned i = 0; i != 16; ++i) 1446 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1447 return false; 1448 } else if (ShuffleKind == 1) { 1449 unsigned j = IsLE ? 0 : 1; 1450 for (unsigned i = 0; i != 8; ++i) 1451 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1452 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1453 return false; 1454 } 1455 return true; 1456 } 1457 1458 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1459 /// VPKUWUM instruction. 1460 /// The ShuffleKind distinguishes between big-endian operations with 1461 /// two different inputs (0), either-endian operations with two identical 1462 /// inputs (1), and little-endian operations with two different inputs (2). 1463 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1464 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1465 SelectionDAG &DAG) { 1466 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1467 if (ShuffleKind == 0) { 1468 if (IsLE) 1469 return false; 1470 for (unsigned i = 0; i != 16; i += 2) 1471 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1472 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1473 return false; 1474 } else if (ShuffleKind == 2) { 1475 if (!IsLE) 1476 return false; 1477 for (unsigned i = 0; i != 16; i += 2) 1478 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1479 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1480 return false; 1481 } else if (ShuffleKind == 1) { 1482 unsigned j = IsLE ? 0 : 2; 1483 for (unsigned i = 0; i != 8; i += 2) 1484 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1485 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1486 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1487 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1488 return false; 1489 } 1490 return true; 1491 } 1492 1493 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1494 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1495 /// current subtarget. 1496 /// 1497 /// The ShuffleKind distinguishes between big-endian operations with 1498 /// two different inputs (0), either-endian operations with two identical 1499 /// inputs (1), and little-endian operations with two different inputs (2). 1500 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1501 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1502 SelectionDAG &DAG) { 1503 const PPCSubtarget& Subtarget = 1504 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1505 if (!Subtarget.hasP8Vector()) 1506 return false; 1507 1508 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1509 if (ShuffleKind == 0) { 1510 if (IsLE) 1511 return false; 1512 for (unsigned i = 0; i != 16; i += 4) 1513 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1514 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1515 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1516 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1517 return false; 1518 } else if (ShuffleKind == 2) { 1519 if (!IsLE) 1520 return false; 1521 for (unsigned i = 0; i != 16; i += 4) 1522 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1523 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1524 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1525 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1526 return false; 1527 } else if (ShuffleKind == 1) { 1528 unsigned j = IsLE ? 0 : 4; 1529 for (unsigned i = 0; i != 8; i += 4) 1530 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1531 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1532 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1533 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1534 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1535 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1536 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1537 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1538 return false; 1539 } 1540 return true; 1541 } 1542 1543 /// isVMerge - Common function, used to match vmrg* shuffles. 1544 /// 1545 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1546 unsigned LHSStart, unsigned RHSStart) { 1547 if (N->getValueType(0) != MVT::v16i8) 1548 return false; 1549 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1550 "Unsupported merge size!"); 1551 1552 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1553 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1554 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1555 LHSStart+j+i*UnitSize) || 1556 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1557 RHSStart+j+i*UnitSize)) 1558 return false; 1559 } 1560 return true; 1561 } 1562 1563 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1564 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1565 /// The ShuffleKind distinguishes between big-endian merges with two 1566 /// different inputs (0), either-endian merges with two identical inputs (1), 1567 /// and little-endian merges with two different inputs (2). For the latter, 1568 /// the input operands are swapped (see PPCInstrAltivec.td). 1569 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1570 unsigned ShuffleKind, SelectionDAG &DAG) { 1571 if (DAG.getDataLayout().isLittleEndian()) { 1572 if (ShuffleKind == 1) // unary 1573 return isVMerge(N, UnitSize, 0, 0); 1574 else if (ShuffleKind == 2) // swapped 1575 return isVMerge(N, UnitSize, 0, 16); 1576 else 1577 return false; 1578 } else { 1579 if (ShuffleKind == 1) // unary 1580 return isVMerge(N, UnitSize, 8, 8); 1581 else if (ShuffleKind == 0) // normal 1582 return isVMerge(N, UnitSize, 8, 24); 1583 else 1584 return false; 1585 } 1586 } 1587 1588 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1589 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1590 /// The ShuffleKind distinguishes between big-endian merges with two 1591 /// different inputs (0), either-endian merges with two identical inputs (1), 1592 /// and little-endian merges with two different inputs (2). For the latter, 1593 /// the input operands are swapped (see PPCInstrAltivec.td). 1594 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1595 unsigned ShuffleKind, SelectionDAG &DAG) { 1596 if (DAG.getDataLayout().isLittleEndian()) { 1597 if (ShuffleKind == 1) // unary 1598 return isVMerge(N, UnitSize, 8, 8); 1599 else if (ShuffleKind == 2) // swapped 1600 return isVMerge(N, UnitSize, 8, 24); 1601 else 1602 return false; 1603 } else { 1604 if (ShuffleKind == 1) // unary 1605 return isVMerge(N, UnitSize, 0, 0); 1606 else if (ShuffleKind == 0) // normal 1607 return isVMerge(N, UnitSize, 0, 16); 1608 else 1609 return false; 1610 } 1611 } 1612 1613 /** 1614 * Common function used to match vmrgew and vmrgow shuffles 1615 * 1616 * The indexOffset determines whether to look for even or odd words in 1617 * the shuffle mask. This is based on the of the endianness of the target 1618 * machine. 1619 * - Little Endian: 1620 * - Use offset of 0 to check for odd elements 1621 * - Use offset of 4 to check for even elements 1622 * - Big Endian: 1623 * - Use offset of 0 to check for even elements 1624 * - Use offset of 4 to check for odd elements 1625 * A detailed description of the vector element ordering for little endian and 1626 * big endian can be found at 1627 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1628 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1629 * compiler differences mean to you 1630 * 1631 * The mask to the shuffle vector instruction specifies the indices of the 1632 * elements from the two input vectors to place in the result. The elements are 1633 * numbered in array-access order, starting with the first vector. These vectors 1634 * are always of type v16i8, thus each vector will contain 16 elements of size 1635 * 8. More info on the shuffle vector can be found in the 1636 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1637 * Language Reference. 1638 * 1639 * The RHSStartValue indicates whether the same input vectors are used (unary) 1640 * or two different input vectors are used, based on the following: 1641 * - If the instruction uses the same vector for both inputs, the range of the 1642 * indices will be 0 to 15. In this case, the RHSStart value passed should 1643 * be 0. 1644 * - If the instruction has two different vectors then the range of the 1645 * indices will be 0 to 31. In this case, the RHSStart value passed should 1646 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1647 * to 31 specify elements in the second vector). 1648 * 1649 * \param[in] N The shuffle vector SD Node to analyze 1650 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1651 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1652 * vector to the shuffle_vector instruction 1653 * \return true iff this shuffle vector represents an even or odd word merge 1654 */ 1655 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1656 unsigned RHSStartValue) { 1657 if (N->getValueType(0) != MVT::v16i8) 1658 return false; 1659 1660 for (unsigned i = 0; i < 2; ++i) 1661 for (unsigned j = 0; j < 4; ++j) 1662 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1663 i*RHSStartValue+j+IndexOffset) || 1664 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1665 i*RHSStartValue+j+IndexOffset+8)) 1666 return false; 1667 return true; 1668 } 1669 1670 /** 1671 * Determine if the specified shuffle mask is suitable for the vmrgew or 1672 * vmrgow instructions. 1673 * 1674 * \param[in] N The shuffle vector SD Node to analyze 1675 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1676 * \param[in] ShuffleKind Identify the type of merge: 1677 * - 0 = big-endian merge with two different inputs; 1678 * - 1 = either-endian merge with two identical inputs; 1679 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1680 * little-endian merges). 1681 * \param[in] DAG The current SelectionDAG 1682 * \return true iff this shuffle mask 1683 */ 1684 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1685 unsigned ShuffleKind, SelectionDAG &DAG) { 1686 if (DAG.getDataLayout().isLittleEndian()) { 1687 unsigned indexOffset = CheckEven ? 4 : 0; 1688 if (ShuffleKind == 1) // Unary 1689 return isVMerge(N, indexOffset, 0); 1690 else if (ShuffleKind == 2) // swapped 1691 return isVMerge(N, indexOffset, 16); 1692 else 1693 return false; 1694 } 1695 else { 1696 unsigned indexOffset = CheckEven ? 0 : 4; 1697 if (ShuffleKind == 1) // Unary 1698 return isVMerge(N, indexOffset, 0); 1699 else if (ShuffleKind == 0) // Normal 1700 return isVMerge(N, indexOffset, 16); 1701 else 1702 return false; 1703 } 1704 return false; 1705 } 1706 1707 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1708 /// amount, otherwise return -1. 1709 /// The ShuffleKind distinguishes between big-endian operations with two 1710 /// different inputs (0), either-endian operations with two identical inputs 1711 /// (1), and little-endian operations with two different inputs (2). For the 1712 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1713 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1714 SelectionDAG &DAG) { 1715 if (N->getValueType(0) != MVT::v16i8) 1716 return -1; 1717 1718 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1719 1720 // Find the first non-undef value in the shuffle mask. 1721 unsigned i; 1722 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1723 /*search*/; 1724 1725 if (i == 16) return -1; // all undef. 1726 1727 // Otherwise, check to see if the rest of the elements are consecutively 1728 // numbered from this value. 1729 unsigned ShiftAmt = SVOp->getMaskElt(i); 1730 if (ShiftAmt < i) return -1; 1731 1732 ShiftAmt -= i; 1733 bool isLE = DAG.getDataLayout().isLittleEndian(); 1734 1735 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1736 // Check the rest of the elements to see if they are consecutive. 1737 for (++i; i != 16; ++i) 1738 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1739 return -1; 1740 } else if (ShuffleKind == 1) { 1741 // Check the rest of the elements to see if they are consecutive. 1742 for (++i; i != 16; ++i) 1743 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1744 return -1; 1745 } else 1746 return -1; 1747 1748 if (isLE) 1749 ShiftAmt = 16 - ShiftAmt; 1750 1751 return ShiftAmt; 1752 } 1753 1754 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1755 /// specifies a splat of a single element that is suitable for input to 1756 /// VSPLTB/VSPLTH/VSPLTW. 1757 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1758 assert(N->getValueType(0) == MVT::v16i8 && 1759 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1760 1761 // The consecutive indices need to specify an element, not part of two 1762 // different elements. So abandon ship early if this isn't the case. 1763 if (N->getMaskElt(0) % EltSize != 0) 1764 return false; 1765 1766 // This is a splat operation if each element of the permute is the same, and 1767 // if the value doesn't reference the second vector. 1768 unsigned ElementBase = N->getMaskElt(0); 1769 1770 // FIXME: Handle UNDEF elements too! 1771 if (ElementBase >= 16) 1772 return false; 1773 1774 // Check that the indices are consecutive, in the case of a multi-byte element 1775 // splatted with a v16i8 mask. 1776 for (unsigned i = 1; i != EltSize; ++i) 1777 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1778 return false; 1779 1780 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1781 if (N->getMaskElt(i) < 0) continue; 1782 for (unsigned j = 0; j != EltSize; ++j) 1783 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1784 return false; 1785 } 1786 return true; 1787 } 1788 1789 /// Check that the mask is shuffling N byte elements. Within each N byte 1790 /// element of the mask, the indices could be either in increasing or 1791 /// decreasing order as long as they are consecutive. 1792 /// \param[in] N the shuffle vector SD Node to analyze 1793 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1794 /// Word/DoubleWord/QuadWord). 1795 /// \param[in] StepLen the delta indices number among the N byte element, if 1796 /// the mask is in increasing/decreasing order then it is 1/-1. 1797 /// \return true iff the mask is shuffling N byte elements. 1798 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1799 int StepLen) { 1800 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1801 "Unexpected element width."); 1802 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1803 1804 unsigned NumOfElem = 16 / Width; 1805 unsigned MaskVal[16]; // Width is never greater than 16 1806 for (unsigned i = 0; i < NumOfElem; ++i) { 1807 MaskVal[0] = N->getMaskElt(i * Width); 1808 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1809 return false; 1810 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1811 return false; 1812 } 1813 1814 for (unsigned int j = 1; j < Width; ++j) { 1815 MaskVal[j] = N->getMaskElt(i * Width + j); 1816 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1817 return false; 1818 } 1819 } 1820 } 1821 1822 return true; 1823 } 1824 1825 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1826 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1827 if (!isNByteElemShuffleMask(N, 4, 1)) 1828 return false; 1829 1830 // Now we look at mask elements 0,4,8,12 1831 unsigned M0 = N->getMaskElt(0) / 4; 1832 unsigned M1 = N->getMaskElt(4) / 4; 1833 unsigned M2 = N->getMaskElt(8) / 4; 1834 unsigned M3 = N->getMaskElt(12) / 4; 1835 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1836 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1837 1838 // Below, let H and L be arbitrary elements of the shuffle mask 1839 // where H is in the range [4,7] and L is in the range [0,3]. 1840 // H, 1, 2, 3 or L, 5, 6, 7 1841 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1842 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1843 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1844 InsertAtByte = IsLE ? 12 : 0; 1845 Swap = M0 < 4; 1846 return true; 1847 } 1848 // 0, H, 2, 3 or 4, L, 6, 7 1849 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1850 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1851 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1852 InsertAtByte = IsLE ? 8 : 4; 1853 Swap = M1 < 4; 1854 return true; 1855 } 1856 // 0, 1, H, 3 or 4, 5, L, 7 1857 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1858 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1859 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1860 InsertAtByte = IsLE ? 4 : 8; 1861 Swap = M2 < 4; 1862 return true; 1863 } 1864 // 0, 1, 2, H or 4, 5, 6, L 1865 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1866 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1867 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1868 InsertAtByte = IsLE ? 0 : 12; 1869 Swap = M3 < 4; 1870 return true; 1871 } 1872 1873 // If both vector operands for the shuffle are the same vector, the mask will 1874 // contain only elements from the first one and the second one will be undef. 1875 if (N->getOperand(1).isUndef()) { 1876 ShiftElts = 0; 1877 Swap = true; 1878 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1879 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1880 InsertAtByte = IsLE ? 12 : 0; 1881 return true; 1882 } 1883 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1884 InsertAtByte = IsLE ? 8 : 4; 1885 return true; 1886 } 1887 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1888 InsertAtByte = IsLE ? 4 : 8; 1889 return true; 1890 } 1891 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1892 InsertAtByte = IsLE ? 0 : 12; 1893 return true; 1894 } 1895 } 1896 1897 return false; 1898 } 1899 1900 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1901 bool &Swap, bool IsLE) { 1902 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1903 // Ensure each byte index of the word is consecutive. 1904 if (!isNByteElemShuffleMask(N, 4, 1)) 1905 return false; 1906 1907 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1908 unsigned M0 = N->getMaskElt(0) / 4; 1909 unsigned M1 = N->getMaskElt(4) / 4; 1910 unsigned M2 = N->getMaskElt(8) / 4; 1911 unsigned M3 = N->getMaskElt(12) / 4; 1912 1913 // If both vector operands for the shuffle are the same vector, the mask will 1914 // contain only elements from the first one and the second one will be undef. 1915 if (N->getOperand(1).isUndef()) { 1916 assert(M0 < 4 && "Indexing into an undef vector?"); 1917 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1918 return false; 1919 1920 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1921 Swap = false; 1922 return true; 1923 } 1924 1925 // Ensure each word index of the ShuffleVector Mask is consecutive. 1926 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1927 return false; 1928 1929 if (IsLE) { 1930 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1931 // Input vectors don't need to be swapped if the leading element 1932 // of the result is one of the 3 left elements of the second vector 1933 // (or if there is no shift to be done at all). 1934 Swap = false; 1935 ShiftElts = (8 - M0) % 8; 1936 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1937 // Input vectors need to be swapped if the leading element 1938 // of the result is one of the 3 left elements of the first vector 1939 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1940 Swap = true; 1941 ShiftElts = (4 - M0) % 4; 1942 } 1943 1944 return true; 1945 } else { // BE 1946 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1947 // Input vectors don't need to be swapped if the leading element 1948 // of the result is one of the 4 elements of the first vector. 1949 Swap = false; 1950 ShiftElts = M0; 1951 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1952 // Input vectors need to be swapped if the leading element 1953 // of the result is one of the 4 elements of the right vector. 1954 Swap = true; 1955 ShiftElts = M0 - 4; 1956 } 1957 1958 return true; 1959 } 1960 } 1961 1962 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1963 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1964 1965 if (!isNByteElemShuffleMask(N, Width, -1)) 1966 return false; 1967 1968 for (int i = 0; i < 16; i += Width) 1969 if (N->getMaskElt(i) != i + Width - 1) 1970 return false; 1971 1972 return true; 1973 } 1974 1975 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1976 return isXXBRShuffleMaskHelper(N, 2); 1977 } 1978 1979 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1980 return isXXBRShuffleMaskHelper(N, 4); 1981 } 1982 1983 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1984 return isXXBRShuffleMaskHelper(N, 8); 1985 } 1986 1987 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1988 return isXXBRShuffleMaskHelper(N, 16); 1989 } 1990 1991 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1992 /// if the inputs to the instruction should be swapped and set \p DM to the 1993 /// value for the immediate. 1994 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1995 /// AND element 0 of the result comes from the first input (LE) or second input 1996 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1997 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1998 /// mask. 1999 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2000 bool &Swap, bool IsLE) { 2001 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2002 2003 // Ensure each byte index of the double word is consecutive. 2004 if (!isNByteElemShuffleMask(N, 8, 1)) 2005 return false; 2006 2007 unsigned M0 = N->getMaskElt(0) / 8; 2008 unsigned M1 = N->getMaskElt(8) / 8; 2009 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2010 2011 // If both vector operands for the shuffle are the same vector, the mask will 2012 // contain only elements from the first one and the second one will be undef. 2013 if (N->getOperand(1).isUndef()) { 2014 if ((M0 | M1) < 2) { 2015 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2016 Swap = false; 2017 return true; 2018 } else 2019 return false; 2020 } 2021 2022 if (IsLE) { 2023 if (M0 > 1 && M1 < 2) { 2024 Swap = false; 2025 } else if (M0 < 2 && M1 > 1) { 2026 M0 = (M0 + 2) % 4; 2027 M1 = (M1 + 2) % 4; 2028 Swap = true; 2029 } else 2030 return false; 2031 2032 // Note: if control flow comes here that means Swap is already set above 2033 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2034 return true; 2035 } else { // BE 2036 if (M0 < 2 && M1 > 1) { 2037 Swap = false; 2038 } else if (M0 > 1 && M1 < 2) { 2039 M0 = (M0 + 2) % 4; 2040 M1 = (M1 + 2) % 4; 2041 Swap = true; 2042 } else 2043 return false; 2044 2045 // Note: if control flow comes here that means Swap is already set above 2046 DM = (M0 << 1) + (M1 & 1); 2047 return true; 2048 } 2049 } 2050 2051 2052 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2053 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2054 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2055 SelectionDAG &DAG) { 2056 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2057 assert(isSplatShuffleMask(SVOp, EltSize)); 2058 if (DAG.getDataLayout().isLittleEndian()) 2059 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2060 else 2061 return SVOp->getMaskElt(0) / EltSize; 2062 } 2063 2064 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2065 /// by using a vspltis[bhw] instruction of the specified element size, return 2066 /// the constant being splatted. The ByteSize field indicates the number of 2067 /// bytes of each element [124] -> [bhw]. 2068 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2069 SDValue OpVal(nullptr, 0); 2070 2071 // If ByteSize of the splat is bigger than the element size of the 2072 // build_vector, then we have a case where we are checking for a splat where 2073 // multiple elements of the buildvector are folded together into a single 2074 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2075 unsigned EltSize = 16/N->getNumOperands(); 2076 if (EltSize < ByteSize) { 2077 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2078 SDValue UniquedVals[4]; 2079 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2080 2081 // See if all of the elements in the buildvector agree across. 2082 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2083 if (N->getOperand(i).isUndef()) continue; 2084 // If the element isn't a constant, bail fully out. 2085 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2086 2087 if (!UniquedVals[i&(Multiple-1)].getNode()) 2088 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2089 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2090 return SDValue(); // no match. 2091 } 2092 2093 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2094 // either constant or undef values that are identical for each chunk. See 2095 // if these chunks can form into a larger vspltis*. 2096 2097 // Check to see if all of the leading entries are either 0 or -1. If 2098 // neither, then this won't fit into the immediate field. 2099 bool LeadingZero = true; 2100 bool LeadingOnes = true; 2101 for (unsigned i = 0; i != Multiple-1; ++i) { 2102 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2103 2104 LeadingZero &= isNullConstant(UniquedVals[i]); 2105 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2106 } 2107 // Finally, check the least significant entry. 2108 if (LeadingZero) { 2109 if (!UniquedVals[Multiple-1].getNode()) 2110 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2111 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2112 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2113 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2114 } 2115 if (LeadingOnes) { 2116 if (!UniquedVals[Multiple-1].getNode()) 2117 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2118 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2119 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2120 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2121 } 2122 2123 return SDValue(); 2124 } 2125 2126 // Check to see if this buildvec has a single non-undef value in its elements. 2127 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2128 if (N->getOperand(i).isUndef()) continue; 2129 if (!OpVal.getNode()) 2130 OpVal = N->getOperand(i); 2131 else if (OpVal != N->getOperand(i)) 2132 return SDValue(); 2133 } 2134 2135 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2136 2137 unsigned ValSizeInBytes = EltSize; 2138 uint64_t Value = 0; 2139 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2140 Value = CN->getZExtValue(); 2141 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2142 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2143 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2144 } 2145 2146 // If the splat value is larger than the element value, then we can never do 2147 // this splat. The only case that we could fit the replicated bits into our 2148 // immediate field for would be zero, and we prefer to use vxor for it. 2149 if (ValSizeInBytes < ByteSize) return SDValue(); 2150 2151 // If the element value is larger than the splat value, check if it consists 2152 // of a repeated bit pattern of size ByteSize. 2153 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2154 return SDValue(); 2155 2156 // Properly sign extend the value. 2157 int MaskVal = SignExtend32(Value, ByteSize * 8); 2158 2159 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2160 if (MaskVal == 0) return SDValue(); 2161 2162 // Finally, if this value fits in a 5 bit sext field, return it 2163 if (SignExtend32<5>(MaskVal) == MaskVal) 2164 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2165 return SDValue(); 2166 } 2167 2168 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2169 /// amount, otherwise return -1. 2170 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2171 EVT VT = N->getValueType(0); 2172 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2173 return -1; 2174 2175 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2176 2177 // Find the first non-undef value in the shuffle mask. 2178 unsigned i; 2179 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2180 /*search*/; 2181 2182 if (i == 4) return -1; // all undef. 2183 2184 // Otherwise, check to see if the rest of the elements are consecutively 2185 // numbered from this value. 2186 unsigned ShiftAmt = SVOp->getMaskElt(i); 2187 if (ShiftAmt < i) return -1; 2188 ShiftAmt -= i; 2189 2190 // Check the rest of the elements to see if they are consecutive. 2191 for (++i; i != 4; ++i) 2192 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2193 return -1; 2194 2195 return ShiftAmt; 2196 } 2197 2198 //===----------------------------------------------------------------------===// 2199 // Addressing Mode Selection 2200 //===----------------------------------------------------------------------===// 2201 2202 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2203 /// or 64-bit immediate, and if the value can be accurately represented as a 2204 /// sign extension from a 16-bit value. If so, this returns true and the 2205 /// immediate. 2206 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2207 if (!isa<ConstantSDNode>(N)) 2208 return false; 2209 2210 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2211 if (N->getValueType(0) == MVT::i32) 2212 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2213 else 2214 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2215 } 2216 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2217 return isIntS16Immediate(Op.getNode(), Imm); 2218 } 2219 2220 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2221 /// can be represented as an indexed [r+r] operation. Returns false if it 2222 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2223 /// non-zero and N can be represented by a base register plus a signed 16-bit 2224 /// displacement, make a more precise judgement by checking (displacement % \p 2225 /// EncodingAlignment). 2226 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2227 SDValue &Index, SelectionDAG &DAG, 2228 unsigned EncodingAlignment) const { 2229 int16_t imm = 0; 2230 if (N.getOpcode() == ISD::ADD) { 2231 if (isIntS16Immediate(N.getOperand(1), imm) && 2232 (!EncodingAlignment || !(imm % EncodingAlignment))) 2233 return false; // r+i 2234 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2235 return false; // r+i 2236 2237 Base = N.getOperand(0); 2238 Index = N.getOperand(1); 2239 return true; 2240 } else if (N.getOpcode() == ISD::OR) { 2241 if (isIntS16Immediate(N.getOperand(1), imm) && 2242 (!EncodingAlignment || !(imm % EncodingAlignment))) 2243 return false; // r+i can fold it if we can. 2244 2245 // If this is an or of disjoint bitfields, we can codegen this as an add 2246 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2247 // disjoint. 2248 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2249 2250 if (LHSKnown.Zero.getBoolValue()) { 2251 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2252 // If all of the bits are known zero on the LHS or RHS, the add won't 2253 // carry. 2254 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2255 Base = N.getOperand(0); 2256 Index = N.getOperand(1); 2257 return true; 2258 } 2259 } 2260 } 2261 2262 return false; 2263 } 2264 2265 // If we happen to be doing an i64 load or store into a stack slot that has 2266 // less than a 4-byte alignment, then the frame-index elimination may need to 2267 // use an indexed load or store instruction (because the offset may not be a 2268 // multiple of 4). The extra register needed to hold the offset comes from the 2269 // register scavenger, and it is possible that the scavenger will need to use 2270 // an emergency spill slot. As a result, we need to make sure that a spill slot 2271 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2272 // stack slot. 2273 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2274 // FIXME: This does not handle the LWA case. 2275 if (VT != MVT::i64) 2276 return; 2277 2278 // NOTE: We'll exclude negative FIs here, which come from argument 2279 // lowering, because there are no known test cases triggering this problem 2280 // using packed structures (or similar). We can remove this exclusion if 2281 // we find such a test case. The reason why this is so test-case driven is 2282 // because this entire 'fixup' is only to prevent crashes (from the 2283 // register scavenger) on not-really-valid inputs. For example, if we have: 2284 // %a = alloca i1 2285 // %b = bitcast i1* %a to i64* 2286 // store i64* a, i64 b 2287 // then the store should really be marked as 'align 1', but is not. If it 2288 // were marked as 'align 1' then the indexed form would have been 2289 // instruction-selected initially, and the problem this 'fixup' is preventing 2290 // won't happen regardless. 2291 if (FrameIdx < 0) 2292 return; 2293 2294 MachineFunction &MF = DAG.getMachineFunction(); 2295 MachineFrameInfo &MFI = MF.getFrameInfo(); 2296 2297 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2298 if (Align >= 4) 2299 return; 2300 2301 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2302 FuncInfo->setHasNonRISpills(); 2303 } 2304 2305 /// Returns true if the address N can be represented by a base register plus 2306 /// a signed 16-bit displacement [r+imm], and if it is not better 2307 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2308 /// displacements that are multiples of that value. 2309 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2310 SDValue &Base, 2311 SelectionDAG &DAG, 2312 unsigned EncodingAlignment) const { 2313 // FIXME dl should come from parent load or store, not from address 2314 SDLoc dl(N); 2315 // If this can be more profitably realized as r+r, fail. 2316 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2317 return false; 2318 2319 if (N.getOpcode() == ISD::ADD) { 2320 int16_t imm = 0; 2321 if (isIntS16Immediate(N.getOperand(1), imm) && 2322 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2323 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2324 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2325 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2326 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2327 } else { 2328 Base = N.getOperand(0); 2329 } 2330 return true; // [r+i] 2331 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2332 // Match LOAD (ADD (X, Lo(G))). 2333 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2334 && "Cannot handle constant offsets yet!"); 2335 Disp = N.getOperand(1).getOperand(0); // The global address. 2336 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2337 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2338 Disp.getOpcode() == ISD::TargetConstantPool || 2339 Disp.getOpcode() == ISD::TargetJumpTable); 2340 Base = N.getOperand(0); 2341 return true; // [&g+r] 2342 } 2343 } else if (N.getOpcode() == ISD::OR) { 2344 int16_t imm = 0; 2345 if (isIntS16Immediate(N.getOperand(1), imm) && 2346 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2347 // If this is an or of disjoint bitfields, we can codegen this as an add 2348 // (for better address arithmetic) if the LHS and RHS of the OR are 2349 // provably disjoint. 2350 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2351 2352 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2353 // If all of the bits are known zero on the LHS or RHS, the add won't 2354 // carry. 2355 if (FrameIndexSDNode *FI = 2356 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2357 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2358 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2359 } else { 2360 Base = N.getOperand(0); 2361 } 2362 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2363 return true; 2364 } 2365 } 2366 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2367 // Loading from a constant address. 2368 2369 // If this address fits entirely in a 16-bit sext immediate field, codegen 2370 // this as "d, 0" 2371 int16_t Imm; 2372 if (isIntS16Immediate(CN, Imm) && 2373 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2374 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2375 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2376 CN->getValueType(0)); 2377 return true; 2378 } 2379 2380 // Handle 32-bit sext immediates with LIS + addr mode. 2381 if ((CN->getValueType(0) == MVT::i32 || 2382 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2383 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2384 int Addr = (int)CN->getZExtValue(); 2385 2386 // Otherwise, break this down into an LIS + disp. 2387 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2388 2389 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2390 MVT::i32); 2391 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2392 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2393 return true; 2394 } 2395 } 2396 2397 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2398 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2399 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2400 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2401 } else 2402 Base = N; 2403 return true; // [r+0] 2404 } 2405 2406 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2407 /// represented as an indexed [r+r] operation. 2408 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2409 SDValue &Index, 2410 SelectionDAG &DAG) const { 2411 // Check to see if we can easily represent this as an [r+r] address. This 2412 // will fail if it thinks that the address is more profitably represented as 2413 // reg+imm, e.g. where imm = 0. 2414 if (SelectAddressRegReg(N, Base, Index, DAG)) 2415 return true; 2416 2417 // If the address is the result of an add, we will utilize the fact that the 2418 // address calculation includes an implicit add. However, we can reduce 2419 // register pressure if we do not materialize a constant just for use as the 2420 // index register. We only get rid of the add if it is not an add of a 2421 // value and a 16-bit signed constant and both have a single use. 2422 int16_t imm = 0; 2423 if (N.getOpcode() == ISD::ADD && 2424 (!isIntS16Immediate(N.getOperand(1), imm) || 2425 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2426 Base = N.getOperand(0); 2427 Index = N.getOperand(1); 2428 return true; 2429 } 2430 2431 // Otherwise, do it the hard way, using R0 as the base register. 2432 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2433 N.getValueType()); 2434 Index = N; 2435 return true; 2436 } 2437 2438 /// Returns true if we should use a direct load into vector instruction 2439 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2440 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2441 2442 // If there are any other uses other than scalar to vector, then we should 2443 // keep it as a scalar load -> direct move pattern to prevent multiple 2444 // loads. 2445 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2446 if (!LD) 2447 return false; 2448 2449 EVT MemVT = LD->getMemoryVT(); 2450 if (!MemVT.isSimple()) 2451 return false; 2452 switch(MemVT.getSimpleVT().SimpleTy) { 2453 case MVT::i64: 2454 break; 2455 case MVT::i32: 2456 if (!ST.hasP8Vector()) 2457 return false; 2458 break; 2459 case MVT::i16: 2460 case MVT::i8: 2461 if (!ST.hasP9Vector()) 2462 return false; 2463 break; 2464 default: 2465 return false; 2466 } 2467 2468 SDValue LoadedVal(N, 0); 2469 if (!LoadedVal.hasOneUse()) 2470 return false; 2471 2472 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2473 UI != UE; ++UI) 2474 if (UI.getUse().get().getResNo() == 0 && 2475 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2476 return false; 2477 2478 return true; 2479 } 2480 2481 /// getPreIndexedAddressParts - returns true by value, base pointer and 2482 /// offset pointer and addressing mode by reference if the node's address 2483 /// can be legally represented as pre-indexed load / store address. 2484 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2485 SDValue &Offset, 2486 ISD::MemIndexedMode &AM, 2487 SelectionDAG &DAG) const { 2488 if (DisablePPCPreinc) return false; 2489 2490 bool isLoad = true; 2491 SDValue Ptr; 2492 EVT VT; 2493 unsigned Alignment; 2494 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2495 Ptr = LD->getBasePtr(); 2496 VT = LD->getMemoryVT(); 2497 Alignment = LD->getAlignment(); 2498 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2499 Ptr = ST->getBasePtr(); 2500 VT = ST->getMemoryVT(); 2501 Alignment = ST->getAlignment(); 2502 isLoad = false; 2503 } else 2504 return false; 2505 2506 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2507 // instructions because we can fold these into a more efficient instruction 2508 // instead, (such as LXSD). 2509 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2510 return false; 2511 } 2512 2513 // PowerPC doesn't have preinc load/store instructions for vectors (except 2514 // for QPX, which does have preinc r+r forms). 2515 if (VT.isVector()) { 2516 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2517 return false; 2518 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2519 AM = ISD::PRE_INC; 2520 return true; 2521 } 2522 } 2523 2524 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2525 // Common code will reject creating a pre-inc form if the base pointer 2526 // is a frame index, or if N is a store and the base pointer is either 2527 // the same as or a predecessor of the value being stored. Check for 2528 // those situations here, and try with swapped Base/Offset instead. 2529 bool Swap = false; 2530 2531 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2532 Swap = true; 2533 else if (!isLoad) { 2534 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2535 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2536 Swap = true; 2537 } 2538 2539 if (Swap) 2540 std::swap(Base, Offset); 2541 2542 AM = ISD::PRE_INC; 2543 return true; 2544 } 2545 2546 // LDU/STU can only handle immediates that are a multiple of 4. 2547 if (VT != MVT::i64) { 2548 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2549 return false; 2550 } else { 2551 // LDU/STU need an address with at least 4-byte alignment. 2552 if (Alignment < 4) 2553 return false; 2554 2555 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2556 return false; 2557 } 2558 2559 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2560 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2561 // sext i32 to i64 when addr mode is r+i. 2562 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2563 LD->getExtensionType() == ISD::SEXTLOAD && 2564 isa<ConstantSDNode>(Offset)) 2565 return false; 2566 } 2567 2568 AM = ISD::PRE_INC; 2569 return true; 2570 } 2571 2572 //===----------------------------------------------------------------------===// 2573 // LowerOperation implementation 2574 //===----------------------------------------------------------------------===// 2575 2576 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2577 /// and LoOpFlags to the target MO flags. 2578 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2579 unsigned &HiOpFlags, unsigned &LoOpFlags, 2580 const GlobalValue *GV = nullptr) { 2581 HiOpFlags = PPCII::MO_HA; 2582 LoOpFlags = PPCII::MO_LO; 2583 2584 // Don't use the pic base if not in PIC relocation model. 2585 if (IsPIC) { 2586 HiOpFlags |= PPCII::MO_PIC_FLAG; 2587 LoOpFlags |= PPCII::MO_PIC_FLAG; 2588 } 2589 2590 // If this is a reference to a global value that requires a non-lazy-ptr, make 2591 // sure that instruction lowering adds it. 2592 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2593 HiOpFlags |= PPCII::MO_NLP_FLAG; 2594 LoOpFlags |= PPCII::MO_NLP_FLAG; 2595 2596 if (GV->hasHiddenVisibility()) { 2597 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2598 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2599 } 2600 } 2601 } 2602 2603 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2604 SelectionDAG &DAG) { 2605 SDLoc DL(HiPart); 2606 EVT PtrVT = HiPart.getValueType(); 2607 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2608 2609 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2610 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2611 2612 // With PIC, the first instruction is actually "GR+hi(&G)". 2613 if (isPIC) 2614 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2615 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2616 2617 // Generate non-pic code that has direct accesses to the constant pool. 2618 // The address of the global is just (hi(&g)+lo(&g)). 2619 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2620 } 2621 2622 static void setUsesTOCBasePtr(MachineFunction &MF) { 2623 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2624 FuncInfo->setUsesTOCBasePtr(); 2625 } 2626 2627 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2628 setUsesTOCBasePtr(DAG.getMachineFunction()); 2629 } 2630 2631 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2632 SDValue GA) { 2633 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2634 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2635 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2636 2637 SDValue Ops[] = { GA, Reg }; 2638 return DAG.getMemIntrinsicNode( 2639 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2640 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2641 MachineMemOperand::MOLoad); 2642 } 2643 2644 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2645 SelectionDAG &DAG) const { 2646 EVT PtrVT = Op.getValueType(); 2647 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2648 const Constant *C = CP->getConstVal(); 2649 2650 // 64-bit SVR4 ABI code is always position-independent. 2651 // The actual address of the GlobalValue is stored in the TOC. 2652 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2653 setUsesTOCBasePtr(DAG); 2654 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2655 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2656 } 2657 2658 unsigned MOHiFlag, MOLoFlag; 2659 bool IsPIC = isPositionIndependent(); 2660 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2661 2662 if (IsPIC && Subtarget.isSVR4ABI()) { 2663 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2664 PPCII::MO_PIC_FLAG); 2665 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2666 } 2667 2668 SDValue CPIHi = 2669 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2670 SDValue CPILo = 2671 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2672 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2673 } 2674 2675 // For 64-bit PowerPC, prefer the more compact relative encodings. 2676 // This trades 32 bits per jump table entry for one or two instructions 2677 // on the jump site. 2678 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2679 if (isJumpTableRelative()) 2680 return MachineJumpTableInfo::EK_LabelDifference32; 2681 2682 return TargetLowering::getJumpTableEncoding(); 2683 } 2684 2685 bool PPCTargetLowering::isJumpTableRelative() const { 2686 if (Subtarget.isPPC64()) 2687 return true; 2688 return TargetLowering::isJumpTableRelative(); 2689 } 2690 2691 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2692 SelectionDAG &DAG) const { 2693 if (!Subtarget.isPPC64()) 2694 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2695 2696 switch (getTargetMachine().getCodeModel()) { 2697 case CodeModel::Small: 2698 case CodeModel::Medium: 2699 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2700 default: 2701 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2702 getPointerTy(DAG.getDataLayout())); 2703 } 2704 } 2705 2706 const MCExpr * 2707 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2708 unsigned JTI, 2709 MCContext &Ctx) const { 2710 if (!Subtarget.isPPC64()) 2711 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2712 2713 switch (getTargetMachine().getCodeModel()) { 2714 case CodeModel::Small: 2715 case CodeModel::Medium: 2716 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2717 default: 2718 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2719 } 2720 } 2721 2722 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2723 EVT PtrVT = Op.getValueType(); 2724 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2725 2726 // 64-bit SVR4 ABI code is always position-independent. 2727 // The actual address of the GlobalValue is stored in the TOC. 2728 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2729 setUsesTOCBasePtr(DAG); 2730 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2731 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2732 } 2733 2734 unsigned MOHiFlag, MOLoFlag; 2735 bool IsPIC = isPositionIndependent(); 2736 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2737 2738 if (IsPIC && Subtarget.isSVR4ABI()) { 2739 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2740 PPCII::MO_PIC_FLAG); 2741 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2742 } 2743 2744 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2745 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2746 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2747 } 2748 2749 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2750 SelectionDAG &DAG) const { 2751 EVT PtrVT = Op.getValueType(); 2752 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2753 const BlockAddress *BA = BASDN->getBlockAddress(); 2754 2755 // 64-bit SVR4 ABI code is always position-independent. 2756 // The actual BlockAddress is stored in the TOC. 2757 if (Subtarget.isSVR4ABI() && 2758 (Subtarget.isPPC64() || isPositionIndependent())) { 2759 if (Subtarget.isPPC64()) 2760 setUsesTOCBasePtr(DAG); 2761 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2762 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2763 } 2764 2765 unsigned MOHiFlag, MOLoFlag; 2766 bool IsPIC = isPositionIndependent(); 2767 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2768 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2769 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2770 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2771 } 2772 2773 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2774 SelectionDAG &DAG) const { 2775 // FIXME: TLS addresses currently use medium model code sequences, 2776 // which is the most useful form. Eventually support for small and 2777 // large models could be added if users need it, at the cost of 2778 // additional complexity. 2779 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2780 if (DAG.getTarget().useEmulatedTLS()) 2781 return LowerToTLSEmulatedModel(GA, DAG); 2782 2783 SDLoc dl(GA); 2784 const GlobalValue *GV = GA->getGlobal(); 2785 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2786 bool is64bit = Subtarget.isPPC64(); 2787 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2788 PICLevel::Level picLevel = M->getPICLevel(); 2789 2790 const TargetMachine &TM = getTargetMachine(); 2791 TLSModel::Model Model = TM.getTLSModel(GV); 2792 2793 if (Model == TLSModel::LocalExec) { 2794 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2795 PPCII::MO_TPREL_HA); 2796 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2797 PPCII::MO_TPREL_LO); 2798 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2799 : DAG.getRegister(PPC::R2, MVT::i32); 2800 2801 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2802 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2803 } 2804 2805 if (Model == TLSModel::InitialExec) { 2806 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2807 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2808 PPCII::MO_TLS); 2809 SDValue GOTPtr; 2810 if (is64bit) { 2811 setUsesTOCBasePtr(DAG); 2812 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2813 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2814 PtrVT, GOTReg, TGA); 2815 } else { 2816 if (!TM.isPositionIndependent()) 2817 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2818 else if (picLevel == PICLevel::SmallPIC) 2819 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2820 else 2821 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2822 } 2823 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2824 PtrVT, TGA, GOTPtr); 2825 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2826 } 2827 2828 if (Model == TLSModel::GeneralDynamic) { 2829 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2830 SDValue GOTPtr; 2831 if (is64bit) { 2832 setUsesTOCBasePtr(DAG); 2833 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2834 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2835 GOTReg, TGA); 2836 } else { 2837 if (picLevel == PICLevel::SmallPIC) 2838 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2839 else 2840 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2841 } 2842 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2843 GOTPtr, TGA, TGA); 2844 } 2845 2846 if (Model == TLSModel::LocalDynamic) { 2847 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2848 SDValue GOTPtr; 2849 if (is64bit) { 2850 setUsesTOCBasePtr(DAG); 2851 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2852 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2853 GOTReg, TGA); 2854 } else { 2855 if (picLevel == PICLevel::SmallPIC) 2856 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2857 else 2858 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2859 } 2860 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2861 PtrVT, GOTPtr, TGA, TGA); 2862 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2863 PtrVT, TLSAddr, TGA); 2864 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2865 } 2866 2867 llvm_unreachable("Unknown TLS model!"); 2868 } 2869 2870 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 EVT PtrVT = Op.getValueType(); 2873 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2874 SDLoc DL(GSDN); 2875 const GlobalValue *GV = GSDN->getGlobal(); 2876 2877 // 64-bit SVR4 ABI code is always position-independent. 2878 // The actual address of the GlobalValue is stored in the TOC. 2879 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2880 setUsesTOCBasePtr(DAG); 2881 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2882 return getTOCEntry(DAG, DL, true, GA); 2883 } 2884 2885 unsigned MOHiFlag, MOLoFlag; 2886 bool IsPIC = isPositionIndependent(); 2887 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2888 2889 if (IsPIC && Subtarget.isSVR4ABI()) { 2890 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2891 GSDN->getOffset(), 2892 PPCII::MO_PIC_FLAG); 2893 return getTOCEntry(DAG, DL, false, GA); 2894 } 2895 2896 SDValue GAHi = 2897 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2898 SDValue GALo = 2899 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2900 2901 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2902 2903 // If the global reference is actually to a non-lazy-pointer, we have to do an 2904 // extra load to get the address of the global. 2905 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2906 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2907 return Ptr; 2908 } 2909 2910 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2911 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2912 SDLoc dl(Op); 2913 2914 if (Op.getValueType() == MVT::v2i64) { 2915 // When the operands themselves are v2i64 values, we need to do something 2916 // special because VSX has no underlying comparison operations for these. 2917 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2918 // Equality can be handled by casting to the legal type for Altivec 2919 // comparisons, everything else needs to be expanded. 2920 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2921 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2922 DAG.getSetCC(dl, MVT::v4i32, 2923 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2924 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2925 CC)); 2926 } 2927 2928 return SDValue(); 2929 } 2930 2931 // We handle most of these in the usual way. 2932 return Op; 2933 } 2934 2935 // If we're comparing for equality to zero, expose the fact that this is 2936 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2937 // fold the new nodes. 2938 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2939 return V; 2940 2941 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2942 // Leave comparisons against 0 and -1 alone for now, since they're usually 2943 // optimized. FIXME: revisit this when we can custom lower all setcc 2944 // optimizations. 2945 if (C->isAllOnesValue() || C->isNullValue()) 2946 return SDValue(); 2947 } 2948 2949 // If we have an integer seteq/setne, turn it into a compare against zero 2950 // by xor'ing the rhs with the lhs, which is faster than setting a 2951 // condition register, reading it back out, and masking the correct bit. The 2952 // normal approach here uses sub to do this instead of xor. Using xor exposes 2953 // the result to other bit-twiddling opportunities. 2954 EVT LHSVT = Op.getOperand(0).getValueType(); 2955 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2956 EVT VT = Op.getValueType(); 2957 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2958 Op.getOperand(1)); 2959 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2960 } 2961 return SDValue(); 2962 } 2963 2964 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2965 SDNode *Node = Op.getNode(); 2966 EVT VT = Node->getValueType(0); 2967 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2968 SDValue InChain = Node->getOperand(0); 2969 SDValue VAListPtr = Node->getOperand(1); 2970 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2971 SDLoc dl(Node); 2972 2973 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2974 2975 // gpr_index 2976 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2977 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2978 InChain = GprIndex.getValue(1); 2979 2980 if (VT == MVT::i64) { 2981 // Check if GprIndex is even 2982 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2983 DAG.getConstant(1, dl, MVT::i32)); 2984 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2985 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2986 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2987 DAG.getConstant(1, dl, MVT::i32)); 2988 // Align GprIndex to be even if it isn't 2989 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2990 GprIndex); 2991 } 2992 2993 // fpr index is 1 byte after gpr 2994 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2995 DAG.getConstant(1, dl, MVT::i32)); 2996 2997 // fpr 2998 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2999 FprPtr, MachinePointerInfo(SV), MVT::i8); 3000 InChain = FprIndex.getValue(1); 3001 3002 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3003 DAG.getConstant(8, dl, MVT::i32)); 3004 3005 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3006 DAG.getConstant(4, dl, MVT::i32)); 3007 3008 // areas 3009 SDValue OverflowArea = 3010 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3011 InChain = OverflowArea.getValue(1); 3012 3013 SDValue RegSaveArea = 3014 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3015 InChain = RegSaveArea.getValue(1); 3016 3017 // select overflow_area if index > 8 3018 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3019 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3020 3021 // adjustment constant gpr_index * 4/8 3022 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3023 VT.isInteger() ? GprIndex : FprIndex, 3024 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3025 MVT::i32)); 3026 3027 // OurReg = RegSaveArea + RegConstant 3028 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3029 RegConstant); 3030 3031 // Floating types are 32 bytes into RegSaveArea 3032 if (VT.isFloatingPoint()) 3033 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3034 DAG.getConstant(32, dl, MVT::i32)); 3035 3036 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3037 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3038 VT.isInteger() ? GprIndex : FprIndex, 3039 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3040 MVT::i32)); 3041 3042 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3043 VT.isInteger() ? VAListPtr : FprPtr, 3044 MachinePointerInfo(SV), MVT::i8); 3045 3046 // determine if we should load from reg_save_area or overflow_area 3047 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3048 3049 // increase overflow_area by 4/8 if gpr/fpr > 8 3050 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3051 DAG.getConstant(VT.isInteger() ? 4 : 8, 3052 dl, MVT::i32)); 3053 3054 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3055 OverflowAreaPlusN); 3056 3057 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3058 MachinePointerInfo(), MVT::i32); 3059 3060 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3061 } 3062 3063 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3064 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3065 3066 // We have to copy the entire va_list struct: 3067 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3068 return DAG.getMemcpy(Op.getOperand(0), Op, 3069 Op.getOperand(1), Op.getOperand(2), 3070 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3071 false, MachinePointerInfo(), MachinePointerInfo()); 3072 } 3073 3074 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3075 SelectionDAG &DAG) const { 3076 return Op.getOperand(0); 3077 } 3078 3079 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3080 SelectionDAG &DAG) const { 3081 SDValue Chain = Op.getOperand(0); 3082 SDValue Trmp = Op.getOperand(1); // trampoline 3083 SDValue FPtr = Op.getOperand(2); // nested function 3084 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3085 SDLoc dl(Op); 3086 3087 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3088 bool isPPC64 = (PtrVT == MVT::i64); 3089 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3090 3091 TargetLowering::ArgListTy Args; 3092 TargetLowering::ArgListEntry Entry; 3093 3094 Entry.Ty = IntPtrTy; 3095 Entry.Node = Trmp; Args.push_back(Entry); 3096 3097 // TrampSize == (isPPC64 ? 48 : 40); 3098 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3099 isPPC64 ? MVT::i64 : MVT::i32); 3100 Args.push_back(Entry); 3101 3102 Entry.Node = FPtr; Args.push_back(Entry); 3103 Entry.Node = Nest; Args.push_back(Entry); 3104 3105 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3106 TargetLowering::CallLoweringInfo CLI(DAG); 3107 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3108 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3109 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3110 3111 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3112 return CallResult.second; 3113 } 3114 3115 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3116 MachineFunction &MF = DAG.getMachineFunction(); 3117 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3118 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3119 3120 SDLoc dl(Op); 3121 3122 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3123 // vastart just stores the address of the VarArgsFrameIndex slot into the 3124 // memory location argument. 3125 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3126 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3127 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3128 MachinePointerInfo(SV)); 3129 } 3130 3131 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3132 // We suppose the given va_list is already allocated. 3133 // 3134 // typedef struct { 3135 // char gpr; /* index into the array of 8 GPRs 3136 // * stored in the register save area 3137 // * gpr=0 corresponds to r3, 3138 // * gpr=1 to r4, etc. 3139 // */ 3140 // char fpr; /* index into the array of 8 FPRs 3141 // * stored in the register save area 3142 // * fpr=0 corresponds to f1, 3143 // * fpr=1 to f2, etc. 3144 // */ 3145 // char *overflow_arg_area; 3146 // /* location on stack that holds 3147 // * the next overflow argument 3148 // */ 3149 // char *reg_save_area; 3150 // /* where r3:r10 and f1:f8 (if saved) 3151 // * are stored 3152 // */ 3153 // } va_list[1]; 3154 3155 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3156 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3157 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3158 PtrVT); 3159 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3160 PtrVT); 3161 3162 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3163 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3164 3165 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3166 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3167 3168 uint64_t FPROffset = 1; 3169 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3170 3171 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3172 3173 // Store first byte : number of int regs 3174 SDValue firstStore = 3175 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3176 MachinePointerInfo(SV), MVT::i8); 3177 uint64_t nextOffset = FPROffset; 3178 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3179 ConstFPROffset); 3180 3181 // Store second byte : number of float regs 3182 SDValue secondStore = 3183 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3184 MachinePointerInfo(SV, nextOffset), MVT::i8); 3185 nextOffset += StackOffset; 3186 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3187 3188 // Store second word : arguments given on stack 3189 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3190 MachinePointerInfo(SV, nextOffset)); 3191 nextOffset += FrameOffset; 3192 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3193 3194 // Store third word : arguments given in registers 3195 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3196 MachinePointerInfo(SV, nextOffset)); 3197 } 3198 3199 /// FPR - The set of FP registers that should be allocated for arguments, 3200 /// on Darwin. 3201 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3202 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3203 PPC::F11, PPC::F12, PPC::F13}; 3204 3205 /// QFPR - The set of QPX registers that should be allocated for arguments. 3206 static const MCPhysReg QFPR[] = { 3207 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3208 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3209 3210 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3211 /// the stack. 3212 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3213 unsigned PtrByteSize) { 3214 unsigned ArgSize = ArgVT.getStoreSize(); 3215 if (Flags.isByVal()) 3216 ArgSize = Flags.getByValSize(); 3217 3218 // Round up to multiples of the pointer size, except for array members, 3219 // which are always packed. 3220 if (!Flags.isInConsecutiveRegs()) 3221 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3222 3223 return ArgSize; 3224 } 3225 3226 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3227 /// on the stack. 3228 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3229 ISD::ArgFlagsTy Flags, 3230 unsigned PtrByteSize) { 3231 unsigned Align = PtrByteSize; 3232 3233 // Altivec parameters are padded to a 16 byte boundary. 3234 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3235 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3236 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3237 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3238 Align = 16; 3239 // QPX vector types stored in double-precision are padded to a 32 byte 3240 // boundary. 3241 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3242 Align = 32; 3243 3244 // ByVal parameters are aligned as requested. 3245 if (Flags.isByVal()) { 3246 unsigned BVAlign = Flags.getByValAlign(); 3247 if (BVAlign > PtrByteSize) { 3248 if (BVAlign % PtrByteSize != 0) 3249 llvm_unreachable( 3250 "ByVal alignment is not a multiple of the pointer size"); 3251 3252 Align = BVAlign; 3253 } 3254 } 3255 3256 // Array members are always packed to their original alignment. 3257 if (Flags.isInConsecutiveRegs()) { 3258 // If the array member was split into multiple registers, the first 3259 // needs to be aligned to the size of the full type. (Except for 3260 // ppcf128, which is only aligned as its f64 components.) 3261 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3262 Align = OrigVT.getStoreSize(); 3263 else 3264 Align = ArgVT.getStoreSize(); 3265 } 3266 3267 return Align; 3268 } 3269 3270 /// CalculateStackSlotUsed - Return whether this argument will use its 3271 /// stack slot (instead of being passed in registers). ArgOffset, 3272 /// AvailableFPRs, and AvailableVRs must hold the current argument 3273 /// position, and will be updated to account for this argument. 3274 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3275 ISD::ArgFlagsTy Flags, 3276 unsigned PtrByteSize, 3277 unsigned LinkageSize, 3278 unsigned ParamAreaSize, 3279 unsigned &ArgOffset, 3280 unsigned &AvailableFPRs, 3281 unsigned &AvailableVRs, bool HasQPX) { 3282 bool UseMemory = false; 3283 3284 // Respect alignment of argument on the stack. 3285 unsigned Align = 3286 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3287 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3288 // If there's no space left in the argument save area, we must 3289 // use memory (this check also catches zero-sized arguments). 3290 if (ArgOffset >= LinkageSize + ParamAreaSize) 3291 UseMemory = true; 3292 3293 // Allocate argument on the stack. 3294 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3295 if (Flags.isInConsecutiveRegsLast()) 3296 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3297 // If we overran the argument save area, we must use memory 3298 // (this check catches arguments passed partially in memory) 3299 if (ArgOffset > LinkageSize + ParamAreaSize) 3300 UseMemory = true; 3301 3302 // However, if the argument is actually passed in an FPR or a VR, 3303 // we don't use memory after all. 3304 if (!Flags.isByVal()) { 3305 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3306 // QPX registers overlap with the scalar FP registers. 3307 (HasQPX && (ArgVT == MVT::v4f32 || 3308 ArgVT == MVT::v4f64 || 3309 ArgVT == MVT::v4i1))) 3310 if (AvailableFPRs > 0) { 3311 --AvailableFPRs; 3312 return false; 3313 } 3314 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3315 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3316 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3317 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3318 if (AvailableVRs > 0) { 3319 --AvailableVRs; 3320 return false; 3321 } 3322 } 3323 3324 return UseMemory; 3325 } 3326 3327 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3328 /// ensure minimum alignment required for target. 3329 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3330 unsigned NumBytes) { 3331 unsigned TargetAlign = Lowering->getStackAlignment(); 3332 unsigned AlignMask = TargetAlign - 1; 3333 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3334 return NumBytes; 3335 } 3336 3337 SDValue PPCTargetLowering::LowerFormalArguments( 3338 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3339 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3340 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3341 if (Subtarget.isSVR4ABI()) { 3342 if (Subtarget.isPPC64()) 3343 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3344 dl, DAG, InVals); 3345 else 3346 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3347 dl, DAG, InVals); 3348 } else { 3349 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3350 dl, DAG, InVals); 3351 } 3352 } 3353 3354 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3355 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3356 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3357 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3358 3359 // 32-bit SVR4 ABI Stack Frame Layout: 3360 // +-----------------------------------+ 3361 // +--> | Back chain | 3362 // | +-----------------------------------+ 3363 // | | Floating-point register save area | 3364 // | +-----------------------------------+ 3365 // | | General register save area | 3366 // | +-----------------------------------+ 3367 // | | CR save word | 3368 // | +-----------------------------------+ 3369 // | | VRSAVE save word | 3370 // | +-----------------------------------+ 3371 // | | Alignment padding | 3372 // | +-----------------------------------+ 3373 // | | Vector register save area | 3374 // | +-----------------------------------+ 3375 // | | Local variable space | 3376 // | +-----------------------------------+ 3377 // | | Parameter list area | 3378 // | +-----------------------------------+ 3379 // | | LR save word | 3380 // | +-----------------------------------+ 3381 // SP--> +--- | Back chain | 3382 // +-----------------------------------+ 3383 // 3384 // Specifications: 3385 // System V Application Binary Interface PowerPC Processor Supplement 3386 // AltiVec Technology Programming Interface Manual 3387 3388 MachineFunction &MF = DAG.getMachineFunction(); 3389 MachineFrameInfo &MFI = MF.getFrameInfo(); 3390 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3391 3392 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3393 // Potential tail calls could cause overwriting of argument stack slots. 3394 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3395 (CallConv == CallingConv::Fast)); 3396 unsigned PtrByteSize = 4; 3397 3398 // Assign locations to all of the incoming arguments. 3399 SmallVector<CCValAssign, 16> ArgLocs; 3400 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3401 *DAG.getContext()); 3402 3403 // Reserve space for the linkage area on the stack. 3404 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3405 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3406 if (useSoftFloat() || hasSPE()) 3407 CCInfo.PreAnalyzeFormalArguments(Ins); 3408 3409 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3410 CCInfo.clearWasPPCF128(); 3411 3412 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3413 CCValAssign &VA = ArgLocs[i]; 3414 3415 // Arguments stored in registers. 3416 if (VA.isRegLoc()) { 3417 const TargetRegisterClass *RC; 3418 EVT ValVT = VA.getValVT(); 3419 3420 switch (ValVT.getSimpleVT().SimpleTy) { 3421 default: 3422 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3423 case MVT::i1: 3424 case MVT::i32: 3425 RC = &PPC::GPRCRegClass; 3426 break; 3427 case MVT::f32: 3428 if (Subtarget.hasP8Vector()) 3429 RC = &PPC::VSSRCRegClass; 3430 else if (Subtarget.hasSPE()) 3431 RC = &PPC::SPE4RCRegClass; 3432 else 3433 RC = &PPC::F4RCRegClass; 3434 break; 3435 case MVT::f64: 3436 if (Subtarget.hasVSX()) 3437 RC = &PPC::VSFRCRegClass; 3438 else if (Subtarget.hasSPE()) 3439 RC = &PPC::SPERCRegClass; 3440 else 3441 RC = &PPC::F8RCRegClass; 3442 break; 3443 case MVT::v16i8: 3444 case MVT::v8i16: 3445 case MVT::v4i32: 3446 RC = &PPC::VRRCRegClass; 3447 break; 3448 case MVT::v4f32: 3449 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3450 break; 3451 case MVT::v2f64: 3452 case MVT::v2i64: 3453 RC = &PPC::VRRCRegClass; 3454 break; 3455 case MVT::v4f64: 3456 RC = &PPC::QFRCRegClass; 3457 break; 3458 case MVT::v4i1: 3459 RC = &PPC::QBRCRegClass; 3460 break; 3461 } 3462 3463 // Transform the arguments stored in physical registers into virtual ones. 3464 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3465 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3466 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3467 3468 if (ValVT == MVT::i1) 3469 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3470 3471 InVals.push_back(ArgValue); 3472 } else { 3473 // Argument stored in memory. 3474 assert(VA.isMemLoc()); 3475 3476 // Get the extended size of the argument type in stack 3477 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3478 // Get the actual size of the argument type 3479 unsigned ObjSize = VA.getValVT().getStoreSize(); 3480 unsigned ArgOffset = VA.getLocMemOffset(); 3481 // Stack objects in PPC32 are right justified. 3482 ArgOffset += ArgSize - ObjSize; 3483 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3484 3485 // Create load nodes to retrieve arguments from the stack. 3486 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3487 InVals.push_back( 3488 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3489 } 3490 } 3491 3492 // Assign locations to all of the incoming aggregate by value arguments. 3493 // Aggregates passed by value are stored in the local variable space of the 3494 // caller's stack frame, right above the parameter list area. 3495 SmallVector<CCValAssign, 16> ByValArgLocs; 3496 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3497 ByValArgLocs, *DAG.getContext()); 3498 3499 // Reserve stack space for the allocations in CCInfo. 3500 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3501 3502 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3503 3504 // Area that is at least reserved in the caller of this function. 3505 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3506 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3507 3508 // Set the size that is at least reserved in caller of this function. Tail 3509 // call optimized function's reserved stack space needs to be aligned so that 3510 // taking the difference between two stack areas will result in an aligned 3511 // stack. 3512 MinReservedArea = 3513 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3514 FuncInfo->setMinReservedArea(MinReservedArea); 3515 3516 SmallVector<SDValue, 8> MemOps; 3517 3518 // If the function takes variable number of arguments, make a frame index for 3519 // the start of the first vararg value... for expansion of llvm.va_start. 3520 if (isVarArg) { 3521 static const MCPhysReg GPArgRegs[] = { 3522 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3523 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3524 }; 3525 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3526 3527 static const MCPhysReg FPArgRegs[] = { 3528 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3529 PPC::F8 3530 }; 3531 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3532 3533 if (useSoftFloat() || hasSPE()) 3534 NumFPArgRegs = 0; 3535 3536 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3537 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3538 3539 // Make room for NumGPArgRegs and NumFPArgRegs. 3540 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3541 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3542 3543 FuncInfo->setVarArgsStackOffset( 3544 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3545 CCInfo.getNextStackOffset(), true)); 3546 3547 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3548 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3549 3550 // The fixed integer arguments of a variadic function are stored to the 3551 // VarArgsFrameIndex on the stack so that they may be loaded by 3552 // dereferencing the result of va_next. 3553 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3554 // Get an existing live-in vreg, or add a new one. 3555 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3556 if (!VReg) 3557 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3558 3559 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3560 SDValue Store = 3561 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3562 MemOps.push_back(Store); 3563 // Increment the address by four for the next argument to store 3564 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3565 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3566 } 3567 3568 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3569 // is set. 3570 // The double arguments are stored to the VarArgsFrameIndex 3571 // on the stack. 3572 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3573 // Get an existing live-in vreg, or add a new one. 3574 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3575 if (!VReg) 3576 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3577 3578 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3579 SDValue Store = 3580 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3581 MemOps.push_back(Store); 3582 // Increment the address by eight for the next argument to store 3583 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3584 PtrVT); 3585 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3586 } 3587 } 3588 3589 if (!MemOps.empty()) 3590 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3591 3592 return Chain; 3593 } 3594 3595 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3596 // value to MVT::i64 and then truncate to the correct register size. 3597 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3598 EVT ObjectVT, SelectionDAG &DAG, 3599 SDValue ArgVal, 3600 const SDLoc &dl) const { 3601 if (Flags.isSExt()) 3602 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3603 DAG.getValueType(ObjectVT)); 3604 else if (Flags.isZExt()) 3605 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3606 DAG.getValueType(ObjectVT)); 3607 3608 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3609 } 3610 3611 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3612 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3613 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3614 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3615 // TODO: add description of PPC stack frame format, or at least some docs. 3616 // 3617 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3618 bool isLittleEndian = Subtarget.isLittleEndian(); 3619 MachineFunction &MF = DAG.getMachineFunction(); 3620 MachineFrameInfo &MFI = MF.getFrameInfo(); 3621 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3622 3623 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3624 "fastcc not supported on varargs functions"); 3625 3626 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3627 // Potential tail calls could cause overwriting of argument stack slots. 3628 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3629 (CallConv == CallingConv::Fast)); 3630 unsigned PtrByteSize = 8; 3631 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3632 3633 static const MCPhysReg GPR[] = { 3634 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3635 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3636 }; 3637 static const MCPhysReg VR[] = { 3638 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3639 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3640 }; 3641 3642 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3643 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3644 const unsigned Num_VR_Regs = array_lengthof(VR); 3645 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3646 3647 // Do a first pass over the arguments to determine whether the ABI 3648 // guarantees that our caller has allocated the parameter save area 3649 // on its stack frame. In the ELFv1 ABI, this is always the case; 3650 // in the ELFv2 ABI, it is true if this is a vararg function or if 3651 // any parameter is located in a stack slot. 3652 3653 bool HasParameterArea = !isELFv2ABI || isVarArg; 3654 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3655 unsigned NumBytes = LinkageSize; 3656 unsigned AvailableFPRs = Num_FPR_Regs; 3657 unsigned AvailableVRs = Num_VR_Regs; 3658 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3659 if (Ins[i].Flags.isNest()) 3660 continue; 3661 3662 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3663 PtrByteSize, LinkageSize, ParamAreaSize, 3664 NumBytes, AvailableFPRs, AvailableVRs, 3665 Subtarget.hasQPX())) 3666 HasParameterArea = true; 3667 } 3668 3669 // Add DAG nodes to load the arguments or copy them out of registers. On 3670 // entry to a function on PPC, the arguments start after the linkage area, 3671 // although the first ones are often in registers. 3672 3673 unsigned ArgOffset = LinkageSize; 3674 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3675 unsigned &QFPR_idx = FPR_idx; 3676 SmallVector<SDValue, 8> MemOps; 3677 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3678 unsigned CurArgIdx = 0; 3679 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3680 SDValue ArgVal; 3681 bool needsLoad = false; 3682 EVT ObjectVT = Ins[ArgNo].VT; 3683 EVT OrigVT = Ins[ArgNo].ArgVT; 3684 unsigned ObjSize = ObjectVT.getStoreSize(); 3685 unsigned ArgSize = ObjSize; 3686 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3687 if (Ins[ArgNo].isOrigArg()) { 3688 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3689 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3690 } 3691 // We re-align the argument offset for each argument, except when using the 3692 // fast calling convention, when we need to make sure we do that only when 3693 // we'll actually use a stack slot. 3694 unsigned CurArgOffset, Align; 3695 auto ComputeArgOffset = [&]() { 3696 /* Respect alignment of argument on the stack. */ 3697 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3698 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3699 CurArgOffset = ArgOffset; 3700 }; 3701 3702 if (CallConv != CallingConv::Fast) { 3703 ComputeArgOffset(); 3704 3705 /* Compute GPR index associated with argument offset. */ 3706 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3707 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3708 } 3709 3710 // FIXME the codegen can be much improved in some cases. 3711 // We do not have to keep everything in memory. 3712 if (Flags.isByVal()) { 3713 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3714 3715 if (CallConv == CallingConv::Fast) 3716 ComputeArgOffset(); 3717 3718 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3719 ObjSize = Flags.getByValSize(); 3720 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3721 // Empty aggregate parameters do not take up registers. Examples: 3722 // struct { } a; 3723 // union { } b; 3724 // int c[0]; 3725 // etc. However, we have to provide a place-holder in InVals, so 3726 // pretend we have an 8-byte item at the current address for that 3727 // purpose. 3728 if (!ObjSize) { 3729 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3730 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3731 InVals.push_back(FIN); 3732 continue; 3733 } 3734 3735 // Create a stack object covering all stack doublewords occupied 3736 // by the argument. If the argument is (fully or partially) on 3737 // the stack, or if the argument is fully in registers but the 3738 // caller has allocated the parameter save anyway, we can refer 3739 // directly to the caller's stack frame. Otherwise, create a 3740 // local copy in our own frame. 3741 int FI; 3742 if (HasParameterArea || 3743 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3744 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3745 else 3746 FI = MFI.CreateStackObject(ArgSize, Align, false); 3747 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3748 3749 // Handle aggregates smaller than 8 bytes. 3750 if (ObjSize < PtrByteSize) { 3751 // The value of the object is its address, which differs from the 3752 // address of the enclosing doubleword on big-endian systems. 3753 SDValue Arg = FIN; 3754 if (!isLittleEndian) { 3755 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3756 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3757 } 3758 InVals.push_back(Arg); 3759 3760 if (GPR_idx != Num_GPR_Regs) { 3761 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3762 FuncInfo->addLiveInAttr(VReg, Flags); 3763 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3764 SDValue Store; 3765 3766 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3767 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3768 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3769 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3770 MachinePointerInfo(&*FuncArg), ObjType); 3771 } else { 3772 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3773 // store the whole register as-is to the parameter save area 3774 // slot. 3775 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3776 MachinePointerInfo(&*FuncArg)); 3777 } 3778 3779 MemOps.push_back(Store); 3780 } 3781 // Whether we copied from a register or not, advance the offset 3782 // into the parameter save area by a full doubleword. 3783 ArgOffset += PtrByteSize; 3784 continue; 3785 } 3786 3787 // The value of the object is its address, which is the address of 3788 // its first stack doubleword. 3789 InVals.push_back(FIN); 3790 3791 // Store whatever pieces of the object are in registers to memory. 3792 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3793 if (GPR_idx == Num_GPR_Regs) 3794 break; 3795 3796 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3797 FuncInfo->addLiveInAttr(VReg, Flags); 3798 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3799 SDValue Addr = FIN; 3800 if (j) { 3801 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3802 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3803 } 3804 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3805 MachinePointerInfo(&*FuncArg, j)); 3806 MemOps.push_back(Store); 3807 ++GPR_idx; 3808 } 3809 ArgOffset += ArgSize; 3810 continue; 3811 } 3812 3813 switch (ObjectVT.getSimpleVT().SimpleTy) { 3814 default: llvm_unreachable("Unhandled argument type!"); 3815 case MVT::i1: 3816 case MVT::i32: 3817 case MVT::i64: 3818 if (Flags.isNest()) { 3819 // The 'nest' parameter, if any, is passed in R11. 3820 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3821 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3822 3823 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3824 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3825 3826 break; 3827 } 3828 3829 // These can be scalar arguments or elements of an integer array type 3830 // passed directly. Clang may use those instead of "byval" aggregate 3831 // types to avoid forcing arguments to memory unnecessarily. 3832 if (GPR_idx != Num_GPR_Regs) { 3833 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3834 FuncInfo->addLiveInAttr(VReg, Flags); 3835 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3836 3837 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3838 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3839 // value to MVT::i64 and then truncate to the correct register size. 3840 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3841 } else { 3842 if (CallConv == CallingConv::Fast) 3843 ComputeArgOffset(); 3844 3845 needsLoad = true; 3846 ArgSize = PtrByteSize; 3847 } 3848 if (CallConv != CallingConv::Fast || needsLoad) 3849 ArgOffset += 8; 3850 break; 3851 3852 case MVT::f32: 3853 case MVT::f64: 3854 // These can be scalar arguments or elements of a float array type 3855 // passed directly. The latter are used to implement ELFv2 homogenous 3856 // float aggregates. 3857 if (FPR_idx != Num_FPR_Regs) { 3858 unsigned VReg; 3859 3860 if (ObjectVT == MVT::f32) 3861 VReg = MF.addLiveIn(FPR[FPR_idx], 3862 Subtarget.hasP8Vector() 3863 ? &PPC::VSSRCRegClass 3864 : &PPC::F4RCRegClass); 3865 else 3866 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3867 ? &PPC::VSFRCRegClass 3868 : &PPC::F8RCRegClass); 3869 3870 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3871 ++FPR_idx; 3872 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3873 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3874 // once we support fp <-> gpr moves. 3875 3876 // This can only ever happen in the presence of f32 array types, 3877 // since otherwise we never run out of FPRs before running out 3878 // of GPRs. 3879 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3880 FuncInfo->addLiveInAttr(VReg, Flags); 3881 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3882 3883 if (ObjectVT == MVT::f32) { 3884 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3885 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3886 DAG.getConstant(32, dl, MVT::i32)); 3887 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3888 } 3889 3890 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3891 } else { 3892 if (CallConv == CallingConv::Fast) 3893 ComputeArgOffset(); 3894 3895 needsLoad = true; 3896 } 3897 3898 // When passing an array of floats, the array occupies consecutive 3899 // space in the argument area; only round up to the next doubleword 3900 // at the end of the array. Otherwise, each float takes 8 bytes. 3901 if (CallConv != CallingConv::Fast || needsLoad) { 3902 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3903 ArgOffset += ArgSize; 3904 if (Flags.isInConsecutiveRegsLast()) 3905 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3906 } 3907 break; 3908 case MVT::v4f32: 3909 case MVT::v4i32: 3910 case MVT::v8i16: 3911 case MVT::v16i8: 3912 case MVT::v2f64: 3913 case MVT::v2i64: 3914 case MVT::v1i128: 3915 case MVT::f128: 3916 if (!Subtarget.hasQPX()) { 3917 // These can be scalar arguments or elements of a vector array type 3918 // passed directly. The latter are used to implement ELFv2 homogenous 3919 // vector aggregates. 3920 if (VR_idx != Num_VR_Regs) { 3921 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3922 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3923 ++VR_idx; 3924 } else { 3925 if (CallConv == CallingConv::Fast) 3926 ComputeArgOffset(); 3927 needsLoad = true; 3928 } 3929 if (CallConv != CallingConv::Fast || needsLoad) 3930 ArgOffset += 16; 3931 break; 3932 } // not QPX 3933 3934 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3935 "Invalid QPX parameter type"); 3936 LLVM_FALLTHROUGH; 3937 3938 case MVT::v4f64: 3939 case MVT::v4i1: 3940 // QPX vectors are treated like their scalar floating-point subregisters 3941 // (except that they're larger). 3942 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3943 if (QFPR_idx != Num_QFPR_Regs) { 3944 const TargetRegisterClass *RC; 3945 switch (ObjectVT.getSimpleVT().SimpleTy) { 3946 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3947 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3948 default: RC = &PPC::QBRCRegClass; break; 3949 } 3950 3951 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3952 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3953 ++QFPR_idx; 3954 } else { 3955 if (CallConv == CallingConv::Fast) 3956 ComputeArgOffset(); 3957 needsLoad = true; 3958 } 3959 if (CallConv != CallingConv::Fast || needsLoad) 3960 ArgOffset += Sz; 3961 break; 3962 } 3963 3964 // We need to load the argument to a virtual register if we determined 3965 // above that we ran out of physical registers of the appropriate type. 3966 if (needsLoad) { 3967 if (ObjSize < ArgSize && !isLittleEndian) 3968 CurArgOffset += ArgSize - ObjSize; 3969 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3970 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3971 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3972 } 3973 3974 InVals.push_back(ArgVal); 3975 } 3976 3977 // Area that is at least reserved in the caller of this function. 3978 unsigned MinReservedArea; 3979 if (HasParameterArea) 3980 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3981 else 3982 MinReservedArea = LinkageSize; 3983 3984 // Set the size that is at least reserved in caller of this function. Tail 3985 // call optimized functions' reserved stack space needs to be aligned so that 3986 // taking the difference between two stack areas will result in an aligned 3987 // stack. 3988 MinReservedArea = 3989 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3990 FuncInfo->setMinReservedArea(MinReservedArea); 3991 3992 // If the function takes variable number of arguments, make a frame index for 3993 // the start of the first vararg value... for expansion of llvm.va_start. 3994 if (isVarArg) { 3995 int Depth = ArgOffset; 3996 3997 FuncInfo->setVarArgsFrameIndex( 3998 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3999 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4000 4001 // If this function is vararg, store any remaining integer argument regs 4002 // to their spots on the stack so that they may be loaded by dereferencing 4003 // the result of va_next. 4004 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4005 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4006 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4007 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4008 SDValue Store = 4009 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4010 MemOps.push_back(Store); 4011 // Increment the address by four for the next argument to store 4012 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4013 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4014 } 4015 } 4016 4017 if (!MemOps.empty()) 4018 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4019 4020 return Chain; 4021 } 4022 4023 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4024 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4025 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4026 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4027 // TODO: add description of PPC stack frame format, or at least some docs. 4028 // 4029 MachineFunction &MF = DAG.getMachineFunction(); 4030 MachineFrameInfo &MFI = MF.getFrameInfo(); 4031 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4032 4033 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4034 bool isPPC64 = PtrVT == MVT::i64; 4035 // Potential tail calls could cause overwriting of argument stack slots. 4036 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4037 (CallConv == CallingConv::Fast)); 4038 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4039 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4040 unsigned ArgOffset = LinkageSize; 4041 // Area that is at least reserved in caller of this function. 4042 unsigned MinReservedArea = ArgOffset; 4043 4044 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4045 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4046 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4047 }; 4048 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4049 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4050 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4051 }; 4052 static const MCPhysReg VR[] = { 4053 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4054 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4055 }; 4056 4057 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4058 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4059 const unsigned Num_VR_Regs = array_lengthof( VR); 4060 4061 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4062 4063 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4064 4065 // In 32-bit non-varargs functions, the stack space for vectors is after the 4066 // stack space for non-vectors. We do not use this space unless we have 4067 // too many vectors to fit in registers, something that only occurs in 4068 // constructed examples:), but we have to walk the arglist to figure 4069 // that out...for the pathological case, compute VecArgOffset as the 4070 // start of the vector parameter area. Computing VecArgOffset is the 4071 // entire point of the following loop. 4072 unsigned VecArgOffset = ArgOffset; 4073 if (!isVarArg && !isPPC64) { 4074 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4075 ++ArgNo) { 4076 EVT ObjectVT = Ins[ArgNo].VT; 4077 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4078 4079 if (Flags.isByVal()) { 4080 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4081 unsigned ObjSize = Flags.getByValSize(); 4082 unsigned ArgSize = 4083 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4084 VecArgOffset += ArgSize; 4085 continue; 4086 } 4087 4088 switch(ObjectVT.getSimpleVT().SimpleTy) { 4089 default: llvm_unreachable("Unhandled argument type!"); 4090 case MVT::i1: 4091 case MVT::i32: 4092 case MVT::f32: 4093 VecArgOffset += 4; 4094 break; 4095 case MVT::i64: // PPC64 4096 case MVT::f64: 4097 // FIXME: We are guaranteed to be !isPPC64 at this point. 4098 // Does MVT::i64 apply? 4099 VecArgOffset += 8; 4100 break; 4101 case MVT::v4f32: 4102 case MVT::v4i32: 4103 case MVT::v8i16: 4104 case MVT::v16i8: 4105 // Nothing to do, we're only looking at Nonvector args here. 4106 break; 4107 } 4108 } 4109 } 4110 // We've found where the vector parameter area in memory is. Skip the 4111 // first 12 parameters; these don't use that memory. 4112 VecArgOffset = ((VecArgOffset+15)/16)*16; 4113 VecArgOffset += 12*16; 4114 4115 // Add DAG nodes to load the arguments or copy them out of registers. On 4116 // entry to a function on PPC, the arguments start after the linkage area, 4117 // although the first ones are often in registers. 4118 4119 SmallVector<SDValue, 8> MemOps; 4120 unsigned nAltivecParamsAtEnd = 0; 4121 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4122 unsigned CurArgIdx = 0; 4123 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4124 SDValue ArgVal; 4125 bool needsLoad = false; 4126 EVT ObjectVT = Ins[ArgNo].VT; 4127 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4128 unsigned ArgSize = ObjSize; 4129 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4130 if (Ins[ArgNo].isOrigArg()) { 4131 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4132 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4133 } 4134 unsigned CurArgOffset = ArgOffset; 4135 4136 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4137 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4138 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4139 if (isVarArg || isPPC64) { 4140 MinReservedArea = ((MinReservedArea+15)/16)*16; 4141 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4142 Flags, 4143 PtrByteSize); 4144 } else nAltivecParamsAtEnd++; 4145 } else 4146 // Calculate min reserved area. 4147 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4148 Flags, 4149 PtrByteSize); 4150 4151 // FIXME the codegen can be much improved in some cases. 4152 // We do not have to keep everything in memory. 4153 if (Flags.isByVal()) { 4154 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4155 4156 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4157 ObjSize = Flags.getByValSize(); 4158 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4159 // Objects of size 1 and 2 are right justified, everything else is 4160 // left justified. This means the memory address is adjusted forwards. 4161 if (ObjSize==1 || ObjSize==2) { 4162 CurArgOffset = CurArgOffset + (4 - ObjSize); 4163 } 4164 // The value of the object is its address. 4165 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4166 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4167 InVals.push_back(FIN); 4168 if (ObjSize==1 || ObjSize==2) { 4169 if (GPR_idx != Num_GPR_Regs) { 4170 unsigned VReg; 4171 if (isPPC64) 4172 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4173 else 4174 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4175 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4176 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4177 SDValue Store = 4178 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4179 MachinePointerInfo(&*FuncArg), ObjType); 4180 MemOps.push_back(Store); 4181 ++GPR_idx; 4182 } 4183 4184 ArgOffset += PtrByteSize; 4185 4186 continue; 4187 } 4188 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4189 // Store whatever pieces of the object are in registers 4190 // to memory. ArgOffset will be the address of the beginning 4191 // of the object. 4192 if (GPR_idx != Num_GPR_Regs) { 4193 unsigned VReg; 4194 if (isPPC64) 4195 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4196 else 4197 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4198 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4199 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4200 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4201 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4202 MachinePointerInfo(&*FuncArg, j)); 4203 MemOps.push_back(Store); 4204 ++GPR_idx; 4205 ArgOffset += PtrByteSize; 4206 } else { 4207 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4208 break; 4209 } 4210 } 4211 continue; 4212 } 4213 4214 switch (ObjectVT.getSimpleVT().SimpleTy) { 4215 default: llvm_unreachable("Unhandled argument type!"); 4216 case MVT::i1: 4217 case MVT::i32: 4218 if (!isPPC64) { 4219 if (GPR_idx != Num_GPR_Regs) { 4220 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4221 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4222 4223 if (ObjectVT == MVT::i1) 4224 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4225 4226 ++GPR_idx; 4227 } else { 4228 needsLoad = true; 4229 ArgSize = PtrByteSize; 4230 } 4231 // All int arguments reserve stack space in the Darwin ABI. 4232 ArgOffset += PtrByteSize; 4233 break; 4234 } 4235 LLVM_FALLTHROUGH; 4236 case MVT::i64: // PPC64 4237 if (GPR_idx != Num_GPR_Regs) { 4238 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4239 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4240 4241 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4242 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4243 // value to MVT::i64 and then truncate to the correct register size. 4244 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4245 4246 ++GPR_idx; 4247 } else { 4248 needsLoad = true; 4249 ArgSize = PtrByteSize; 4250 } 4251 // All int arguments reserve stack space in the Darwin ABI. 4252 ArgOffset += 8; 4253 break; 4254 4255 case MVT::f32: 4256 case MVT::f64: 4257 // Every 4 bytes of argument space consumes one of the GPRs available for 4258 // argument passing. 4259 if (GPR_idx != Num_GPR_Regs) { 4260 ++GPR_idx; 4261 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4262 ++GPR_idx; 4263 } 4264 if (FPR_idx != Num_FPR_Regs) { 4265 unsigned VReg; 4266 4267 if (ObjectVT == MVT::f32) 4268 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4269 else 4270 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4271 4272 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4273 ++FPR_idx; 4274 } else { 4275 needsLoad = true; 4276 } 4277 4278 // All FP arguments reserve stack space in the Darwin ABI. 4279 ArgOffset += isPPC64 ? 8 : ObjSize; 4280 break; 4281 case MVT::v4f32: 4282 case MVT::v4i32: 4283 case MVT::v8i16: 4284 case MVT::v16i8: 4285 // Note that vector arguments in registers don't reserve stack space, 4286 // except in varargs functions. 4287 if (VR_idx != Num_VR_Regs) { 4288 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4289 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4290 if (isVarArg) { 4291 while ((ArgOffset % 16) != 0) { 4292 ArgOffset += PtrByteSize; 4293 if (GPR_idx != Num_GPR_Regs) 4294 GPR_idx++; 4295 } 4296 ArgOffset += 16; 4297 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4298 } 4299 ++VR_idx; 4300 } else { 4301 if (!isVarArg && !isPPC64) { 4302 // Vectors go after all the nonvectors. 4303 CurArgOffset = VecArgOffset; 4304 VecArgOffset += 16; 4305 } else { 4306 // Vectors are aligned. 4307 ArgOffset = ((ArgOffset+15)/16)*16; 4308 CurArgOffset = ArgOffset; 4309 ArgOffset += 16; 4310 } 4311 needsLoad = true; 4312 } 4313 break; 4314 } 4315 4316 // We need to load the argument to a virtual register if we determined above 4317 // that we ran out of physical registers of the appropriate type. 4318 if (needsLoad) { 4319 int FI = MFI.CreateFixedObject(ObjSize, 4320 CurArgOffset + (ArgSize - ObjSize), 4321 isImmutable); 4322 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4323 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4324 } 4325 4326 InVals.push_back(ArgVal); 4327 } 4328 4329 // Allow for Altivec parameters at the end, if needed. 4330 if (nAltivecParamsAtEnd) { 4331 MinReservedArea = ((MinReservedArea+15)/16)*16; 4332 MinReservedArea += 16*nAltivecParamsAtEnd; 4333 } 4334 4335 // Area that is at least reserved in the caller of this function. 4336 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4337 4338 // Set the size that is at least reserved in caller of this function. Tail 4339 // call optimized functions' reserved stack space needs to be aligned so that 4340 // taking the difference between two stack areas will result in an aligned 4341 // stack. 4342 MinReservedArea = 4343 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4344 FuncInfo->setMinReservedArea(MinReservedArea); 4345 4346 // If the function takes variable number of arguments, make a frame index for 4347 // the start of the first vararg value... for expansion of llvm.va_start. 4348 if (isVarArg) { 4349 int Depth = ArgOffset; 4350 4351 FuncInfo->setVarArgsFrameIndex( 4352 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4353 Depth, true)); 4354 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4355 4356 // If this function is vararg, store any remaining integer argument regs 4357 // to their spots on the stack so that they may be loaded by dereferencing 4358 // the result of va_next. 4359 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4360 unsigned VReg; 4361 4362 if (isPPC64) 4363 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4364 else 4365 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4366 4367 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4368 SDValue Store = 4369 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4370 MemOps.push_back(Store); 4371 // Increment the address by four for the next argument to store 4372 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4373 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4374 } 4375 } 4376 4377 if (!MemOps.empty()) 4378 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4379 4380 return Chain; 4381 } 4382 4383 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4384 /// adjusted to accommodate the arguments for the tailcall. 4385 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4386 unsigned ParamSize) { 4387 4388 if (!isTailCall) return 0; 4389 4390 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4391 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4392 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4393 // Remember only if the new adjustment is bigger. 4394 if (SPDiff < FI->getTailCallSPDelta()) 4395 FI->setTailCallSPDelta(SPDiff); 4396 4397 return SPDiff; 4398 } 4399 4400 static bool isFunctionGlobalAddress(SDValue Callee); 4401 4402 static bool 4403 callsShareTOCBase(const Function *Caller, SDValue Callee, 4404 const TargetMachine &TM) { 4405 // If !G, Callee can be an external symbol. 4406 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4407 if (!G) 4408 return false; 4409 4410 // The medium and large code models are expected to provide a sufficiently 4411 // large TOC to provide all data addressing needs of a module with a 4412 // single TOC. Since each module will be addressed with a single TOC then we 4413 // only need to check that caller and callee don't cross dso boundaries. 4414 if (CodeModel::Medium == TM.getCodeModel() || 4415 CodeModel::Large == TM.getCodeModel()) 4416 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4417 4418 // Otherwise we need to ensure callee and caller are in the same section, 4419 // since the linker may allocate multiple TOCs, and we don't know which 4420 // sections will belong to the same TOC base. 4421 4422 const GlobalValue *GV = G->getGlobal(); 4423 if (!GV->isStrongDefinitionForLinker()) 4424 return false; 4425 4426 // Any explicitly-specified sections and section prefixes must also match. 4427 // Also, if we're using -ffunction-sections, then each function is always in 4428 // a different section (the same is true for COMDAT functions). 4429 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4430 GV->getSection() != Caller->getSection()) 4431 return false; 4432 if (const auto *F = dyn_cast<Function>(GV)) { 4433 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4434 return false; 4435 } 4436 4437 // If the callee might be interposed, then we can't assume the ultimate call 4438 // target will be in the same section. Even in cases where we can assume that 4439 // interposition won't happen, in any case where the linker might insert a 4440 // stub to allow for interposition, we must generate code as though 4441 // interposition might occur. To understand why this matters, consider a 4442 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4443 // in the same section, but a is in a different module (i.e. has a different 4444 // TOC base pointer). If the linker allows for interposition between b and c, 4445 // then it will generate a stub for the call edge between b and c which will 4446 // save the TOC pointer into the designated stack slot allocated by b. If we 4447 // return true here, and therefore allow a tail call between b and c, that 4448 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4449 // pointer into the stack slot allocated by a (where the a -> b stub saved 4450 // a's TOC base pointer). If we're not considering a tail call, but rather, 4451 // whether a nop is needed after the call instruction in b, because the linker 4452 // will insert a stub, it might complain about a missing nop if we omit it 4453 // (although many don't complain in this case). 4454 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4455 return false; 4456 4457 return true; 4458 } 4459 4460 static bool 4461 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4462 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4463 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4464 4465 const unsigned PtrByteSize = 8; 4466 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4467 4468 static const MCPhysReg GPR[] = { 4469 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4470 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4471 }; 4472 static const MCPhysReg VR[] = { 4473 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4474 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4475 }; 4476 4477 const unsigned NumGPRs = array_lengthof(GPR); 4478 const unsigned NumFPRs = 13; 4479 const unsigned NumVRs = array_lengthof(VR); 4480 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4481 4482 unsigned NumBytes = LinkageSize; 4483 unsigned AvailableFPRs = NumFPRs; 4484 unsigned AvailableVRs = NumVRs; 4485 4486 for (const ISD::OutputArg& Param : Outs) { 4487 if (Param.Flags.isNest()) continue; 4488 4489 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4490 PtrByteSize, LinkageSize, ParamAreaSize, 4491 NumBytes, AvailableFPRs, AvailableVRs, 4492 Subtarget.hasQPX())) 4493 return true; 4494 } 4495 return false; 4496 } 4497 4498 static bool 4499 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4500 if (CS.arg_size() != CallerFn->arg_size()) 4501 return false; 4502 4503 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4504 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4505 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4506 4507 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4508 const Value* CalleeArg = *CalleeArgIter; 4509 const Value* CallerArg = &(*CallerArgIter); 4510 if (CalleeArg == CallerArg) 4511 continue; 4512 4513 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4514 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4515 // } 4516 // 1st argument of callee is undef and has the same type as caller. 4517 if (CalleeArg->getType() == CallerArg->getType() && 4518 isa<UndefValue>(CalleeArg)) 4519 continue; 4520 4521 return false; 4522 } 4523 4524 return true; 4525 } 4526 4527 // Returns true if TCO is possible between the callers and callees 4528 // calling conventions. 4529 static bool 4530 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4531 CallingConv::ID CalleeCC) { 4532 // Tail calls are possible with fastcc and ccc. 4533 auto isTailCallableCC = [] (CallingConv::ID CC){ 4534 return CC == CallingConv::C || CC == CallingConv::Fast; 4535 }; 4536 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4537 return false; 4538 4539 // We can safely tail call both fastcc and ccc callees from a c calling 4540 // convention caller. If the caller is fastcc, we may have less stack space 4541 // than a non-fastcc caller with the same signature so disable tail-calls in 4542 // that case. 4543 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4544 } 4545 4546 bool 4547 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4548 SDValue Callee, 4549 CallingConv::ID CalleeCC, 4550 ImmutableCallSite CS, 4551 bool isVarArg, 4552 const SmallVectorImpl<ISD::OutputArg> &Outs, 4553 const SmallVectorImpl<ISD::InputArg> &Ins, 4554 SelectionDAG& DAG) const { 4555 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4556 4557 if (DisableSCO && !TailCallOpt) return false; 4558 4559 // Variadic argument functions are not supported. 4560 if (isVarArg) return false; 4561 4562 auto &Caller = DAG.getMachineFunction().getFunction(); 4563 // Check that the calling conventions are compatible for tco. 4564 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4565 return false; 4566 4567 // Caller contains any byval parameter is not supported. 4568 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4569 return false; 4570 4571 // Callee contains any byval parameter is not supported, too. 4572 // Note: This is a quick work around, because in some cases, e.g. 4573 // caller's stack size > callee's stack size, we are still able to apply 4574 // sibling call optimization. For example, gcc is able to do SCO for caller1 4575 // in the following example, but not for caller2. 4576 // struct test { 4577 // long int a; 4578 // char ary[56]; 4579 // } gTest; 4580 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4581 // b->a = v.a; 4582 // return 0; 4583 // } 4584 // void caller1(struct test a, struct test c, struct test *b) { 4585 // callee(gTest, b); } 4586 // void caller2(struct test *b) { callee(gTest, b); } 4587 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4588 return false; 4589 4590 // If callee and caller use different calling conventions, we cannot pass 4591 // parameters on stack since offsets for the parameter area may be different. 4592 if (Caller.getCallingConv() != CalleeCC && 4593 needStackSlotPassParameters(Subtarget, Outs)) 4594 return false; 4595 4596 // No TCO/SCO on indirect call because Caller have to restore its TOC 4597 if (!isFunctionGlobalAddress(Callee) && 4598 !isa<ExternalSymbolSDNode>(Callee)) 4599 return false; 4600 4601 // If the caller and callee potentially have different TOC bases then we 4602 // cannot tail call since we need to restore the TOC pointer after the call. 4603 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4604 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4605 return false; 4606 4607 // TCO allows altering callee ABI, so we don't have to check further. 4608 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4609 return true; 4610 4611 if (DisableSCO) return false; 4612 4613 // If callee use the same argument list that caller is using, then we can 4614 // apply SCO on this case. If it is not, then we need to check if callee needs 4615 // stack for passing arguments. 4616 if (!hasSameArgumentList(&Caller, CS) && 4617 needStackSlotPassParameters(Subtarget, Outs)) { 4618 return false; 4619 } 4620 4621 return true; 4622 } 4623 4624 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4625 /// for tail call optimization. Targets which want to do tail call 4626 /// optimization should implement this function. 4627 bool 4628 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4629 CallingConv::ID CalleeCC, 4630 bool isVarArg, 4631 const SmallVectorImpl<ISD::InputArg> &Ins, 4632 SelectionDAG& DAG) const { 4633 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4634 return false; 4635 4636 // Variable argument functions are not supported. 4637 if (isVarArg) 4638 return false; 4639 4640 MachineFunction &MF = DAG.getMachineFunction(); 4641 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4642 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4643 // Functions containing by val parameters are not supported. 4644 for (unsigned i = 0; i != Ins.size(); i++) { 4645 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4646 if (Flags.isByVal()) return false; 4647 } 4648 4649 // Non-PIC/GOT tail calls are supported. 4650 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4651 return true; 4652 4653 // At the moment we can only do local tail calls (in same module, hidden 4654 // or protected) if we are generating PIC. 4655 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4656 return G->getGlobal()->hasHiddenVisibility() 4657 || G->getGlobal()->hasProtectedVisibility(); 4658 } 4659 4660 return false; 4661 } 4662 4663 /// isCallCompatibleAddress - Return the immediate to use if the specified 4664 /// 32-bit value is representable in the immediate field of a BxA instruction. 4665 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4666 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4667 if (!C) return nullptr; 4668 4669 int Addr = C->getZExtValue(); 4670 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4671 SignExtend32<26>(Addr) != Addr) 4672 return nullptr; // Top 6 bits have to be sext of immediate. 4673 4674 return DAG 4675 .getConstant( 4676 (int)C->getZExtValue() >> 2, SDLoc(Op), 4677 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4678 .getNode(); 4679 } 4680 4681 namespace { 4682 4683 struct TailCallArgumentInfo { 4684 SDValue Arg; 4685 SDValue FrameIdxOp; 4686 int FrameIdx = 0; 4687 4688 TailCallArgumentInfo() = default; 4689 }; 4690 4691 } // end anonymous namespace 4692 4693 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4694 static void StoreTailCallArgumentsToStackSlot( 4695 SelectionDAG &DAG, SDValue Chain, 4696 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4697 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4698 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4699 SDValue Arg = TailCallArgs[i].Arg; 4700 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4701 int FI = TailCallArgs[i].FrameIdx; 4702 // Store relative to framepointer. 4703 MemOpChains.push_back(DAG.getStore( 4704 Chain, dl, Arg, FIN, 4705 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4706 } 4707 } 4708 4709 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4710 /// the appropriate stack slot for the tail call optimized function call. 4711 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4712 SDValue OldRetAddr, SDValue OldFP, 4713 int SPDiff, const SDLoc &dl) { 4714 if (SPDiff) { 4715 // Calculate the new stack slot for the return address. 4716 MachineFunction &MF = DAG.getMachineFunction(); 4717 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4718 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4719 bool isPPC64 = Subtarget.isPPC64(); 4720 int SlotSize = isPPC64 ? 8 : 4; 4721 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4722 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4723 NewRetAddrLoc, true); 4724 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4725 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4726 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4727 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4728 4729 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4730 // slot as the FP is never overwritten. 4731 if (Subtarget.isDarwinABI()) { 4732 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4733 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4734 true); 4735 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4736 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4737 MachinePointerInfo::getFixedStack( 4738 DAG.getMachineFunction(), NewFPIdx)); 4739 } 4740 } 4741 return Chain; 4742 } 4743 4744 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4745 /// the position of the argument. 4746 static void 4747 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4748 SDValue Arg, int SPDiff, unsigned ArgOffset, 4749 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4750 int Offset = ArgOffset + SPDiff; 4751 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4752 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4753 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4754 SDValue FIN = DAG.getFrameIndex(FI, VT); 4755 TailCallArgumentInfo Info; 4756 Info.Arg = Arg; 4757 Info.FrameIdxOp = FIN; 4758 Info.FrameIdx = FI; 4759 TailCallArguments.push_back(Info); 4760 } 4761 4762 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4763 /// stack slot. Returns the chain as result and the loaded frame pointers in 4764 /// LROpOut/FPOpout. Used when tail calling. 4765 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4766 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4767 SDValue &FPOpOut, const SDLoc &dl) const { 4768 if (SPDiff) { 4769 // Load the LR and FP stack slot for later adjusting. 4770 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4771 LROpOut = getReturnAddrFrameIndex(DAG); 4772 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4773 Chain = SDValue(LROpOut.getNode(), 1); 4774 4775 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4776 // slot as the FP is never overwritten. 4777 if (Subtarget.isDarwinABI()) { 4778 FPOpOut = getFramePointerFrameIndex(DAG); 4779 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4780 Chain = SDValue(FPOpOut.getNode(), 1); 4781 } 4782 } 4783 return Chain; 4784 } 4785 4786 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4787 /// by "Src" to address "Dst" of size "Size". Alignment information is 4788 /// specified by the specific parameter attribute. The copy will be passed as 4789 /// a byval function parameter. 4790 /// Sometimes what we are copying is the end of a larger object, the part that 4791 /// does not fit in registers. 4792 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4793 SDValue Chain, ISD::ArgFlagsTy Flags, 4794 SelectionDAG &DAG, const SDLoc &dl) { 4795 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4796 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4797 false, false, false, MachinePointerInfo(), 4798 MachinePointerInfo()); 4799 } 4800 4801 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4802 /// tail calls. 4803 static void LowerMemOpCallTo( 4804 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4805 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4806 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4807 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4808 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4809 if (!isTailCall) { 4810 if (isVector) { 4811 SDValue StackPtr; 4812 if (isPPC64) 4813 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4814 else 4815 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4816 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4817 DAG.getConstant(ArgOffset, dl, PtrVT)); 4818 } 4819 MemOpChains.push_back( 4820 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4821 // Calculate and remember argument location. 4822 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4823 TailCallArguments); 4824 } 4825 4826 static void 4827 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4828 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4829 SDValue FPOp, 4830 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4831 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4832 // might overwrite each other in case of tail call optimization. 4833 SmallVector<SDValue, 8> MemOpChains2; 4834 // Do not flag preceding copytoreg stuff together with the following stuff. 4835 InFlag = SDValue(); 4836 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4837 MemOpChains2, dl); 4838 if (!MemOpChains2.empty()) 4839 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4840 4841 // Store the return address to the appropriate stack slot. 4842 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4843 4844 // Emit callseq_end just before tailcall node. 4845 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4846 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4847 InFlag = Chain.getValue(1); 4848 } 4849 4850 // Is this global address that of a function that can be called by name? (as 4851 // opposed to something that must hold a descriptor for an indirect call). 4852 static bool isFunctionGlobalAddress(SDValue Callee) { 4853 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4854 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4855 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4856 return false; 4857 4858 return G->getGlobal()->getValueType()->isFunctionTy(); 4859 } 4860 4861 return false; 4862 } 4863 4864 static unsigned 4865 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4866 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4867 bool isPatchPoint, bool hasNest, 4868 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4869 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4870 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4871 bool isPPC64 = Subtarget.isPPC64(); 4872 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4873 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4874 4875 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4876 NodeTys.push_back(MVT::Other); // Returns a chain 4877 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4878 4879 unsigned CallOpc = PPCISD::CALL; 4880 4881 bool needIndirectCall = true; 4882 if (!isSVR4ABI || !isPPC64) 4883 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4884 // If this is an absolute destination address, use the munged value. 4885 Callee = SDValue(Dest, 0); 4886 needIndirectCall = false; 4887 } 4888 4889 // PC-relative references to external symbols should go through $stub, unless 4890 // we're building with the leopard linker or later, which automatically 4891 // synthesizes these stubs. 4892 const TargetMachine &TM = DAG.getTarget(); 4893 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4894 const GlobalValue *GV = nullptr; 4895 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4896 GV = G->getGlobal(); 4897 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4898 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4899 4900 if (isFunctionGlobalAddress(Callee)) { 4901 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4902 // A call to a TLS address is actually an indirect call to a 4903 // thread-specific pointer. 4904 unsigned OpFlags = 0; 4905 if (UsePlt) 4906 OpFlags = PPCII::MO_PLT; 4907 4908 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4909 // every direct call is) turn it into a TargetGlobalAddress / 4910 // TargetExternalSymbol node so that legalize doesn't hack it. 4911 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4912 Callee.getValueType(), 0, OpFlags); 4913 needIndirectCall = false; 4914 } 4915 4916 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4917 unsigned char OpFlags = 0; 4918 4919 if (UsePlt) 4920 OpFlags = PPCII::MO_PLT; 4921 4922 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4923 OpFlags); 4924 needIndirectCall = false; 4925 } 4926 4927 if (isPatchPoint) { 4928 // We'll form an invalid direct call when lowering a patchpoint; the full 4929 // sequence for an indirect call is complicated, and many of the 4930 // instructions introduced might have side effects (and, thus, can't be 4931 // removed later). The call itself will be removed as soon as the 4932 // argument/return lowering is complete, so the fact that it has the wrong 4933 // kind of operands should not really matter. 4934 needIndirectCall = false; 4935 } 4936 4937 if (needIndirectCall) { 4938 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4939 // to do the call, we can't use PPCISD::CALL. 4940 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4941 4942 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4943 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4944 // entry point, but to the function descriptor (the function entry point 4945 // address is part of the function descriptor though). 4946 // The function descriptor is a three doubleword structure with the 4947 // following fields: function entry point, TOC base address and 4948 // environment pointer. 4949 // Thus for a call through a function pointer, the following actions need 4950 // to be performed: 4951 // 1. Save the TOC of the caller in the TOC save area of its stack 4952 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4953 // 2. Load the address of the function entry point from the function 4954 // descriptor. 4955 // 3. Load the TOC of the callee from the function descriptor into r2. 4956 // 4. Load the environment pointer from the function descriptor into 4957 // r11. 4958 // 5. Branch to the function entry point address. 4959 // 6. On return of the callee, the TOC of the caller needs to be 4960 // restored (this is done in FinishCall()). 4961 // 4962 // The loads are scheduled at the beginning of the call sequence, and the 4963 // register copies are flagged together to ensure that no other 4964 // operations can be scheduled in between. E.g. without flagging the 4965 // copies together, a TOC access in the caller could be scheduled between 4966 // the assignment of the callee TOC and the branch to the callee, which 4967 // results in the TOC access going through the TOC of the callee instead 4968 // of going through the TOC of the caller, which leads to incorrect code. 4969 4970 // Load the address of the function entry point from the function 4971 // descriptor. 4972 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4973 if (LDChain.getValueType() == MVT::Glue) 4974 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4975 4976 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4977 ? (MachineMemOperand::MODereferenceable | 4978 MachineMemOperand::MOInvariant) 4979 : MachineMemOperand::MONone; 4980 4981 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4982 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4983 /* Alignment = */ 8, MMOFlags); 4984 4985 // Load environment pointer into r11. 4986 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4987 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4988 SDValue LoadEnvPtr = 4989 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4990 /* Alignment = */ 8, MMOFlags); 4991 4992 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4993 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4994 SDValue TOCPtr = 4995 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4996 /* Alignment = */ 8, MMOFlags); 4997 4998 setUsesTOCBasePtr(DAG); 4999 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5000 InFlag); 5001 Chain = TOCVal.getValue(0); 5002 InFlag = TOCVal.getValue(1); 5003 5004 // If the function call has an explicit 'nest' parameter, it takes the 5005 // place of the environment pointer. 5006 if (!hasNest) { 5007 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5008 InFlag); 5009 5010 Chain = EnvVal.getValue(0); 5011 InFlag = EnvVal.getValue(1); 5012 } 5013 5014 MTCTROps[0] = Chain; 5015 MTCTROps[1] = LoadFuncPtr; 5016 MTCTROps[2] = InFlag; 5017 } 5018 5019 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5020 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5021 InFlag = Chain.getValue(1); 5022 5023 NodeTys.clear(); 5024 NodeTys.push_back(MVT::Other); 5025 NodeTys.push_back(MVT::Glue); 5026 Ops.push_back(Chain); 5027 CallOpc = PPCISD::BCTRL; 5028 Callee.setNode(nullptr); 5029 // Add use of X11 (holding environment pointer) 5030 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5031 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5032 // Add CTR register as callee so a bctr can be emitted later. 5033 if (isTailCall) 5034 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5035 } 5036 5037 // If this is a direct call, pass the chain and the callee. 5038 if (Callee.getNode()) { 5039 Ops.push_back(Chain); 5040 Ops.push_back(Callee); 5041 } 5042 // If this is a tail call add stack pointer delta. 5043 if (isTailCall) 5044 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5045 5046 // Add argument registers to the end of the list so that they are known live 5047 // into the call. 5048 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5049 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5050 RegsToPass[i].second.getValueType())); 5051 5052 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5053 // into the call. 5054 // We do need to reserve X2 to appease the verifier for the PATCHPOINT. 5055 if (isSVR4ABI && isPPC64) { 5056 setUsesTOCBasePtr(DAG); 5057 5058 // We cannot add X2 as an operand here for PATCHPOINT, because there is no 5059 // way to mark dependencies as implicit here. We will add the X2 dependency 5060 // in EmitInstrWithCustomInserter. 5061 if (!isPatchPoint) 5062 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5063 } 5064 5065 return CallOpc; 5066 } 5067 5068 SDValue PPCTargetLowering::LowerCallResult( 5069 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5070 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5071 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5072 SmallVector<CCValAssign, 16> RVLocs; 5073 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5074 *DAG.getContext()); 5075 5076 CCRetInfo.AnalyzeCallResult( 5077 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5078 ? RetCC_PPC_Cold 5079 : RetCC_PPC); 5080 5081 // Copy all of the result registers out of their specified physreg. 5082 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5083 CCValAssign &VA = RVLocs[i]; 5084 assert(VA.isRegLoc() && "Can only return in registers!"); 5085 5086 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5087 VA.getLocReg(), VA.getLocVT(), InFlag); 5088 Chain = Val.getValue(1); 5089 InFlag = Val.getValue(2); 5090 5091 switch (VA.getLocInfo()) { 5092 default: llvm_unreachable("Unknown loc info!"); 5093 case CCValAssign::Full: break; 5094 case CCValAssign::AExt: 5095 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5096 break; 5097 case CCValAssign::ZExt: 5098 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5099 DAG.getValueType(VA.getValVT())); 5100 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5101 break; 5102 case CCValAssign::SExt: 5103 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5104 DAG.getValueType(VA.getValVT())); 5105 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5106 break; 5107 } 5108 5109 InVals.push_back(Val); 5110 } 5111 5112 return Chain; 5113 } 5114 5115 SDValue PPCTargetLowering::FinishCall( 5116 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5117 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5118 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5119 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5120 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5121 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5122 std::vector<EVT> NodeTys; 5123 SmallVector<SDValue, 8> Ops; 5124 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5125 SPDiff, isTailCall, isPatchPoint, hasNest, 5126 RegsToPass, Ops, NodeTys, CS, Subtarget); 5127 5128 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5129 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5130 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5131 5132 // When performing tail call optimization the callee pops its arguments off 5133 // the stack. Account for this here so these bytes can be pushed back on in 5134 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5135 int BytesCalleePops = 5136 (CallConv == CallingConv::Fast && 5137 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5138 5139 // Add a register mask operand representing the call-preserved registers. 5140 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5141 const uint32_t *Mask = 5142 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5143 assert(Mask && "Missing call preserved mask for calling convention"); 5144 Ops.push_back(DAG.getRegisterMask(Mask)); 5145 5146 if (InFlag.getNode()) 5147 Ops.push_back(InFlag); 5148 5149 // Emit tail call. 5150 if (isTailCall) { 5151 assert(((Callee.getOpcode() == ISD::Register && 5152 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5153 Callee.getOpcode() == ISD::TargetExternalSymbol || 5154 Callee.getOpcode() == ISD::TargetGlobalAddress || 5155 isa<ConstantSDNode>(Callee)) && 5156 "Expecting an global address, external symbol, absolute value or register"); 5157 5158 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5159 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5160 } 5161 5162 // Add a NOP immediately after the branch instruction when using the 64-bit 5163 // SVR4 ABI. At link time, if caller and callee are in a different module and 5164 // thus have a different TOC, the call will be replaced with a call to a stub 5165 // function which saves the current TOC, loads the TOC of the callee and 5166 // branches to the callee. The NOP will be replaced with a load instruction 5167 // which restores the TOC of the caller from the TOC save slot of the current 5168 // stack frame. If caller and callee belong to the same module (and have the 5169 // same TOC), the NOP will remain unchanged. 5170 5171 MachineFunction &MF = DAG.getMachineFunction(); 5172 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5173 !isPatchPoint) { 5174 if (CallOpc == PPCISD::BCTRL) { 5175 // This is a call through a function pointer. 5176 // Restore the caller TOC from the save area into R2. 5177 // See PrepareCall() for more information about calls through function 5178 // pointers in the 64-bit SVR4 ABI. 5179 // We are using a target-specific load with r2 hard coded, because the 5180 // result of a target-independent load would never go directly into r2, 5181 // since r2 is a reserved register (which prevents the register allocator 5182 // from allocating it), resulting in an additional register being 5183 // allocated and an unnecessary move instruction being generated. 5184 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5185 5186 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5187 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5188 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5189 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5190 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5191 5192 // The address needs to go after the chain input but before the flag (or 5193 // any other variadic arguments). 5194 Ops.insert(std::next(Ops.begin()), AddTOC); 5195 } else if (CallOpc == PPCISD::CALL && 5196 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5197 // Otherwise insert NOP for non-local calls. 5198 CallOpc = PPCISD::CALL_NOP; 5199 } 5200 } 5201 5202 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5203 InFlag = Chain.getValue(1); 5204 5205 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5206 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5207 InFlag, dl); 5208 if (!Ins.empty()) 5209 InFlag = Chain.getValue(1); 5210 5211 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5212 Ins, dl, DAG, InVals); 5213 } 5214 5215 SDValue 5216 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5217 SmallVectorImpl<SDValue> &InVals) const { 5218 SelectionDAG &DAG = CLI.DAG; 5219 SDLoc &dl = CLI.DL; 5220 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5221 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5222 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5223 SDValue Chain = CLI.Chain; 5224 SDValue Callee = CLI.Callee; 5225 bool &isTailCall = CLI.IsTailCall; 5226 CallingConv::ID CallConv = CLI.CallConv; 5227 bool isVarArg = CLI.IsVarArg; 5228 bool isPatchPoint = CLI.IsPatchPoint; 5229 ImmutableCallSite CS = CLI.CS; 5230 5231 if (isTailCall) { 5232 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5233 isTailCall = false; 5234 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5235 isTailCall = 5236 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5237 isVarArg, Outs, Ins, DAG); 5238 else 5239 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5240 Ins, DAG); 5241 if (isTailCall) { 5242 ++NumTailCalls; 5243 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5244 ++NumSiblingCalls; 5245 5246 assert(isa<GlobalAddressSDNode>(Callee) && 5247 "Callee should be an llvm::Function object."); 5248 LLVM_DEBUG( 5249 const GlobalValue *GV = 5250 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5251 const unsigned Width = 5252 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5253 dbgs() << "TCO caller: " 5254 << left_justify(DAG.getMachineFunction().getName(), Width) 5255 << ", callee linkage: " << GV->getVisibility() << ", " 5256 << GV->getLinkage() << "\n"); 5257 } 5258 } 5259 5260 if (!isTailCall && CS && CS.isMustTailCall()) 5261 report_fatal_error("failed to perform tail call elimination on a call " 5262 "site marked musttail"); 5263 5264 // When long calls (i.e. indirect calls) are always used, calls are always 5265 // made via function pointer. If we have a function name, first translate it 5266 // into a pointer. 5267 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5268 !isTailCall) 5269 Callee = LowerGlobalAddress(Callee, DAG); 5270 5271 if (Subtarget.isSVR4ABI()) { 5272 if (Subtarget.isPPC64()) 5273 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5274 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5275 dl, DAG, InVals, CS); 5276 else 5277 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5278 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5279 dl, DAG, InVals, CS); 5280 } 5281 5282 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5283 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5284 dl, DAG, InVals, CS); 5285 } 5286 5287 SDValue PPCTargetLowering::LowerCall_32SVR4( 5288 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5289 bool isTailCall, bool isPatchPoint, 5290 const SmallVectorImpl<ISD::OutputArg> &Outs, 5291 const SmallVectorImpl<SDValue> &OutVals, 5292 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5293 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5294 ImmutableCallSite CS) const { 5295 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5296 // of the 32-bit SVR4 ABI stack frame layout. 5297 5298 assert((CallConv == CallingConv::C || 5299 CallConv == CallingConv::Cold || 5300 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5301 5302 unsigned PtrByteSize = 4; 5303 5304 MachineFunction &MF = DAG.getMachineFunction(); 5305 5306 // Mark this function as potentially containing a function that contains a 5307 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5308 // and restoring the callers stack pointer in this functions epilog. This is 5309 // done because by tail calling the called function might overwrite the value 5310 // in this function's (MF) stack pointer stack slot 0(SP). 5311 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5312 CallConv == CallingConv::Fast) 5313 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5314 5315 // Count how many bytes are to be pushed on the stack, including the linkage 5316 // area, parameter list area and the part of the local variable space which 5317 // contains copies of aggregates which are passed by value. 5318 5319 // Assign locations to all of the outgoing arguments. 5320 SmallVector<CCValAssign, 16> ArgLocs; 5321 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5322 5323 // Reserve space for the linkage area on the stack. 5324 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5325 PtrByteSize); 5326 if (useSoftFloat()) 5327 CCInfo.PreAnalyzeCallOperands(Outs); 5328 5329 if (isVarArg) { 5330 // Handle fixed and variable vector arguments differently. 5331 // Fixed vector arguments go into registers as long as registers are 5332 // available. Variable vector arguments always go into memory. 5333 unsigned NumArgs = Outs.size(); 5334 5335 for (unsigned i = 0; i != NumArgs; ++i) { 5336 MVT ArgVT = Outs[i].VT; 5337 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5338 bool Result; 5339 5340 if (Outs[i].IsFixed) { 5341 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5342 CCInfo); 5343 } else { 5344 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5345 ArgFlags, CCInfo); 5346 } 5347 5348 if (Result) { 5349 #ifndef NDEBUG 5350 errs() << "Call operand #" << i << " has unhandled type " 5351 << EVT(ArgVT).getEVTString() << "\n"; 5352 #endif 5353 llvm_unreachable(nullptr); 5354 } 5355 } 5356 } else { 5357 // All arguments are treated the same. 5358 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5359 } 5360 CCInfo.clearWasPPCF128(); 5361 5362 // Assign locations to all of the outgoing aggregate by value arguments. 5363 SmallVector<CCValAssign, 16> ByValArgLocs; 5364 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5365 5366 // Reserve stack space for the allocations in CCInfo. 5367 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5368 5369 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5370 5371 // Size of the linkage area, parameter list area and the part of the local 5372 // space variable where copies of aggregates which are passed by value are 5373 // stored. 5374 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5375 5376 // Calculate by how many bytes the stack has to be adjusted in case of tail 5377 // call optimization. 5378 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5379 5380 // Adjust the stack pointer for the new arguments... 5381 // These operations are automatically eliminated by the prolog/epilog pass 5382 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5383 SDValue CallSeqStart = Chain; 5384 5385 // Load the return address and frame pointer so it can be moved somewhere else 5386 // later. 5387 SDValue LROp, FPOp; 5388 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5389 5390 // Set up a copy of the stack pointer for use loading and storing any 5391 // arguments that may not fit in the registers available for argument 5392 // passing. 5393 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5394 5395 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5396 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5397 SmallVector<SDValue, 8> MemOpChains; 5398 5399 bool seenFloatArg = false; 5400 // Walk the register/memloc assignments, inserting copies/loads. 5401 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5402 i != e; 5403 ++i) { 5404 CCValAssign &VA = ArgLocs[i]; 5405 SDValue Arg = OutVals[i]; 5406 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5407 5408 if (Flags.isByVal()) { 5409 // Argument is an aggregate which is passed by value, thus we need to 5410 // create a copy of it in the local variable space of the current stack 5411 // frame (which is the stack frame of the caller) and pass the address of 5412 // this copy to the callee. 5413 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5414 CCValAssign &ByValVA = ByValArgLocs[j++]; 5415 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5416 5417 // Memory reserved in the local variable space of the callers stack frame. 5418 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5419 5420 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5421 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5422 StackPtr, PtrOff); 5423 5424 // Create a copy of the argument in the local area of the current 5425 // stack frame. 5426 SDValue MemcpyCall = 5427 CreateCopyOfByValArgument(Arg, PtrOff, 5428 CallSeqStart.getNode()->getOperand(0), 5429 Flags, DAG, dl); 5430 5431 // This must go outside the CALLSEQ_START..END. 5432 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5433 SDLoc(MemcpyCall)); 5434 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5435 NewCallSeqStart.getNode()); 5436 Chain = CallSeqStart = NewCallSeqStart; 5437 5438 // Pass the address of the aggregate copy on the stack either in a 5439 // physical register or in the parameter list area of the current stack 5440 // frame to the callee. 5441 Arg = PtrOff; 5442 } 5443 5444 // When useCRBits() is true, there can be i1 arguments. 5445 // It is because getRegisterType(MVT::i1) => MVT::i1, 5446 // and for other integer types getRegisterType() => MVT::i32. 5447 // Extend i1 and ensure callee will get i32. 5448 if (Arg.getValueType() == MVT::i1) 5449 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5450 dl, MVT::i32, Arg); 5451 5452 if (VA.isRegLoc()) { 5453 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5454 // Put argument in a physical register. 5455 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5456 } else { 5457 // Put argument in the parameter list area of the current stack frame. 5458 assert(VA.isMemLoc()); 5459 unsigned LocMemOffset = VA.getLocMemOffset(); 5460 5461 if (!isTailCall) { 5462 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5463 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5464 StackPtr, PtrOff); 5465 5466 MemOpChains.push_back( 5467 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5468 } else { 5469 // Calculate and remember argument location. 5470 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5471 TailCallArguments); 5472 } 5473 } 5474 } 5475 5476 if (!MemOpChains.empty()) 5477 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5478 5479 // Build a sequence of copy-to-reg nodes chained together with token chain 5480 // and flag operands which copy the outgoing args into the appropriate regs. 5481 SDValue InFlag; 5482 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5483 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5484 RegsToPass[i].second, InFlag); 5485 InFlag = Chain.getValue(1); 5486 } 5487 5488 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5489 // registers. 5490 if (isVarArg) { 5491 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5492 SDValue Ops[] = { Chain, InFlag }; 5493 5494 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5495 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5496 5497 InFlag = Chain.getValue(1); 5498 } 5499 5500 if (isTailCall) 5501 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5502 TailCallArguments); 5503 5504 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5505 /* unused except on PPC64 ELFv1 */ false, DAG, 5506 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5507 NumBytes, Ins, InVals, CS); 5508 } 5509 5510 // Copy an argument into memory, being careful to do this outside the 5511 // call sequence for the call to which the argument belongs. 5512 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5513 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5514 SelectionDAG &DAG, const SDLoc &dl) const { 5515 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5516 CallSeqStart.getNode()->getOperand(0), 5517 Flags, DAG, dl); 5518 // The MEMCPY must go outside the CALLSEQ_START..END. 5519 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5520 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5521 SDLoc(MemcpyCall)); 5522 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5523 NewCallSeqStart.getNode()); 5524 return NewCallSeqStart; 5525 } 5526 5527 SDValue PPCTargetLowering::LowerCall_64SVR4( 5528 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5529 bool isTailCall, bool isPatchPoint, 5530 const SmallVectorImpl<ISD::OutputArg> &Outs, 5531 const SmallVectorImpl<SDValue> &OutVals, 5532 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5533 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5534 ImmutableCallSite CS) const { 5535 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5536 bool isLittleEndian = Subtarget.isLittleEndian(); 5537 unsigned NumOps = Outs.size(); 5538 bool hasNest = false; 5539 bool IsSibCall = false; 5540 5541 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5542 unsigned PtrByteSize = 8; 5543 5544 MachineFunction &MF = DAG.getMachineFunction(); 5545 5546 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5547 IsSibCall = true; 5548 5549 // Mark this function as potentially containing a function that contains a 5550 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5551 // and restoring the callers stack pointer in this functions epilog. This is 5552 // done because by tail calling the called function might overwrite the value 5553 // in this function's (MF) stack pointer stack slot 0(SP). 5554 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5555 CallConv == CallingConv::Fast) 5556 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5557 5558 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5559 "fastcc not supported on varargs functions"); 5560 5561 // Count how many bytes are to be pushed on the stack, including the linkage 5562 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5563 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5564 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5565 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5566 unsigned NumBytes = LinkageSize; 5567 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5568 unsigned &QFPR_idx = FPR_idx; 5569 5570 static const MCPhysReg GPR[] = { 5571 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5572 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5573 }; 5574 static const MCPhysReg VR[] = { 5575 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5576 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5577 }; 5578 5579 const unsigned NumGPRs = array_lengthof(GPR); 5580 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5581 const unsigned NumVRs = array_lengthof(VR); 5582 const unsigned NumQFPRs = NumFPRs; 5583 5584 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5585 // can be passed to the callee in registers. 5586 // For the fast calling convention, there is another check below. 5587 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5588 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5589 if (!HasParameterArea) { 5590 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5591 unsigned AvailableFPRs = NumFPRs; 5592 unsigned AvailableVRs = NumVRs; 5593 unsigned NumBytesTmp = NumBytes; 5594 for (unsigned i = 0; i != NumOps; ++i) { 5595 if (Outs[i].Flags.isNest()) continue; 5596 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5597 PtrByteSize, LinkageSize, ParamAreaSize, 5598 NumBytesTmp, AvailableFPRs, AvailableVRs, 5599 Subtarget.hasQPX())) 5600 HasParameterArea = true; 5601 } 5602 } 5603 5604 // When using the fast calling convention, we don't provide backing for 5605 // arguments that will be in registers. 5606 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5607 5608 // Avoid allocating parameter area for fastcc functions if all the arguments 5609 // can be passed in the registers. 5610 if (CallConv == CallingConv::Fast) 5611 HasParameterArea = false; 5612 5613 // Add up all the space actually used. 5614 for (unsigned i = 0; i != NumOps; ++i) { 5615 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5616 EVT ArgVT = Outs[i].VT; 5617 EVT OrigVT = Outs[i].ArgVT; 5618 5619 if (Flags.isNest()) 5620 continue; 5621 5622 if (CallConv == CallingConv::Fast) { 5623 if (Flags.isByVal()) { 5624 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5625 if (NumGPRsUsed > NumGPRs) 5626 HasParameterArea = true; 5627 } else { 5628 switch (ArgVT.getSimpleVT().SimpleTy) { 5629 default: llvm_unreachable("Unexpected ValueType for argument!"); 5630 case MVT::i1: 5631 case MVT::i32: 5632 case MVT::i64: 5633 if (++NumGPRsUsed <= NumGPRs) 5634 continue; 5635 break; 5636 case MVT::v4i32: 5637 case MVT::v8i16: 5638 case MVT::v16i8: 5639 case MVT::v2f64: 5640 case MVT::v2i64: 5641 case MVT::v1i128: 5642 case MVT::f128: 5643 if (++NumVRsUsed <= NumVRs) 5644 continue; 5645 break; 5646 case MVT::v4f32: 5647 // When using QPX, this is handled like a FP register, otherwise, it 5648 // is an Altivec register. 5649 if (Subtarget.hasQPX()) { 5650 if (++NumFPRsUsed <= NumFPRs) 5651 continue; 5652 } else { 5653 if (++NumVRsUsed <= NumVRs) 5654 continue; 5655 } 5656 break; 5657 case MVT::f32: 5658 case MVT::f64: 5659 case MVT::v4f64: // QPX 5660 case MVT::v4i1: // QPX 5661 if (++NumFPRsUsed <= NumFPRs) 5662 continue; 5663 break; 5664 } 5665 HasParameterArea = true; 5666 } 5667 } 5668 5669 /* Respect alignment of argument on the stack. */ 5670 unsigned Align = 5671 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5672 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5673 5674 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5675 if (Flags.isInConsecutiveRegsLast()) 5676 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5677 } 5678 5679 unsigned NumBytesActuallyUsed = NumBytes; 5680 5681 // In the old ELFv1 ABI, 5682 // the prolog code of the callee may store up to 8 GPR argument registers to 5683 // the stack, allowing va_start to index over them in memory if its varargs. 5684 // Because we cannot tell if this is needed on the caller side, we have to 5685 // conservatively assume that it is needed. As such, make sure we have at 5686 // least enough stack space for the caller to store the 8 GPRs. 5687 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5688 // really requires memory operands, e.g. a vararg function. 5689 if (HasParameterArea) 5690 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5691 else 5692 NumBytes = LinkageSize; 5693 5694 // Tail call needs the stack to be aligned. 5695 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5696 CallConv == CallingConv::Fast) 5697 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5698 5699 int SPDiff = 0; 5700 5701 // Calculate by how many bytes the stack has to be adjusted in case of tail 5702 // call optimization. 5703 if (!IsSibCall) 5704 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5705 5706 // To protect arguments on the stack from being clobbered in a tail call, 5707 // force all the loads to happen before doing any other lowering. 5708 if (isTailCall) 5709 Chain = DAG.getStackArgumentTokenFactor(Chain); 5710 5711 // Adjust the stack pointer for the new arguments... 5712 // These operations are automatically eliminated by the prolog/epilog pass 5713 if (!IsSibCall) 5714 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5715 SDValue CallSeqStart = Chain; 5716 5717 // Load the return address and frame pointer so it can be move somewhere else 5718 // later. 5719 SDValue LROp, FPOp; 5720 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5721 5722 // Set up a copy of the stack pointer for use loading and storing any 5723 // arguments that may not fit in the registers available for argument 5724 // passing. 5725 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5726 5727 // Figure out which arguments are going to go in registers, and which in 5728 // memory. Also, if this is a vararg function, floating point operations 5729 // must be stored to our stack, and loaded into integer regs as well, if 5730 // any integer regs are available for argument passing. 5731 unsigned ArgOffset = LinkageSize; 5732 5733 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5734 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5735 5736 SmallVector<SDValue, 8> MemOpChains; 5737 for (unsigned i = 0; i != NumOps; ++i) { 5738 SDValue Arg = OutVals[i]; 5739 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5740 EVT ArgVT = Outs[i].VT; 5741 EVT OrigVT = Outs[i].ArgVT; 5742 5743 // PtrOff will be used to store the current argument to the stack if a 5744 // register cannot be found for it. 5745 SDValue PtrOff; 5746 5747 // We re-align the argument offset for each argument, except when using the 5748 // fast calling convention, when we need to make sure we do that only when 5749 // we'll actually use a stack slot. 5750 auto ComputePtrOff = [&]() { 5751 /* Respect alignment of argument on the stack. */ 5752 unsigned Align = 5753 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5754 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5755 5756 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5757 5758 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5759 }; 5760 5761 if (CallConv != CallingConv::Fast) { 5762 ComputePtrOff(); 5763 5764 /* Compute GPR index associated with argument offset. */ 5765 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5766 GPR_idx = std::min(GPR_idx, NumGPRs); 5767 } 5768 5769 // Promote integers to 64-bit values. 5770 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5771 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5772 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5773 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5774 } 5775 5776 // FIXME memcpy is used way more than necessary. Correctness first. 5777 // Note: "by value" is code for passing a structure by value, not 5778 // basic types. 5779 if (Flags.isByVal()) { 5780 // Note: Size includes alignment padding, so 5781 // struct x { short a; char b; } 5782 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5783 // These are the proper values we need for right-justifying the 5784 // aggregate in a parameter register. 5785 unsigned Size = Flags.getByValSize(); 5786 5787 // An empty aggregate parameter takes up no storage and no 5788 // registers. 5789 if (Size == 0) 5790 continue; 5791 5792 if (CallConv == CallingConv::Fast) 5793 ComputePtrOff(); 5794 5795 // All aggregates smaller than 8 bytes must be passed right-justified. 5796 if (Size==1 || Size==2 || Size==4) { 5797 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5798 if (GPR_idx != NumGPRs) { 5799 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5800 MachinePointerInfo(), VT); 5801 MemOpChains.push_back(Load.getValue(1)); 5802 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5803 5804 ArgOffset += PtrByteSize; 5805 continue; 5806 } 5807 } 5808 5809 if (GPR_idx == NumGPRs && Size < 8) { 5810 SDValue AddPtr = PtrOff; 5811 if (!isLittleEndian) { 5812 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5813 PtrOff.getValueType()); 5814 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5815 } 5816 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5817 CallSeqStart, 5818 Flags, DAG, dl); 5819 ArgOffset += PtrByteSize; 5820 continue; 5821 } 5822 // Copy entire object into memory. There are cases where gcc-generated 5823 // code assumes it is there, even if it could be put entirely into 5824 // registers. (This is not what the doc says.) 5825 5826 // FIXME: The above statement is likely due to a misunderstanding of the 5827 // documents. All arguments must be copied into the parameter area BY 5828 // THE CALLEE in the event that the callee takes the address of any 5829 // formal argument. That has not yet been implemented. However, it is 5830 // reasonable to use the stack area as a staging area for the register 5831 // load. 5832 5833 // Skip this for small aggregates, as we will use the same slot for a 5834 // right-justified copy, below. 5835 if (Size >= 8) 5836 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5837 CallSeqStart, 5838 Flags, DAG, dl); 5839 5840 // When a register is available, pass a small aggregate right-justified. 5841 if (Size < 8 && GPR_idx != NumGPRs) { 5842 // The easiest way to get this right-justified in a register 5843 // is to copy the structure into the rightmost portion of a 5844 // local variable slot, then load the whole slot into the 5845 // register. 5846 // FIXME: The memcpy seems to produce pretty awful code for 5847 // small aggregates, particularly for packed ones. 5848 // FIXME: It would be preferable to use the slot in the 5849 // parameter save area instead of a new local variable. 5850 SDValue AddPtr = PtrOff; 5851 if (!isLittleEndian) { 5852 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5853 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5854 } 5855 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5856 CallSeqStart, 5857 Flags, DAG, dl); 5858 5859 // Load the slot into the register. 5860 SDValue Load = 5861 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5862 MemOpChains.push_back(Load.getValue(1)); 5863 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5864 5865 // Done with this argument. 5866 ArgOffset += PtrByteSize; 5867 continue; 5868 } 5869 5870 // For aggregates larger than PtrByteSize, copy the pieces of the 5871 // object that fit into registers from the parameter save area. 5872 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5873 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5874 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5875 if (GPR_idx != NumGPRs) { 5876 SDValue Load = 5877 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5878 MemOpChains.push_back(Load.getValue(1)); 5879 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5880 ArgOffset += PtrByteSize; 5881 } else { 5882 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5883 break; 5884 } 5885 } 5886 continue; 5887 } 5888 5889 switch (Arg.getSimpleValueType().SimpleTy) { 5890 default: llvm_unreachable("Unexpected ValueType for argument!"); 5891 case MVT::i1: 5892 case MVT::i32: 5893 case MVT::i64: 5894 if (Flags.isNest()) { 5895 // The 'nest' parameter, if any, is passed in R11. 5896 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5897 hasNest = true; 5898 break; 5899 } 5900 5901 // These can be scalar arguments or elements of an integer array type 5902 // passed directly. Clang may use those instead of "byval" aggregate 5903 // types to avoid forcing arguments to memory unnecessarily. 5904 if (GPR_idx != NumGPRs) { 5905 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5906 } else { 5907 if (CallConv == CallingConv::Fast) 5908 ComputePtrOff(); 5909 5910 assert(HasParameterArea && 5911 "Parameter area must exist to pass an argument in memory."); 5912 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5913 true, isTailCall, false, MemOpChains, 5914 TailCallArguments, dl); 5915 if (CallConv == CallingConv::Fast) 5916 ArgOffset += PtrByteSize; 5917 } 5918 if (CallConv != CallingConv::Fast) 5919 ArgOffset += PtrByteSize; 5920 break; 5921 case MVT::f32: 5922 case MVT::f64: { 5923 // These can be scalar arguments or elements of a float array type 5924 // passed directly. The latter are used to implement ELFv2 homogenous 5925 // float aggregates. 5926 5927 // Named arguments go into FPRs first, and once they overflow, the 5928 // remaining arguments go into GPRs and then the parameter save area. 5929 // Unnamed arguments for vararg functions always go to GPRs and 5930 // then the parameter save area. For now, put all arguments to vararg 5931 // routines always in both locations (FPR *and* GPR or stack slot). 5932 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5933 bool NeededLoad = false; 5934 5935 // First load the argument into the next available FPR. 5936 if (FPR_idx != NumFPRs) 5937 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5938 5939 // Next, load the argument into GPR or stack slot if needed. 5940 if (!NeedGPROrStack) 5941 ; 5942 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5943 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5944 // once we support fp <-> gpr moves. 5945 5946 // In the non-vararg case, this can only ever happen in the 5947 // presence of f32 array types, since otherwise we never run 5948 // out of FPRs before running out of GPRs. 5949 SDValue ArgVal; 5950 5951 // Double values are always passed in a single GPR. 5952 if (Arg.getValueType() != MVT::f32) { 5953 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5954 5955 // Non-array float values are extended and passed in a GPR. 5956 } else if (!Flags.isInConsecutiveRegs()) { 5957 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5958 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5959 5960 // If we have an array of floats, we collect every odd element 5961 // together with its predecessor into one GPR. 5962 } else if (ArgOffset % PtrByteSize != 0) { 5963 SDValue Lo, Hi; 5964 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5965 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5966 if (!isLittleEndian) 5967 std::swap(Lo, Hi); 5968 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5969 5970 // The final element, if even, goes into the first half of a GPR. 5971 } else if (Flags.isInConsecutiveRegsLast()) { 5972 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5973 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5974 if (!isLittleEndian) 5975 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5976 DAG.getConstant(32, dl, MVT::i32)); 5977 5978 // Non-final even elements are skipped; they will be handled 5979 // together the with subsequent argument on the next go-around. 5980 } else 5981 ArgVal = SDValue(); 5982 5983 if (ArgVal.getNode()) 5984 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5985 } else { 5986 if (CallConv == CallingConv::Fast) 5987 ComputePtrOff(); 5988 5989 // Single-precision floating-point values are mapped to the 5990 // second (rightmost) word of the stack doubleword. 5991 if (Arg.getValueType() == MVT::f32 && 5992 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5993 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5994 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5995 } 5996 5997 assert(HasParameterArea && 5998 "Parameter area must exist to pass an argument in memory."); 5999 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6000 true, isTailCall, false, MemOpChains, 6001 TailCallArguments, dl); 6002 6003 NeededLoad = true; 6004 } 6005 // When passing an array of floats, the array occupies consecutive 6006 // space in the argument area; only round up to the next doubleword 6007 // at the end of the array. Otherwise, each float takes 8 bytes. 6008 if (CallConv != CallingConv::Fast || NeededLoad) { 6009 ArgOffset += (Arg.getValueType() == MVT::f32 && 6010 Flags.isInConsecutiveRegs()) ? 4 : 8; 6011 if (Flags.isInConsecutiveRegsLast()) 6012 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6013 } 6014 break; 6015 } 6016 case MVT::v4f32: 6017 case MVT::v4i32: 6018 case MVT::v8i16: 6019 case MVT::v16i8: 6020 case MVT::v2f64: 6021 case MVT::v2i64: 6022 case MVT::v1i128: 6023 case MVT::f128: 6024 if (!Subtarget.hasQPX()) { 6025 // These can be scalar arguments or elements of a vector array type 6026 // passed directly. The latter are used to implement ELFv2 homogenous 6027 // vector aggregates. 6028 6029 // For a varargs call, named arguments go into VRs or on the stack as 6030 // usual; unnamed arguments always go to the stack or the corresponding 6031 // GPRs when within range. For now, we always put the value in both 6032 // locations (or even all three). 6033 if (isVarArg) { 6034 assert(HasParameterArea && 6035 "Parameter area must exist if we have a varargs call."); 6036 // We could elide this store in the case where the object fits 6037 // entirely in R registers. Maybe later. 6038 SDValue Store = 6039 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6040 MemOpChains.push_back(Store); 6041 if (VR_idx != NumVRs) { 6042 SDValue Load = 6043 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6044 MemOpChains.push_back(Load.getValue(1)); 6045 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6046 } 6047 ArgOffset += 16; 6048 for (unsigned i=0; i<16; i+=PtrByteSize) { 6049 if (GPR_idx == NumGPRs) 6050 break; 6051 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6052 DAG.getConstant(i, dl, PtrVT)); 6053 SDValue Load = 6054 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6055 MemOpChains.push_back(Load.getValue(1)); 6056 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6057 } 6058 break; 6059 } 6060 6061 // Non-varargs Altivec params go into VRs or on the stack. 6062 if (VR_idx != NumVRs) { 6063 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6064 } else { 6065 if (CallConv == CallingConv::Fast) 6066 ComputePtrOff(); 6067 6068 assert(HasParameterArea && 6069 "Parameter area must exist to pass an argument in memory."); 6070 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6071 true, isTailCall, true, MemOpChains, 6072 TailCallArguments, dl); 6073 if (CallConv == CallingConv::Fast) 6074 ArgOffset += 16; 6075 } 6076 6077 if (CallConv != CallingConv::Fast) 6078 ArgOffset += 16; 6079 break; 6080 } // not QPX 6081 6082 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6083 "Invalid QPX parameter type"); 6084 6085 LLVM_FALLTHROUGH; 6086 case MVT::v4f64: 6087 case MVT::v4i1: { 6088 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6089 if (isVarArg) { 6090 assert(HasParameterArea && 6091 "Parameter area must exist if we have a varargs call."); 6092 // We could elide this store in the case where the object fits 6093 // entirely in R registers. Maybe later. 6094 SDValue Store = 6095 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6096 MemOpChains.push_back(Store); 6097 if (QFPR_idx != NumQFPRs) { 6098 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6099 PtrOff, MachinePointerInfo()); 6100 MemOpChains.push_back(Load.getValue(1)); 6101 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6102 } 6103 ArgOffset += (IsF32 ? 16 : 32); 6104 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6105 if (GPR_idx == NumGPRs) 6106 break; 6107 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6108 DAG.getConstant(i, dl, PtrVT)); 6109 SDValue Load = 6110 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6111 MemOpChains.push_back(Load.getValue(1)); 6112 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6113 } 6114 break; 6115 } 6116 6117 // Non-varargs QPX params go into registers or on the stack. 6118 if (QFPR_idx != NumQFPRs) { 6119 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6120 } else { 6121 if (CallConv == CallingConv::Fast) 6122 ComputePtrOff(); 6123 6124 assert(HasParameterArea && 6125 "Parameter area must exist to pass an argument in memory."); 6126 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6127 true, isTailCall, true, MemOpChains, 6128 TailCallArguments, dl); 6129 if (CallConv == CallingConv::Fast) 6130 ArgOffset += (IsF32 ? 16 : 32); 6131 } 6132 6133 if (CallConv != CallingConv::Fast) 6134 ArgOffset += (IsF32 ? 16 : 32); 6135 break; 6136 } 6137 } 6138 } 6139 6140 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6141 "mismatch in size of parameter area"); 6142 (void)NumBytesActuallyUsed; 6143 6144 if (!MemOpChains.empty()) 6145 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6146 6147 // Check if this is an indirect call (MTCTR/BCTRL). 6148 // See PrepareCall() for more information about calls through function 6149 // pointers in the 64-bit SVR4 ABI. 6150 if (!isTailCall && !isPatchPoint && 6151 !isFunctionGlobalAddress(Callee) && 6152 !isa<ExternalSymbolSDNode>(Callee)) { 6153 // Load r2 into a virtual register and store it to the TOC save area. 6154 setUsesTOCBasePtr(DAG); 6155 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6156 // TOC save area offset. 6157 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6158 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6159 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6160 Chain = DAG.getStore( 6161 Val.getValue(1), dl, Val, AddPtr, 6162 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6163 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6164 // This does not mean the MTCTR instruction must use R12; it's easier 6165 // to model this as an extra parameter, so do that. 6166 if (isELFv2ABI && !isPatchPoint) 6167 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6168 } 6169 6170 // Build a sequence of copy-to-reg nodes chained together with token chain 6171 // and flag operands which copy the outgoing args into the appropriate regs. 6172 SDValue InFlag; 6173 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6174 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6175 RegsToPass[i].second, InFlag); 6176 InFlag = Chain.getValue(1); 6177 } 6178 6179 if (isTailCall && !IsSibCall) 6180 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6181 TailCallArguments); 6182 6183 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6184 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6185 SPDiff, NumBytes, Ins, InVals, CS); 6186 } 6187 6188 SDValue PPCTargetLowering::LowerCall_Darwin( 6189 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6190 bool isTailCall, bool isPatchPoint, 6191 const SmallVectorImpl<ISD::OutputArg> &Outs, 6192 const SmallVectorImpl<SDValue> &OutVals, 6193 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6194 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6195 ImmutableCallSite CS) const { 6196 unsigned NumOps = Outs.size(); 6197 6198 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6199 bool isPPC64 = PtrVT == MVT::i64; 6200 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6201 6202 MachineFunction &MF = DAG.getMachineFunction(); 6203 6204 // Mark this function as potentially containing a function that contains a 6205 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6206 // and restoring the callers stack pointer in this functions epilog. This is 6207 // done because by tail calling the called function might overwrite the value 6208 // in this function's (MF) stack pointer stack slot 0(SP). 6209 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6210 CallConv == CallingConv::Fast) 6211 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6212 6213 // Count how many bytes are to be pushed on the stack, including the linkage 6214 // area, and parameter passing area. We start with 24/48 bytes, which is 6215 // prereserved space for [SP][CR][LR][3 x unused]. 6216 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6217 unsigned NumBytes = LinkageSize; 6218 6219 // Add up all the space actually used. 6220 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6221 // they all go in registers, but we must reserve stack space for them for 6222 // possible use by the caller. In varargs or 64-bit calls, parameters are 6223 // assigned stack space in order, with padding so Altivec parameters are 6224 // 16-byte aligned. 6225 unsigned nAltivecParamsAtEnd = 0; 6226 for (unsigned i = 0; i != NumOps; ++i) { 6227 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6228 EVT ArgVT = Outs[i].VT; 6229 // Varargs Altivec parameters are padded to a 16 byte boundary. 6230 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6231 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6232 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6233 if (!isVarArg && !isPPC64) { 6234 // Non-varargs Altivec parameters go after all the non-Altivec 6235 // parameters; handle those later so we know how much padding we need. 6236 nAltivecParamsAtEnd++; 6237 continue; 6238 } 6239 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6240 NumBytes = ((NumBytes+15)/16)*16; 6241 } 6242 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6243 } 6244 6245 // Allow for Altivec parameters at the end, if needed. 6246 if (nAltivecParamsAtEnd) { 6247 NumBytes = ((NumBytes+15)/16)*16; 6248 NumBytes += 16*nAltivecParamsAtEnd; 6249 } 6250 6251 // The prolog code of the callee may store up to 8 GPR argument registers to 6252 // the stack, allowing va_start to index over them in memory if its varargs. 6253 // Because we cannot tell if this is needed on the caller side, we have to 6254 // conservatively assume that it is needed. As such, make sure we have at 6255 // least enough stack space for the caller to store the 8 GPRs. 6256 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6257 6258 // Tail call needs the stack to be aligned. 6259 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6260 CallConv == CallingConv::Fast) 6261 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6262 6263 // Calculate by how many bytes the stack has to be adjusted in case of tail 6264 // call optimization. 6265 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6266 6267 // To protect arguments on the stack from being clobbered in a tail call, 6268 // force all the loads to happen before doing any other lowering. 6269 if (isTailCall) 6270 Chain = DAG.getStackArgumentTokenFactor(Chain); 6271 6272 // Adjust the stack pointer for the new arguments... 6273 // These operations are automatically eliminated by the prolog/epilog pass 6274 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6275 SDValue CallSeqStart = Chain; 6276 6277 // Load the return address and frame pointer so it can be move somewhere else 6278 // later. 6279 SDValue LROp, FPOp; 6280 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6281 6282 // Set up a copy of the stack pointer for use loading and storing any 6283 // arguments that may not fit in the registers available for argument 6284 // passing. 6285 SDValue StackPtr; 6286 if (isPPC64) 6287 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6288 else 6289 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6290 6291 // Figure out which arguments are going to go in registers, and which in 6292 // memory. Also, if this is a vararg function, floating point operations 6293 // must be stored to our stack, and loaded into integer regs as well, if 6294 // any integer regs are available for argument passing. 6295 unsigned ArgOffset = LinkageSize; 6296 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6297 6298 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6299 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6300 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6301 }; 6302 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6303 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6304 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6305 }; 6306 static const MCPhysReg VR[] = { 6307 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6308 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6309 }; 6310 const unsigned NumGPRs = array_lengthof(GPR_32); 6311 const unsigned NumFPRs = 13; 6312 const unsigned NumVRs = array_lengthof(VR); 6313 6314 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6315 6316 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6317 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6318 6319 SmallVector<SDValue, 8> MemOpChains; 6320 for (unsigned i = 0; i != NumOps; ++i) { 6321 SDValue Arg = OutVals[i]; 6322 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6323 6324 // PtrOff will be used to store the current argument to the stack if a 6325 // register cannot be found for it. 6326 SDValue PtrOff; 6327 6328 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6329 6330 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6331 6332 // On PPC64, promote integers to 64-bit values. 6333 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6334 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6335 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6336 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6337 } 6338 6339 // FIXME memcpy is used way more than necessary. Correctness first. 6340 // Note: "by value" is code for passing a structure by value, not 6341 // basic types. 6342 if (Flags.isByVal()) { 6343 unsigned Size = Flags.getByValSize(); 6344 // Very small objects are passed right-justified. Everything else is 6345 // passed left-justified. 6346 if (Size==1 || Size==2) { 6347 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6348 if (GPR_idx != NumGPRs) { 6349 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6350 MachinePointerInfo(), VT); 6351 MemOpChains.push_back(Load.getValue(1)); 6352 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6353 6354 ArgOffset += PtrByteSize; 6355 } else { 6356 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6357 PtrOff.getValueType()); 6358 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6359 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6360 CallSeqStart, 6361 Flags, DAG, dl); 6362 ArgOffset += PtrByteSize; 6363 } 6364 continue; 6365 } 6366 // Copy entire object into memory. There are cases where gcc-generated 6367 // code assumes it is there, even if it could be put entirely into 6368 // registers. (This is not what the doc says.) 6369 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6370 CallSeqStart, 6371 Flags, DAG, dl); 6372 6373 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6374 // copy the pieces of the object that fit into registers from the 6375 // parameter save area. 6376 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6377 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6378 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6379 if (GPR_idx != NumGPRs) { 6380 SDValue Load = 6381 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6382 MemOpChains.push_back(Load.getValue(1)); 6383 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6384 ArgOffset += PtrByteSize; 6385 } else { 6386 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6387 break; 6388 } 6389 } 6390 continue; 6391 } 6392 6393 switch (Arg.getSimpleValueType().SimpleTy) { 6394 default: llvm_unreachable("Unexpected ValueType for argument!"); 6395 case MVT::i1: 6396 case MVT::i32: 6397 case MVT::i64: 6398 if (GPR_idx != NumGPRs) { 6399 if (Arg.getValueType() == MVT::i1) 6400 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6401 6402 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6403 } else { 6404 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6405 isPPC64, isTailCall, false, MemOpChains, 6406 TailCallArguments, dl); 6407 } 6408 ArgOffset += PtrByteSize; 6409 break; 6410 case MVT::f32: 6411 case MVT::f64: 6412 if (FPR_idx != NumFPRs) { 6413 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6414 6415 if (isVarArg) { 6416 SDValue Store = 6417 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6418 MemOpChains.push_back(Store); 6419 6420 // Float varargs are always shadowed in available integer registers 6421 if (GPR_idx != NumGPRs) { 6422 SDValue Load = 6423 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6424 MemOpChains.push_back(Load.getValue(1)); 6425 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6426 } 6427 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6428 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6429 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6430 SDValue Load = 6431 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6432 MemOpChains.push_back(Load.getValue(1)); 6433 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6434 } 6435 } else { 6436 // If we have any FPRs remaining, we may also have GPRs remaining. 6437 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6438 // GPRs. 6439 if (GPR_idx != NumGPRs) 6440 ++GPR_idx; 6441 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6442 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6443 ++GPR_idx; 6444 } 6445 } else 6446 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6447 isPPC64, isTailCall, false, MemOpChains, 6448 TailCallArguments, dl); 6449 if (isPPC64) 6450 ArgOffset += 8; 6451 else 6452 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6453 break; 6454 case MVT::v4f32: 6455 case MVT::v4i32: 6456 case MVT::v8i16: 6457 case MVT::v16i8: 6458 if (isVarArg) { 6459 // These go aligned on the stack, or in the corresponding R registers 6460 // when within range. The Darwin PPC ABI doc claims they also go in 6461 // V registers; in fact gcc does this only for arguments that are 6462 // prototyped, not for those that match the ... We do it for all 6463 // arguments, seems to work. 6464 while (ArgOffset % 16 !=0) { 6465 ArgOffset += PtrByteSize; 6466 if (GPR_idx != NumGPRs) 6467 GPR_idx++; 6468 } 6469 // We could elide this store in the case where the object fits 6470 // entirely in R registers. Maybe later. 6471 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6472 DAG.getConstant(ArgOffset, dl, PtrVT)); 6473 SDValue Store = 6474 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6475 MemOpChains.push_back(Store); 6476 if (VR_idx != NumVRs) { 6477 SDValue Load = 6478 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6479 MemOpChains.push_back(Load.getValue(1)); 6480 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6481 } 6482 ArgOffset += 16; 6483 for (unsigned i=0; i<16; i+=PtrByteSize) { 6484 if (GPR_idx == NumGPRs) 6485 break; 6486 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6487 DAG.getConstant(i, dl, PtrVT)); 6488 SDValue Load = 6489 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6490 MemOpChains.push_back(Load.getValue(1)); 6491 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6492 } 6493 break; 6494 } 6495 6496 // Non-varargs Altivec params generally go in registers, but have 6497 // stack space allocated at the end. 6498 if (VR_idx != NumVRs) { 6499 // Doesn't have GPR space allocated. 6500 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6501 } else if (nAltivecParamsAtEnd==0) { 6502 // We are emitting Altivec params in order. 6503 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6504 isPPC64, isTailCall, true, MemOpChains, 6505 TailCallArguments, dl); 6506 ArgOffset += 16; 6507 } 6508 break; 6509 } 6510 } 6511 // If all Altivec parameters fit in registers, as they usually do, 6512 // they get stack space following the non-Altivec parameters. We 6513 // don't track this here because nobody below needs it. 6514 // If there are more Altivec parameters than fit in registers emit 6515 // the stores here. 6516 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6517 unsigned j = 0; 6518 // Offset is aligned; skip 1st 12 params which go in V registers. 6519 ArgOffset = ((ArgOffset+15)/16)*16; 6520 ArgOffset += 12*16; 6521 for (unsigned i = 0; i != NumOps; ++i) { 6522 SDValue Arg = OutVals[i]; 6523 EVT ArgType = Outs[i].VT; 6524 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6525 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6526 if (++j > NumVRs) { 6527 SDValue PtrOff; 6528 // We are emitting Altivec params in order. 6529 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6530 isPPC64, isTailCall, true, MemOpChains, 6531 TailCallArguments, dl); 6532 ArgOffset += 16; 6533 } 6534 } 6535 } 6536 } 6537 6538 if (!MemOpChains.empty()) 6539 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6540 6541 // On Darwin, R12 must contain the address of an indirect callee. This does 6542 // not mean the MTCTR instruction must use R12; it's easier to model this as 6543 // an extra parameter, so do that. 6544 if (!isTailCall && 6545 !isFunctionGlobalAddress(Callee) && 6546 !isa<ExternalSymbolSDNode>(Callee) && 6547 !isBLACompatibleAddress(Callee, DAG)) 6548 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6549 PPC::R12), Callee)); 6550 6551 // Build a sequence of copy-to-reg nodes chained together with token chain 6552 // and flag operands which copy the outgoing args into the appropriate regs. 6553 SDValue InFlag; 6554 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6555 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6556 RegsToPass[i].second, InFlag); 6557 InFlag = Chain.getValue(1); 6558 } 6559 6560 if (isTailCall) 6561 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6562 TailCallArguments); 6563 6564 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6565 /* unused except on PPC64 ELFv1 */ false, DAG, 6566 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6567 NumBytes, Ins, InVals, CS); 6568 } 6569 6570 bool 6571 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6572 MachineFunction &MF, bool isVarArg, 6573 const SmallVectorImpl<ISD::OutputArg> &Outs, 6574 LLVMContext &Context) const { 6575 SmallVector<CCValAssign, 16> RVLocs; 6576 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6577 return CCInfo.CheckReturn( 6578 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6579 ? RetCC_PPC_Cold 6580 : RetCC_PPC); 6581 } 6582 6583 SDValue 6584 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6585 bool isVarArg, 6586 const SmallVectorImpl<ISD::OutputArg> &Outs, 6587 const SmallVectorImpl<SDValue> &OutVals, 6588 const SDLoc &dl, SelectionDAG &DAG) const { 6589 SmallVector<CCValAssign, 16> RVLocs; 6590 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6591 *DAG.getContext()); 6592 CCInfo.AnalyzeReturn(Outs, 6593 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6594 ? RetCC_PPC_Cold 6595 : RetCC_PPC); 6596 6597 SDValue Flag; 6598 SmallVector<SDValue, 4> RetOps(1, Chain); 6599 6600 // Copy the result values into the output registers. 6601 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6602 CCValAssign &VA = RVLocs[i]; 6603 assert(VA.isRegLoc() && "Can only return in registers!"); 6604 6605 SDValue Arg = OutVals[i]; 6606 6607 switch (VA.getLocInfo()) { 6608 default: llvm_unreachable("Unknown loc info!"); 6609 case CCValAssign::Full: break; 6610 case CCValAssign::AExt: 6611 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6612 break; 6613 case CCValAssign::ZExt: 6614 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6615 break; 6616 case CCValAssign::SExt: 6617 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6618 break; 6619 } 6620 6621 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6622 Flag = Chain.getValue(1); 6623 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6624 } 6625 6626 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6627 const MCPhysReg *I = 6628 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6629 if (I) { 6630 for (; *I; ++I) { 6631 6632 if (PPC::G8RCRegClass.contains(*I)) 6633 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6634 else if (PPC::F8RCRegClass.contains(*I)) 6635 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6636 else if (PPC::CRRCRegClass.contains(*I)) 6637 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6638 else if (PPC::VRRCRegClass.contains(*I)) 6639 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6640 else 6641 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6642 } 6643 } 6644 6645 RetOps[0] = Chain; // Update chain. 6646 6647 // Add the flag if we have it. 6648 if (Flag.getNode()) 6649 RetOps.push_back(Flag); 6650 6651 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6652 } 6653 6654 SDValue 6655 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6656 SelectionDAG &DAG) const { 6657 SDLoc dl(Op); 6658 6659 // Get the correct type for integers. 6660 EVT IntVT = Op.getValueType(); 6661 6662 // Get the inputs. 6663 SDValue Chain = Op.getOperand(0); 6664 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6665 // Build a DYNAREAOFFSET node. 6666 SDValue Ops[2] = {Chain, FPSIdx}; 6667 SDVTList VTs = DAG.getVTList(IntVT); 6668 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6669 } 6670 6671 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6672 SelectionDAG &DAG) const { 6673 // When we pop the dynamic allocation we need to restore the SP link. 6674 SDLoc dl(Op); 6675 6676 // Get the correct type for pointers. 6677 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6678 6679 // Construct the stack pointer operand. 6680 bool isPPC64 = Subtarget.isPPC64(); 6681 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6682 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6683 6684 // Get the operands for the STACKRESTORE. 6685 SDValue Chain = Op.getOperand(0); 6686 SDValue SaveSP = Op.getOperand(1); 6687 6688 // Load the old link SP. 6689 SDValue LoadLinkSP = 6690 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6691 6692 // Restore the stack pointer. 6693 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6694 6695 // Store the old link SP. 6696 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6697 } 6698 6699 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6700 MachineFunction &MF = DAG.getMachineFunction(); 6701 bool isPPC64 = Subtarget.isPPC64(); 6702 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6703 6704 // Get current frame pointer save index. The users of this index will be 6705 // primarily DYNALLOC instructions. 6706 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6707 int RASI = FI->getReturnAddrSaveIndex(); 6708 6709 // If the frame pointer save index hasn't been defined yet. 6710 if (!RASI) { 6711 // Find out what the fix offset of the frame pointer save area. 6712 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6713 // Allocate the frame index for frame pointer save area. 6714 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6715 // Save the result. 6716 FI->setReturnAddrSaveIndex(RASI); 6717 } 6718 return DAG.getFrameIndex(RASI, PtrVT); 6719 } 6720 6721 SDValue 6722 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6723 MachineFunction &MF = DAG.getMachineFunction(); 6724 bool isPPC64 = Subtarget.isPPC64(); 6725 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6726 6727 // Get current frame pointer save index. The users of this index will be 6728 // primarily DYNALLOC instructions. 6729 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6730 int FPSI = FI->getFramePointerSaveIndex(); 6731 6732 // If the frame pointer save index hasn't been defined yet. 6733 if (!FPSI) { 6734 // Find out what the fix offset of the frame pointer save area. 6735 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6736 // Allocate the frame index for frame pointer save area. 6737 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6738 // Save the result. 6739 FI->setFramePointerSaveIndex(FPSI); 6740 } 6741 return DAG.getFrameIndex(FPSI, PtrVT); 6742 } 6743 6744 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6745 SelectionDAG &DAG) const { 6746 // Get the inputs. 6747 SDValue Chain = Op.getOperand(0); 6748 SDValue Size = Op.getOperand(1); 6749 SDLoc dl(Op); 6750 6751 // Get the correct type for pointers. 6752 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6753 // Negate the size. 6754 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6755 DAG.getConstant(0, dl, PtrVT), Size); 6756 // Construct a node for the frame pointer save index. 6757 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6758 // Build a DYNALLOC node. 6759 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6760 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6761 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6762 } 6763 6764 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6765 SelectionDAG &DAG) const { 6766 MachineFunction &MF = DAG.getMachineFunction(); 6767 6768 bool isPPC64 = Subtarget.isPPC64(); 6769 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6770 6771 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6772 return DAG.getFrameIndex(FI, PtrVT); 6773 } 6774 6775 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6776 SelectionDAG &DAG) const { 6777 SDLoc DL(Op); 6778 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6779 DAG.getVTList(MVT::i32, MVT::Other), 6780 Op.getOperand(0), Op.getOperand(1)); 6781 } 6782 6783 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6784 SelectionDAG &DAG) const { 6785 SDLoc DL(Op); 6786 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6787 Op.getOperand(0), Op.getOperand(1)); 6788 } 6789 6790 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6791 if (Op.getValueType().isVector()) 6792 return LowerVectorLoad(Op, DAG); 6793 6794 assert(Op.getValueType() == MVT::i1 && 6795 "Custom lowering only for i1 loads"); 6796 6797 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6798 6799 SDLoc dl(Op); 6800 LoadSDNode *LD = cast<LoadSDNode>(Op); 6801 6802 SDValue Chain = LD->getChain(); 6803 SDValue BasePtr = LD->getBasePtr(); 6804 MachineMemOperand *MMO = LD->getMemOperand(); 6805 6806 SDValue NewLD = 6807 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6808 BasePtr, MVT::i8, MMO); 6809 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6810 6811 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6812 return DAG.getMergeValues(Ops, dl); 6813 } 6814 6815 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6816 if (Op.getOperand(1).getValueType().isVector()) 6817 return LowerVectorStore(Op, DAG); 6818 6819 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6820 "Custom lowering only for i1 stores"); 6821 6822 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6823 6824 SDLoc dl(Op); 6825 StoreSDNode *ST = cast<StoreSDNode>(Op); 6826 6827 SDValue Chain = ST->getChain(); 6828 SDValue BasePtr = ST->getBasePtr(); 6829 SDValue Value = ST->getValue(); 6830 MachineMemOperand *MMO = ST->getMemOperand(); 6831 6832 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6833 Value); 6834 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6835 } 6836 6837 // FIXME: Remove this once the ANDI glue bug is fixed: 6838 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6839 assert(Op.getValueType() == MVT::i1 && 6840 "Custom lowering only for i1 results"); 6841 6842 SDLoc DL(Op); 6843 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6844 Op.getOperand(0)); 6845 } 6846 6847 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 6848 SelectionDAG &DAG) const { 6849 6850 // Implements a vector truncate that fits in a vector register as a shuffle. 6851 // We want to legalize vector truncates down to where the source fits in 6852 // a vector register (and target is therefore smaller than vector register 6853 // size). At that point legalization will try to custom lower the sub-legal 6854 // result and get here - where we can contain the truncate as a single target 6855 // operation. 6856 6857 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 6858 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 6859 // 6860 // We will implement it for big-endian ordering as this (where x denotes 6861 // undefined): 6862 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 6863 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 6864 // 6865 // The same operation in little-endian ordering will be: 6866 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 6867 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 6868 6869 assert(Op.getValueType().isVector() && "Vector type expected."); 6870 6871 SDLoc DL(Op); 6872 SDValue N1 = Op.getOperand(0); 6873 unsigned SrcSize = N1.getValueType().getSizeInBits(); 6874 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 6875 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 6876 6877 EVT TrgVT = Op.getValueType(); 6878 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 6879 EVT EltVT = TrgVT.getVectorElementType(); 6880 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 6881 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 6882 6883 // First list the elements we want to keep. 6884 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 6885 SmallVector<int, 16> ShuffV; 6886 if (Subtarget.isLittleEndian()) 6887 for (unsigned i = 0; i < TrgNumElts; ++i) 6888 ShuffV.push_back(i * SizeMult); 6889 else 6890 for (unsigned i = 1; i <= TrgNumElts; ++i) 6891 ShuffV.push_back(i * SizeMult - 1); 6892 6893 // Populate the remaining elements with undefs. 6894 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 6895 // ShuffV.push_back(i + WideNumElts); 6896 ShuffV.push_back(WideNumElts + 1); 6897 6898 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 6899 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 6900 } 6901 6902 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6903 /// possible. 6904 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6905 // Not FP? Not a fsel. 6906 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6907 !Op.getOperand(2).getValueType().isFloatingPoint()) 6908 return Op; 6909 6910 // We might be able to do better than this under some circumstances, but in 6911 // general, fsel-based lowering of select is a finite-math-only optimization. 6912 // For more information, see section F.3 of the 2.06 ISA specification. 6913 if (!DAG.getTarget().Options.NoInfsFPMath || 6914 !DAG.getTarget().Options.NoNaNsFPMath) 6915 return Op; 6916 // TODO: Propagate flags from the select rather than global settings. 6917 SDNodeFlags Flags; 6918 Flags.setNoInfs(true); 6919 Flags.setNoNaNs(true); 6920 6921 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6922 6923 EVT ResVT = Op.getValueType(); 6924 EVT CmpVT = Op.getOperand(0).getValueType(); 6925 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6926 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6927 SDLoc dl(Op); 6928 6929 // If the RHS of the comparison is a 0.0, we don't need to do the 6930 // subtraction at all. 6931 SDValue Sel1; 6932 if (isFloatingPointZero(RHS)) 6933 switch (CC) { 6934 default: break; // SETUO etc aren't handled by fsel. 6935 case ISD::SETNE: 6936 std::swap(TV, FV); 6937 LLVM_FALLTHROUGH; 6938 case ISD::SETEQ: 6939 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6940 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6941 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6942 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6943 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6944 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6945 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6946 case ISD::SETULT: 6947 case ISD::SETLT: 6948 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6949 LLVM_FALLTHROUGH; 6950 case ISD::SETOGE: 6951 case ISD::SETGE: 6952 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6953 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6954 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6955 case ISD::SETUGT: 6956 case ISD::SETGT: 6957 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6958 LLVM_FALLTHROUGH; 6959 case ISD::SETOLE: 6960 case ISD::SETLE: 6961 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6962 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6963 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6964 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6965 } 6966 6967 SDValue Cmp; 6968 switch (CC) { 6969 default: break; // SETUO etc aren't handled by fsel. 6970 case ISD::SETNE: 6971 std::swap(TV, FV); 6972 LLVM_FALLTHROUGH; 6973 case ISD::SETEQ: 6974 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6975 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6976 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6977 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6978 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6979 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6980 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6981 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6982 case ISD::SETULT: 6983 case ISD::SETLT: 6984 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6985 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6986 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6987 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6988 case ISD::SETOGE: 6989 case ISD::SETGE: 6990 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6991 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6992 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6993 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6994 case ISD::SETUGT: 6995 case ISD::SETGT: 6996 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6997 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6998 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6999 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7000 case ISD::SETOLE: 7001 case ISD::SETLE: 7002 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7003 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7004 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7005 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7006 } 7007 return Op; 7008 } 7009 7010 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7011 SelectionDAG &DAG, 7012 const SDLoc &dl) const { 7013 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7014 SDValue Src = Op.getOperand(0); 7015 if (Src.getValueType() == MVT::f32) 7016 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7017 7018 SDValue Tmp; 7019 switch (Op.getSimpleValueType().SimpleTy) { 7020 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7021 case MVT::i32: 7022 Tmp = DAG.getNode( 7023 Op.getOpcode() == ISD::FP_TO_SINT 7024 ? PPCISD::FCTIWZ 7025 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7026 dl, MVT::f64, Src); 7027 break; 7028 case MVT::i64: 7029 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7030 "i64 FP_TO_UINT is supported only with FPCVT"); 7031 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7032 PPCISD::FCTIDUZ, 7033 dl, MVT::f64, Src); 7034 break; 7035 } 7036 7037 // Convert the FP value to an int value through memory. 7038 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7039 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7040 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7041 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7042 MachinePointerInfo MPI = 7043 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7044 7045 // Emit a store to the stack slot. 7046 SDValue Chain; 7047 if (i32Stack) { 7048 MachineFunction &MF = DAG.getMachineFunction(); 7049 MachineMemOperand *MMO = 7050 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7051 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7052 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7053 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7054 } else 7055 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7056 7057 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7058 // add in a bias on big endian. 7059 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7060 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7061 DAG.getConstant(4, dl, FIPtr.getValueType())); 7062 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7063 } 7064 7065 RLI.Chain = Chain; 7066 RLI.Ptr = FIPtr; 7067 RLI.MPI = MPI; 7068 } 7069 7070 /// Custom lowers floating point to integer conversions to use 7071 /// the direct move instructions available in ISA 2.07 to avoid the 7072 /// need for load/store combinations. 7073 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7074 SelectionDAG &DAG, 7075 const SDLoc &dl) const { 7076 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7077 SDValue Src = Op.getOperand(0); 7078 7079 if (Src.getValueType() == MVT::f32) 7080 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7081 7082 SDValue Tmp; 7083 switch (Op.getSimpleValueType().SimpleTy) { 7084 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7085 case MVT::i32: 7086 Tmp = DAG.getNode( 7087 Op.getOpcode() == ISD::FP_TO_SINT 7088 ? PPCISD::FCTIWZ 7089 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7090 dl, MVT::f64, Src); 7091 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7092 break; 7093 case MVT::i64: 7094 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7095 "i64 FP_TO_UINT is supported only with FPCVT"); 7096 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7097 PPCISD::FCTIDUZ, 7098 dl, MVT::f64, Src); 7099 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7100 break; 7101 } 7102 return Tmp; 7103 } 7104 7105 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7106 const SDLoc &dl) const { 7107 7108 // FP to INT conversions are legal for f128. 7109 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7110 return Op; 7111 7112 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7113 // PPC (the libcall is not available). 7114 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7115 if (Op.getValueType() == MVT::i32) { 7116 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7117 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7118 MVT::f64, Op.getOperand(0), 7119 DAG.getIntPtrConstant(0, dl)); 7120 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7121 MVT::f64, Op.getOperand(0), 7122 DAG.getIntPtrConstant(1, dl)); 7123 7124 // Add the two halves of the long double in round-to-zero mode. 7125 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7126 7127 // Now use a smaller FP_TO_SINT. 7128 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7129 } 7130 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7131 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7132 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7133 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7134 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7135 // FIXME: generated code sucks. 7136 // TODO: Are there fast-math-flags to propagate to this FSUB? 7137 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7138 Op.getOperand(0), Tmp); 7139 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7140 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7141 DAG.getConstant(0x80000000, dl, MVT::i32)); 7142 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7143 Op.getOperand(0)); 7144 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7145 ISD::SETGE); 7146 } 7147 } 7148 7149 return SDValue(); 7150 } 7151 7152 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7153 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7154 7155 ReuseLoadInfo RLI; 7156 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7157 7158 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7159 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7160 } 7161 7162 // We're trying to insert a regular store, S, and then a load, L. If the 7163 // incoming value, O, is a load, we might just be able to have our load use the 7164 // address used by O. However, we don't know if anything else will store to 7165 // that address before we can load from it. To prevent this situation, we need 7166 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7167 // the same chain operand as O, we create a token factor from the chain results 7168 // of O and L, and we replace all uses of O's chain result with that token 7169 // factor (see spliceIntoChain below for this last part). 7170 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7171 ReuseLoadInfo &RLI, 7172 SelectionDAG &DAG, 7173 ISD::LoadExtType ET) const { 7174 SDLoc dl(Op); 7175 if (ET == ISD::NON_EXTLOAD && 7176 (Op.getOpcode() == ISD::FP_TO_UINT || 7177 Op.getOpcode() == ISD::FP_TO_SINT) && 7178 isOperationLegalOrCustom(Op.getOpcode(), 7179 Op.getOperand(0).getValueType())) { 7180 7181 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7182 return true; 7183 } 7184 7185 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7186 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7187 LD->isNonTemporal()) 7188 return false; 7189 if (LD->getMemoryVT() != MemVT) 7190 return false; 7191 7192 RLI.Ptr = LD->getBasePtr(); 7193 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7194 assert(LD->getAddressingMode() == ISD::PRE_INC && 7195 "Non-pre-inc AM on PPC?"); 7196 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7197 LD->getOffset()); 7198 } 7199 7200 RLI.Chain = LD->getChain(); 7201 RLI.MPI = LD->getPointerInfo(); 7202 RLI.IsDereferenceable = LD->isDereferenceable(); 7203 RLI.IsInvariant = LD->isInvariant(); 7204 RLI.Alignment = LD->getAlignment(); 7205 RLI.AAInfo = LD->getAAInfo(); 7206 RLI.Ranges = LD->getRanges(); 7207 7208 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7209 return true; 7210 } 7211 7212 // Given the head of the old chain, ResChain, insert a token factor containing 7213 // it and NewResChain, and make users of ResChain now be users of that token 7214 // factor. 7215 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7216 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7217 SDValue NewResChain, 7218 SelectionDAG &DAG) const { 7219 if (!ResChain) 7220 return; 7221 7222 SDLoc dl(NewResChain); 7223 7224 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7225 NewResChain, DAG.getUNDEF(MVT::Other)); 7226 assert(TF.getNode() != NewResChain.getNode() && 7227 "A new TF really is required here"); 7228 7229 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7230 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7231 } 7232 7233 /// Analyze profitability of direct move 7234 /// prefer float load to int load plus direct move 7235 /// when there is no integer use of int load 7236 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7237 SDNode *Origin = Op.getOperand(0).getNode(); 7238 if (Origin->getOpcode() != ISD::LOAD) 7239 return true; 7240 7241 // If there is no LXSIBZX/LXSIHZX, like Power8, 7242 // prefer direct move if the memory size is 1 or 2 bytes. 7243 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7244 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7245 return true; 7246 7247 for (SDNode::use_iterator UI = Origin->use_begin(), 7248 UE = Origin->use_end(); 7249 UI != UE; ++UI) { 7250 7251 // Only look at the users of the loaded value. 7252 if (UI.getUse().get().getResNo() != 0) 7253 continue; 7254 7255 if (UI->getOpcode() != ISD::SINT_TO_FP && 7256 UI->getOpcode() != ISD::UINT_TO_FP) 7257 return true; 7258 } 7259 7260 return false; 7261 } 7262 7263 /// Custom lowers integer to floating point conversions to use 7264 /// the direct move instructions available in ISA 2.07 to avoid the 7265 /// need for load/store combinations. 7266 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7267 SelectionDAG &DAG, 7268 const SDLoc &dl) const { 7269 assert((Op.getValueType() == MVT::f32 || 7270 Op.getValueType() == MVT::f64) && 7271 "Invalid floating point type as target of conversion"); 7272 assert(Subtarget.hasFPCVT() && 7273 "Int to FP conversions with direct moves require FPCVT"); 7274 SDValue FP; 7275 SDValue Src = Op.getOperand(0); 7276 bool SinglePrec = Op.getValueType() == MVT::f32; 7277 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7278 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7279 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7280 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7281 7282 if (WordInt) { 7283 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7284 dl, MVT::f64, Src); 7285 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7286 } 7287 else { 7288 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7289 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7290 } 7291 7292 return FP; 7293 } 7294 7295 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7296 7297 EVT VecVT = Vec.getValueType(); 7298 assert(VecVT.isVector() && "Expected a vector type."); 7299 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7300 7301 EVT EltVT = VecVT.getVectorElementType(); 7302 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7303 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7304 7305 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7306 SmallVector<SDValue, 16> Ops(NumConcat); 7307 Ops[0] = Vec; 7308 SDValue UndefVec = DAG.getUNDEF(VecVT); 7309 for (unsigned i = 1; i < NumConcat; ++i) 7310 Ops[i] = UndefVec; 7311 7312 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7313 } 7314 7315 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7316 const SDLoc &dl) const { 7317 7318 unsigned Opc = Op.getOpcode(); 7319 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7320 "Unexpected conversion type"); 7321 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7322 "Supports conversions to v2f64/v4f32 only."); 7323 7324 bool SignedConv = Opc == ISD::SINT_TO_FP; 7325 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7326 7327 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7328 EVT WideVT = Wide.getValueType(); 7329 unsigned WideNumElts = WideVT.getVectorNumElements(); 7330 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7331 7332 SmallVector<int, 16> ShuffV; 7333 for (unsigned i = 0; i < WideNumElts; ++i) 7334 ShuffV.push_back(i + WideNumElts); 7335 7336 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7337 int SaveElts = FourEltRes ? 4 : 2; 7338 if (Subtarget.isLittleEndian()) 7339 for (int i = 0; i < SaveElts; i++) 7340 ShuffV[i * Stride] = i; 7341 else 7342 for (int i = 1; i <= SaveElts; i++) 7343 ShuffV[i * Stride - 1] = i - 1; 7344 7345 SDValue ShuffleSrc2 = 7346 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7347 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7348 unsigned ExtendOp = 7349 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7350 7351 SDValue Extend; 7352 if (!Subtarget.hasP9Altivec() && SignedConv) { 7353 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7354 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7355 DAG.getValueType(Op.getOperand(0).getValueType())); 7356 } else 7357 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7358 7359 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7360 } 7361 7362 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7363 SelectionDAG &DAG) const { 7364 SDLoc dl(Op); 7365 7366 EVT InVT = Op.getOperand(0).getValueType(); 7367 EVT OutVT = Op.getValueType(); 7368 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7369 isOperationCustom(Op.getOpcode(), InVT)) 7370 return LowerINT_TO_FPVector(Op, DAG, dl); 7371 7372 // Conversions to f128 are legal. 7373 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7374 return Op; 7375 7376 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7377 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7378 return SDValue(); 7379 7380 SDValue Value = Op.getOperand(0); 7381 // The values are now known to be -1 (false) or 1 (true). To convert this 7382 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7383 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7384 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7385 7386 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7387 7388 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7389 7390 if (Op.getValueType() != MVT::v4f64) 7391 Value = DAG.getNode(ISD::FP_ROUND, dl, 7392 Op.getValueType(), Value, 7393 DAG.getIntPtrConstant(1, dl)); 7394 return Value; 7395 } 7396 7397 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7398 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7399 return SDValue(); 7400 7401 if (Op.getOperand(0).getValueType() == MVT::i1) 7402 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7403 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7404 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7405 7406 // If we have direct moves, we can do all the conversion, skip the store/load 7407 // however, without FPCVT we can't do most conversions. 7408 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7409 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7410 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7411 7412 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7413 "UINT_TO_FP is supported only with FPCVT"); 7414 7415 // If we have FCFIDS, then use it when converting to single-precision. 7416 // Otherwise, convert to double-precision and then round. 7417 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7418 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7419 : PPCISD::FCFIDS) 7420 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7421 : PPCISD::FCFID); 7422 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7423 ? MVT::f32 7424 : MVT::f64; 7425 7426 if (Op.getOperand(0).getValueType() == MVT::i64) { 7427 SDValue SINT = Op.getOperand(0); 7428 // When converting to single-precision, we actually need to convert 7429 // to double-precision first and then round to single-precision. 7430 // To avoid double-rounding effects during that operation, we have 7431 // to prepare the input operand. Bits that might be truncated when 7432 // converting to double-precision are replaced by a bit that won't 7433 // be lost at this stage, but is below the single-precision rounding 7434 // position. 7435 // 7436 // However, if -enable-unsafe-fp-math is in effect, accept double 7437 // rounding to avoid the extra overhead. 7438 if (Op.getValueType() == MVT::f32 && 7439 !Subtarget.hasFPCVT() && 7440 !DAG.getTarget().Options.UnsafeFPMath) { 7441 7442 // Twiddle input to make sure the low 11 bits are zero. (If this 7443 // is the case, we are guaranteed the value will fit into the 53 bit 7444 // mantissa of an IEEE double-precision value without rounding.) 7445 // If any of those low 11 bits were not zero originally, make sure 7446 // bit 12 (value 2048) is set instead, so that the final rounding 7447 // to single-precision gets the correct result. 7448 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7449 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7450 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7451 Round, DAG.getConstant(2047, dl, MVT::i64)); 7452 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7453 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7454 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7455 7456 // However, we cannot use that value unconditionally: if the magnitude 7457 // of the input value is small, the bit-twiddling we did above might 7458 // end up visibly changing the output. Fortunately, in that case, we 7459 // don't need to twiddle bits since the original input will convert 7460 // exactly to double-precision floating-point already. Therefore, 7461 // construct a conditional to use the original value if the top 11 7462 // bits are all sign-bit copies, and use the rounded value computed 7463 // above otherwise. 7464 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7465 SINT, DAG.getConstant(53, dl, MVT::i32)); 7466 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7467 Cond, DAG.getConstant(1, dl, MVT::i64)); 7468 Cond = DAG.getSetCC(dl, MVT::i32, 7469 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7470 7471 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7472 } 7473 7474 ReuseLoadInfo RLI; 7475 SDValue Bits; 7476 7477 MachineFunction &MF = DAG.getMachineFunction(); 7478 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7479 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7480 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7481 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7482 } else if (Subtarget.hasLFIWAX() && 7483 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7484 MachineMemOperand *MMO = 7485 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7486 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7487 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7488 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7489 DAG.getVTList(MVT::f64, MVT::Other), 7490 Ops, MVT::i32, MMO); 7491 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7492 } else if (Subtarget.hasFPCVT() && 7493 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7494 MachineMemOperand *MMO = 7495 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7496 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7497 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7498 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7499 DAG.getVTList(MVT::f64, MVT::Other), 7500 Ops, MVT::i32, MMO); 7501 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7502 } else if (((Subtarget.hasLFIWAX() && 7503 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7504 (Subtarget.hasFPCVT() && 7505 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7506 SINT.getOperand(0).getValueType() == MVT::i32) { 7507 MachineFrameInfo &MFI = MF.getFrameInfo(); 7508 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7509 7510 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7511 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7512 7513 SDValue Store = 7514 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7515 MachinePointerInfo::getFixedStack( 7516 DAG.getMachineFunction(), FrameIdx)); 7517 7518 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7519 "Expected an i32 store"); 7520 7521 RLI.Ptr = FIdx; 7522 RLI.Chain = Store; 7523 RLI.MPI = 7524 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7525 RLI.Alignment = 4; 7526 7527 MachineMemOperand *MMO = 7528 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7529 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7530 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7531 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7532 PPCISD::LFIWZX : PPCISD::LFIWAX, 7533 dl, DAG.getVTList(MVT::f64, MVT::Other), 7534 Ops, MVT::i32, MMO); 7535 } else 7536 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7537 7538 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7539 7540 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7541 FP = DAG.getNode(ISD::FP_ROUND, dl, 7542 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7543 return FP; 7544 } 7545 7546 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7547 "Unhandled INT_TO_FP type in custom expander!"); 7548 // Since we only generate this in 64-bit mode, we can take advantage of 7549 // 64-bit registers. In particular, sign extend the input value into the 7550 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7551 // then lfd it and fcfid it. 7552 MachineFunction &MF = DAG.getMachineFunction(); 7553 MachineFrameInfo &MFI = MF.getFrameInfo(); 7554 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7555 7556 SDValue Ld; 7557 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7558 ReuseLoadInfo RLI; 7559 bool ReusingLoad; 7560 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7561 DAG))) { 7562 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7563 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7564 7565 SDValue Store = 7566 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7567 MachinePointerInfo::getFixedStack( 7568 DAG.getMachineFunction(), FrameIdx)); 7569 7570 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7571 "Expected an i32 store"); 7572 7573 RLI.Ptr = FIdx; 7574 RLI.Chain = Store; 7575 RLI.MPI = 7576 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7577 RLI.Alignment = 4; 7578 } 7579 7580 MachineMemOperand *MMO = 7581 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7582 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7583 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7584 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7585 PPCISD::LFIWZX : PPCISD::LFIWAX, 7586 dl, DAG.getVTList(MVT::f64, MVT::Other), 7587 Ops, MVT::i32, MMO); 7588 if (ReusingLoad) 7589 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7590 } else { 7591 assert(Subtarget.isPPC64() && 7592 "i32->FP without LFIWAX supported only on PPC64"); 7593 7594 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7595 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7596 7597 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7598 Op.getOperand(0)); 7599 7600 // STD the extended value into the stack slot. 7601 SDValue Store = DAG.getStore( 7602 DAG.getEntryNode(), dl, Ext64, FIdx, 7603 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7604 7605 // Load the value as a double. 7606 Ld = DAG.getLoad( 7607 MVT::f64, dl, Store, FIdx, 7608 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7609 } 7610 7611 // FCFID it and return it. 7612 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7613 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7614 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7615 DAG.getIntPtrConstant(0, dl)); 7616 return FP; 7617 } 7618 7619 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7620 SelectionDAG &DAG) const { 7621 SDLoc dl(Op); 7622 /* 7623 The rounding mode is in bits 30:31 of FPSR, and has the following 7624 settings: 7625 00 Round to nearest 7626 01 Round to 0 7627 10 Round to +inf 7628 11 Round to -inf 7629 7630 FLT_ROUNDS, on the other hand, expects the following: 7631 -1 Undefined 7632 0 Round to 0 7633 1 Round to nearest 7634 2 Round to +inf 7635 3 Round to -inf 7636 7637 To perform the conversion, we do: 7638 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7639 */ 7640 7641 MachineFunction &MF = DAG.getMachineFunction(); 7642 EVT VT = Op.getValueType(); 7643 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7644 7645 // Save FP Control Word to register 7646 EVT NodeTys[] = { 7647 MVT::f64, // return register 7648 MVT::Glue // unused in this context 7649 }; 7650 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7651 7652 // Save FP register to stack slot 7653 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7654 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7655 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7656 MachinePointerInfo()); 7657 7658 // Load FP Control Word from low 32 bits of stack slot. 7659 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7660 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7661 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7662 7663 // Transform as necessary 7664 SDValue CWD1 = 7665 DAG.getNode(ISD::AND, dl, MVT::i32, 7666 CWD, DAG.getConstant(3, dl, MVT::i32)); 7667 SDValue CWD2 = 7668 DAG.getNode(ISD::SRL, dl, MVT::i32, 7669 DAG.getNode(ISD::AND, dl, MVT::i32, 7670 DAG.getNode(ISD::XOR, dl, MVT::i32, 7671 CWD, DAG.getConstant(3, dl, MVT::i32)), 7672 DAG.getConstant(3, dl, MVT::i32)), 7673 DAG.getConstant(1, dl, MVT::i32)); 7674 7675 SDValue RetVal = 7676 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7677 7678 return DAG.getNode((VT.getSizeInBits() < 16 ? 7679 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7680 } 7681 7682 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7683 EVT VT = Op.getValueType(); 7684 unsigned BitWidth = VT.getSizeInBits(); 7685 SDLoc dl(Op); 7686 assert(Op.getNumOperands() == 3 && 7687 VT == Op.getOperand(1).getValueType() && 7688 "Unexpected SHL!"); 7689 7690 // Expand into a bunch of logical ops. Note that these ops 7691 // depend on the PPC behavior for oversized shift amounts. 7692 SDValue Lo = Op.getOperand(0); 7693 SDValue Hi = Op.getOperand(1); 7694 SDValue Amt = Op.getOperand(2); 7695 EVT AmtVT = Amt.getValueType(); 7696 7697 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7698 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7699 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7700 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7701 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7702 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7703 DAG.getConstant(-BitWidth, dl, AmtVT)); 7704 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7705 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7706 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7707 SDValue OutOps[] = { OutLo, OutHi }; 7708 return DAG.getMergeValues(OutOps, dl); 7709 } 7710 7711 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7712 EVT VT = Op.getValueType(); 7713 SDLoc dl(Op); 7714 unsigned BitWidth = VT.getSizeInBits(); 7715 assert(Op.getNumOperands() == 3 && 7716 VT == Op.getOperand(1).getValueType() && 7717 "Unexpected SRL!"); 7718 7719 // Expand into a bunch of logical ops. Note that these ops 7720 // depend on the PPC behavior for oversized shift amounts. 7721 SDValue Lo = Op.getOperand(0); 7722 SDValue Hi = Op.getOperand(1); 7723 SDValue Amt = Op.getOperand(2); 7724 EVT AmtVT = Amt.getValueType(); 7725 7726 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7727 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7728 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7729 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7730 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7731 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7732 DAG.getConstant(-BitWidth, dl, AmtVT)); 7733 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7734 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7735 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7736 SDValue OutOps[] = { OutLo, OutHi }; 7737 return DAG.getMergeValues(OutOps, dl); 7738 } 7739 7740 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7741 SDLoc dl(Op); 7742 EVT VT = Op.getValueType(); 7743 unsigned BitWidth = VT.getSizeInBits(); 7744 assert(Op.getNumOperands() == 3 && 7745 VT == Op.getOperand(1).getValueType() && 7746 "Unexpected SRA!"); 7747 7748 // Expand into a bunch of logical ops, followed by a select_cc. 7749 SDValue Lo = Op.getOperand(0); 7750 SDValue Hi = Op.getOperand(1); 7751 SDValue Amt = Op.getOperand(2); 7752 EVT AmtVT = Amt.getValueType(); 7753 7754 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7755 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7756 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7757 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7758 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7759 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7760 DAG.getConstant(-BitWidth, dl, AmtVT)); 7761 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7762 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7763 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7764 Tmp4, Tmp6, ISD::SETLE); 7765 SDValue OutOps[] = { OutLo, OutHi }; 7766 return DAG.getMergeValues(OutOps, dl); 7767 } 7768 7769 //===----------------------------------------------------------------------===// 7770 // Vector related lowering. 7771 // 7772 7773 /// BuildSplatI - Build a canonical splati of Val with an element size of 7774 /// SplatSize. Cast the result to VT. 7775 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7776 SelectionDAG &DAG, const SDLoc &dl) { 7777 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7778 7779 static const MVT VTys[] = { // canonical VT to use for each size. 7780 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7781 }; 7782 7783 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7784 7785 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7786 if (Val == -1) 7787 SplatSize = 1; 7788 7789 EVT CanonicalVT = VTys[SplatSize-1]; 7790 7791 // Build a canonical splat for this value. 7792 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7793 } 7794 7795 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7796 /// specified intrinsic ID. 7797 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7798 const SDLoc &dl, EVT DestVT = MVT::Other) { 7799 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7800 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7801 DAG.getConstant(IID, dl, MVT::i32), Op); 7802 } 7803 7804 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7805 /// specified intrinsic ID. 7806 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7807 SelectionDAG &DAG, const SDLoc &dl, 7808 EVT DestVT = MVT::Other) { 7809 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7810 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7811 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7812 } 7813 7814 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7815 /// specified intrinsic ID. 7816 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7817 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7818 EVT DestVT = MVT::Other) { 7819 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7820 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7821 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7822 } 7823 7824 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7825 /// amount. The result has the specified value type. 7826 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7827 SelectionDAG &DAG, const SDLoc &dl) { 7828 // Force LHS/RHS to be the right type. 7829 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7830 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7831 7832 int Ops[16]; 7833 for (unsigned i = 0; i != 16; ++i) 7834 Ops[i] = i + Amt; 7835 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7836 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7837 } 7838 7839 /// Do we have an efficient pattern in a .td file for this node? 7840 /// 7841 /// \param V - pointer to the BuildVectorSDNode being matched 7842 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7843 /// 7844 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7845 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7846 /// the opposite is true (expansion is beneficial) are: 7847 /// - The node builds a vector out of integers that are not 32 or 64-bits 7848 /// - The node builds a vector out of constants 7849 /// - The node is a "load-and-splat" 7850 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7851 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7852 bool HasDirectMove, 7853 bool HasP8Vector) { 7854 EVT VecVT = V->getValueType(0); 7855 bool RightType = VecVT == MVT::v2f64 || 7856 (HasP8Vector && VecVT == MVT::v4f32) || 7857 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7858 if (!RightType) 7859 return false; 7860 7861 bool IsSplat = true; 7862 bool IsLoad = false; 7863 SDValue Op0 = V->getOperand(0); 7864 7865 // This function is called in a block that confirms the node is not a constant 7866 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7867 // different constants. 7868 if (V->isConstant()) 7869 return false; 7870 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7871 if (V->getOperand(i).isUndef()) 7872 return false; 7873 // We want to expand nodes that represent load-and-splat even if the 7874 // loaded value is a floating point truncation or conversion to int. 7875 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7876 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7877 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7878 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7879 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7880 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7881 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7882 IsLoad = true; 7883 // If the operands are different or the input is not a load and has more 7884 // uses than just this BV node, then it isn't a splat. 7885 if (V->getOperand(i) != Op0 || 7886 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7887 IsSplat = false; 7888 } 7889 return !(IsSplat && IsLoad); 7890 } 7891 7892 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7893 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7894 7895 SDLoc dl(Op); 7896 SDValue Op0 = Op->getOperand(0); 7897 7898 if (!EnableQuadPrecision || 7899 (Op.getValueType() != MVT::f128 ) || 7900 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7901 (Op0.getOperand(0).getValueType() != MVT::i64) || 7902 (Op0.getOperand(1).getValueType() != MVT::i64)) 7903 return SDValue(); 7904 7905 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7906 Op0.getOperand(1)); 7907 } 7908 7909 // If this is a case we can't handle, return null and let the default 7910 // expansion code take care of it. If we CAN select this case, and if it 7911 // selects to a single instruction, return Op. Otherwise, if we can codegen 7912 // this case more efficiently than a constant pool load, lower it to the 7913 // sequence of ops that should be used. 7914 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7915 SelectionDAG &DAG) const { 7916 SDLoc dl(Op); 7917 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7918 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7919 7920 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7921 // We first build an i32 vector, load it into a QPX register, 7922 // then convert it to a floating-point vector and compare it 7923 // to a zero vector to get the boolean result. 7924 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7925 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7926 MachinePointerInfo PtrInfo = 7927 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7928 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7929 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7930 7931 assert(BVN->getNumOperands() == 4 && 7932 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7933 7934 bool IsConst = true; 7935 for (unsigned i = 0; i < 4; ++i) { 7936 if (BVN->getOperand(i).isUndef()) continue; 7937 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7938 IsConst = false; 7939 break; 7940 } 7941 } 7942 7943 if (IsConst) { 7944 Constant *One = 7945 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7946 Constant *NegOne = 7947 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7948 7949 Constant *CV[4]; 7950 for (unsigned i = 0; i < 4; ++i) { 7951 if (BVN->getOperand(i).isUndef()) 7952 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7953 else if (isNullConstant(BVN->getOperand(i))) 7954 CV[i] = NegOne; 7955 else 7956 CV[i] = One; 7957 } 7958 7959 Constant *CP = ConstantVector::get(CV); 7960 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7961 16 /* alignment */); 7962 7963 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7964 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7965 return DAG.getMemIntrinsicNode( 7966 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7967 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7968 } 7969 7970 SmallVector<SDValue, 4> Stores; 7971 for (unsigned i = 0; i < 4; ++i) { 7972 if (BVN->getOperand(i).isUndef()) continue; 7973 7974 unsigned Offset = 4*i; 7975 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7976 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7977 7978 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7979 if (StoreSize > 4) { 7980 Stores.push_back( 7981 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7982 PtrInfo.getWithOffset(Offset), MVT::i32)); 7983 } else { 7984 SDValue StoreValue = BVN->getOperand(i); 7985 if (StoreSize < 4) 7986 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7987 7988 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7989 PtrInfo.getWithOffset(Offset))); 7990 } 7991 } 7992 7993 SDValue StoreChain; 7994 if (!Stores.empty()) 7995 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7996 else 7997 StoreChain = DAG.getEntryNode(); 7998 7999 // Now load from v4i32 into the QPX register; this will extend it to 8000 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8001 // is typed as v4f64 because the QPX register integer states are not 8002 // explicitly represented. 8003 8004 SDValue Ops[] = {StoreChain, 8005 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8006 FIdx}; 8007 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8008 8009 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8010 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8011 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8012 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8013 LoadedVect); 8014 8015 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8016 8017 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8018 } 8019 8020 // All other QPX vectors are handled by generic code. 8021 if (Subtarget.hasQPX()) 8022 return SDValue(); 8023 8024 // Check if this is a splat of a constant value. 8025 APInt APSplatBits, APSplatUndef; 8026 unsigned SplatBitSize; 8027 bool HasAnyUndefs; 8028 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8029 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8030 SplatBitSize > 32) { 8031 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8032 // lowered to VSX instructions under certain conditions. 8033 // Without VSX, there is no pattern more efficient than expanding the node. 8034 if (Subtarget.hasVSX() && 8035 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8036 Subtarget.hasP8Vector())) 8037 return Op; 8038 return SDValue(); 8039 } 8040 8041 unsigned SplatBits = APSplatBits.getZExtValue(); 8042 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8043 unsigned SplatSize = SplatBitSize / 8; 8044 8045 // First, handle single instruction cases. 8046 8047 // All zeros? 8048 if (SplatBits == 0) { 8049 // Canonicalize all zero vectors to be v4i32. 8050 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8051 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8052 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8053 } 8054 return Op; 8055 } 8056 8057 // We have XXSPLTIB for constant splats one byte wide 8058 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8059 // This is a splat of 1-byte elements with some elements potentially undef. 8060 // Rather than trying to match undef in the SDAG patterns, ensure that all 8061 // elements are the same constant. 8062 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8063 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8064 dl, MVT::i32)); 8065 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8066 if (Op.getValueType() != MVT::v16i8) 8067 return DAG.getBitcast(Op.getValueType(), NewBV); 8068 return NewBV; 8069 } 8070 8071 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8072 // detect that constant splats like v8i16: 0xABAB are really just splats 8073 // of a 1-byte constant. In this case, we need to convert the node to a 8074 // splat of v16i8 and a bitcast. 8075 if (Op.getValueType() != MVT::v16i8) 8076 return DAG.getBitcast(Op.getValueType(), 8077 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8078 8079 return Op; 8080 } 8081 8082 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8083 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8084 (32-SplatBitSize)); 8085 if (SextVal >= -16 && SextVal <= 15) 8086 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8087 8088 // Two instruction sequences. 8089 8090 // If this value is in the range [-32,30] and is even, use: 8091 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8092 // If this value is in the range [17,31] and is odd, use: 8093 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8094 // If this value is in the range [-31,-17] and is odd, use: 8095 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8096 // Note the last two are three-instruction sequences. 8097 if (SextVal >= -32 && SextVal <= 31) { 8098 // To avoid having these optimizations undone by constant folding, 8099 // we convert to a pseudo that will be expanded later into one of 8100 // the above forms. 8101 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8102 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8103 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8104 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8105 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8106 if (VT == Op.getValueType()) 8107 return RetVal; 8108 else 8109 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8110 } 8111 8112 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8113 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8114 // for fneg/fabs. 8115 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8116 // Make -1 and vspltisw -1: 8117 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8118 8119 // Make the VSLW intrinsic, computing 0x8000_0000. 8120 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8121 OnesV, DAG, dl); 8122 8123 // xor by OnesV to invert it. 8124 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8125 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8126 } 8127 8128 // Check to see if this is a wide variety of vsplti*, binop self cases. 8129 static const signed char SplatCsts[] = { 8130 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8131 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8132 }; 8133 8134 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8135 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8136 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8137 int i = SplatCsts[idx]; 8138 8139 // Figure out what shift amount will be used by altivec if shifted by i in 8140 // this splat size. 8141 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8142 8143 // vsplti + shl self. 8144 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8145 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8146 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8147 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8148 Intrinsic::ppc_altivec_vslw 8149 }; 8150 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8151 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8152 } 8153 8154 // vsplti + srl self. 8155 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8156 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8157 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8158 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8159 Intrinsic::ppc_altivec_vsrw 8160 }; 8161 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8162 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8163 } 8164 8165 // vsplti + sra self. 8166 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8167 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8168 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8169 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8170 Intrinsic::ppc_altivec_vsraw 8171 }; 8172 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8173 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8174 } 8175 8176 // vsplti + rol self. 8177 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8178 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8179 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8180 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8181 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8182 Intrinsic::ppc_altivec_vrlw 8183 }; 8184 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8185 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8186 } 8187 8188 // t = vsplti c, result = vsldoi t, t, 1 8189 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8190 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8191 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8192 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8193 } 8194 // t = vsplti c, result = vsldoi t, t, 2 8195 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8196 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8197 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8198 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8199 } 8200 // t = vsplti c, result = vsldoi t, t, 3 8201 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8202 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8203 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8204 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8205 } 8206 } 8207 8208 return SDValue(); 8209 } 8210 8211 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8212 /// the specified operations to build the shuffle. 8213 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8214 SDValue RHS, SelectionDAG &DAG, 8215 const SDLoc &dl) { 8216 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8217 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8218 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8219 8220 enum { 8221 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8222 OP_VMRGHW, 8223 OP_VMRGLW, 8224 OP_VSPLTISW0, 8225 OP_VSPLTISW1, 8226 OP_VSPLTISW2, 8227 OP_VSPLTISW3, 8228 OP_VSLDOI4, 8229 OP_VSLDOI8, 8230 OP_VSLDOI12 8231 }; 8232 8233 if (OpNum == OP_COPY) { 8234 if (LHSID == (1*9+2)*9+3) return LHS; 8235 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8236 return RHS; 8237 } 8238 8239 SDValue OpLHS, OpRHS; 8240 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8241 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8242 8243 int ShufIdxs[16]; 8244 switch (OpNum) { 8245 default: llvm_unreachable("Unknown i32 permute!"); 8246 case OP_VMRGHW: 8247 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8248 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8249 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8250 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8251 break; 8252 case OP_VMRGLW: 8253 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8254 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8255 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8256 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8257 break; 8258 case OP_VSPLTISW0: 8259 for (unsigned i = 0; i != 16; ++i) 8260 ShufIdxs[i] = (i&3)+0; 8261 break; 8262 case OP_VSPLTISW1: 8263 for (unsigned i = 0; i != 16; ++i) 8264 ShufIdxs[i] = (i&3)+4; 8265 break; 8266 case OP_VSPLTISW2: 8267 for (unsigned i = 0; i != 16; ++i) 8268 ShufIdxs[i] = (i&3)+8; 8269 break; 8270 case OP_VSPLTISW3: 8271 for (unsigned i = 0; i != 16; ++i) 8272 ShufIdxs[i] = (i&3)+12; 8273 break; 8274 case OP_VSLDOI4: 8275 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8276 case OP_VSLDOI8: 8277 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8278 case OP_VSLDOI12: 8279 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8280 } 8281 EVT VT = OpLHS.getValueType(); 8282 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8283 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8284 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8285 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8286 } 8287 8288 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8289 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8290 /// SDValue. 8291 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8292 SelectionDAG &DAG) const { 8293 const unsigned BytesInVector = 16; 8294 bool IsLE = Subtarget.isLittleEndian(); 8295 SDLoc dl(N); 8296 SDValue V1 = N->getOperand(0); 8297 SDValue V2 = N->getOperand(1); 8298 unsigned ShiftElts = 0, InsertAtByte = 0; 8299 bool Swap = false; 8300 8301 // Shifts required to get the byte we want at element 7. 8302 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8303 0, 15, 14, 13, 12, 11, 10, 9}; 8304 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8305 1, 2, 3, 4, 5, 6, 7, 8}; 8306 8307 ArrayRef<int> Mask = N->getMask(); 8308 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8309 8310 // For each mask element, find out if we're just inserting something 8311 // from V2 into V1 or vice versa. 8312 // Possible permutations inserting an element from V2 into V1: 8313 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8314 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8315 // ... 8316 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8317 // Inserting from V1 into V2 will be similar, except mask range will be 8318 // [16,31]. 8319 8320 bool FoundCandidate = false; 8321 // If both vector operands for the shuffle are the same vector, the mask 8322 // will contain only elements from the first one and the second one will be 8323 // undef. 8324 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8325 // Go through the mask of half-words to find an element that's being moved 8326 // from one vector to the other. 8327 for (unsigned i = 0; i < BytesInVector; ++i) { 8328 unsigned CurrentElement = Mask[i]; 8329 // If 2nd operand is undefined, we should only look for element 7 in the 8330 // Mask. 8331 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8332 continue; 8333 8334 bool OtherElementsInOrder = true; 8335 // Examine the other elements in the Mask to see if they're in original 8336 // order. 8337 for (unsigned j = 0; j < BytesInVector; ++j) { 8338 if (j == i) 8339 continue; 8340 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8341 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8342 // in which we always assume we're always picking from the 1st operand. 8343 int MaskOffset = 8344 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8345 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8346 OtherElementsInOrder = false; 8347 break; 8348 } 8349 } 8350 // If other elements are in original order, we record the number of shifts 8351 // we need to get the element we want into element 7. Also record which byte 8352 // in the vector we should insert into. 8353 if (OtherElementsInOrder) { 8354 // If 2nd operand is undefined, we assume no shifts and no swapping. 8355 if (V2.isUndef()) { 8356 ShiftElts = 0; 8357 Swap = false; 8358 } else { 8359 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8360 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8361 : BigEndianShifts[CurrentElement & 0xF]; 8362 Swap = CurrentElement < BytesInVector; 8363 } 8364 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8365 FoundCandidate = true; 8366 break; 8367 } 8368 } 8369 8370 if (!FoundCandidate) 8371 return SDValue(); 8372 8373 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8374 // optionally with VECSHL if shift is required. 8375 if (Swap) 8376 std::swap(V1, V2); 8377 if (V2.isUndef()) 8378 V2 = V1; 8379 if (ShiftElts) { 8380 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8381 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8382 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8383 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8384 } 8385 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8386 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8387 } 8388 8389 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8390 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8391 /// SDValue. 8392 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8393 SelectionDAG &DAG) const { 8394 const unsigned NumHalfWords = 8; 8395 const unsigned BytesInVector = NumHalfWords * 2; 8396 // Check that the shuffle is on half-words. 8397 if (!isNByteElemShuffleMask(N, 2, 1)) 8398 return SDValue(); 8399 8400 bool IsLE = Subtarget.isLittleEndian(); 8401 SDLoc dl(N); 8402 SDValue V1 = N->getOperand(0); 8403 SDValue V2 = N->getOperand(1); 8404 unsigned ShiftElts = 0, InsertAtByte = 0; 8405 bool Swap = false; 8406 8407 // Shifts required to get the half-word we want at element 3. 8408 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8409 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8410 8411 uint32_t Mask = 0; 8412 uint32_t OriginalOrderLow = 0x1234567; 8413 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8414 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8415 // 32-bit space, only need 4-bit nibbles per element. 8416 for (unsigned i = 0; i < NumHalfWords; ++i) { 8417 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8418 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8419 } 8420 8421 // For each mask element, find out if we're just inserting something 8422 // from V2 into V1 or vice versa. Possible permutations inserting an element 8423 // from V2 into V1: 8424 // X, 1, 2, 3, 4, 5, 6, 7 8425 // 0, X, 2, 3, 4, 5, 6, 7 8426 // 0, 1, X, 3, 4, 5, 6, 7 8427 // 0, 1, 2, X, 4, 5, 6, 7 8428 // 0, 1, 2, 3, X, 5, 6, 7 8429 // 0, 1, 2, 3, 4, X, 6, 7 8430 // 0, 1, 2, 3, 4, 5, X, 7 8431 // 0, 1, 2, 3, 4, 5, 6, X 8432 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8433 8434 bool FoundCandidate = false; 8435 // Go through the mask of half-words to find an element that's being moved 8436 // from one vector to the other. 8437 for (unsigned i = 0; i < NumHalfWords; ++i) { 8438 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8439 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8440 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8441 uint32_t TargetOrder = 0x0; 8442 8443 // If both vector operands for the shuffle are the same vector, the mask 8444 // will contain only elements from the first one and the second one will be 8445 // undef. 8446 if (V2.isUndef()) { 8447 ShiftElts = 0; 8448 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8449 TargetOrder = OriginalOrderLow; 8450 Swap = false; 8451 // Skip if not the correct element or mask of other elements don't equal 8452 // to our expected order. 8453 if (MaskOneElt == VINSERTHSrcElem && 8454 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8455 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8456 FoundCandidate = true; 8457 break; 8458 } 8459 } else { // If both operands are defined. 8460 // Target order is [8,15] if the current mask is between [0,7]. 8461 TargetOrder = 8462 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8463 // Skip if mask of other elements don't equal our expected order. 8464 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8465 // We only need the last 3 bits for the number of shifts. 8466 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8467 : BigEndianShifts[MaskOneElt & 0x7]; 8468 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8469 Swap = MaskOneElt < NumHalfWords; 8470 FoundCandidate = true; 8471 break; 8472 } 8473 } 8474 } 8475 8476 if (!FoundCandidate) 8477 return SDValue(); 8478 8479 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8480 // optionally with VECSHL if shift is required. 8481 if (Swap) 8482 std::swap(V1, V2); 8483 if (V2.isUndef()) 8484 V2 = V1; 8485 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8486 if (ShiftElts) { 8487 // Double ShiftElts because we're left shifting on v16i8 type. 8488 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8489 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8490 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8491 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8492 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8493 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8494 } 8495 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8496 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8497 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8498 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8499 } 8500 8501 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8502 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8503 /// return the code it can be lowered into. Worst case, it can always be 8504 /// lowered into a vperm. 8505 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8506 SelectionDAG &DAG) const { 8507 SDLoc dl(Op); 8508 SDValue V1 = Op.getOperand(0); 8509 SDValue V2 = Op.getOperand(1); 8510 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8511 EVT VT = Op.getValueType(); 8512 bool isLittleEndian = Subtarget.isLittleEndian(); 8513 8514 unsigned ShiftElts, InsertAtByte; 8515 bool Swap = false; 8516 if (Subtarget.hasP9Vector() && 8517 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8518 isLittleEndian)) { 8519 if (Swap) 8520 std::swap(V1, V2); 8521 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8522 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8523 if (ShiftElts) { 8524 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8525 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8526 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8527 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8528 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8529 } 8530 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8531 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8532 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8533 } 8534 8535 if (Subtarget.hasP9Altivec()) { 8536 SDValue NewISDNode; 8537 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8538 return NewISDNode; 8539 8540 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8541 return NewISDNode; 8542 } 8543 8544 if (Subtarget.hasVSX() && 8545 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8546 if (Swap) 8547 std::swap(V1, V2); 8548 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8549 SDValue Conv2 = 8550 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8551 8552 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8553 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8554 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8555 } 8556 8557 if (Subtarget.hasVSX() && 8558 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8559 if (Swap) 8560 std::swap(V1, V2); 8561 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8562 SDValue Conv2 = 8563 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8564 8565 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8566 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8567 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8568 } 8569 8570 if (Subtarget.hasP9Vector()) { 8571 if (PPC::isXXBRHShuffleMask(SVOp)) { 8572 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8573 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8574 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8575 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8576 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8577 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8578 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8579 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8580 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8581 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8582 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8583 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8584 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8585 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8586 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8587 } 8588 } 8589 8590 if (Subtarget.hasVSX()) { 8591 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8592 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8593 8594 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8595 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8596 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8597 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8598 } 8599 8600 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8601 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8602 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8603 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8604 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8605 } 8606 } 8607 8608 if (Subtarget.hasQPX()) { 8609 if (VT.getVectorNumElements() != 4) 8610 return SDValue(); 8611 8612 if (V2.isUndef()) V2 = V1; 8613 8614 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8615 if (AlignIdx != -1) { 8616 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8617 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8618 } else if (SVOp->isSplat()) { 8619 int SplatIdx = SVOp->getSplatIndex(); 8620 if (SplatIdx >= 4) { 8621 std::swap(V1, V2); 8622 SplatIdx -= 4; 8623 } 8624 8625 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8626 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8627 } 8628 8629 // Lower this into a qvgpci/qvfperm pair. 8630 8631 // Compute the qvgpci literal 8632 unsigned idx = 0; 8633 for (unsigned i = 0; i < 4; ++i) { 8634 int m = SVOp->getMaskElt(i); 8635 unsigned mm = m >= 0 ? (unsigned) m : i; 8636 idx |= mm << (3-i)*3; 8637 } 8638 8639 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8640 DAG.getConstant(idx, dl, MVT::i32)); 8641 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8642 } 8643 8644 // Cases that are handled by instructions that take permute immediates 8645 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8646 // selected by the instruction selector. 8647 if (V2.isUndef()) { 8648 if (PPC::isSplatShuffleMask(SVOp, 1) || 8649 PPC::isSplatShuffleMask(SVOp, 2) || 8650 PPC::isSplatShuffleMask(SVOp, 4) || 8651 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8652 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8653 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8654 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8655 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8656 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8657 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8658 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8659 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8660 (Subtarget.hasP8Altivec() && ( 8661 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8662 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8663 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8664 return Op; 8665 } 8666 } 8667 8668 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8669 // and produce a fixed permutation. If any of these match, do not lower to 8670 // VPERM. 8671 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8672 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8673 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8674 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8675 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8676 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8677 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8678 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8679 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8680 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8681 (Subtarget.hasP8Altivec() && ( 8682 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8683 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8684 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8685 return Op; 8686 8687 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8688 // perfect shuffle table to emit an optimal matching sequence. 8689 ArrayRef<int> PermMask = SVOp->getMask(); 8690 8691 unsigned PFIndexes[4]; 8692 bool isFourElementShuffle = true; 8693 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8694 unsigned EltNo = 8; // Start out undef. 8695 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8696 if (PermMask[i*4+j] < 0) 8697 continue; // Undef, ignore it. 8698 8699 unsigned ByteSource = PermMask[i*4+j]; 8700 if ((ByteSource & 3) != j) { 8701 isFourElementShuffle = false; 8702 break; 8703 } 8704 8705 if (EltNo == 8) { 8706 EltNo = ByteSource/4; 8707 } else if (EltNo != ByteSource/4) { 8708 isFourElementShuffle = false; 8709 break; 8710 } 8711 } 8712 PFIndexes[i] = EltNo; 8713 } 8714 8715 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8716 // perfect shuffle vector to determine if it is cost effective to do this as 8717 // discrete instructions, or whether we should use a vperm. 8718 // For now, we skip this for little endian until such time as we have a 8719 // little-endian perfect shuffle table. 8720 if (isFourElementShuffle && !isLittleEndian) { 8721 // Compute the index in the perfect shuffle table. 8722 unsigned PFTableIndex = 8723 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8724 8725 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8726 unsigned Cost = (PFEntry >> 30); 8727 8728 // Determining when to avoid vperm is tricky. Many things affect the cost 8729 // of vperm, particularly how many times the perm mask needs to be computed. 8730 // For example, if the perm mask can be hoisted out of a loop or is already 8731 // used (perhaps because there are multiple permutes with the same shuffle 8732 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8733 // the loop requires an extra register. 8734 // 8735 // As a compromise, we only emit discrete instructions if the shuffle can be 8736 // generated in 3 or fewer operations. When we have loop information 8737 // available, if this block is within a loop, we should avoid using vperm 8738 // for 3-operation perms and use a constant pool load instead. 8739 if (Cost < 3) 8740 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8741 } 8742 8743 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8744 // vector that will get spilled to the constant pool. 8745 if (V2.isUndef()) V2 = V1; 8746 8747 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8748 // that it is in input element units, not in bytes. Convert now. 8749 8750 // For little endian, the order of the input vectors is reversed, and 8751 // the permutation mask is complemented with respect to 31. This is 8752 // necessary to produce proper semantics with the big-endian-biased vperm 8753 // instruction. 8754 EVT EltVT = V1.getValueType().getVectorElementType(); 8755 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8756 8757 SmallVector<SDValue, 16> ResultMask; 8758 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8759 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8760 8761 for (unsigned j = 0; j != BytesPerElement; ++j) 8762 if (isLittleEndian) 8763 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8764 dl, MVT::i32)); 8765 else 8766 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8767 MVT::i32)); 8768 } 8769 8770 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8771 if (isLittleEndian) 8772 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8773 V2, V1, VPermMask); 8774 else 8775 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8776 V1, V2, VPermMask); 8777 } 8778 8779 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8780 /// vector comparison. If it is, return true and fill in Opc/isDot with 8781 /// information about the intrinsic. 8782 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8783 bool &isDot, const PPCSubtarget &Subtarget) { 8784 unsigned IntrinsicID = 8785 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8786 CompareOpc = -1; 8787 isDot = false; 8788 switch (IntrinsicID) { 8789 default: 8790 return false; 8791 // Comparison predicates. 8792 case Intrinsic::ppc_altivec_vcmpbfp_p: 8793 CompareOpc = 966; 8794 isDot = true; 8795 break; 8796 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8797 CompareOpc = 198; 8798 isDot = true; 8799 break; 8800 case Intrinsic::ppc_altivec_vcmpequb_p: 8801 CompareOpc = 6; 8802 isDot = true; 8803 break; 8804 case Intrinsic::ppc_altivec_vcmpequh_p: 8805 CompareOpc = 70; 8806 isDot = true; 8807 break; 8808 case Intrinsic::ppc_altivec_vcmpequw_p: 8809 CompareOpc = 134; 8810 isDot = true; 8811 break; 8812 case Intrinsic::ppc_altivec_vcmpequd_p: 8813 if (Subtarget.hasP8Altivec()) { 8814 CompareOpc = 199; 8815 isDot = true; 8816 } else 8817 return false; 8818 break; 8819 case Intrinsic::ppc_altivec_vcmpneb_p: 8820 case Intrinsic::ppc_altivec_vcmpneh_p: 8821 case Intrinsic::ppc_altivec_vcmpnew_p: 8822 case Intrinsic::ppc_altivec_vcmpnezb_p: 8823 case Intrinsic::ppc_altivec_vcmpnezh_p: 8824 case Intrinsic::ppc_altivec_vcmpnezw_p: 8825 if (Subtarget.hasP9Altivec()) { 8826 switch (IntrinsicID) { 8827 default: 8828 llvm_unreachable("Unknown comparison intrinsic."); 8829 case Intrinsic::ppc_altivec_vcmpneb_p: 8830 CompareOpc = 7; 8831 break; 8832 case Intrinsic::ppc_altivec_vcmpneh_p: 8833 CompareOpc = 71; 8834 break; 8835 case Intrinsic::ppc_altivec_vcmpnew_p: 8836 CompareOpc = 135; 8837 break; 8838 case Intrinsic::ppc_altivec_vcmpnezb_p: 8839 CompareOpc = 263; 8840 break; 8841 case Intrinsic::ppc_altivec_vcmpnezh_p: 8842 CompareOpc = 327; 8843 break; 8844 case Intrinsic::ppc_altivec_vcmpnezw_p: 8845 CompareOpc = 391; 8846 break; 8847 } 8848 isDot = true; 8849 } else 8850 return false; 8851 break; 8852 case Intrinsic::ppc_altivec_vcmpgefp_p: 8853 CompareOpc = 454; 8854 isDot = true; 8855 break; 8856 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8857 CompareOpc = 710; 8858 isDot = true; 8859 break; 8860 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8861 CompareOpc = 774; 8862 isDot = true; 8863 break; 8864 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8865 CompareOpc = 838; 8866 isDot = true; 8867 break; 8868 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8869 CompareOpc = 902; 8870 isDot = true; 8871 break; 8872 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8873 if (Subtarget.hasP8Altivec()) { 8874 CompareOpc = 967; 8875 isDot = true; 8876 } else 8877 return false; 8878 break; 8879 case Intrinsic::ppc_altivec_vcmpgtub_p: 8880 CompareOpc = 518; 8881 isDot = true; 8882 break; 8883 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8884 CompareOpc = 582; 8885 isDot = true; 8886 break; 8887 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8888 CompareOpc = 646; 8889 isDot = true; 8890 break; 8891 case Intrinsic::ppc_altivec_vcmpgtud_p: 8892 if (Subtarget.hasP8Altivec()) { 8893 CompareOpc = 711; 8894 isDot = true; 8895 } else 8896 return false; 8897 break; 8898 8899 // VSX predicate comparisons use the same infrastructure 8900 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8901 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8902 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8903 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8904 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8905 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8906 if (Subtarget.hasVSX()) { 8907 switch (IntrinsicID) { 8908 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8909 CompareOpc = 99; 8910 break; 8911 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8912 CompareOpc = 115; 8913 break; 8914 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8915 CompareOpc = 107; 8916 break; 8917 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8918 CompareOpc = 67; 8919 break; 8920 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8921 CompareOpc = 83; 8922 break; 8923 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8924 CompareOpc = 75; 8925 break; 8926 } 8927 isDot = true; 8928 } else 8929 return false; 8930 break; 8931 8932 // Normal Comparisons. 8933 case Intrinsic::ppc_altivec_vcmpbfp: 8934 CompareOpc = 966; 8935 break; 8936 case Intrinsic::ppc_altivec_vcmpeqfp: 8937 CompareOpc = 198; 8938 break; 8939 case Intrinsic::ppc_altivec_vcmpequb: 8940 CompareOpc = 6; 8941 break; 8942 case Intrinsic::ppc_altivec_vcmpequh: 8943 CompareOpc = 70; 8944 break; 8945 case Intrinsic::ppc_altivec_vcmpequw: 8946 CompareOpc = 134; 8947 break; 8948 case Intrinsic::ppc_altivec_vcmpequd: 8949 if (Subtarget.hasP8Altivec()) 8950 CompareOpc = 199; 8951 else 8952 return false; 8953 break; 8954 case Intrinsic::ppc_altivec_vcmpneb: 8955 case Intrinsic::ppc_altivec_vcmpneh: 8956 case Intrinsic::ppc_altivec_vcmpnew: 8957 case Intrinsic::ppc_altivec_vcmpnezb: 8958 case Intrinsic::ppc_altivec_vcmpnezh: 8959 case Intrinsic::ppc_altivec_vcmpnezw: 8960 if (Subtarget.hasP9Altivec()) 8961 switch (IntrinsicID) { 8962 default: 8963 llvm_unreachable("Unknown comparison intrinsic."); 8964 case Intrinsic::ppc_altivec_vcmpneb: 8965 CompareOpc = 7; 8966 break; 8967 case Intrinsic::ppc_altivec_vcmpneh: 8968 CompareOpc = 71; 8969 break; 8970 case Intrinsic::ppc_altivec_vcmpnew: 8971 CompareOpc = 135; 8972 break; 8973 case Intrinsic::ppc_altivec_vcmpnezb: 8974 CompareOpc = 263; 8975 break; 8976 case Intrinsic::ppc_altivec_vcmpnezh: 8977 CompareOpc = 327; 8978 break; 8979 case Intrinsic::ppc_altivec_vcmpnezw: 8980 CompareOpc = 391; 8981 break; 8982 } 8983 else 8984 return false; 8985 break; 8986 case Intrinsic::ppc_altivec_vcmpgefp: 8987 CompareOpc = 454; 8988 break; 8989 case Intrinsic::ppc_altivec_vcmpgtfp: 8990 CompareOpc = 710; 8991 break; 8992 case Intrinsic::ppc_altivec_vcmpgtsb: 8993 CompareOpc = 774; 8994 break; 8995 case Intrinsic::ppc_altivec_vcmpgtsh: 8996 CompareOpc = 838; 8997 break; 8998 case Intrinsic::ppc_altivec_vcmpgtsw: 8999 CompareOpc = 902; 9000 break; 9001 case Intrinsic::ppc_altivec_vcmpgtsd: 9002 if (Subtarget.hasP8Altivec()) 9003 CompareOpc = 967; 9004 else 9005 return false; 9006 break; 9007 case Intrinsic::ppc_altivec_vcmpgtub: 9008 CompareOpc = 518; 9009 break; 9010 case Intrinsic::ppc_altivec_vcmpgtuh: 9011 CompareOpc = 582; 9012 break; 9013 case Intrinsic::ppc_altivec_vcmpgtuw: 9014 CompareOpc = 646; 9015 break; 9016 case Intrinsic::ppc_altivec_vcmpgtud: 9017 if (Subtarget.hasP8Altivec()) 9018 CompareOpc = 711; 9019 else 9020 return false; 9021 break; 9022 } 9023 return true; 9024 } 9025 9026 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9027 /// lower, do it, otherwise return null. 9028 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9029 SelectionDAG &DAG) const { 9030 unsigned IntrinsicID = 9031 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9032 9033 SDLoc dl(Op); 9034 9035 if (IntrinsicID == Intrinsic::thread_pointer) { 9036 // Reads the thread pointer register, used for __builtin_thread_pointer. 9037 if (Subtarget.isPPC64()) 9038 return DAG.getRegister(PPC::X13, MVT::i64); 9039 return DAG.getRegister(PPC::R2, MVT::i32); 9040 } 9041 9042 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9043 // opcode number of the comparison. 9044 int CompareOpc; 9045 bool isDot; 9046 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9047 return SDValue(); // Don't custom lower most intrinsics. 9048 9049 // If this is a non-dot comparison, make the VCMP node and we are done. 9050 if (!isDot) { 9051 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9052 Op.getOperand(1), Op.getOperand(2), 9053 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9054 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9055 } 9056 9057 // Create the PPCISD altivec 'dot' comparison node. 9058 SDValue Ops[] = { 9059 Op.getOperand(2), // LHS 9060 Op.getOperand(3), // RHS 9061 DAG.getConstant(CompareOpc, dl, MVT::i32) 9062 }; 9063 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9064 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9065 9066 // Now that we have the comparison, emit a copy from the CR to a GPR. 9067 // This is flagged to the above dot comparison. 9068 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9069 DAG.getRegister(PPC::CR6, MVT::i32), 9070 CompNode.getValue(1)); 9071 9072 // Unpack the result based on how the target uses it. 9073 unsigned BitNo; // Bit # of CR6. 9074 bool InvertBit; // Invert result? 9075 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9076 default: // Can't happen, don't crash on invalid number though. 9077 case 0: // Return the value of the EQ bit of CR6. 9078 BitNo = 0; InvertBit = false; 9079 break; 9080 case 1: // Return the inverted value of the EQ bit of CR6. 9081 BitNo = 0; InvertBit = true; 9082 break; 9083 case 2: // Return the value of the LT bit of CR6. 9084 BitNo = 2; InvertBit = false; 9085 break; 9086 case 3: // Return the inverted value of the LT bit of CR6. 9087 BitNo = 2; InvertBit = true; 9088 break; 9089 } 9090 9091 // Shift the bit into the low position. 9092 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9093 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9094 // Isolate the bit. 9095 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9096 DAG.getConstant(1, dl, MVT::i32)); 9097 9098 // If we are supposed to, toggle the bit. 9099 if (InvertBit) 9100 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9101 DAG.getConstant(1, dl, MVT::i32)); 9102 return Flags; 9103 } 9104 9105 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9106 SelectionDAG &DAG) const { 9107 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9108 // the beginning of the argument list. 9109 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9110 SDLoc DL(Op); 9111 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9112 case Intrinsic::ppc_cfence: { 9113 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9114 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9115 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9116 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9117 Op.getOperand(ArgStart + 1)), 9118 Op.getOperand(0)), 9119 0); 9120 } 9121 default: 9122 break; 9123 } 9124 return SDValue(); 9125 } 9126 9127 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9128 // Check for a DIV with the same operands as this REM. 9129 for (auto UI : Op.getOperand(1)->uses()) { 9130 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9131 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9132 if (UI->getOperand(0) == Op.getOperand(0) && 9133 UI->getOperand(1) == Op.getOperand(1)) 9134 return SDValue(); 9135 } 9136 return Op; 9137 } 9138 9139 // Lower scalar BSWAP64 to xxbrd. 9140 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9141 SDLoc dl(Op); 9142 // MTVSRDD 9143 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9144 Op.getOperand(0)); 9145 // XXBRD 9146 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9147 // MFVSRD 9148 int VectorIndex = 0; 9149 if (Subtarget.isLittleEndian()) 9150 VectorIndex = 1; 9151 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9152 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9153 return Op; 9154 } 9155 9156 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9157 // compared to a value that is atomically loaded (atomic loads zero-extend). 9158 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9159 SelectionDAG &DAG) const { 9160 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9161 "Expecting an atomic compare-and-swap here."); 9162 SDLoc dl(Op); 9163 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9164 EVT MemVT = AtomicNode->getMemoryVT(); 9165 if (MemVT.getSizeInBits() >= 32) 9166 return Op; 9167 9168 SDValue CmpOp = Op.getOperand(2); 9169 // If this is already correctly zero-extended, leave it alone. 9170 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9171 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9172 return Op; 9173 9174 // Clear the high bits of the compare operand. 9175 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9176 SDValue NewCmpOp = 9177 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9178 DAG.getConstant(MaskVal, dl, MVT::i32)); 9179 9180 // Replace the existing compare operand with the properly zero-extended one. 9181 SmallVector<SDValue, 4> Ops; 9182 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9183 Ops.push_back(AtomicNode->getOperand(i)); 9184 Ops[2] = NewCmpOp; 9185 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9186 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9187 auto NodeTy = 9188 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9189 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9190 } 9191 9192 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9193 SelectionDAG &DAG) const { 9194 SDLoc dl(Op); 9195 // Create a stack slot that is 16-byte aligned. 9196 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9197 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9198 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9199 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9200 9201 // Store the input value into Value#0 of the stack slot. 9202 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9203 MachinePointerInfo()); 9204 // Load it out. 9205 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9206 } 9207 9208 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9209 SelectionDAG &DAG) const { 9210 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9211 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9212 9213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9214 // We have legal lowering for constant indices but not for variable ones. 9215 if (!C) 9216 return SDValue(); 9217 9218 EVT VT = Op.getValueType(); 9219 SDLoc dl(Op); 9220 SDValue V1 = Op.getOperand(0); 9221 SDValue V2 = Op.getOperand(1); 9222 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9223 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9224 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9225 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9226 unsigned InsertAtElement = C->getZExtValue(); 9227 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9228 if (Subtarget.isLittleEndian()) { 9229 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9230 } 9231 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9232 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9233 } 9234 return Op; 9235 } 9236 9237 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9238 SelectionDAG &DAG) const { 9239 SDLoc dl(Op); 9240 SDNode *N = Op.getNode(); 9241 9242 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9243 "Unknown extract_vector_elt type"); 9244 9245 SDValue Value = N->getOperand(0); 9246 9247 // The first part of this is like the store lowering except that we don't 9248 // need to track the chain. 9249 9250 // The values are now known to be -1 (false) or 1 (true). To convert this 9251 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9252 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9253 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9254 9255 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9256 // understand how to form the extending load. 9257 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9258 9259 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9260 9261 // Now convert to an integer and store. 9262 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9263 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9264 Value); 9265 9266 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9267 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9268 MachinePointerInfo PtrInfo = 9269 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9270 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9271 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9272 9273 SDValue StoreChain = DAG.getEntryNode(); 9274 SDValue Ops[] = {StoreChain, 9275 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9276 Value, FIdx}; 9277 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9278 9279 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9280 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9281 9282 // Extract the value requested. 9283 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9284 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9285 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9286 9287 SDValue IntVal = 9288 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9289 9290 if (!Subtarget.useCRBits()) 9291 return IntVal; 9292 9293 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9294 } 9295 9296 /// Lowering for QPX v4i1 loads 9297 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9298 SelectionDAG &DAG) const { 9299 SDLoc dl(Op); 9300 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9301 SDValue LoadChain = LN->getChain(); 9302 SDValue BasePtr = LN->getBasePtr(); 9303 9304 if (Op.getValueType() == MVT::v4f64 || 9305 Op.getValueType() == MVT::v4f32) { 9306 EVT MemVT = LN->getMemoryVT(); 9307 unsigned Alignment = LN->getAlignment(); 9308 9309 // If this load is properly aligned, then it is legal. 9310 if (Alignment >= MemVT.getStoreSize()) 9311 return Op; 9312 9313 EVT ScalarVT = Op.getValueType().getScalarType(), 9314 ScalarMemVT = MemVT.getScalarType(); 9315 unsigned Stride = ScalarMemVT.getStoreSize(); 9316 9317 SDValue Vals[4], LoadChains[4]; 9318 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9319 SDValue Load; 9320 if (ScalarVT != ScalarMemVT) 9321 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9322 BasePtr, 9323 LN->getPointerInfo().getWithOffset(Idx * Stride), 9324 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9325 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9326 else 9327 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9328 LN->getPointerInfo().getWithOffset(Idx * Stride), 9329 MinAlign(Alignment, Idx * Stride), 9330 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9331 9332 if (Idx == 0 && LN->isIndexed()) { 9333 assert(LN->getAddressingMode() == ISD::PRE_INC && 9334 "Unknown addressing mode on vector load"); 9335 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9336 LN->getAddressingMode()); 9337 } 9338 9339 Vals[Idx] = Load; 9340 LoadChains[Idx] = Load.getValue(1); 9341 9342 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9343 DAG.getConstant(Stride, dl, 9344 BasePtr.getValueType())); 9345 } 9346 9347 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9348 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9349 9350 if (LN->isIndexed()) { 9351 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9352 return DAG.getMergeValues(RetOps, dl); 9353 } 9354 9355 SDValue RetOps[] = { Value, TF }; 9356 return DAG.getMergeValues(RetOps, dl); 9357 } 9358 9359 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9360 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9361 9362 // To lower v4i1 from a byte array, we load the byte elements of the 9363 // vector and then reuse the BUILD_VECTOR logic. 9364 9365 SDValue VectElmts[4], VectElmtChains[4]; 9366 for (unsigned i = 0; i < 4; ++i) { 9367 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9368 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9369 9370 VectElmts[i] = DAG.getExtLoad( 9371 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9372 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9373 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9374 VectElmtChains[i] = VectElmts[i].getValue(1); 9375 } 9376 9377 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9378 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9379 9380 SDValue RVals[] = { Value, LoadChain }; 9381 return DAG.getMergeValues(RVals, dl); 9382 } 9383 9384 /// Lowering for QPX v4i1 stores 9385 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9386 SelectionDAG &DAG) const { 9387 SDLoc dl(Op); 9388 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9389 SDValue StoreChain = SN->getChain(); 9390 SDValue BasePtr = SN->getBasePtr(); 9391 SDValue Value = SN->getValue(); 9392 9393 if (Value.getValueType() == MVT::v4f64 || 9394 Value.getValueType() == MVT::v4f32) { 9395 EVT MemVT = SN->getMemoryVT(); 9396 unsigned Alignment = SN->getAlignment(); 9397 9398 // If this store is properly aligned, then it is legal. 9399 if (Alignment >= MemVT.getStoreSize()) 9400 return Op; 9401 9402 EVT ScalarVT = Value.getValueType().getScalarType(), 9403 ScalarMemVT = MemVT.getScalarType(); 9404 unsigned Stride = ScalarMemVT.getStoreSize(); 9405 9406 SDValue Stores[4]; 9407 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9408 SDValue Ex = DAG.getNode( 9409 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9410 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9411 SDValue Store; 9412 if (ScalarVT != ScalarMemVT) 9413 Store = 9414 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9415 SN->getPointerInfo().getWithOffset(Idx * Stride), 9416 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9417 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9418 else 9419 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9420 SN->getPointerInfo().getWithOffset(Idx * Stride), 9421 MinAlign(Alignment, Idx * Stride), 9422 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9423 9424 if (Idx == 0 && SN->isIndexed()) { 9425 assert(SN->getAddressingMode() == ISD::PRE_INC && 9426 "Unknown addressing mode on vector store"); 9427 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9428 SN->getAddressingMode()); 9429 } 9430 9431 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9432 DAG.getConstant(Stride, dl, 9433 BasePtr.getValueType())); 9434 Stores[Idx] = Store; 9435 } 9436 9437 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9438 9439 if (SN->isIndexed()) { 9440 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9441 return DAG.getMergeValues(RetOps, dl); 9442 } 9443 9444 return TF; 9445 } 9446 9447 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9448 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9449 9450 // The values are now known to be -1 (false) or 1 (true). To convert this 9451 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9452 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9453 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9454 9455 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9456 // understand how to form the extending load. 9457 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9458 9459 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9460 9461 // Now convert to an integer and store. 9462 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9463 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9464 Value); 9465 9466 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9467 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9468 MachinePointerInfo PtrInfo = 9469 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9470 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9471 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9472 9473 SDValue Ops[] = {StoreChain, 9474 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9475 Value, FIdx}; 9476 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9477 9478 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9479 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9480 9481 // Move data into the byte array. 9482 SDValue Loads[4], LoadChains[4]; 9483 for (unsigned i = 0; i < 4; ++i) { 9484 unsigned Offset = 4*i; 9485 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9486 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9487 9488 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9489 PtrInfo.getWithOffset(Offset)); 9490 LoadChains[i] = Loads[i].getValue(1); 9491 } 9492 9493 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9494 9495 SDValue Stores[4]; 9496 for (unsigned i = 0; i < 4; ++i) { 9497 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9498 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9499 9500 Stores[i] = DAG.getTruncStore( 9501 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9502 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9503 SN->getAAInfo()); 9504 } 9505 9506 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9507 9508 return StoreChain; 9509 } 9510 9511 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9512 SDLoc dl(Op); 9513 if (Op.getValueType() == MVT::v4i32) { 9514 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9515 9516 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9517 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9518 9519 SDValue RHSSwap = // = vrlw RHS, 16 9520 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9521 9522 // Shrinkify inputs to v8i16. 9523 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9524 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9525 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9526 9527 // Low parts multiplied together, generating 32-bit results (we ignore the 9528 // top parts). 9529 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9530 LHS, RHS, DAG, dl, MVT::v4i32); 9531 9532 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9533 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9534 // Shift the high parts up 16 bits. 9535 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9536 Neg16, DAG, dl); 9537 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9538 } else if (Op.getValueType() == MVT::v8i16) { 9539 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9540 9541 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9542 9543 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9544 LHS, RHS, Zero, DAG, dl); 9545 } else if (Op.getValueType() == MVT::v16i8) { 9546 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9547 bool isLittleEndian = Subtarget.isLittleEndian(); 9548 9549 // Multiply the even 8-bit parts, producing 16-bit sums. 9550 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9551 LHS, RHS, DAG, dl, MVT::v8i16); 9552 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9553 9554 // Multiply the odd 8-bit parts, producing 16-bit sums. 9555 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9556 LHS, RHS, DAG, dl, MVT::v8i16); 9557 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9558 9559 // Merge the results together. Because vmuleub and vmuloub are 9560 // instructions with a big-endian bias, we must reverse the 9561 // element numbering and reverse the meaning of "odd" and "even" 9562 // when generating little endian code. 9563 int Ops[16]; 9564 for (unsigned i = 0; i != 8; ++i) { 9565 if (isLittleEndian) { 9566 Ops[i*2 ] = 2*i; 9567 Ops[i*2+1] = 2*i+16; 9568 } else { 9569 Ops[i*2 ] = 2*i+1; 9570 Ops[i*2+1] = 2*i+1+16; 9571 } 9572 } 9573 if (isLittleEndian) 9574 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9575 else 9576 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9577 } else { 9578 llvm_unreachable("Unknown mul to lower!"); 9579 } 9580 } 9581 9582 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9583 9584 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9585 9586 EVT VT = Op.getValueType(); 9587 assert(VT.isVector() && 9588 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9589 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9590 VT == MVT::v16i8) && 9591 "Unexpected vector element type!"); 9592 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9593 "Current subtarget doesn't support smax v2i64!"); 9594 9595 // For vector abs, it can be lowered to: 9596 // abs x 9597 // ==> 9598 // y = -x 9599 // smax(x, y) 9600 9601 SDLoc dl(Op); 9602 SDValue X = Op.getOperand(0); 9603 SDValue Zero = DAG.getConstant(0, dl, VT); 9604 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9605 9606 // SMAX patch https://reviews.llvm.org/D47332 9607 // hasn't landed yet, so use intrinsic first here. 9608 // TODO: Should use SMAX directly once SMAX patch landed 9609 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9610 if (VT == MVT::v2i64) 9611 BifID = Intrinsic::ppc_altivec_vmaxsd; 9612 else if (VT == MVT::v8i16) 9613 BifID = Intrinsic::ppc_altivec_vmaxsh; 9614 else if (VT == MVT::v16i8) 9615 BifID = Intrinsic::ppc_altivec_vmaxsb; 9616 9617 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9618 } 9619 9620 // Custom lowering for fpext vf32 to v2f64 9621 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 9622 9623 assert(Op.getOpcode() == ISD::FP_EXTEND && 9624 "Should only be called for ISD::FP_EXTEND"); 9625 9626 // We only want to custom lower an extend from v2f32 to v2f64. 9627 if (Op.getValueType() != MVT::v2f64 || 9628 Op.getOperand(0).getValueType() != MVT::v2f32) 9629 return SDValue(); 9630 9631 SDLoc dl(Op); 9632 SDValue Op0 = Op.getOperand(0); 9633 9634 switch (Op0.getOpcode()) { 9635 default: 9636 return SDValue(); 9637 case ISD::FADD: 9638 case ISD::FMUL: 9639 case ISD::FSUB: { 9640 SDValue NewLoad[2]; 9641 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 9642 // Ensure both input are loads. 9643 SDValue LdOp = Op0.getOperand(i); 9644 if (LdOp.getOpcode() != ISD::LOAD) 9645 return SDValue(); 9646 // Generate new load node. 9647 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 9648 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9649 NewLoad[i] = 9650 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9651 DAG.getVTList(MVT::v4f32, MVT::Other), 9652 LoadOps, LD->getMemoryVT(), 9653 LD->getMemOperand()); 9654 } 9655 SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, 9656 NewLoad[0], NewLoad[1], 9657 Op0.getNode()->getFlags()); 9658 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp); 9659 } 9660 case ISD::LOAD: { 9661 LoadSDNode *LD = cast<LoadSDNode>(Op0); 9662 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9663 SDValue NewLd = 9664 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9665 DAG.getVTList(MVT::v4f32, MVT::Other), 9666 LoadOps, LD->getMemoryVT(), LD->getMemOperand()); 9667 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd); 9668 } 9669 } 9670 llvm_unreachable("ERROR:Should return for all cases within swtich."); 9671 } 9672 9673 /// LowerOperation - Provide custom lowering hooks for some operations. 9674 /// 9675 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9676 switch (Op.getOpcode()) { 9677 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9678 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9679 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9680 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9681 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9682 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9683 case ISD::SETCC: return LowerSETCC(Op, DAG); 9684 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9685 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9686 9687 // Variable argument lowering. 9688 case ISD::VASTART: return LowerVASTART(Op, DAG); 9689 case ISD::VAARG: return LowerVAARG(Op, DAG); 9690 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9691 9692 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9693 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9694 case ISD::GET_DYNAMIC_AREA_OFFSET: 9695 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9696 9697 // Exception handling lowering. 9698 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9699 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9700 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9701 9702 case ISD::LOAD: return LowerLOAD(Op, DAG); 9703 case ISD::STORE: return LowerSTORE(Op, DAG); 9704 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9705 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9706 case ISD::FP_TO_UINT: 9707 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9708 case ISD::UINT_TO_FP: 9709 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9710 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9711 9712 // Lower 64-bit shifts. 9713 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9714 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9715 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9716 9717 // Vector-related lowering. 9718 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9719 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9720 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9721 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9722 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9723 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9724 case ISD::MUL: return LowerMUL(Op, DAG); 9725 case ISD::ABS: return LowerABS(Op, DAG); 9726 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9727 9728 // For counter-based loop handling. 9729 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9730 9731 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9732 9733 // Frame & Return address. 9734 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9735 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9736 9737 case ISD::INTRINSIC_VOID: 9738 return LowerINTRINSIC_VOID(Op, DAG); 9739 case ISD::SREM: 9740 case ISD::UREM: 9741 return LowerREM(Op, DAG); 9742 case ISD::BSWAP: 9743 return LowerBSWAP(Op, DAG); 9744 case ISD::ATOMIC_CMP_SWAP: 9745 return LowerATOMIC_CMP_SWAP(Op, DAG); 9746 } 9747 } 9748 9749 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9750 SmallVectorImpl<SDValue>&Results, 9751 SelectionDAG &DAG) const { 9752 SDLoc dl(N); 9753 switch (N->getOpcode()) { 9754 default: 9755 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9756 case ISD::READCYCLECOUNTER: { 9757 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9758 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9759 9760 Results.push_back(RTB); 9761 Results.push_back(RTB.getValue(1)); 9762 Results.push_back(RTB.getValue(2)); 9763 break; 9764 } 9765 case ISD::INTRINSIC_W_CHAIN: { 9766 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9767 Intrinsic::ppc_is_decremented_ctr_nonzero) 9768 break; 9769 9770 assert(N->getValueType(0) == MVT::i1 && 9771 "Unexpected result type for CTR decrement intrinsic"); 9772 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9773 N->getValueType(0)); 9774 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9775 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9776 N->getOperand(1)); 9777 9778 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9779 Results.push_back(NewInt.getValue(1)); 9780 break; 9781 } 9782 case ISD::VAARG: { 9783 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9784 return; 9785 9786 EVT VT = N->getValueType(0); 9787 9788 if (VT == MVT::i64) { 9789 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9790 9791 Results.push_back(NewNode); 9792 Results.push_back(NewNode.getValue(1)); 9793 } 9794 return; 9795 } 9796 case ISD::FP_TO_SINT: 9797 case ISD::FP_TO_UINT: 9798 // LowerFP_TO_INT() can only handle f32 and f64. 9799 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9800 return; 9801 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9802 return; 9803 case ISD::TRUNCATE: { 9804 EVT TrgVT = N->getValueType(0); 9805 if (TrgVT.isVector() && 9806 isOperationCustom(N->getOpcode(), TrgVT) && 9807 N->getOperand(0).getValueType().getSizeInBits() <= 128) 9808 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 9809 return; 9810 } 9811 case ISD::BITCAST: 9812 // Don't handle bitcast here. 9813 return; 9814 } 9815 } 9816 9817 //===----------------------------------------------------------------------===// 9818 // Other Lowering Code 9819 //===----------------------------------------------------------------------===// 9820 9821 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9822 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9823 Function *Func = Intrinsic::getDeclaration(M, Id); 9824 return Builder.CreateCall(Func, {}); 9825 } 9826 9827 // The mappings for emitLeading/TrailingFence is taken from 9828 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9829 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9830 Instruction *Inst, 9831 AtomicOrdering Ord) const { 9832 if (Ord == AtomicOrdering::SequentiallyConsistent) 9833 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9834 if (isReleaseOrStronger(Ord)) 9835 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9836 return nullptr; 9837 } 9838 9839 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9840 Instruction *Inst, 9841 AtomicOrdering Ord) const { 9842 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9843 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9844 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9845 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9846 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9847 return Builder.CreateCall( 9848 Intrinsic::getDeclaration( 9849 Builder.GetInsertBlock()->getParent()->getParent(), 9850 Intrinsic::ppc_cfence, {Inst->getType()}), 9851 {Inst}); 9852 // FIXME: Can use isync for rmw operation. 9853 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9854 } 9855 return nullptr; 9856 } 9857 9858 MachineBasicBlock * 9859 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9860 unsigned AtomicSize, 9861 unsigned BinOpcode, 9862 unsigned CmpOpcode, 9863 unsigned CmpPred) const { 9864 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9865 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9866 9867 auto LoadMnemonic = PPC::LDARX; 9868 auto StoreMnemonic = PPC::STDCX; 9869 switch (AtomicSize) { 9870 default: 9871 llvm_unreachable("Unexpected size of atomic entity"); 9872 case 1: 9873 LoadMnemonic = PPC::LBARX; 9874 StoreMnemonic = PPC::STBCX; 9875 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9876 break; 9877 case 2: 9878 LoadMnemonic = PPC::LHARX; 9879 StoreMnemonic = PPC::STHCX; 9880 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9881 break; 9882 case 4: 9883 LoadMnemonic = PPC::LWARX; 9884 StoreMnemonic = PPC::STWCX; 9885 break; 9886 case 8: 9887 LoadMnemonic = PPC::LDARX; 9888 StoreMnemonic = PPC::STDCX; 9889 break; 9890 } 9891 9892 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9893 MachineFunction *F = BB->getParent(); 9894 MachineFunction::iterator It = ++BB->getIterator(); 9895 9896 unsigned dest = MI.getOperand(0).getReg(); 9897 unsigned ptrA = MI.getOperand(1).getReg(); 9898 unsigned ptrB = MI.getOperand(2).getReg(); 9899 unsigned incr = MI.getOperand(3).getReg(); 9900 DebugLoc dl = MI.getDebugLoc(); 9901 9902 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9903 MachineBasicBlock *loop2MBB = 9904 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9905 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9906 F->insert(It, loopMBB); 9907 if (CmpOpcode) 9908 F->insert(It, loop2MBB); 9909 F->insert(It, exitMBB); 9910 exitMBB->splice(exitMBB->begin(), BB, 9911 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9912 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9913 9914 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9915 unsigned TmpReg = (!BinOpcode) ? incr : 9916 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9917 : &PPC::GPRCRegClass); 9918 9919 // thisMBB: 9920 // ... 9921 // fallthrough --> loopMBB 9922 BB->addSuccessor(loopMBB); 9923 9924 // loopMBB: 9925 // l[wd]arx dest, ptr 9926 // add r0, dest, incr 9927 // st[wd]cx. r0, ptr 9928 // bne- loopMBB 9929 // fallthrough --> exitMBB 9930 9931 // For max/min... 9932 // loopMBB: 9933 // l[wd]arx dest, ptr 9934 // cmpl?[wd] incr, dest 9935 // bgt exitMBB 9936 // loop2MBB: 9937 // st[wd]cx. dest, ptr 9938 // bne- loopMBB 9939 // fallthrough --> exitMBB 9940 9941 BB = loopMBB; 9942 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9943 .addReg(ptrA).addReg(ptrB); 9944 if (BinOpcode) 9945 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9946 if (CmpOpcode) { 9947 // Signed comparisons of byte or halfword values must be sign-extended. 9948 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9949 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9950 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9951 ExtReg).addReg(dest); 9952 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9953 .addReg(incr).addReg(ExtReg); 9954 } else 9955 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9956 .addReg(incr).addReg(dest); 9957 9958 BuildMI(BB, dl, TII->get(PPC::BCC)) 9959 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9960 BB->addSuccessor(loop2MBB); 9961 BB->addSuccessor(exitMBB); 9962 BB = loop2MBB; 9963 } 9964 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9965 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9966 BuildMI(BB, dl, TII->get(PPC::BCC)) 9967 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9968 BB->addSuccessor(loopMBB); 9969 BB->addSuccessor(exitMBB); 9970 9971 // exitMBB: 9972 // ... 9973 BB = exitMBB; 9974 return BB; 9975 } 9976 9977 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 9978 MachineInstr &MI, MachineBasicBlock *BB, 9979 bool is8bit, // operation 9980 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 9981 // If we support part-word atomic mnemonics, just use them 9982 if (Subtarget.hasPartwordAtomics()) 9983 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 9984 CmpPred); 9985 9986 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9987 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9988 // In 64 bit mode we have to use 64 bits for addresses, even though the 9989 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9990 // registers without caring whether they're 32 or 64, but here we're 9991 // doing actual arithmetic on the addresses. 9992 bool is64bit = Subtarget.isPPC64(); 9993 bool isLittleEndian = Subtarget.isLittleEndian(); 9994 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9995 9996 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9997 MachineFunction *F = BB->getParent(); 9998 MachineFunction::iterator It = ++BB->getIterator(); 9999 10000 unsigned dest = MI.getOperand(0).getReg(); 10001 unsigned ptrA = MI.getOperand(1).getReg(); 10002 unsigned ptrB = MI.getOperand(2).getReg(); 10003 unsigned incr = MI.getOperand(3).getReg(); 10004 DebugLoc dl = MI.getDebugLoc(); 10005 10006 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10007 MachineBasicBlock *loop2MBB = 10008 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10009 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10010 F->insert(It, loopMBB); 10011 if (CmpOpcode) 10012 F->insert(It, loop2MBB); 10013 F->insert(It, exitMBB); 10014 exitMBB->splice(exitMBB->begin(), BB, 10015 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10016 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10017 10018 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10019 const TargetRegisterClass *RC = 10020 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10021 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10022 10023 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10024 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10025 unsigned ShiftReg = 10026 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10027 unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10028 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 10029 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10030 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10031 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10032 unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10033 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10034 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10035 unsigned Ptr1Reg; 10036 unsigned TmpReg = 10037 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10038 10039 // thisMBB: 10040 // ... 10041 // fallthrough --> loopMBB 10042 BB->addSuccessor(loopMBB); 10043 10044 // The 4-byte load must be aligned, while a char or short may be 10045 // anywhere in the word. Hence all this nasty bookkeeping code. 10046 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10047 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10048 // xori shift, shift1, 24 [16] 10049 // rlwinm ptr, ptr1, 0, 0, 29 10050 // slw incr2, incr, shift 10051 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10052 // slw mask, mask2, shift 10053 // loopMBB: 10054 // lwarx tmpDest, ptr 10055 // add tmp, tmpDest, incr2 10056 // andc tmp2, tmpDest, mask 10057 // and tmp3, tmp, mask 10058 // or tmp4, tmp3, tmp2 10059 // stwcx. tmp4, ptr 10060 // bne- loopMBB 10061 // fallthrough --> exitMBB 10062 // srw dest, tmpDest, shift 10063 if (ptrA != ZeroReg) { 10064 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10065 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10066 .addReg(ptrA) 10067 .addReg(ptrB); 10068 } else { 10069 Ptr1Reg = ptrB; 10070 } 10071 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10072 // mode. 10073 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10074 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10075 .addImm(3) 10076 .addImm(27) 10077 .addImm(is8bit ? 28 : 27); 10078 if (!isLittleEndian) 10079 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10080 .addReg(Shift1Reg) 10081 .addImm(is8bit ? 24 : 16); 10082 if (is64bit) 10083 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10084 .addReg(Ptr1Reg) 10085 .addImm(0) 10086 .addImm(61); 10087 else 10088 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10089 .addReg(Ptr1Reg) 10090 .addImm(0) 10091 .addImm(0) 10092 .addImm(29); 10093 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10094 if (is8bit) 10095 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10096 else { 10097 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10098 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10099 .addReg(Mask3Reg) 10100 .addImm(65535); 10101 } 10102 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10103 .addReg(Mask2Reg) 10104 .addReg(ShiftReg); 10105 10106 BB = loopMBB; 10107 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10108 .addReg(ZeroReg) 10109 .addReg(PtrReg); 10110 if (BinOpcode) 10111 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10112 .addReg(Incr2Reg) 10113 .addReg(TmpDestReg); 10114 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10115 .addReg(TmpDestReg) 10116 .addReg(MaskReg); 10117 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10118 if (CmpOpcode) { 10119 // For unsigned comparisons, we can directly compare the shifted values. 10120 // For signed comparisons we shift and sign extend. 10121 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10122 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10123 .addReg(TmpDestReg) 10124 .addReg(MaskReg); 10125 unsigned ValueReg = SReg; 10126 unsigned CmpReg = Incr2Reg; 10127 if (CmpOpcode == PPC::CMPW) { 10128 ValueReg = RegInfo.createVirtualRegister(GPRC); 10129 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10130 .addReg(SReg) 10131 .addReg(ShiftReg); 10132 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10133 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10134 .addReg(ValueReg); 10135 ValueReg = ValueSReg; 10136 CmpReg = incr; 10137 } 10138 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10139 .addReg(CmpReg) 10140 .addReg(ValueReg); 10141 BuildMI(BB, dl, TII->get(PPC::BCC)) 10142 .addImm(CmpPred) 10143 .addReg(PPC::CR0) 10144 .addMBB(exitMBB); 10145 BB->addSuccessor(loop2MBB); 10146 BB->addSuccessor(exitMBB); 10147 BB = loop2MBB; 10148 } 10149 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10150 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10151 .addReg(Tmp4Reg) 10152 .addReg(ZeroReg) 10153 .addReg(PtrReg); 10154 BuildMI(BB, dl, TII->get(PPC::BCC)) 10155 .addImm(PPC::PRED_NE) 10156 .addReg(PPC::CR0) 10157 .addMBB(loopMBB); 10158 BB->addSuccessor(loopMBB); 10159 BB->addSuccessor(exitMBB); 10160 10161 // exitMBB: 10162 // ... 10163 BB = exitMBB; 10164 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10165 .addReg(TmpDestReg) 10166 .addReg(ShiftReg); 10167 return BB; 10168 } 10169 10170 llvm::MachineBasicBlock * 10171 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10172 MachineBasicBlock *MBB) const { 10173 DebugLoc DL = MI.getDebugLoc(); 10174 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10175 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10176 10177 MachineFunction *MF = MBB->getParent(); 10178 MachineRegisterInfo &MRI = MF->getRegInfo(); 10179 10180 const BasicBlock *BB = MBB->getBasicBlock(); 10181 MachineFunction::iterator I = ++MBB->getIterator(); 10182 10183 unsigned DstReg = MI.getOperand(0).getReg(); 10184 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10185 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10186 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10187 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10188 10189 MVT PVT = getPointerTy(MF->getDataLayout()); 10190 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10191 "Invalid Pointer Size!"); 10192 // For v = setjmp(buf), we generate 10193 // 10194 // thisMBB: 10195 // SjLjSetup mainMBB 10196 // bl mainMBB 10197 // v_restore = 1 10198 // b sinkMBB 10199 // 10200 // mainMBB: 10201 // buf[LabelOffset] = LR 10202 // v_main = 0 10203 // 10204 // sinkMBB: 10205 // v = phi(main, restore) 10206 // 10207 10208 MachineBasicBlock *thisMBB = MBB; 10209 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10210 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10211 MF->insert(I, mainMBB); 10212 MF->insert(I, sinkMBB); 10213 10214 MachineInstrBuilder MIB; 10215 10216 // Transfer the remainder of BB and its successor edges to sinkMBB. 10217 sinkMBB->splice(sinkMBB->begin(), MBB, 10218 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10219 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10220 10221 // Note that the structure of the jmp_buf used here is not compatible 10222 // with that used by libc, and is not designed to be. Specifically, it 10223 // stores only those 'reserved' registers that LLVM does not otherwise 10224 // understand how to spill. Also, by convention, by the time this 10225 // intrinsic is called, Clang has already stored the frame address in the 10226 // first slot of the buffer and stack address in the third. Following the 10227 // X86 target code, we'll store the jump address in the second slot. We also 10228 // need to save the TOC pointer (R2) to handle jumps between shared 10229 // libraries, and that will be stored in the fourth slot. The thread 10230 // identifier (R13) is not affected. 10231 10232 // thisMBB: 10233 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10234 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10235 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10236 10237 // Prepare IP either in reg. 10238 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10239 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10240 unsigned BufReg = MI.getOperand(1).getReg(); 10241 10242 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10243 setUsesTOCBasePtr(*MBB->getParent()); 10244 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10245 .addReg(PPC::X2) 10246 .addImm(TOCOffset) 10247 .addReg(BufReg) 10248 .cloneMemRefs(MI); 10249 } 10250 10251 // Naked functions never have a base pointer, and so we use r1. For all 10252 // other functions, this decision must be delayed until during PEI. 10253 unsigned BaseReg; 10254 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10255 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10256 else 10257 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10258 10259 MIB = BuildMI(*thisMBB, MI, DL, 10260 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10261 .addReg(BaseReg) 10262 .addImm(BPOffset) 10263 .addReg(BufReg) 10264 .cloneMemRefs(MI); 10265 10266 // Setup 10267 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10268 MIB.addRegMask(TRI->getNoPreservedMask()); 10269 10270 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10271 10272 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10273 .addMBB(mainMBB); 10274 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10275 10276 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10277 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10278 10279 // mainMBB: 10280 // mainDstReg = 0 10281 MIB = 10282 BuildMI(mainMBB, DL, 10283 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10284 10285 // Store IP 10286 if (Subtarget.isPPC64()) { 10287 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10288 .addReg(LabelReg) 10289 .addImm(LabelOffset) 10290 .addReg(BufReg); 10291 } else { 10292 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10293 .addReg(LabelReg) 10294 .addImm(LabelOffset) 10295 .addReg(BufReg); 10296 } 10297 MIB.cloneMemRefs(MI); 10298 10299 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10300 mainMBB->addSuccessor(sinkMBB); 10301 10302 // sinkMBB: 10303 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10304 TII->get(PPC::PHI), DstReg) 10305 .addReg(mainDstReg).addMBB(mainMBB) 10306 .addReg(restoreDstReg).addMBB(thisMBB); 10307 10308 MI.eraseFromParent(); 10309 return sinkMBB; 10310 } 10311 10312 MachineBasicBlock * 10313 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10314 MachineBasicBlock *MBB) const { 10315 DebugLoc DL = MI.getDebugLoc(); 10316 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10317 10318 MachineFunction *MF = MBB->getParent(); 10319 MachineRegisterInfo &MRI = MF->getRegInfo(); 10320 10321 MVT PVT = getPointerTy(MF->getDataLayout()); 10322 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10323 "Invalid Pointer Size!"); 10324 10325 const TargetRegisterClass *RC = 10326 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10327 unsigned Tmp = MRI.createVirtualRegister(RC); 10328 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10329 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10330 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10331 unsigned BP = 10332 (PVT == MVT::i64) 10333 ? PPC::X30 10334 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10335 : PPC::R30); 10336 10337 MachineInstrBuilder MIB; 10338 10339 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10340 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10341 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10342 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10343 10344 unsigned BufReg = MI.getOperand(0).getReg(); 10345 10346 // Reload FP (the jumped-to function may not have had a 10347 // frame pointer, and if so, then its r31 will be restored 10348 // as necessary). 10349 if (PVT == MVT::i64) { 10350 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10351 .addImm(0) 10352 .addReg(BufReg); 10353 } else { 10354 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10355 .addImm(0) 10356 .addReg(BufReg); 10357 } 10358 MIB.cloneMemRefs(MI); 10359 10360 // Reload IP 10361 if (PVT == MVT::i64) { 10362 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10363 .addImm(LabelOffset) 10364 .addReg(BufReg); 10365 } else { 10366 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10367 .addImm(LabelOffset) 10368 .addReg(BufReg); 10369 } 10370 MIB.cloneMemRefs(MI); 10371 10372 // Reload SP 10373 if (PVT == MVT::i64) { 10374 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10375 .addImm(SPOffset) 10376 .addReg(BufReg); 10377 } else { 10378 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10379 .addImm(SPOffset) 10380 .addReg(BufReg); 10381 } 10382 MIB.cloneMemRefs(MI); 10383 10384 // Reload BP 10385 if (PVT == MVT::i64) { 10386 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10387 .addImm(BPOffset) 10388 .addReg(BufReg); 10389 } else { 10390 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10391 .addImm(BPOffset) 10392 .addReg(BufReg); 10393 } 10394 MIB.cloneMemRefs(MI); 10395 10396 // Reload TOC 10397 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10398 setUsesTOCBasePtr(*MBB->getParent()); 10399 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10400 .addImm(TOCOffset) 10401 .addReg(BufReg) 10402 .cloneMemRefs(MI); 10403 } 10404 10405 // Jump 10406 BuildMI(*MBB, MI, DL, 10407 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10408 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10409 10410 MI.eraseFromParent(); 10411 return MBB; 10412 } 10413 10414 MachineBasicBlock * 10415 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10416 MachineBasicBlock *BB) const { 10417 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10418 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10419 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10420 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10421 // Call lowering should have added an r2 operand to indicate a dependence 10422 // on the TOC base pointer value. It can't however, because there is no 10423 // way to mark the dependence as implicit there, and so the stackmap code 10424 // will confuse it with a regular operand. Instead, add the dependence 10425 // here. 10426 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10427 } 10428 10429 return emitPatchPoint(MI, BB); 10430 } 10431 10432 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10433 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10434 return emitEHSjLjSetJmp(MI, BB); 10435 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10436 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10437 return emitEHSjLjLongJmp(MI, BB); 10438 } 10439 10440 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10441 10442 // To "insert" these instructions we actually have to insert their 10443 // control-flow patterns. 10444 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10445 MachineFunction::iterator It = ++BB->getIterator(); 10446 10447 MachineFunction *F = BB->getParent(); 10448 10449 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10450 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10451 MI.getOpcode() == PPC::SELECT_I8) { 10452 SmallVector<MachineOperand, 2> Cond; 10453 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10454 MI.getOpcode() == PPC::SELECT_CC_I8) 10455 Cond.push_back(MI.getOperand(4)); 10456 else 10457 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10458 Cond.push_back(MI.getOperand(1)); 10459 10460 DebugLoc dl = MI.getDebugLoc(); 10461 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10462 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10463 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10464 MI.getOpcode() == PPC::SELECT_CC_I8 || 10465 MI.getOpcode() == PPC::SELECT_CC_F4 || 10466 MI.getOpcode() == PPC::SELECT_CC_F8 || 10467 MI.getOpcode() == PPC::SELECT_CC_F16 || 10468 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10469 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10470 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10471 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10472 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10473 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10474 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10475 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10476 MI.getOpcode() == PPC::SELECT_CC_SPE || 10477 MI.getOpcode() == PPC::SELECT_I4 || 10478 MI.getOpcode() == PPC::SELECT_I8 || 10479 MI.getOpcode() == PPC::SELECT_F4 || 10480 MI.getOpcode() == PPC::SELECT_F8 || 10481 MI.getOpcode() == PPC::SELECT_F16 || 10482 MI.getOpcode() == PPC::SELECT_QFRC || 10483 MI.getOpcode() == PPC::SELECT_QSRC || 10484 MI.getOpcode() == PPC::SELECT_QBRC || 10485 MI.getOpcode() == PPC::SELECT_SPE || 10486 MI.getOpcode() == PPC::SELECT_SPE4 || 10487 MI.getOpcode() == PPC::SELECT_VRRC || 10488 MI.getOpcode() == PPC::SELECT_VSFRC || 10489 MI.getOpcode() == PPC::SELECT_VSSRC || 10490 MI.getOpcode() == PPC::SELECT_VSRC) { 10491 // The incoming instruction knows the destination vreg to set, the 10492 // condition code register to branch on, the true/false values to 10493 // select between, and a branch opcode to use. 10494 10495 // thisMBB: 10496 // ... 10497 // TrueVal = ... 10498 // cmpTY ccX, r1, r2 10499 // bCC copy1MBB 10500 // fallthrough --> copy0MBB 10501 MachineBasicBlock *thisMBB = BB; 10502 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10503 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10504 DebugLoc dl = MI.getDebugLoc(); 10505 F->insert(It, copy0MBB); 10506 F->insert(It, sinkMBB); 10507 10508 // Transfer the remainder of BB and its successor edges to sinkMBB. 10509 sinkMBB->splice(sinkMBB->begin(), BB, 10510 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10511 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10512 10513 // Next, add the true and fallthrough blocks as its successors. 10514 BB->addSuccessor(copy0MBB); 10515 BB->addSuccessor(sinkMBB); 10516 10517 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10518 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10519 MI.getOpcode() == PPC::SELECT_F16 || 10520 MI.getOpcode() == PPC::SELECT_SPE4 || 10521 MI.getOpcode() == PPC::SELECT_SPE || 10522 MI.getOpcode() == PPC::SELECT_QFRC || 10523 MI.getOpcode() == PPC::SELECT_QSRC || 10524 MI.getOpcode() == PPC::SELECT_QBRC || 10525 MI.getOpcode() == PPC::SELECT_VRRC || 10526 MI.getOpcode() == PPC::SELECT_VSFRC || 10527 MI.getOpcode() == PPC::SELECT_VSSRC || 10528 MI.getOpcode() == PPC::SELECT_VSRC) { 10529 BuildMI(BB, dl, TII->get(PPC::BC)) 10530 .addReg(MI.getOperand(1).getReg()) 10531 .addMBB(sinkMBB); 10532 } else { 10533 unsigned SelectPred = MI.getOperand(4).getImm(); 10534 BuildMI(BB, dl, TII->get(PPC::BCC)) 10535 .addImm(SelectPred) 10536 .addReg(MI.getOperand(1).getReg()) 10537 .addMBB(sinkMBB); 10538 } 10539 10540 // copy0MBB: 10541 // %FalseValue = ... 10542 // # fallthrough to sinkMBB 10543 BB = copy0MBB; 10544 10545 // Update machine-CFG edges 10546 BB->addSuccessor(sinkMBB); 10547 10548 // sinkMBB: 10549 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10550 // ... 10551 BB = sinkMBB; 10552 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10553 .addReg(MI.getOperand(3).getReg()) 10554 .addMBB(copy0MBB) 10555 .addReg(MI.getOperand(2).getReg()) 10556 .addMBB(thisMBB); 10557 } else if (MI.getOpcode() == PPC::ReadTB) { 10558 // To read the 64-bit time-base register on a 32-bit target, we read the 10559 // two halves. Should the counter have wrapped while it was being read, we 10560 // need to try again. 10561 // ... 10562 // readLoop: 10563 // mfspr Rx,TBU # load from TBU 10564 // mfspr Ry,TB # load from TB 10565 // mfspr Rz,TBU # load from TBU 10566 // cmpw crX,Rx,Rz # check if 'old'='new' 10567 // bne readLoop # branch if they're not equal 10568 // ... 10569 10570 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10571 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10572 DebugLoc dl = MI.getDebugLoc(); 10573 F->insert(It, readMBB); 10574 F->insert(It, sinkMBB); 10575 10576 // Transfer the remainder of BB and its successor edges to sinkMBB. 10577 sinkMBB->splice(sinkMBB->begin(), BB, 10578 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10579 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10580 10581 BB->addSuccessor(readMBB); 10582 BB = readMBB; 10583 10584 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10585 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10586 unsigned LoReg = MI.getOperand(0).getReg(); 10587 unsigned HiReg = MI.getOperand(1).getReg(); 10588 10589 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10590 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10591 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10592 10593 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10594 10595 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10596 .addReg(HiReg) 10597 .addReg(ReadAgainReg); 10598 BuildMI(BB, dl, TII->get(PPC::BCC)) 10599 .addImm(PPC::PRED_NE) 10600 .addReg(CmpReg) 10601 .addMBB(readMBB); 10602 10603 BB->addSuccessor(readMBB); 10604 BB->addSuccessor(sinkMBB); 10605 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10606 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10607 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10608 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10609 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10610 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10611 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10612 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10613 10614 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10615 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10616 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10617 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10618 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10619 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10620 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10621 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10622 10623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10624 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10625 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10626 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10627 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10628 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10629 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10630 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10631 10632 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10633 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10634 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10635 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10636 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10637 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10638 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10639 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10640 10641 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10642 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10643 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10644 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10645 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10646 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10647 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10648 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10649 10650 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10651 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10652 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10653 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10654 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10655 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10656 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10657 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10658 10659 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10660 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10661 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10662 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10663 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10664 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10665 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10666 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10667 10668 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10669 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10670 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10671 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10672 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10673 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10674 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10675 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10676 10677 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10678 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10679 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10680 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10681 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10682 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10683 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10684 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10685 10686 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10687 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10688 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10689 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10690 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10691 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10692 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10693 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10694 10695 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10696 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10697 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10698 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10699 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10700 BB = EmitAtomicBinary(MI, BB, 4, 0); 10701 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10702 BB = EmitAtomicBinary(MI, BB, 8, 0); 10703 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10704 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10705 (Subtarget.hasPartwordAtomics() && 10706 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10707 (Subtarget.hasPartwordAtomics() && 10708 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10709 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10710 10711 auto LoadMnemonic = PPC::LDARX; 10712 auto StoreMnemonic = PPC::STDCX; 10713 switch (MI.getOpcode()) { 10714 default: 10715 llvm_unreachable("Compare and swap of unknown size"); 10716 case PPC::ATOMIC_CMP_SWAP_I8: 10717 LoadMnemonic = PPC::LBARX; 10718 StoreMnemonic = PPC::STBCX; 10719 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10720 break; 10721 case PPC::ATOMIC_CMP_SWAP_I16: 10722 LoadMnemonic = PPC::LHARX; 10723 StoreMnemonic = PPC::STHCX; 10724 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10725 break; 10726 case PPC::ATOMIC_CMP_SWAP_I32: 10727 LoadMnemonic = PPC::LWARX; 10728 StoreMnemonic = PPC::STWCX; 10729 break; 10730 case PPC::ATOMIC_CMP_SWAP_I64: 10731 LoadMnemonic = PPC::LDARX; 10732 StoreMnemonic = PPC::STDCX; 10733 break; 10734 } 10735 unsigned dest = MI.getOperand(0).getReg(); 10736 unsigned ptrA = MI.getOperand(1).getReg(); 10737 unsigned ptrB = MI.getOperand(2).getReg(); 10738 unsigned oldval = MI.getOperand(3).getReg(); 10739 unsigned newval = MI.getOperand(4).getReg(); 10740 DebugLoc dl = MI.getDebugLoc(); 10741 10742 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10743 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10744 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10745 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10746 F->insert(It, loop1MBB); 10747 F->insert(It, loop2MBB); 10748 F->insert(It, midMBB); 10749 F->insert(It, exitMBB); 10750 exitMBB->splice(exitMBB->begin(), BB, 10751 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10752 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10753 10754 // thisMBB: 10755 // ... 10756 // fallthrough --> loopMBB 10757 BB->addSuccessor(loop1MBB); 10758 10759 // loop1MBB: 10760 // l[bhwd]arx dest, ptr 10761 // cmp[wd] dest, oldval 10762 // bne- midMBB 10763 // loop2MBB: 10764 // st[bhwd]cx. newval, ptr 10765 // bne- loopMBB 10766 // b exitBB 10767 // midMBB: 10768 // st[bhwd]cx. dest, ptr 10769 // exitBB: 10770 BB = loop1MBB; 10771 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 10772 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10773 .addReg(oldval) 10774 .addReg(dest); 10775 BuildMI(BB, dl, TII->get(PPC::BCC)) 10776 .addImm(PPC::PRED_NE) 10777 .addReg(PPC::CR0) 10778 .addMBB(midMBB); 10779 BB->addSuccessor(loop2MBB); 10780 BB->addSuccessor(midMBB); 10781 10782 BB = loop2MBB; 10783 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10784 .addReg(newval) 10785 .addReg(ptrA) 10786 .addReg(ptrB); 10787 BuildMI(BB, dl, TII->get(PPC::BCC)) 10788 .addImm(PPC::PRED_NE) 10789 .addReg(PPC::CR0) 10790 .addMBB(loop1MBB); 10791 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10792 BB->addSuccessor(loop1MBB); 10793 BB->addSuccessor(exitMBB); 10794 10795 BB = midMBB; 10796 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10797 .addReg(dest) 10798 .addReg(ptrA) 10799 .addReg(ptrB); 10800 BB->addSuccessor(exitMBB); 10801 10802 // exitMBB: 10803 // ... 10804 BB = exitMBB; 10805 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10806 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10807 // We must use 64-bit registers for addresses when targeting 64-bit, 10808 // since we're actually doing arithmetic on them. Other registers 10809 // can be 32-bit. 10810 bool is64bit = Subtarget.isPPC64(); 10811 bool isLittleEndian = Subtarget.isLittleEndian(); 10812 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10813 10814 unsigned dest = MI.getOperand(0).getReg(); 10815 unsigned ptrA = MI.getOperand(1).getReg(); 10816 unsigned ptrB = MI.getOperand(2).getReg(); 10817 unsigned oldval = MI.getOperand(3).getReg(); 10818 unsigned newval = MI.getOperand(4).getReg(); 10819 DebugLoc dl = MI.getDebugLoc(); 10820 10821 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10822 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10823 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10824 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10825 F->insert(It, loop1MBB); 10826 F->insert(It, loop2MBB); 10827 F->insert(It, midMBB); 10828 F->insert(It, exitMBB); 10829 exitMBB->splice(exitMBB->begin(), BB, 10830 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10831 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10832 10833 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10834 const TargetRegisterClass *RC = 10835 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10836 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10837 10838 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10839 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10840 unsigned ShiftReg = 10841 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10842 unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 10843 unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 10844 unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 10845 unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 10846 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 10847 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10848 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10849 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10850 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10851 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10852 unsigned Ptr1Reg; 10853 unsigned TmpReg = RegInfo.createVirtualRegister(GPRC); 10854 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10855 // thisMBB: 10856 // ... 10857 // fallthrough --> loopMBB 10858 BB->addSuccessor(loop1MBB); 10859 10860 // The 4-byte load must be aligned, while a char or short may be 10861 // anywhere in the word. Hence all this nasty bookkeeping code. 10862 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10863 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10864 // xori shift, shift1, 24 [16] 10865 // rlwinm ptr, ptr1, 0, 0, 29 10866 // slw newval2, newval, shift 10867 // slw oldval2, oldval,shift 10868 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10869 // slw mask, mask2, shift 10870 // and newval3, newval2, mask 10871 // and oldval3, oldval2, mask 10872 // loop1MBB: 10873 // lwarx tmpDest, ptr 10874 // and tmp, tmpDest, mask 10875 // cmpw tmp, oldval3 10876 // bne- midMBB 10877 // loop2MBB: 10878 // andc tmp2, tmpDest, mask 10879 // or tmp4, tmp2, newval3 10880 // stwcx. tmp4, ptr 10881 // bne- loop1MBB 10882 // b exitBB 10883 // midMBB: 10884 // stwcx. tmpDest, ptr 10885 // exitBB: 10886 // srw dest, tmpDest, shift 10887 if (ptrA != ZeroReg) { 10888 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10889 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10890 .addReg(ptrA) 10891 .addReg(ptrB); 10892 } else { 10893 Ptr1Reg = ptrB; 10894 } 10895 10896 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10897 // mode. 10898 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10899 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10900 .addImm(3) 10901 .addImm(27) 10902 .addImm(is8bit ? 28 : 27); 10903 if (!isLittleEndian) 10904 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10905 .addReg(Shift1Reg) 10906 .addImm(is8bit ? 24 : 16); 10907 if (is64bit) 10908 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10909 .addReg(Ptr1Reg) 10910 .addImm(0) 10911 .addImm(61); 10912 else 10913 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10914 .addReg(Ptr1Reg) 10915 .addImm(0) 10916 .addImm(0) 10917 .addImm(29); 10918 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10919 .addReg(newval) 10920 .addReg(ShiftReg); 10921 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10922 .addReg(oldval) 10923 .addReg(ShiftReg); 10924 if (is8bit) 10925 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10926 else { 10927 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10928 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10929 .addReg(Mask3Reg) 10930 .addImm(65535); 10931 } 10932 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10933 .addReg(Mask2Reg) 10934 .addReg(ShiftReg); 10935 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10936 .addReg(NewVal2Reg) 10937 .addReg(MaskReg); 10938 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10939 .addReg(OldVal2Reg) 10940 .addReg(MaskReg); 10941 10942 BB = loop1MBB; 10943 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10944 .addReg(ZeroReg) 10945 .addReg(PtrReg); 10946 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 10947 .addReg(TmpDestReg) 10948 .addReg(MaskReg); 10949 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10950 .addReg(TmpReg) 10951 .addReg(OldVal3Reg); 10952 BuildMI(BB, dl, TII->get(PPC::BCC)) 10953 .addImm(PPC::PRED_NE) 10954 .addReg(PPC::CR0) 10955 .addMBB(midMBB); 10956 BB->addSuccessor(loop2MBB); 10957 BB->addSuccessor(midMBB); 10958 10959 BB = loop2MBB; 10960 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10961 .addReg(TmpDestReg) 10962 .addReg(MaskReg); 10963 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 10964 .addReg(Tmp2Reg) 10965 .addReg(NewVal3Reg); 10966 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10967 .addReg(Tmp4Reg) 10968 .addReg(ZeroReg) 10969 .addReg(PtrReg); 10970 BuildMI(BB, dl, TII->get(PPC::BCC)) 10971 .addImm(PPC::PRED_NE) 10972 .addReg(PPC::CR0) 10973 .addMBB(loop1MBB); 10974 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10975 BB->addSuccessor(loop1MBB); 10976 BB->addSuccessor(exitMBB); 10977 10978 BB = midMBB; 10979 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10980 .addReg(TmpDestReg) 10981 .addReg(ZeroReg) 10982 .addReg(PtrReg); 10983 BB->addSuccessor(exitMBB); 10984 10985 // exitMBB: 10986 // ... 10987 BB = exitMBB; 10988 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10989 .addReg(TmpReg) 10990 .addReg(ShiftReg); 10991 } else if (MI.getOpcode() == PPC::FADDrtz) { 10992 // This pseudo performs an FADD with rounding mode temporarily forced 10993 // to round-to-zero. We emit this via custom inserter since the FPSCR 10994 // is not modeled at the SelectionDAG level. 10995 unsigned Dest = MI.getOperand(0).getReg(); 10996 unsigned Src1 = MI.getOperand(1).getReg(); 10997 unsigned Src2 = MI.getOperand(2).getReg(); 10998 DebugLoc dl = MI.getDebugLoc(); 10999 11000 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11001 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11002 11003 // Save FPSCR value. 11004 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11005 11006 // Set rounding mode to round-to-zero. 11007 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11008 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11009 11010 // Perform addition. 11011 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11012 11013 // Restore FPSCR value. 11014 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11015 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11016 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11017 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11018 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11019 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11020 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11021 ? PPC::ANDIo8 11022 : PPC::ANDIo; 11023 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11024 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11025 11026 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11027 unsigned Dest = RegInfo.createVirtualRegister( 11028 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11029 11030 DebugLoc dl = MI.getDebugLoc(); 11031 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11032 .addReg(MI.getOperand(1).getReg()) 11033 .addImm(1); 11034 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11035 MI.getOperand(0).getReg()) 11036 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11037 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11038 DebugLoc Dl = MI.getDebugLoc(); 11039 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11040 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11041 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11042 return BB; 11043 } else if (MI.getOpcode() == PPC::SETRNDi) { 11044 DebugLoc dl = MI.getDebugLoc(); 11045 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11046 11047 // Save FPSCR value. 11048 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11049 11050 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11051 // the following settings: 11052 // 00 Round to nearest 11053 // 01 Round to 0 11054 // 10 Round to +inf 11055 // 11 Round to -inf 11056 11057 // When the operand is immediate, using the two least significant bits of 11058 // the immediate to set the bits 62:63 of FPSCR. 11059 unsigned Mode = MI.getOperand(1).getImm(); 11060 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11061 .addImm(31); 11062 11063 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11064 .addImm(30); 11065 } else if (MI.getOpcode() == PPC::SETRND) { 11066 DebugLoc dl = MI.getDebugLoc(); 11067 11068 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11069 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11070 // If the target doesn't have DirectMove, we should use stack to do the 11071 // conversion, because the target doesn't have the instructions like mtvsrd 11072 // or mfvsrd to do this conversion directly. 11073 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11074 if (Subtarget.hasDirectMove()) { 11075 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11076 .addReg(SrcReg); 11077 } else { 11078 // Use stack to do the register copy. 11079 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11080 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11081 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11082 if (RC == &PPC::F8RCRegClass) { 11083 // Copy register from F8RCRegClass to G8RCRegclass. 11084 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11085 "Unsupported RegClass."); 11086 11087 StoreOp = PPC::STFD; 11088 LoadOp = PPC::LD; 11089 } else { 11090 // Copy register from G8RCRegClass to F8RCRegclass. 11091 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11092 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11093 "Unsupported RegClass."); 11094 } 11095 11096 MachineFrameInfo &MFI = F->getFrameInfo(); 11097 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11098 11099 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11100 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11101 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11102 MFI.getObjectAlignment(FrameIdx)); 11103 11104 // Store the SrcReg into the stack. 11105 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11106 .addReg(SrcReg) 11107 .addImm(0) 11108 .addFrameIndex(FrameIdx) 11109 .addMemOperand(MMOStore); 11110 11111 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11112 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11113 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11114 MFI.getObjectAlignment(FrameIdx)); 11115 11116 // Load from the stack where SrcReg is stored, and save to DestReg, 11117 // so we have done the RegClass conversion from RegClass::SrcReg to 11118 // RegClass::DestReg. 11119 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11120 .addImm(0) 11121 .addFrameIndex(FrameIdx) 11122 .addMemOperand(MMOLoad); 11123 } 11124 }; 11125 11126 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11127 11128 // Save FPSCR value. 11129 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11130 11131 // When the operand is gprc register, use two least significant bits of the 11132 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11133 // 11134 // copy OldFPSCRTmpReg, OldFPSCRReg 11135 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11136 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11137 // copy NewFPSCRReg, NewFPSCRTmpReg 11138 // mtfsf 255, NewFPSCRReg 11139 MachineOperand SrcOp = MI.getOperand(1); 11140 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11141 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11142 11143 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11144 11145 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11146 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11147 11148 // The first operand of INSERT_SUBREG should be a register which has 11149 // subregisters, we only care about its RegClass, so we should use an 11150 // IMPLICIT_DEF register. 11151 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11152 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11153 .addReg(ImDefReg) 11154 .add(SrcOp) 11155 .addImm(1); 11156 11157 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11158 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11159 .addReg(OldFPSCRTmpReg) 11160 .addReg(ExtSrcReg) 11161 .addImm(0) 11162 .addImm(62); 11163 11164 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11165 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11166 11167 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11168 // bits of FPSCR. 11169 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11170 .addImm(255) 11171 .addReg(NewFPSCRReg) 11172 .addImm(0) 11173 .addImm(0); 11174 } else { 11175 llvm_unreachable("Unexpected instr type to insert"); 11176 } 11177 11178 MI.eraseFromParent(); // The pseudo instruction is gone now. 11179 return BB; 11180 } 11181 11182 //===----------------------------------------------------------------------===// 11183 // Target Optimization Hooks 11184 //===----------------------------------------------------------------------===// 11185 11186 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11187 // For the estimates, convergence is quadratic, so we essentially double the 11188 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11189 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11190 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11191 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11192 if (VT.getScalarType() == MVT::f64) 11193 RefinementSteps++; 11194 return RefinementSteps; 11195 } 11196 11197 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11198 int Enabled, int &RefinementSteps, 11199 bool &UseOneConstNR, 11200 bool Reciprocal) const { 11201 EVT VT = Operand.getValueType(); 11202 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11203 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11204 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11205 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11206 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11207 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11208 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11209 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11210 11211 // The Newton-Raphson computation with a single constant does not provide 11212 // enough accuracy on some CPUs. 11213 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11214 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11215 } 11216 return SDValue(); 11217 } 11218 11219 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11220 int Enabled, 11221 int &RefinementSteps) const { 11222 EVT VT = Operand.getValueType(); 11223 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11224 (VT == MVT::f64 && Subtarget.hasFRE()) || 11225 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11226 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11227 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11228 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11229 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11230 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11231 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11232 } 11233 return SDValue(); 11234 } 11235 11236 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11237 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11238 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11239 // enabled for division), this functionality is redundant with the default 11240 // combiner logic (once the division -> reciprocal/multiply transformation 11241 // has taken place). As a result, this matters more for older cores than for 11242 // newer ones. 11243 11244 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11245 // reciprocal if there are two or more FDIVs (for embedded cores with only 11246 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11247 switch (Subtarget.getDarwinDirective()) { 11248 default: 11249 return 3; 11250 case PPC::DIR_440: 11251 case PPC::DIR_A2: 11252 case PPC::DIR_E500: 11253 case PPC::DIR_E500mc: 11254 case PPC::DIR_E5500: 11255 return 2; 11256 } 11257 } 11258 11259 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11260 // collapsed, and so we need to look through chains of them. 11261 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11262 int64_t& Offset, SelectionDAG &DAG) { 11263 if (DAG.isBaseWithConstantOffset(Loc)) { 11264 Base = Loc.getOperand(0); 11265 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11266 11267 // The base might itself be a base plus an offset, and if so, accumulate 11268 // that as well. 11269 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11270 } 11271 } 11272 11273 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11274 unsigned Bytes, int Dist, 11275 SelectionDAG &DAG) { 11276 if (VT.getSizeInBits() / 8 != Bytes) 11277 return false; 11278 11279 SDValue BaseLoc = Base->getBasePtr(); 11280 if (Loc.getOpcode() == ISD::FrameIndex) { 11281 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11282 return false; 11283 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11284 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11285 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11286 int FS = MFI.getObjectSize(FI); 11287 int BFS = MFI.getObjectSize(BFI); 11288 if (FS != BFS || FS != (int)Bytes) return false; 11289 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11290 } 11291 11292 SDValue Base1 = Loc, Base2 = BaseLoc; 11293 int64_t Offset1 = 0, Offset2 = 0; 11294 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11295 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11296 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11297 return true; 11298 11299 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11300 const GlobalValue *GV1 = nullptr; 11301 const GlobalValue *GV2 = nullptr; 11302 Offset1 = 0; 11303 Offset2 = 0; 11304 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11305 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11306 if (isGA1 && isGA2 && GV1 == GV2) 11307 return Offset1 == (Offset2 + Dist*Bytes); 11308 return false; 11309 } 11310 11311 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11312 // not enforce equality of the chain operands. 11313 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11314 unsigned Bytes, int Dist, 11315 SelectionDAG &DAG) { 11316 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11317 EVT VT = LS->getMemoryVT(); 11318 SDValue Loc = LS->getBasePtr(); 11319 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11320 } 11321 11322 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11323 EVT VT; 11324 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11325 default: return false; 11326 case Intrinsic::ppc_qpx_qvlfd: 11327 case Intrinsic::ppc_qpx_qvlfda: 11328 VT = MVT::v4f64; 11329 break; 11330 case Intrinsic::ppc_qpx_qvlfs: 11331 case Intrinsic::ppc_qpx_qvlfsa: 11332 VT = MVT::v4f32; 11333 break; 11334 case Intrinsic::ppc_qpx_qvlfcd: 11335 case Intrinsic::ppc_qpx_qvlfcda: 11336 VT = MVT::v2f64; 11337 break; 11338 case Intrinsic::ppc_qpx_qvlfcs: 11339 case Intrinsic::ppc_qpx_qvlfcsa: 11340 VT = MVT::v2f32; 11341 break; 11342 case Intrinsic::ppc_qpx_qvlfiwa: 11343 case Intrinsic::ppc_qpx_qvlfiwz: 11344 case Intrinsic::ppc_altivec_lvx: 11345 case Intrinsic::ppc_altivec_lvxl: 11346 case Intrinsic::ppc_vsx_lxvw4x: 11347 case Intrinsic::ppc_vsx_lxvw4x_be: 11348 VT = MVT::v4i32; 11349 break; 11350 case Intrinsic::ppc_vsx_lxvd2x: 11351 case Intrinsic::ppc_vsx_lxvd2x_be: 11352 VT = MVT::v2f64; 11353 break; 11354 case Intrinsic::ppc_altivec_lvebx: 11355 VT = MVT::i8; 11356 break; 11357 case Intrinsic::ppc_altivec_lvehx: 11358 VT = MVT::i16; 11359 break; 11360 case Intrinsic::ppc_altivec_lvewx: 11361 VT = MVT::i32; 11362 break; 11363 } 11364 11365 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11366 } 11367 11368 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11369 EVT VT; 11370 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11371 default: return false; 11372 case Intrinsic::ppc_qpx_qvstfd: 11373 case Intrinsic::ppc_qpx_qvstfda: 11374 VT = MVT::v4f64; 11375 break; 11376 case Intrinsic::ppc_qpx_qvstfs: 11377 case Intrinsic::ppc_qpx_qvstfsa: 11378 VT = MVT::v4f32; 11379 break; 11380 case Intrinsic::ppc_qpx_qvstfcd: 11381 case Intrinsic::ppc_qpx_qvstfcda: 11382 VT = MVT::v2f64; 11383 break; 11384 case Intrinsic::ppc_qpx_qvstfcs: 11385 case Intrinsic::ppc_qpx_qvstfcsa: 11386 VT = MVT::v2f32; 11387 break; 11388 case Intrinsic::ppc_qpx_qvstfiw: 11389 case Intrinsic::ppc_qpx_qvstfiwa: 11390 case Intrinsic::ppc_altivec_stvx: 11391 case Intrinsic::ppc_altivec_stvxl: 11392 case Intrinsic::ppc_vsx_stxvw4x: 11393 VT = MVT::v4i32; 11394 break; 11395 case Intrinsic::ppc_vsx_stxvd2x: 11396 VT = MVT::v2f64; 11397 break; 11398 case Intrinsic::ppc_vsx_stxvw4x_be: 11399 VT = MVT::v4i32; 11400 break; 11401 case Intrinsic::ppc_vsx_stxvd2x_be: 11402 VT = MVT::v2f64; 11403 break; 11404 case Intrinsic::ppc_altivec_stvebx: 11405 VT = MVT::i8; 11406 break; 11407 case Intrinsic::ppc_altivec_stvehx: 11408 VT = MVT::i16; 11409 break; 11410 case Intrinsic::ppc_altivec_stvewx: 11411 VT = MVT::i32; 11412 break; 11413 } 11414 11415 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11416 } 11417 11418 return false; 11419 } 11420 11421 // Return true is there is a nearyby consecutive load to the one provided 11422 // (regardless of alignment). We search up and down the chain, looking though 11423 // token factors and other loads (but nothing else). As a result, a true result 11424 // indicates that it is safe to create a new consecutive load adjacent to the 11425 // load provided. 11426 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11427 SDValue Chain = LD->getChain(); 11428 EVT VT = LD->getMemoryVT(); 11429 11430 SmallSet<SDNode *, 16> LoadRoots; 11431 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11432 SmallSet<SDNode *, 16> Visited; 11433 11434 // First, search up the chain, branching to follow all token-factor operands. 11435 // If we find a consecutive load, then we're done, otherwise, record all 11436 // nodes just above the top-level loads and token factors. 11437 while (!Queue.empty()) { 11438 SDNode *ChainNext = Queue.pop_back_val(); 11439 if (!Visited.insert(ChainNext).second) 11440 continue; 11441 11442 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11443 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11444 return true; 11445 11446 if (!Visited.count(ChainLD->getChain().getNode())) 11447 Queue.push_back(ChainLD->getChain().getNode()); 11448 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11449 for (const SDUse &O : ChainNext->ops()) 11450 if (!Visited.count(O.getNode())) 11451 Queue.push_back(O.getNode()); 11452 } else 11453 LoadRoots.insert(ChainNext); 11454 } 11455 11456 // Second, search down the chain, starting from the top-level nodes recorded 11457 // in the first phase. These top-level nodes are the nodes just above all 11458 // loads and token factors. Starting with their uses, recursively look though 11459 // all loads (just the chain uses) and token factors to find a consecutive 11460 // load. 11461 Visited.clear(); 11462 Queue.clear(); 11463 11464 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11465 IE = LoadRoots.end(); I != IE; ++I) { 11466 Queue.push_back(*I); 11467 11468 while (!Queue.empty()) { 11469 SDNode *LoadRoot = Queue.pop_back_val(); 11470 if (!Visited.insert(LoadRoot).second) 11471 continue; 11472 11473 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11474 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11475 return true; 11476 11477 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11478 UE = LoadRoot->use_end(); UI != UE; ++UI) 11479 if (((isa<MemSDNode>(*UI) && 11480 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11481 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11482 Queue.push_back(*UI); 11483 } 11484 } 11485 11486 return false; 11487 } 11488 11489 /// This function is called when we have proved that a SETCC node can be replaced 11490 /// by subtraction (and other supporting instructions) so that the result of 11491 /// comparison is kept in a GPR instead of CR. This function is purely for 11492 /// codegen purposes and has some flags to guide the codegen process. 11493 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11494 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11495 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11496 11497 // Zero extend the operands to the largest legal integer. Originally, they 11498 // must be of a strictly smaller size. 11499 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11500 DAG.getConstant(Size, DL, MVT::i32)); 11501 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11502 DAG.getConstant(Size, DL, MVT::i32)); 11503 11504 // Swap if needed. Depends on the condition code. 11505 if (Swap) 11506 std::swap(Op0, Op1); 11507 11508 // Subtract extended integers. 11509 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11510 11511 // Move the sign bit to the least significant position and zero out the rest. 11512 // Now the least significant bit carries the result of original comparison. 11513 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11514 DAG.getConstant(Size - 1, DL, MVT::i32)); 11515 auto Final = Shifted; 11516 11517 // Complement the result if needed. Based on the condition code. 11518 if (Complement) 11519 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11520 DAG.getConstant(1, DL, MVT::i64)); 11521 11522 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11523 } 11524 11525 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11526 DAGCombinerInfo &DCI) const { 11527 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11528 11529 SelectionDAG &DAG = DCI.DAG; 11530 SDLoc DL(N); 11531 11532 // Size of integers being compared has a critical role in the following 11533 // analysis, so we prefer to do this when all types are legal. 11534 if (!DCI.isAfterLegalizeDAG()) 11535 return SDValue(); 11536 11537 // If all users of SETCC extend its value to a legal integer type 11538 // then we replace SETCC with a subtraction 11539 for (SDNode::use_iterator UI = N->use_begin(), 11540 UE = N->use_end(); UI != UE; ++UI) { 11541 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11542 return SDValue(); 11543 } 11544 11545 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11546 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11547 11548 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11549 11550 if (OpSize < Size) { 11551 switch (CC) { 11552 default: break; 11553 case ISD::SETULT: 11554 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11555 case ISD::SETULE: 11556 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11557 case ISD::SETUGT: 11558 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11559 case ISD::SETUGE: 11560 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11561 } 11562 } 11563 11564 return SDValue(); 11565 } 11566 11567 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11568 DAGCombinerInfo &DCI) const { 11569 SelectionDAG &DAG = DCI.DAG; 11570 SDLoc dl(N); 11571 11572 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11573 // If we're tracking CR bits, we need to be careful that we don't have: 11574 // trunc(binary-ops(zext(x), zext(y))) 11575 // or 11576 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11577 // such that we're unnecessarily moving things into GPRs when it would be 11578 // better to keep them in CR bits. 11579 11580 // Note that trunc here can be an actual i1 trunc, or can be the effective 11581 // truncation that comes from a setcc or select_cc. 11582 if (N->getOpcode() == ISD::TRUNCATE && 11583 N->getValueType(0) != MVT::i1) 11584 return SDValue(); 11585 11586 if (N->getOperand(0).getValueType() != MVT::i32 && 11587 N->getOperand(0).getValueType() != MVT::i64) 11588 return SDValue(); 11589 11590 if (N->getOpcode() == ISD::SETCC || 11591 N->getOpcode() == ISD::SELECT_CC) { 11592 // If we're looking at a comparison, then we need to make sure that the 11593 // high bits (all except for the first) don't matter the result. 11594 ISD::CondCode CC = 11595 cast<CondCodeSDNode>(N->getOperand( 11596 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11597 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11598 11599 if (ISD::isSignedIntSetCC(CC)) { 11600 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11601 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11602 return SDValue(); 11603 } else if (ISD::isUnsignedIntSetCC(CC)) { 11604 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11605 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11606 !DAG.MaskedValueIsZero(N->getOperand(1), 11607 APInt::getHighBitsSet(OpBits, OpBits-1))) 11608 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11609 : SDValue()); 11610 } else { 11611 // This is neither a signed nor an unsigned comparison, just make sure 11612 // that the high bits are equal. 11613 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11614 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11615 11616 // We don't really care about what is known about the first bit (if 11617 // anything), so clear it in all masks prior to comparing them. 11618 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11619 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11620 11621 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11622 return SDValue(); 11623 } 11624 } 11625 11626 // We now know that the higher-order bits are irrelevant, we just need to 11627 // make sure that all of the intermediate operations are bit operations, and 11628 // all inputs are extensions. 11629 if (N->getOperand(0).getOpcode() != ISD::AND && 11630 N->getOperand(0).getOpcode() != ISD::OR && 11631 N->getOperand(0).getOpcode() != ISD::XOR && 11632 N->getOperand(0).getOpcode() != ISD::SELECT && 11633 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11634 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11635 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11636 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11637 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11638 return SDValue(); 11639 11640 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11641 N->getOperand(1).getOpcode() != ISD::AND && 11642 N->getOperand(1).getOpcode() != ISD::OR && 11643 N->getOperand(1).getOpcode() != ISD::XOR && 11644 N->getOperand(1).getOpcode() != ISD::SELECT && 11645 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11646 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11647 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11648 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11649 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11650 return SDValue(); 11651 11652 SmallVector<SDValue, 4> Inputs; 11653 SmallVector<SDValue, 8> BinOps, PromOps; 11654 SmallPtrSet<SDNode *, 16> Visited; 11655 11656 for (unsigned i = 0; i < 2; ++i) { 11657 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11658 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11659 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11660 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11661 isa<ConstantSDNode>(N->getOperand(i))) 11662 Inputs.push_back(N->getOperand(i)); 11663 else 11664 BinOps.push_back(N->getOperand(i)); 11665 11666 if (N->getOpcode() == ISD::TRUNCATE) 11667 break; 11668 } 11669 11670 // Visit all inputs, collect all binary operations (and, or, xor and 11671 // select) that are all fed by extensions. 11672 while (!BinOps.empty()) { 11673 SDValue BinOp = BinOps.back(); 11674 BinOps.pop_back(); 11675 11676 if (!Visited.insert(BinOp.getNode()).second) 11677 continue; 11678 11679 PromOps.push_back(BinOp); 11680 11681 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11682 // The condition of the select is not promoted. 11683 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11684 continue; 11685 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11686 continue; 11687 11688 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11689 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11690 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11691 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11692 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11693 Inputs.push_back(BinOp.getOperand(i)); 11694 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11695 BinOp.getOperand(i).getOpcode() == ISD::OR || 11696 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11697 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11698 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11699 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11700 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11701 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11702 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11703 BinOps.push_back(BinOp.getOperand(i)); 11704 } else { 11705 // We have an input that is not an extension or another binary 11706 // operation; we'll abort this transformation. 11707 return SDValue(); 11708 } 11709 } 11710 } 11711 11712 // Make sure that this is a self-contained cluster of operations (which 11713 // is not quite the same thing as saying that everything has only one 11714 // use). 11715 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11716 if (isa<ConstantSDNode>(Inputs[i])) 11717 continue; 11718 11719 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11720 UE = Inputs[i].getNode()->use_end(); 11721 UI != UE; ++UI) { 11722 SDNode *User = *UI; 11723 if (User != N && !Visited.count(User)) 11724 return SDValue(); 11725 11726 // Make sure that we're not going to promote the non-output-value 11727 // operand(s) or SELECT or SELECT_CC. 11728 // FIXME: Although we could sometimes handle this, and it does occur in 11729 // practice that one of the condition inputs to the select is also one of 11730 // the outputs, we currently can't deal with this. 11731 if (User->getOpcode() == ISD::SELECT) { 11732 if (User->getOperand(0) == Inputs[i]) 11733 return SDValue(); 11734 } else if (User->getOpcode() == ISD::SELECT_CC) { 11735 if (User->getOperand(0) == Inputs[i] || 11736 User->getOperand(1) == Inputs[i]) 11737 return SDValue(); 11738 } 11739 } 11740 } 11741 11742 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11743 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11744 UE = PromOps[i].getNode()->use_end(); 11745 UI != UE; ++UI) { 11746 SDNode *User = *UI; 11747 if (User != N && !Visited.count(User)) 11748 return SDValue(); 11749 11750 // Make sure that we're not going to promote the non-output-value 11751 // operand(s) or SELECT or SELECT_CC. 11752 // FIXME: Although we could sometimes handle this, and it does occur in 11753 // practice that one of the condition inputs to the select is also one of 11754 // the outputs, we currently can't deal with this. 11755 if (User->getOpcode() == ISD::SELECT) { 11756 if (User->getOperand(0) == PromOps[i]) 11757 return SDValue(); 11758 } else if (User->getOpcode() == ISD::SELECT_CC) { 11759 if (User->getOperand(0) == PromOps[i] || 11760 User->getOperand(1) == PromOps[i]) 11761 return SDValue(); 11762 } 11763 } 11764 } 11765 11766 // Replace all inputs with the extension operand. 11767 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11768 // Constants may have users outside the cluster of to-be-promoted nodes, 11769 // and so we need to replace those as we do the promotions. 11770 if (isa<ConstantSDNode>(Inputs[i])) 11771 continue; 11772 else 11773 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11774 } 11775 11776 std::list<HandleSDNode> PromOpHandles; 11777 for (auto &PromOp : PromOps) 11778 PromOpHandles.emplace_back(PromOp); 11779 11780 // Replace all operations (these are all the same, but have a different 11781 // (i1) return type). DAG.getNode will validate that the types of 11782 // a binary operator match, so go through the list in reverse so that 11783 // we've likely promoted both operands first. Any intermediate truncations or 11784 // extensions disappear. 11785 while (!PromOpHandles.empty()) { 11786 SDValue PromOp = PromOpHandles.back().getValue(); 11787 PromOpHandles.pop_back(); 11788 11789 if (PromOp.getOpcode() == ISD::TRUNCATE || 11790 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11791 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11792 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11793 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11794 PromOp.getOperand(0).getValueType() != MVT::i1) { 11795 // The operand is not yet ready (see comment below). 11796 PromOpHandles.emplace_front(PromOp); 11797 continue; 11798 } 11799 11800 SDValue RepValue = PromOp.getOperand(0); 11801 if (isa<ConstantSDNode>(RepValue)) 11802 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11803 11804 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11805 continue; 11806 } 11807 11808 unsigned C; 11809 switch (PromOp.getOpcode()) { 11810 default: C = 0; break; 11811 case ISD::SELECT: C = 1; break; 11812 case ISD::SELECT_CC: C = 2; break; 11813 } 11814 11815 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11816 PromOp.getOperand(C).getValueType() != MVT::i1) || 11817 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11818 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11819 // The to-be-promoted operands of this node have not yet been 11820 // promoted (this should be rare because we're going through the 11821 // list backward, but if one of the operands has several users in 11822 // this cluster of to-be-promoted nodes, it is possible). 11823 PromOpHandles.emplace_front(PromOp); 11824 continue; 11825 } 11826 11827 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11828 PromOp.getNode()->op_end()); 11829 11830 // If there are any constant inputs, make sure they're replaced now. 11831 for (unsigned i = 0; i < 2; ++i) 11832 if (isa<ConstantSDNode>(Ops[C+i])) 11833 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11834 11835 DAG.ReplaceAllUsesOfValueWith(PromOp, 11836 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11837 } 11838 11839 // Now we're left with the initial truncation itself. 11840 if (N->getOpcode() == ISD::TRUNCATE) 11841 return N->getOperand(0); 11842 11843 // Otherwise, this is a comparison. The operands to be compared have just 11844 // changed type (to i1), but everything else is the same. 11845 return SDValue(N, 0); 11846 } 11847 11848 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11849 DAGCombinerInfo &DCI) const { 11850 SelectionDAG &DAG = DCI.DAG; 11851 SDLoc dl(N); 11852 11853 // If we're tracking CR bits, we need to be careful that we don't have: 11854 // zext(binary-ops(trunc(x), trunc(y))) 11855 // or 11856 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11857 // such that we're unnecessarily moving things into CR bits that can more 11858 // efficiently stay in GPRs. Note that if we're not certain that the high 11859 // bits are set as required by the final extension, we still may need to do 11860 // some masking to get the proper behavior. 11861 11862 // This same functionality is important on PPC64 when dealing with 11863 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11864 // the return values of functions. Because it is so similar, it is handled 11865 // here as well. 11866 11867 if (N->getValueType(0) != MVT::i32 && 11868 N->getValueType(0) != MVT::i64) 11869 return SDValue(); 11870 11871 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11872 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11873 return SDValue(); 11874 11875 if (N->getOperand(0).getOpcode() != ISD::AND && 11876 N->getOperand(0).getOpcode() != ISD::OR && 11877 N->getOperand(0).getOpcode() != ISD::XOR && 11878 N->getOperand(0).getOpcode() != ISD::SELECT && 11879 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11880 return SDValue(); 11881 11882 SmallVector<SDValue, 4> Inputs; 11883 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11884 SmallPtrSet<SDNode *, 16> Visited; 11885 11886 // Visit all inputs, collect all binary operations (and, or, xor and 11887 // select) that are all fed by truncations. 11888 while (!BinOps.empty()) { 11889 SDValue BinOp = BinOps.back(); 11890 BinOps.pop_back(); 11891 11892 if (!Visited.insert(BinOp.getNode()).second) 11893 continue; 11894 11895 PromOps.push_back(BinOp); 11896 11897 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11898 // The condition of the select is not promoted. 11899 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11900 continue; 11901 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11902 continue; 11903 11904 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11905 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11906 Inputs.push_back(BinOp.getOperand(i)); 11907 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11908 BinOp.getOperand(i).getOpcode() == ISD::OR || 11909 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11910 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11911 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11912 BinOps.push_back(BinOp.getOperand(i)); 11913 } else { 11914 // We have an input that is not a truncation or another binary 11915 // operation; we'll abort this transformation. 11916 return SDValue(); 11917 } 11918 } 11919 } 11920 11921 // The operands of a select that must be truncated when the select is 11922 // promoted because the operand is actually part of the to-be-promoted set. 11923 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11924 11925 // Make sure that this is a self-contained cluster of operations (which 11926 // is not quite the same thing as saying that everything has only one 11927 // use). 11928 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11929 if (isa<ConstantSDNode>(Inputs[i])) 11930 continue; 11931 11932 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11933 UE = Inputs[i].getNode()->use_end(); 11934 UI != UE; ++UI) { 11935 SDNode *User = *UI; 11936 if (User != N && !Visited.count(User)) 11937 return SDValue(); 11938 11939 // If we're going to promote the non-output-value operand(s) or SELECT or 11940 // SELECT_CC, record them for truncation. 11941 if (User->getOpcode() == ISD::SELECT) { 11942 if (User->getOperand(0) == Inputs[i]) 11943 SelectTruncOp[0].insert(std::make_pair(User, 11944 User->getOperand(0).getValueType())); 11945 } else if (User->getOpcode() == ISD::SELECT_CC) { 11946 if (User->getOperand(0) == Inputs[i]) 11947 SelectTruncOp[0].insert(std::make_pair(User, 11948 User->getOperand(0).getValueType())); 11949 if (User->getOperand(1) == Inputs[i]) 11950 SelectTruncOp[1].insert(std::make_pair(User, 11951 User->getOperand(1).getValueType())); 11952 } 11953 } 11954 } 11955 11956 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11957 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11958 UE = PromOps[i].getNode()->use_end(); 11959 UI != UE; ++UI) { 11960 SDNode *User = *UI; 11961 if (User != N && !Visited.count(User)) 11962 return SDValue(); 11963 11964 // If we're going to promote the non-output-value operand(s) or SELECT or 11965 // SELECT_CC, record them for truncation. 11966 if (User->getOpcode() == ISD::SELECT) { 11967 if (User->getOperand(0) == PromOps[i]) 11968 SelectTruncOp[0].insert(std::make_pair(User, 11969 User->getOperand(0).getValueType())); 11970 } else if (User->getOpcode() == ISD::SELECT_CC) { 11971 if (User->getOperand(0) == PromOps[i]) 11972 SelectTruncOp[0].insert(std::make_pair(User, 11973 User->getOperand(0).getValueType())); 11974 if (User->getOperand(1) == PromOps[i]) 11975 SelectTruncOp[1].insert(std::make_pair(User, 11976 User->getOperand(1).getValueType())); 11977 } 11978 } 11979 } 11980 11981 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11982 bool ReallyNeedsExt = false; 11983 if (N->getOpcode() != ISD::ANY_EXTEND) { 11984 // If all of the inputs are not already sign/zero extended, then 11985 // we'll still need to do that at the end. 11986 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11987 if (isa<ConstantSDNode>(Inputs[i])) 11988 continue; 11989 11990 unsigned OpBits = 11991 Inputs[i].getOperand(0).getValueSizeInBits(); 11992 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11993 11994 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11995 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11996 APInt::getHighBitsSet(OpBits, 11997 OpBits-PromBits))) || 11998 (N->getOpcode() == ISD::SIGN_EXTEND && 11999 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12000 (OpBits-(PromBits-1)))) { 12001 ReallyNeedsExt = true; 12002 break; 12003 } 12004 } 12005 } 12006 12007 // Replace all inputs, either with the truncation operand, or a 12008 // truncation or extension to the final output type. 12009 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12010 // Constant inputs need to be replaced with the to-be-promoted nodes that 12011 // use them because they might have users outside of the cluster of 12012 // promoted nodes. 12013 if (isa<ConstantSDNode>(Inputs[i])) 12014 continue; 12015 12016 SDValue InSrc = Inputs[i].getOperand(0); 12017 if (Inputs[i].getValueType() == N->getValueType(0)) 12018 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12019 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12020 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12021 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12022 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12023 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12024 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12025 else 12026 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12027 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12028 } 12029 12030 std::list<HandleSDNode> PromOpHandles; 12031 for (auto &PromOp : PromOps) 12032 PromOpHandles.emplace_back(PromOp); 12033 12034 // Replace all operations (these are all the same, but have a different 12035 // (promoted) return type). DAG.getNode will validate that the types of 12036 // a binary operator match, so go through the list in reverse so that 12037 // we've likely promoted both operands first. 12038 while (!PromOpHandles.empty()) { 12039 SDValue PromOp = PromOpHandles.back().getValue(); 12040 PromOpHandles.pop_back(); 12041 12042 unsigned C; 12043 switch (PromOp.getOpcode()) { 12044 default: C = 0; break; 12045 case ISD::SELECT: C = 1; break; 12046 case ISD::SELECT_CC: C = 2; break; 12047 } 12048 12049 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12050 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12051 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12052 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12053 // The to-be-promoted operands of this node have not yet been 12054 // promoted (this should be rare because we're going through the 12055 // list backward, but if one of the operands has several users in 12056 // this cluster of to-be-promoted nodes, it is possible). 12057 PromOpHandles.emplace_front(PromOp); 12058 continue; 12059 } 12060 12061 // For SELECT and SELECT_CC nodes, we do a similar check for any 12062 // to-be-promoted comparison inputs. 12063 if (PromOp.getOpcode() == ISD::SELECT || 12064 PromOp.getOpcode() == ISD::SELECT_CC) { 12065 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12066 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12067 (SelectTruncOp[1].count(PromOp.getNode()) && 12068 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12069 PromOpHandles.emplace_front(PromOp); 12070 continue; 12071 } 12072 } 12073 12074 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12075 PromOp.getNode()->op_end()); 12076 12077 // If this node has constant inputs, then they'll need to be promoted here. 12078 for (unsigned i = 0; i < 2; ++i) { 12079 if (!isa<ConstantSDNode>(Ops[C+i])) 12080 continue; 12081 if (Ops[C+i].getValueType() == N->getValueType(0)) 12082 continue; 12083 12084 if (N->getOpcode() == ISD::SIGN_EXTEND) 12085 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12086 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12087 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12088 else 12089 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12090 } 12091 12092 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12093 // truncate them again to the original value type. 12094 if (PromOp.getOpcode() == ISD::SELECT || 12095 PromOp.getOpcode() == ISD::SELECT_CC) { 12096 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12097 if (SI0 != SelectTruncOp[0].end()) 12098 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12099 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12100 if (SI1 != SelectTruncOp[1].end()) 12101 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12102 } 12103 12104 DAG.ReplaceAllUsesOfValueWith(PromOp, 12105 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12106 } 12107 12108 // Now we're left with the initial extension itself. 12109 if (!ReallyNeedsExt) 12110 return N->getOperand(0); 12111 12112 // To zero extend, just mask off everything except for the first bit (in the 12113 // i1 case). 12114 if (N->getOpcode() == ISD::ZERO_EXTEND) 12115 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12116 DAG.getConstant(APInt::getLowBitsSet( 12117 N->getValueSizeInBits(0), PromBits), 12118 dl, N->getValueType(0))); 12119 12120 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12121 "Invalid extension type"); 12122 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12123 SDValue ShiftCst = 12124 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12125 return DAG.getNode( 12126 ISD::SRA, dl, N->getValueType(0), 12127 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12128 ShiftCst); 12129 } 12130 12131 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12132 DAGCombinerInfo &DCI) const { 12133 assert(N->getOpcode() == ISD::SETCC && 12134 "Should be called with a SETCC node"); 12135 12136 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12137 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12138 SDValue LHS = N->getOperand(0); 12139 SDValue RHS = N->getOperand(1); 12140 12141 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12142 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12143 LHS.hasOneUse()) 12144 std::swap(LHS, RHS); 12145 12146 // x == 0-y --> x+y == 0 12147 // x != 0-y --> x+y != 0 12148 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12149 RHS.hasOneUse()) { 12150 SDLoc DL(N); 12151 SelectionDAG &DAG = DCI.DAG; 12152 EVT VT = N->getValueType(0); 12153 EVT OpVT = LHS.getValueType(); 12154 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12155 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12156 } 12157 } 12158 12159 return DAGCombineTruncBoolExt(N, DCI); 12160 } 12161 12162 // Is this an extending load from an f32 to an f64? 12163 static bool isFPExtLoad(SDValue Op) { 12164 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12165 return LD->getExtensionType() == ISD::EXTLOAD && 12166 Op.getValueType() == MVT::f64; 12167 return false; 12168 } 12169 12170 /// Reduces the number of fp-to-int conversion when building a vector. 12171 /// 12172 /// If this vector is built out of floating to integer conversions, 12173 /// transform it to a vector built out of floating point values followed by a 12174 /// single floating to integer conversion of the vector. 12175 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12176 /// becomes (fptosi (build_vector ($A, $B, ...))) 12177 SDValue PPCTargetLowering:: 12178 combineElementTruncationToVectorTruncation(SDNode *N, 12179 DAGCombinerInfo &DCI) const { 12180 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12181 "Should be called with a BUILD_VECTOR node"); 12182 12183 SelectionDAG &DAG = DCI.DAG; 12184 SDLoc dl(N); 12185 12186 SDValue FirstInput = N->getOperand(0); 12187 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12188 "The input operand must be an fp-to-int conversion."); 12189 12190 // This combine happens after legalization so the fp_to_[su]i nodes are 12191 // already converted to PPCSISD nodes. 12192 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12193 if (FirstConversion == PPCISD::FCTIDZ || 12194 FirstConversion == PPCISD::FCTIDUZ || 12195 FirstConversion == PPCISD::FCTIWZ || 12196 FirstConversion == PPCISD::FCTIWUZ) { 12197 bool IsSplat = true; 12198 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12199 FirstConversion == PPCISD::FCTIWUZ; 12200 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12201 SmallVector<SDValue, 4> Ops; 12202 EVT TargetVT = N->getValueType(0); 12203 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12204 SDValue NextOp = N->getOperand(i); 12205 if (NextOp.getOpcode() != PPCISD::MFVSR) 12206 return SDValue(); 12207 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12208 if (NextConversion != FirstConversion) 12209 return SDValue(); 12210 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12211 // This is not valid if the input was originally double precision. It is 12212 // also not profitable to do unless this is an extending load in which 12213 // case doing this combine will allow us to combine consecutive loads. 12214 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12215 return SDValue(); 12216 if (N->getOperand(i) != FirstInput) 12217 IsSplat = false; 12218 } 12219 12220 // If this is a splat, we leave it as-is since there will be only a single 12221 // fp-to-int conversion followed by a splat of the integer. This is better 12222 // for 32-bit and smaller ints and neutral for 64-bit ints. 12223 if (IsSplat) 12224 return SDValue(); 12225 12226 // Now that we know we have the right type of node, get its operands 12227 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12228 SDValue In = N->getOperand(i).getOperand(0); 12229 if (Is32Bit) { 12230 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12231 // here, we know that all inputs are extending loads so this is safe). 12232 if (In.isUndef()) 12233 Ops.push_back(DAG.getUNDEF(SrcVT)); 12234 else { 12235 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12236 MVT::f32, In.getOperand(0), 12237 DAG.getIntPtrConstant(1, dl)); 12238 Ops.push_back(Trunc); 12239 } 12240 } else 12241 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12242 } 12243 12244 unsigned Opcode; 12245 if (FirstConversion == PPCISD::FCTIDZ || 12246 FirstConversion == PPCISD::FCTIWZ) 12247 Opcode = ISD::FP_TO_SINT; 12248 else 12249 Opcode = ISD::FP_TO_UINT; 12250 12251 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12252 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12253 return DAG.getNode(Opcode, dl, TargetVT, BV); 12254 } 12255 return SDValue(); 12256 } 12257 12258 /// Reduce the number of loads when building a vector. 12259 /// 12260 /// Building a vector out of multiple loads can be converted to a load 12261 /// of the vector type if the loads are consecutive. If the loads are 12262 /// consecutive but in descending order, a shuffle is added at the end 12263 /// to reorder the vector. 12264 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12265 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12266 "Should be called with a BUILD_VECTOR node"); 12267 12268 SDLoc dl(N); 12269 12270 // Return early for non byte-sized type, as they can't be consecutive. 12271 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12272 return SDValue(); 12273 12274 bool InputsAreConsecutiveLoads = true; 12275 bool InputsAreReverseConsecutive = true; 12276 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12277 SDValue FirstInput = N->getOperand(0); 12278 bool IsRoundOfExtLoad = false; 12279 12280 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12281 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12282 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12283 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12284 } 12285 // Not a build vector of (possibly fp_rounded) loads. 12286 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12287 N->getNumOperands() == 1) 12288 return SDValue(); 12289 12290 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12291 // If any inputs are fp_round(extload), they all must be. 12292 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12293 return SDValue(); 12294 12295 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12296 N->getOperand(i); 12297 if (NextInput.getOpcode() != ISD::LOAD) 12298 return SDValue(); 12299 12300 SDValue PreviousInput = 12301 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12302 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12303 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12304 12305 // If any inputs are fp_round(extload), they all must be. 12306 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12307 return SDValue(); 12308 12309 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12310 InputsAreConsecutiveLoads = false; 12311 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12312 InputsAreReverseConsecutive = false; 12313 12314 // Exit early if the loads are neither consecutive nor reverse consecutive. 12315 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12316 return SDValue(); 12317 } 12318 12319 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12320 "The loads cannot be both consecutive and reverse consecutive."); 12321 12322 SDValue FirstLoadOp = 12323 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12324 SDValue LastLoadOp = 12325 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12326 N->getOperand(N->getNumOperands()-1); 12327 12328 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12329 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12330 if (InputsAreConsecutiveLoads) { 12331 assert(LD1 && "Input needs to be a LoadSDNode."); 12332 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12333 LD1->getBasePtr(), LD1->getPointerInfo(), 12334 LD1->getAlignment()); 12335 } 12336 if (InputsAreReverseConsecutive) { 12337 assert(LDL && "Input needs to be a LoadSDNode."); 12338 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12339 LDL->getBasePtr(), LDL->getPointerInfo(), 12340 LDL->getAlignment()); 12341 SmallVector<int, 16> Ops; 12342 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12343 Ops.push_back(i); 12344 12345 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12346 DAG.getUNDEF(N->getValueType(0)), Ops); 12347 } 12348 return SDValue(); 12349 } 12350 12351 // This function adds the required vector_shuffle needed to get 12352 // the elements of the vector extract in the correct position 12353 // as specified by the CorrectElems encoding. 12354 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12355 SDValue Input, uint64_t Elems, 12356 uint64_t CorrectElems) { 12357 SDLoc dl(N); 12358 12359 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12360 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12361 12362 // Knowing the element indices being extracted from the original 12363 // vector and the order in which they're being inserted, just put 12364 // them at element indices required for the instruction. 12365 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12366 if (DAG.getDataLayout().isLittleEndian()) 12367 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12368 else 12369 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12370 CorrectElems = CorrectElems >> 8; 12371 Elems = Elems >> 8; 12372 } 12373 12374 SDValue Shuffle = 12375 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12376 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12377 12378 EVT Ty = N->getValueType(0); 12379 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12380 return BV; 12381 } 12382 12383 // Look for build vector patterns where input operands come from sign 12384 // extended vector_extract elements of specific indices. If the correct indices 12385 // aren't used, add a vector shuffle to fix up the indices and create a new 12386 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12387 // during instruction selection. 12388 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12389 // This array encodes the indices that the vector sign extend instructions 12390 // extract from when extending from one type to another for both BE and LE. 12391 // The right nibble of each byte corresponds to the LE incides. 12392 // and the left nibble of each byte corresponds to the BE incides. 12393 // For example: 0x3074B8FC byte->word 12394 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12395 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12396 // For example: 0x000070F8 byte->double word 12397 // For LE: the allowed indices are: 0x0,0x8 12398 // For BE: the allowed indices are: 0x7,0xF 12399 uint64_t TargetElems[] = { 12400 0x3074B8FC, // b->w 12401 0x000070F8, // b->d 12402 0x10325476, // h->w 12403 0x00003074, // h->d 12404 0x00001032, // w->d 12405 }; 12406 12407 uint64_t Elems = 0; 12408 int Index; 12409 SDValue Input; 12410 12411 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12412 if (!Op) 12413 return false; 12414 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12415 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12416 return false; 12417 12418 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12419 // of the right width. 12420 SDValue Extract = Op.getOperand(0); 12421 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12422 Extract = Extract.getOperand(0); 12423 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12424 return false; 12425 12426 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12427 if (!ExtOp) 12428 return false; 12429 12430 Index = ExtOp->getZExtValue(); 12431 if (Input && Input != Extract.getOperand(0)) 12432 return false; 12433 12434 if (!Input) 12435 Input = Extract.getOperand(0); 12436 12437 Elems = Elems << 8; 12438 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12439 Elems |= Index; 12440 12441 return true; 12442 }; 12443 12444 // If the build vector operands aren't sign extended vector extracts, 12445 // of the same input vector, then return. 12446 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12447 if (!isSExtOfVecExtract(N->getOperand(i))) { 12448 return SDValue(); 12449 } 12450 } 12451 12452 // If the vector extract indicies are not correct, add the appropriate 12453 // vector_shuffle. 12454 int TgtElemArrayIdx; 12455 int InputSize = Input.getValueType().getScalarSizeInBits(); 12456 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12457 if (InputSize + OutputSize == 40) 12458 TgtElemArrayIdx = 0; 12459 else if (InputSize + OutputSize == 72) 12460 TgtElemArrayIdx = 1; 12461 else if (InputSize + OutputSize == 48) 12462 TgtElemArrayIdx = 2; 12463 else if (InputSize + OutputSize == 80) 12464 TgtElemArrayIdx = 3; 12465 else if (InputSize + OutputSize == 96) 12466 TgtElemArrayIdx = 4; 12467 else 12468 return SDValue(); 12469 12470 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12471 CorrectElems = DAG.getDataLayout().isLittleEndian() 12472 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12473 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12474 if (Elems != CorrectElems) { 12475 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12476 } 12477 12478 // Regular lowering will catch cases where a shuffle is not needed. 12479 return SDValue(); 12480 } 12481 12482 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12483 DAGCombinerInfo &DCI) const { 12484 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12485 "Should be called with a BUILD_VECTOR node"); 12486 12487 SelectionDAG &DAG = DCI.DAG; 12488 SDLoc dl(N); 12489 12490 if (!Subtarget.hasVSX()) 12491 return SDValue(); 12492 12493 // The target independent DAG combiner will leave a build_vector of 12494 // float-to-int conversions intact. We can generate MUCH better code for 12495 // a float-to-int conversion of a vector of floats. 12496 SDValue FirstInput = N->getOperand(0); 12497 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12498 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12499 if (Reduced) 12500 return Reduced; 12501 } 12502 12503 // If we're building a vector out of consecutive loads, just load that 12504 // vector type. 12505 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12506 if (Reduced) 12507 return Reduced; 12508 12509 // If we're building a vector out of extended elements from another vector 12510 // we have P9 vector integer extend instructions. The code assumes legal 12511 // input types (i.e. it can't handle things like v4i16) so do not run before 12512 // legalization. 12513 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12514 Reduced = combineBVOfVecSExt(N, DAG); 12515 if (Reduced) 12516 return Reduced; 12517 } 12518 12519 12520 if (N->getValueType(0) != MVT::v2f64) 12521 return SDValue(); 12522 12523 // Looking for: 12524 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12525 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12526 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12527 return SDValue(); 12528 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12529 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12530 return SDValue(); 12531 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12532 return SDValue(); 12533 12534 SDValue Ext1 = FirstInput.getOperand(0); 12535 SDValue Ext2 = N->getOperand(1).getOperand(0); 12536 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12537 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12538 return SDValue(); 12539 12540 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12541 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12542 if (!Ext1Op || !Ext2Op) 12543 return SDValue(); 12544 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12545 Ext1.getOperand(0) != Ext2.getOperand(0)) 12546 return SDValue(); 12547 12548 int FirstElem = Ext1Op->getZExtValue(); 12549 int SecondElem = Ext2Op->getZExtValue(); 12550 int SubvecIdx; 12551 if (FirstElem == 0 && SecondElem == 1) 12552 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12553 else if (FirstElem == 2 && SecondElem == 3) 12554 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12555 else 12556 return SDValue(); 12557 12558 SDValue SrcVec = Ext1.getOperand(0); 12559 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12560 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12561 return DAG.getNode(NodeType, dl, MVT::v2f64, 12562 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12563 } 12564 12565 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12566 DAGCombinerInfo &DCI) const { 12567 assert((N->getOpcode() == ISD::SINT_TO_FP || 12568 N->getOpcode() == ISD::UINT_TO_FP) && 12569 "Need an int -> FP conversion node here"); 12570 12571 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12572 return SDValue(); 12573 12574 SelectionDAG &DAG = DCI.DAG; 12575 SDLoc dl(N); 12576 SDValue Op(N, 0); 12577 12578 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12579 // from the hardware. 12580 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12581 return SDValue(); 12582 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12583 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12584 return SDValue(); 12585 12586 SDValue FirstOperand(Op.getOperand(0)); 12587 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12588 (FirstOperand.getValueType() == MVT::i8 || 12589 FirstOperand.getValueType() == MVT::i16); 12590 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12591 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12592 bool DstDouble = Op.getValueType() == MVT::f64; 12593 unsigned ConvOp = Signed ? 12594 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12595 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12596 SDValue WidthConst = 12597 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12598 dl, false); 12599 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12600 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12601 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12602 DAG.getVTList(MVT::f64, MVT::Other), 12603 Ops, MVT::i8, LDN->getMemOperand()); 12604 12605 // For signed conversion, we need to sign-extend the value in the VSR 12606 if (Signed) { 12607 SDValue ExtOps[] = { Ld, WidthConst }; 12608 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12609 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12610 } else 12611 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12612 } 12613 12614 12615 // For i32 intermediate values, unfortunately, the conversion functions 12616 // leave the upper 32 bits of the value are undefined. Within the set of 12617 // scalar instructions, we have no method for zero- or sign-extending the 12618 // value. Thus, we cannot handle i32 intermediate values here. 12619 if (Op.getOperand(0).getValueType() == MVT::i32) 12620 return SDValue(); 12621 12622 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12623 "UINT_TO_FP is supported only with FPCVT"); 12624 12625 // If we have FCFIDS, then use it when converting to single-precision. 12626 // Otherwise, convert to double-precision and then round. 12627 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12628 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12629 : PPCISD::FCFIDS) 12630 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12631 : PPCISD::FCFID); 12632 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12633 ? MVT::f32 12634 : MVT::f64; 12635 12636 // If we're converting from a float, to an int, and back to a float again, 12637 // then we don't need the store/load pair at all. 12638 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12639 Subtarget.hasFPCVT()) || 12640 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12641 SDValue Src = Op.getOperand(0).getOperand(0); 12642 if (Src.getValueType() == MVT::f32) { 12643 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12644 DCI.AddToWorklist(Src.getNode()); 12645 } else if (Src.getValueType() != MVT::f64) { 12646 // Make sure that we don't pick up a ppc_fp128 source value. 12647 return SDValue(); 12648 } 12649 12650 unsigned FCTOp = 12651 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12652 PPCISD::FCTIDUZ; 12653 12654 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12655 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12656 12657 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12658 FP = DAG.getNode(ISD::FP_ROUND, dl, 12659 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12660 DCI.AddToWorklist(FP.getNode()); 12661 } 12662 12663 return FP; 12664 } 12665 12666 return SDValue(); 12667 } 12668 12669 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12670 // builtins) into loads with swaps. 12671 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12672 DAGCombinerInfo &DCI) const { 12673 SelectionDAG &DAG = DCI.DAG; 12674 SDLoc dl(N); 12675 SDValue Chain; 12676 SDValue Base; 12677 MachineMemOperand *MMO; 12678 12679 switch (N->getOpcode()) { 12680 default: 12681 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12682 case ISD::LOAD: { 12683 LoadSDNode *LD = cast<LoadSDNode>(N); 12684 Chain = LD->getChain(); 12685 Base = LD->getBasePtr(); 12686 MMO = LD->getMemOperand(); 12687 // If the MMO suggests this isn't a load of a full vector, leave 12688 // things alone. For a built-in, we have to make the change for 12689 // correctness, so if there is a size problem that will be a bug. 12690 if (MMO->getSize() < 16) 12691 return SDValue(); 12692 break; 12693 } 12694 case ISD::INTRINSIC_W_CHAIN: { 12695 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12696 Chain = Intrin->getChain(); 12697 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12698 // us what we want. Get operand 2 instead. 12699 Base = Intrin->getOperand(2); 12700 MMO = Intrin->getMemOperand(); 12701 break; 12702 } 12703 } 12704 12705 MVT VecTy = N->getValueType(0).getSimpleVT(); 12706 12707 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12708 // aligned and the type is a vector with elements up to 4 bytes 12709 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12710 && VecTy.getScalarSizeInBits() <= 32 ) { 12711 return SDValue(); 12712 } 12713 12714 SDValue LoadOps[] = { Chain, Base }; 12715 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12716 DAG.getVTList(MVT::v2f64, MVT::Other), 12717 LoadOps, MVT::v2f64, MMO); 12718 12719 DCI.AddToWorklist(Load.getNode()); 12720 Chain = Load.getValue(1); 12721 SDValue Swap = DAG.getNode( 12722 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12723 DCI.AddToWorklist(Swap.getNode()); 12724 12725 // Add a bitcast if the resulting load type doesn't match v2f64. 12726 if (VecTy != MVT::v2f64) { 12727 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12728 DCI.AddToWorklist(N.getNode()); 12729 // Package {bitcast value, swap's chain} to match Load's shape. 12730 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12731 N, Swap.getValue(1)); 12732 } 12733 12734 return Swap; 12735 } 12736 12737 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12738 // builtins) into stores with swaps. 12739 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12740 DAGCombinerInfo &DCI) const { 12741 SelectionDAG &DAG = DCI.DAG; 12742 SDLoc dl(N); 12743 SDValue Chain; 12744 SDValue Base; 12745 unsigned SrcOpnd; 12746 MachineMemOperand *MMO; 12747 12748 switch (N->getOpcode()) { 12749 default: 12750 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12751 case ISD::STORE: { 12752 StoreSDNode *ST = cast<StoreSDNode>(N); 12753 Chain = ST->getChain(); 12754 Base = ST->getBasePtr(); 12755 MMO = ST->getMemOperand(); 12756 SrcOpnd = 1; 12757 // If the MMO suggests this isn't a store of a full vector, leave 12758 // things alone. For a built-in, we have to make the change for 12759 // correctness, so if there is a size problem that will be a bug. 12760 if (MMO->getSize() < 16) 12761 return SDValue(); 12762 break; 12763 } 12764 case ISD::INTRINSIC_VOID: { 12765 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12766 Chain = Intrin->getChain(); 12767 // Intrin->getBasePtr() oddly does not get what we want. 12768 Base = Intrin->getOperand(3); 12769 MMO = Intrin->getMemOperand(); 12770 SrcOpnd = 2; 12771 break; 12772 } 12773 } 12774 12775 SDValue Src = N->getOperand(SrcOpnd); 12776 MVT VecTy = Src.getValueType().getSimpleVT(); 12777 12778 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12779 // aligned and the type is a vector with elements up to 4 bytes 12780 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12781 && VecTy.getScalarSizeInBits() <= 32 ) { 12782 return SDValue(); 12783 } 12784 12785 // All stores are done as v2f64 and possible bit cast. 12786 if (VecTy != MVT::v2f64) { 12787 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12788 DCI.AddToWorklist(Src.getNode()); 12789 } 12790 12791 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12792 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12793 DCI.AddToWorklist(Swap.getNode()); 12794 Chain = Swap.getValue(1); 12795 SDValue StoreOps[] = { Chain, Swap, Base }; 12796 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12797 DAG.getVTList(MVT::Other), 12798 StoreOps, VecTy, MMO); 12799 DCI.AddToWorklist(Store.getNode()); 12800 return Store; 12801 } 12802 12803 // Handle DAG combine for STORE (FP_TO_INT F). 12804 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12805 DAGCombinerInfo &DCI) const { 12806 12807 SelectionDAG &DAG = DCI.DAG; 12808 SDLoc dl(N); 12809 unsigned Opcode = N->getOperand(1).getOpcode(); 12810 12811 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12812 && "Not a FP_TO_INT Instruction!"); 12813 12814 SDValue Val = N->getOperand(1).getOperand(0); 12815 EVT Op1VT = N->getOperand(1).getValueType(); 12816 EVT ResVT = Val.getValueType(); 12817 12818 // Floating point types smaller than 32 bits are not legal on Power. 12819 if (ResVT.getScalarSizeInBits() < 32) 12820 return SDValue(); 12821 12822 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12823 bool ValidTypeForStoreFltAsInt = 12824 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12825 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12826 12827 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12828 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12829 return SDValue(); 12830 12831 // Extend f32 values to f64 12832 if (ResVT.getScalarSizeInBits() == 32) { 12833 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12834 DCI.AddToWorklist(Val.getNode()); 12835 } 12836 12837 // Set signed or unsigned conversion opcode. 12838 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12839 PPCISD::FP_TO_SINT_IN_VSR : 12840 PPCISD::FP_TO_UINT_IN_VSR; 12841 12842 Val = DAG.getNode(ConvOpcode, 12843 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12844 DCI.AddToWorklist(Val.getNode()); 12845 12846 // Set number of bytes being converted. 12847 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12848 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12849 DAG.getIntPtrConstant(ByteSize, dl, false), 12850 DAG.getValueType(Op1VT) }; 12851 12852 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12853 DAG.getVTList(MVT::Other), Ops, 12854 cast<StoreSDNode>(N)->getMemoryVT(), 12855 cast<StoreSDNode>(N)->getMemOperand()); 12856 12857 DCI.AddToWorklist(Val.getNode()); 12858 return Val; 12859 } 12860 12861 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12862 DAGCombinerInfo &DCI) const { 12863 SelectionDAG &DAG = DCI.DAG; 12864 SDLoc dl(N); 12865 switch (N->getOpcode()) { 12866 default: break; 12867 case ISD::ADD: 12868 return combineADD(N, DCI); 12869 case ISD::SHL: 12870 return combineSHL(N, DCI); 12871 case ISD::SRA: 12872 return combineSRA(N, DCI); 12873 case ISD::SRL: 12874 return combineSRL(N, DCI); 12875 case ISD::MUL: 12876 return combineMUL(N, DCI); 12877 case PPCISD::SHL: 12878 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12879 return N->getOperand(0); 12880 break; 12881 case PPCISD::SRL: 12882 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12883 return N->getOperand(0); 12884 break; 12885 case PPCISD::SRA: 12886 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12887 if (C->isNullValue() || // 0 >>s V -> 0. 12888 C->isAllOnesValue()) // -1 >>s V -> -1. 12889 return N->getOperand(0); 12890 } 12891 break; 12892 case ISD::SIGN_EXTEND: 12893 case ISD::ZERO_EXTEND: 12894 case ISD::ANY_EXTEND: 12895 return DAGCombineExtBoolTrunc(N, DCI); 12896 case ISD::TRUNCATE: 12897 return combineTRUNCATE(N, DCI); 12898 case ISD::SETCC: 12899 if (SDValue CSCC = combineSetCC(N, DCI)) 12900 return CSCC; 12901 LLVM_FALLTHROUGH; 12902 case ISD::SELECT_CC: 12903 return DAGCombineTruncBoolExt(N, DCI); 12904 case ISD::SINT_TO_FP: 12905 case ISD::UINT_TO_FP: 12906 return combineFPToIntToFP(N, DCI); 12907 case ISD::STORE: { 12908 12909 EVT Op1VT = N->getOperand(1).getValueType(); 12910 unsigned Opcode = N->getOperand(1).getOpcode(); 12911 12912 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12913 SDValue Val= combineStoreFPToInt(N, DCI); 12914 if (Val) 12915 return Val; 12916 } 12917 12918 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12919 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12920 N->getOperand(1).getNode()->hasOneUse() && 12921 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12922 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12923 12924 // STBRX can only handle simple types and it makes no sense to store less 12925 // two bytes in byte-reversed order. 12926 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12927 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 12928 break; 12929 12930 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12931 // Do an any-extend to 32-bits if this is a half-word input. 12932 if (BSwapOp.getValueType() == MVT::i16) 12933 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12934 12935 // If the type of BSWAP operand is wider than stored memory width 12936 // it need to be shifted to the right side before STBRX. 12937 if (Op1VT.bitsGT(mVT)) { 12938 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12939 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12940 DAG.getConstant(Shift, dl, MVT::i32)); 12941 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12942 if (Op1VT == MVT::i64) 12943 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12944 } 12945 12946 SDValue Ops[] = { 12947 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12948 }; 12949 return 12950 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12951 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12952 cast<StoreSDNode>(N)->getMemOperand()); 12953 } 12954 12955 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12956 // So it can increase the chance of CSE constant construction. 12957 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12958 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12959 // Need to sign-extended to 64-bits to handle negative values. 12960 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12961 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12962 MemVT.getSizeInBits()); 12963 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12964 12965 // DAG.getTruncStore() can't be used here because it doesn't accept 12966 // the general (base + offset) addressing mode. 12967 // So we use UpdateNodeOperands and setTruncatingStore instead. 12968 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12969 N->getOperand(3)); 12970 cast<StoreSDNode>(N)->setTruncatingStore(true); 12971 return SDValue(N, 0); 12972 } 12973 12974 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12975 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12976 if (Op1VT.isSimple()) { 12977 MVT StoreVT = Op1VT.getSimpleVT(); 12978 if (Subtarget.needsSwapsForVSXMemOps() && 12979 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12980 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12981 return expandVSXStoreForLE(N, DCI); 12982 } 12983 break; 12984 } 12985 case ISD::LOAD: { 12986 LoadSDNode *LD = cast<LoadSDNode>(N); 12987 EVT VT = LD->getValueType(0); 12988 12989 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12990 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12991 if (VT.isSimple()) { 12992 MVT LoadVT = VT.getSimpleVT(); 12993 if (Subtarget.needsSwapsForVSXMemOps() && 12994 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12995 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12996 return expandVSXLoadForLE(N, DCI); 12997 } 12998 12999 // We sometimes end up with a 64-bit integer load, from which we extract 13000 // two single-precision floating-point numbers. This happens with 13001 // std::complex<float>, and other similar structures, because of the way we 13002 // canonicalize structure copies. However, if we lack direct moves, 13003 // then the final bitcasts from the extracted integer values to the 13004 // floating-point numbers turn into store/load pairs. Even with direct moves, 13005 // just loading the two floating-point numbers is likely better. 13006 auto ReplaceTwoFloatLoad = [&]() { 13007 if (VT != MVT::i64) 13008 return false; 13009 13010 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13011 LD->isVolatile()) 13012 return false; 13013 13014 // We're looking for a sequence like this: 13015 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13016 // t16: i64 = srl t13, Constant:i32<32> 13017 // t17: i32 = truncate t16 13018 // t18: f32 = bitcast t17 13019 // t19: i32 = truncate t13 13020 // t20: f32 = bitcast t19 13021 13022 if (!LD->hasNUsesOfValue(2, 0)) 13023 return false; 13024 13025 auto UI = LD->use_begin(); 13026 while (UI.getUse().getResNo() != 0) ++UI; 13027 SDNode *Trunc = *UI++; 13028 while (UI.getUse().getResNo() != 0) ++UI; 13029 SDNode *RightShift = *UI; 13030 if (Trunc->getOpcode() != ISD::TRUNCATE) 13031 std::swap(Trunc, RightShift); 13032 13033 if (Trunc->getOpcode() != ISD::TRUNCATE || 13034 Trunc->getValueType(0) != MVT::i32 || 13035 !Trunc->hasOneUse()) 13036 return false; 13037 if (RightShift->getOpcode() != ISD::SRL || 13038 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13039 RightShift->getConstantOperandVal(1) != 32 || 13040 !RightShift->hasOneUse()) 13041 return false; 13042 13043 SDNode *Trunc2 = *RightShift->use_begin(); 13044 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13045 Trunc2->getValueType(0) != MVT::i32 || 13046 !Trunc2->hasOneUse()) 13047 return false; 13048 13049 SDNode *Bitcast = *Trunc->use_begin(); 13050 SDNode *Bitcast2 = *Trunc2->use_begin(); 13051 13052 if (Bitcast->getOpcode() != ISD::BITCAST || 13053 Bitcast->getValueType(0) != MVT::f32) 13054 return false; 13055 if (Bitcast2->getOpcode() != ISD::BITCAST || 13056 Bitcast2->getValueType(0) != MVT::f32) 13057 return false; 13058 13059 if (Subtarget.isLittleEndian()) 13060 std::swap(Bitcast, Bitcast2); 13061 13062 // Bitcast has the second float (in memory-layout order) and Bitcast2 13063 // has the first one. 13064 13065 SDValue BasePtr = LD->getBasePtr(); 13066 if (LD->isIndexed()) { 13067 assert(LD->getAddressingMode() == ISD::PRE_INC && 13068 "Non-pre-inc AM on PPC?"); 13069 BasePtr = 13070 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13071 LD->getOffset()); 13072 } 13073 13074 auto MMOFlags = 13075 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13076 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13077 LD->getPointerInfo(), LD->getAlignment(), 13078 MMOFlags, LD->getAAInfo()); 13079 SDValue AddPtr = 13080 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13081 BasePtr, DAG.getIntPtrConstant(4, dl)); 13082 SDValue FloatLoad2 = DAG.getLoad( 13083 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13084 LD->getPointerInfo().getWithOffset(4), 13085 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13086 13087 if (LD->isIndexed()) { 13088 // Note that DAGCombine should re-form any pre-increment load(s) from 13089 // what is produced here if that makes sense. 13090 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13091 } 13092 13093 DCI.CombineTo(Bitcast2, FloatLoad); 13094 DCI.CombineTo(Bitcast, FloatLoad2); 13095 13096 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13097 SDValue(FloatLoad2.getNode(), 1)); 13098 return true; 13099 }; 13100 13101 if (ReplaceTwoFloatLoad()) 13102 return SDValue(N, 0); 13103 13104 EVT MemVT = LD->getMemoryVT(); 13105 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13106 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13107 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13108 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13109 if (LD->isUnindexed() && VT.isVector() && 13110 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13111 // P8 and later hardware should just use LOAD. 13112 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13113 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13114 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13115 LD->getAlignment() >= ScalarABIAlignment)) && 13116 LD->getAlignment() < ABIAlignment) { 13117 // This is a type-legal unaligned Altivec or QPX load. 13118 SDValue Chain = LD->getChain(); 13119 SDValue Ptr = LD->getBasePtr(); 13120 bool isLittleEndian = Subtarget.isLittleEndian(); 13121 13122 // This implements the loading of unaligned vectors as described in 13123 // the venerable Apple Velocity Engine overview. Specifically: 13124 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13125 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13126 // 13127 // The general idea is to expand a sequence of one or more unaligned 13128 // loads into an alignment-based permutation-control instruction (lvsl 13129 // or lvsr), a series of regular vector loads (which always truncate 13130 // their input address to an aligned address), and a series of 13131 // permutations. The results of these permutations are the requested 13132 // loaded values. The trick is that the last "extra" load is not taken 13133 // from the address you might suspect (sizeof(vector) bytes after the 13134 // last requested load), but rather sizeof(vector) - 1 bytes after the 13135 // last requested vector. The point of this is to avoid a page fault if 13136 // the base address happened to be aligned. This works because if the 13137 // base address is aligned, then adding less than a full vector length 13138 // will cause the last vector in the sequence to be (re)loaded. 13139 // Otherwise, the next vector will be fetched as you might suspect was 13140 // necessary. 13141 13142 // We might be able to reuse the permutation generation from 13143 // a different base address offset from this one by an aligned amount. 13144 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13145 // optimization later. 13146 Intrinsic::ID Intr, IntrLD, IntrPerm; 13147 MVT PermCntlTy, PermTy, LDTy; 13148 if (Subtarget.hasAltivec()) { 13149 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13150 Intrinsic::ppc_altivec_lvsl; 13151 IntrLD = Intrinsic::ppc_altivec_lvx; 13152 IntrPerm = Intrinsic::ppc_altivec_vperm; 13153 PermCntlTy = MVT::v16i8; 13154 PermTy = MVT::v4i32; 13155 LDTy = MVT::v4i32; 13156 } else { 13157 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13158 Intrinsic::ppc_qpx_qvlpcls; 13159 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13160 Intrinsic::ppc_qpx_qvlfs; 13161 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13162 PermCntlTy = MVT::v4f64; 13163 PermTy = MVT::v4f64; 13164 LDTy = MemVT.getSimpleVT(); 13165 } 13166 13167 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13168 13169 // Create the new MMO for the new base load. It is like the original MMO, 13170 // but represents an area in memory almost twice the vector size centered 13171 // on the original address. If the address is unaligned, we might start 13172 // reading up to (sizeof(vector)-1) bytes below the address of the 13173 // original unaligned load. 13174 MachineFunction &MF = DAG.getMachineFunction(); 13175 MachineMemOperand *BaseMMO = 13176 MF.getMachineMemOperand(LD->getMemOperand(), 13177 -(long)MemVT.getStoreSize()+1, 13178 2*MemVT.getStoreSize()-1); 13179 13180 // Create the new base load. 13181 SDValue LDXIntID = 13182 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13183 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13184 SDValue BaseLoad = 13185 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13186 DAG.getVTList(PermTy, MVT::Other), 13187 BaseLoadOps, LDTy, BaseMMO); 13188 13189 // Note that the value of IncOffset (which is provided to the next 13190 // load's pointer info offset value, and thus used to calculate the 13191 // alignment), and the value of IncValue (which is actually used to 13192 // increment the pointer value) are different! This is because we 13193 // require the next load to appear to be aligned, even though it 13194 // is actually offset from the base pointer by a lesser amount. 13195 int IncOffset = VT.getSizeInBits() / 8; 13196 int IncValue = IncOffset; 13197 13198 // Walk (both up and down) the chain looking for another load at the real 13199 // (aligned) offset (the alignment of the other load does not matter in 13200 // this case). If found, then do not use the offset reduction trick, as 13201 // that will prevent the loads from being later combined (as they would 13202 // otherwise be duplicates). 13203 if (!findConsecutiveLoad(LD, DAG)) 13204 --IncValue; 13205 13206 SDValue Increment = 13207 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13208 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13209 13210 MachineMemOperand *ExtraMMO = 13211 MF.getMachineMemOperand(LD->getMemOperand(), 13212 1, 2*MemVT.getStoreSize()-1); 13213 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13214 SDValue ExtraLoad = 13215 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13216 DAG.getVTList(PermTy, MVT::Other), 13217 ExtraLoadOps, LDTy, ExtraMMO); 13218 13219 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13220 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13221 13222 // Because vperm has a big-endian bias, we must reverse the order 13223 // of the input vectors and complement the permute control vector 13224 // when generating little endian code. We have already handled the 13225 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13226 // and ExtraLoad here. 13227 SDValue Perm; 13228 if (isLittleEndian) 13229 Perm = BuildIntrinsicOp(IntrPerm, 13230 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13231 else 13232 Perm = BuildIntrinsicOp(IntrPerm, 13233 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13234 13235 if (VT != PermTy) 13236 Perm = Subtarget.hasAltivec() ? 13237 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13238 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13239 DAG.getTargetConstant(1, dl, MVT::i64)); 13240 // second argument is 1 because this rounding 13241 // is always exact. 13242 13243 // The output of the permutation is our loaded result, the TokenFactor is 13244 // our new chain. 13245 DCI.CombineTo(N, Perm, TF); 13246 return SDValue(N, 0); 13247 } 13248 } 13249 break; 13250 case ISD::INTRINSIC_WO_CHAIN: { 13251 bool isLittleEndian = Subtarget.isLittleEndian(); 13252 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13253 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13254 : Intrinsic::ppc_altivec_lvsl); 13255 if ((IID == Intr || 13256 IID == Intrinsic::ppc_qpx_qvlpcld || 13257 IID == Intrinsic::ppc_qpx_qvlpcls) && 13258 N->getOperand(1)->getOpcode() == ISD::ADD) { 13259 SDValue Add = N->getOperand(1); 13260 13261 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13262 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13263 13264 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13265 APInt::getAllOnesValue(Bits /* alignment */) 13266 .zext(Add.getScalarValueSizeInBits()))) { 13267 SDNode *BasePtr = Add->getOperand(0).getNode(); 13268 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13269 UE = BasePtr->use_end(); 13270 UI != UE; ++UI) { 13271 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13272 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13273 // We've found another LVSL/LVSR, and this address is an aligned 13274 // multiple of that one. The results will be the same, so use the 13275 // one we've just found instead. 13276 13277 return SDValue(*UI, 0); 13278 } 13279 } 13280 } 13281 13282 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13283 SDNode *BasePtr = Add->getOperand(0).getNode(); 13284 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13285 UE = BasePtr->use_end(); UI != UE; ++UI) { 13286 if (UI->getOpcode() == ISD::ADD && 13287 isa<ConstantSDNode>(UI->getOperand(1)) && 13288 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13289 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13290 (1ULL << Bits) == 0) { 13291 SDNode *OtherAdd = *UI; 13292 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13293 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13294 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13295 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13296 return SDValue(*VI, 0); 13297 } 13298 } 13299 } 13300 } 13301 } 13302 } 13303 13304 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13305 // Expose the vabsduw/h/b opportunity for down stream 13306 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13307 (IID == Intrinsic::ppc_altivec_vmaxsw || 13308 IID == Intrinsic::ppc_altivec_vmaxsh || 13309 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13310 SDValue V1 = N->getOperand(1); 13311 SDValue V2 = N->getOperand(2); 13312 if ((V1.getSimpleValueType() == MVT::v4i32 || 13313 V1.getSimpleValueType() == MVT::v8i16 || 13314 V1.getSimpleValueType() == MVT::v16i8) && 13315 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13316 // (0-a, a) 13317 if (V1.getOpcode() == ISD::SUB && 13318 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13319 V1.getOperand(1) == V2) { 13320 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13321 } 13322 // (a, 0-a) 13323 if (V2.getOpcode() == ISD::SUB && 13324 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13325 V2.getOperand(1) == V1) { 13326 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13327 } 13328 // (x-y, y-x) 13329 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13330 V1.getOperand(0) == V2.getOperand(1) && 13331 V1.getOperand(1) == V2.getOperand(0)) { 13332 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13333 } 13334 } 13335 } 13336 } 13337 13338 break; 13339 case ISD::INTRINSIC_W_CHAIN: 13340 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13341 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13342 if (Subtarget.needsSwapsForVSXMemOps()) { 13343 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13344 default: 13345 break; 13346 case Intrinsic::ppc_vsx_lxvw4x: 13347 case Intrinsic::ppc_vsx_lxvd2x: 13348 return expandVSXLoadForLE(N, DCI); 13349 } 13350 } 13351 break; 13352 case ISD::INTRINSIC_VOID: 13353 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13354 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13355 if (Subtarget.needsSwapsForVSXMemOps()) { 13356 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13357 default: 13358 break; 13359 case Intrinsic::ppc_vsx_stxvw4x: 13360 case Intrinsic::ppc_vsx_stxvd2x: 13361 return expandVSXStoreForLE(N, DCI); 13362 } 13363 } 13364 break; 13365 case ISD::BSWAP: 13366 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13367 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13368 N->getOperand(0).hasOneUse() && 13369 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13370 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13371 N->getValueType(0) == MVT::i64))) { 13372 SDValue Load = N->getOperand(0); 13373 LoadSDNode *LD = cast<LoadSDNode>(Load); 13374 // Create the byte-swapping load. 13375 SDValue Ops[] = { 13376 LD->getChain(), // Chain 13377 LD->getBasePtr(), // Ptr 13378 DAG.getValueType(N->getValueType(0)) // VT 13379 }; 13380 SDValue BSLoad = 13381 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13382 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13383 MVT::i64 : MVT::i32, MVT::Other), 13384 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13385 13386 // If this is an i16 load, insert the truncate. 13387 SDValue ResVal = BSLoad; 13388 if (N->getValueType(0) == MVT::i16) 13389 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13390 13391 // First, combine the bswap away. This makes the value produced by the 13392 // load dead. 13393 DCI.CombineTo(N, ResVal); 13394 13395 // Next, combine the load away, we give it a bogus result value but a real 13396 // chain result. The result value is dead because the bswap is dead. 13397 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13398 13399 // Return N so it doesn't get rechecked! 13400 return SDValue(N, 0); 13401 } 13402 break; 13403 case PPCISD::VCMP: 13404 // If a VCMPo node already exists with exactly the same operands as this 13405 // node, use its result instead of this node (VCMPo computes both a CR6 and 13406 // a normal output). 13407 // 13408 if (!N->getOperand(0).hasOneUse() && 13409 !N->getOperand(1).hasOneUse() && 13410 !N->getOperand(2).hasOneUse()) { 13411 13412 // Scan all of the users of the LHS, looking for VCMPo's that match. 13413 SDNode *VCMPoNode = nullptr; 13414 13415 SDNode *LHSN = N->getOperand(0).getNode(); 13416 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13417 UI != E; ++UI) 13418 if (UI->getOpcode() == PPCISD::VCMPo && 13419 UI->getOperand(1) == N->getOperand(1) && 13420 UI->getOperand(2) == N->getOperand(2) && 13421 UI->getOperand(0) == N->getOperand(0)) { 13422 VCMPoNode = *UI; 13423 break; 13424 } 13425 13426 // If there is no VCMPo node, or if the flag value has a single use, don't 13427 // transform this. 13428 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13429 break; 13430 13431 // Look at the (necessarily single) use of the flag value. If it has a 13432 // chain, this transformation is more complex. Note that multiple things 13433 // could use the value result, which we should ignore. 13434 SDNode *FlagUser = nullptr; 13435 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13436 FlagUser == nullptr; ++UI) { 13437 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13438 SDNode *User = *UI; 13439 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13440 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13441 FlagUser = User; 13442 break; 13443 } 13444 } 13445 } 13446 13447 // If the user is a MFOCRF instruction, we know this is safe. 13448 // Otherwise we give up for right now. 13449 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13450 return SDValue(VCMPoNode, 0); 13451 } 13452 break; 13453 case ISD::BRCOND: { 13454 SDValue Cond = N->getOperand(1); 13455 SDValue Target = N->getOperand(2); 13456 13457 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13458 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13459 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13460 13461 // We now need to make the intrinsic dead (it cannot be instruction 13462 // selected). 13463 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13464 assert(Cond.getNode()->hasOneUse() && 13465 "Counter decrement has more than one use"); 13466 13467 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13468 N->getOperand(0), Target); 13469 } 13470 } 13471 break; 13472 case ISD::BR_CC: { 13473 // If this is a branch on an altivec predicate comparison, lower this so 13474 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13475 // lowering is done pre-legalize, because the legalizer lowers the predicate 13476 // compare down to code that is difficult to reassemble. 13477 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13478 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13479 13480 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13481 // value. If so, pass-through the AND to get to the intrinsic. 13482 if (LHS.getOpcode() == ISD::AND && 13483 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13484 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13485 Intrinsic::ppc_is_decremented_ctr_nonzero && 13486 isa<ConstantSDNode>(LHS.getOperand(1)) && 13487 !isNullConstant(LHS.getOperand(1))) 13488 LHS = LHS.getOperand(0); 13489 13490 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13491 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13492 Intrinsic::ppc_is_decremented_ctr_nonzero && 13493 isa<ConstantSDNode>(RHS)) { 13494 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13495 "Counter decrement comparison is not EQ or NE"); 13496 13497 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13498 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13499 (CC == ISD::SETNE && !Val); 13500 13501 // We now need to make the intrinsic dead (it cannot be instruction 13502 // selected). 13503 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13504 assert(LHS.getNode()->hasOneUse() && 13505 "Counter decrement has more than one use"); 13506 13507 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13508 N->getOperand(0), N->getOperand(4)); 13509 } 13510 13511 int CompareOpc; 13512 bool isDot; 13513 13514 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13515 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13516 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13517 assert(isDot && "Can't compare against a vector result!"); 13518 13519 // If this is a comparison against something other than 0/1, then we know 13520 // that the condition is never/always true. 13521 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13522 if (Val != 0 && Val != 1) { 13523 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13524 return N->getOperand(0); 13525 // Always !=, turn it into an unconditional branch. 13526 return DAG.getNode(ISD::BR, dl, MVT::Other, 13527 N->getOperand(0), N->getOperand(4)); 13528 } 13529 13530 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13531 13532 // Create the PPCISD altivec 'dot' comparison node. 13533 SDValue Ops[] = { 13534 LHS.getOperand(2), // LHS of compare 13535 LHS.getOperand(3), // RHS of compare 13536 DAG.getConstant(CompareOpc, dl, MVT::i32) 13537 }; 13538 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13539 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13540 13541 // Unpack the result based on how the target uses it. 13542 PPC::Predicate CompOpc; 13543 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13544 default: // Can't happen, don't crash on invalid number though. 13545 case 0: // Branch on the value of the EQ bit of CR6. 13546 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13547 break; 13548 case 1: // Branch on the inverted value of the EQ bit of CR6. 13549 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13550 break; 13551 case 2: // Branch on the value of the LT bit of CR6. 13552 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13553 break; 13554 case 3: // Branch on the inverted value of the LT bit of CR6. 13555 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13556 break; 13557 } 13558 13559 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13560 DAG.getConstant(CompOpc, dl, MVT::i32), 13561 DAG.getRegister(PPC::CR6, MVT::i32), 13562 N->getOperand(4), CompNode.getValue(1)); 13563 } 13564 break; 13565 } 13566 case ISD::BUILD_VECTOR: 13567 return DAGCombineBuildVector(N, DCI); 13568 case ISD::ABS: 13569 return combineABS(N, DCI); 13570 case ISD::VSELECT: 13571 return combineVSelect(N, DCI); 13572 } 13573 13574 return SDValue(); 13575 } 13576 13577 SDValue 13578 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13579 SelectionDAG &DAG, 13580 SmallVectorImpl<SDNode *> &Created) const { 13581 // fold (sdiv X, pow2) 13582 EVT VT = N->getValueType(0); 13583 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13584 return SDValue(); 13585 if ((VT != MVT::i32 && VT != MVT::i64) || 13586 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13587 return SDValue(); 13588 13589 SDLoc DL(N); 13590 SDValue N0 = N->getOperand(0); 13591 13592 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13593 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13594 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13595 13596 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13597 Created.push_back(Op.getNode()); 13598 13599 if (IsNegPow2) { 13600 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13601 Created.push_back(Op.getNode()); 13602 } 13603 13604 return Op; 13605 } 13606 13607 //===----------------------------------------------------------------------===// 13608 // Inline Assembly Support 13609 //===----------------------------------------------------------------------===// 13610 13611 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13612 KnownBits &Known, 13613 const APInt &DemandedElts, 13614 const SelectionDAG &DAG, 13615 unsigned Depth) const { 13616 Known.resetAll(); 13617 switch (Op.getOpcode()) { 13618 default: break; 13619 case PPCISD::LBRX: { 13620 // lhbrx is known to have the top bits cleared out. 13621 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13622 Known.Zero = 0xFFFF0000; 13623 break; 13624 } 13625 case ISD::INTRINSIC_WO_CHAIN: { 13626 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13627 default: break; 13628 case Intrinsic::ppc_altivec_vcmpbfp_p: 13629 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13630 case Intrinsic::ppc_altivec_vcmpequb_p: 13631 case Intrinsic::ppc_altivec_vcmpequh_p: 13632 case Intrinsic::ppc_altivec_vcmpequw_p: 13633 case Intrinsic::ppc_altivec_vcmpequd_p: 13634 case Intrinsic::ppc_altivec_vcmpgefp_p: 13635 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13636 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13637 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13638 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13639 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13640 case Intrinsic::ppc_altivec_vcmpgtub_p: 13641 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13642 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13643 case Intrinsic::ppc_altivec_vcmpgtud_p: 13644 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13645 break; 13646 } 13647 } 13648 } 13649 } 13650 13651 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13652 switch (Subtarget.getDarwinDirective()) { 13653 default: break; 13654 case PPC::DIR_970: 13655 case PPC::DIR_PWR4: 13656 case PPC::DIR_PWR5: 13657 case PPC::DIR_PWR5X: 13658 case PPC::DIR_PWR6: 13659 case PPC::DIR_PWR6X: 13660 case PPC::DIR_PWR7: 13661 case PPC::DIR_PWR8: 13662 case PPC::DIR_PWR9: { 13663 if (!ML) 13664 break; 13665 13666 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13667 13668 // For small loops (between 5 and 8 instructions), align to a 32-byte 13669 // boundary so that the entire loop fits in one instruction-cache line. 13670 uint64_t LoopSize = 0; 13671 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13672 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13673 LoopSize += TII->getInstSizeInBytes(*J); 13674 if (LoopSize > 32) 13675 break; 13676 } 13677 13678 if (LoopSize > 16 && LoopSize <= 32) 13679 return 5; 13680 13681 break; 13682 } 13683 } 13684 13685 return TargetLowering::getPrefLoopAlignment(ML); 13686 } 13687 13688 /// getConstraintType - Given a constraint, return the type of 13689 /// constraint it is for this target. 13690 PPCTargetLowering::ConstraintType 13691 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13692 if (Constraint.size() == 1) { 13693 switch (Constraint[0]) { 13694 default: break; 13695 case 'b': 13696 case 'r': 13697 case 'f': 13698 case 'd': 13699 case 'v': 13700 case 'y': 13701 return C_RegisterClass; 13702 case 'Z': 13703 // FIXME: While Z does indicate a memory constraint, it specifically 13704 // indicates an r+r address (used in conjunction with the 'y' modifier 13705 // in the replacement string). Currently, we're forcing the base 13706 // register to be r0 in the asm printer (which is interpreted as zero) 13707 // and forming the complete address in the second register. This is 13708 // suboptimal. 13709 return C_Memory; 13710 } 13711 } else if (Constraint == "wc") { // individual CR bits. 13712 return C_RegisterClass; 13713 } else if (Constraint == "wa" || Constraint == "wd" || 13714 Constraint == "wf" || Constraint == "ws" || 13715 Constraint == "wi") { 13716 return C_RegisterClass; // VSX registers. 13717 } 13718 return TargetLowering::getConstraintType(Constraint); 13719 } 13720 13721 /// Examine constraint type and operand type and determine a weight value. 13722 /// This object must already have been set up with the operand type 13723 /// and the current alternative constraint selected. 13724 TargetLowering::ConstraintWeight 13725 PPCTargetLowering::getSingleConstraintMatchWeight( 13726 AsmOperandInfo &info, const char *constraint) const { 13727 ConstraintWeight weight = CW_Invalid; 13728 Value *CallOperandVal = info.CallOperandVal; 13729 // If we don't have a value, we can't do a match, 13730 // but allow it at the lowest weight. 13731 if (!CallOperandVal) 13732 return CW_Default; 13733 Type *type = CallOperandVal->getType(); 13734 13735 // Look at the constraint type. 13736 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13737 return CW_Register; // an individual CR bit. 13738 else if ((StringRef(constraint) == "wa" || 13739 StringRef(constraint) == "wd" || 13740 StringRef(constraint) == "wf") && 13741 type->isVectorTy()) 13742 return CW_Register; 13743 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13744 return CW_Register; 13745 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13746 return CW_Register; // just hold 64-bit integers data. 13747 13748 switch (*constraint) { 13749 default: 13750 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13751 break; 13752 case 'b': 13753 if (type->isIntegerTy()) 13754 weight = CW_Register; 13755 break; 13756 case 'f': 13757 if (type->isFloatTy()) 13758 weight = CW_Register; 13759 break; 13760 case 'd': 13761 if (type->isDoubleTy()) 13762 weight = CW_Register; 13763 break; 13764 case 'v': 13765 if (type->isVectorTy()) 13766 weight = CW_Register; 13767 break; 13768 case 'y': 13769 weight = CW_Register; 13770 break; 13771 case 'Z': 13772 weight = CW_Memory; 13773 break; 13774 } 13775 return weight; 13776 } 13777 13778 std::pair<unsigned, const TargetRegisterClass *> 13779 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13780 StringRef Constraint, 13781 MVT VT) const { 13782 if (Constraint.size() == 1) { 13783 // GCC RS6000 Constraint Letters 13784 switch (Constraint[0]) { 13785 case 'b': // R1-R31 13786 if (VT == MVT::i64 && Subtarget.isPPC64()) 13787 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13788 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13789 case 'r': // R0-R31 13790 if (VT == MVT::i64 && Subtarget.isPPC64()) 13791 return std::make_pair(0U, &PPC::G8RCRegClass); 13792 return std::make_pair(0U, &PPC::GPRCRegClass); 13793 // 'd' and 'f' constraints are both defined to be "the floating point 13794 // registers", where one is for 32-bit and the other for 64-bit. We don't 13795 // really care overly much here so just give them all the same reg classes. 13796 case 'd': 13797 case 'f': 13798 if (Subtarget.hasSPE()) { 13799 if (VT == MVT::f32 || VT == MVT::i32) 13800 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13801 if (VT == MVT::f64 || VT == MVT::i64) 13802 return std::make_pair(0U, &PPC::SPERCRegClass); 13803 } else { 13804 if (VT == MVT::f32 || VT == MVT::i32) 13805 return std::make_pair(0U, &PPC::F4RCRegClass); 13806 if (VT == MVT::f64 || VT == MVT::i64) 13807 return std::make_pair(0U, &PPC::F8RCRegClass); 13808 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13809 return std::make_pair(0U, &PPC::QFRCRegClass); 13810 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13811 return std::make_pair(0U, &PPC::QSRCRegClass); 13812 } 13813 break; 13814 case 'v': 13815 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13816 return std::make_pair(0U, &PPC::QFRCRegClass); 13817 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13818 return std::make_pair(0U, &PPC::QSRCRegClass); 13819 if (Subtarget.hasAltivec()) 13820 return std::make_pair(0U, &PPC::VRRCRegClass); 13821 break; 13822 case 'y': // crrc 13823 return std::make_pair(0U, &PPC::CRRCRegClass); 13824 } 13825 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13826 // An individual CR bit. 13827 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13828 } else if ((Constraint == "wa" || Constraint == "wd" || 13829 Constraint == "wf" || Constraint == "wi") && 13830 Subtarget.hasVSX()) { 13831 return std::make_pair(0U, &PPC::VSRCRegClass); 13832 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13833 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13834 return std::make_pair(0U, &PPC::VSSRCRegClass); 13835 else 13836 return std::make_pair(0U, &PPC::VSFRCRegClass); 13837 } 13838 13839 std::pair<unsigned, const TargetRegisterClass *> R = 13840 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13841 13842 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13843 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13844 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13845 // register. 13846 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13847 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13848 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13849 PPC::GPRCRegClass.contains(R.first)) 13850 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13851 PPC::sub_32, &PPC::G8RCRegClass), 13852 &PPC::G8RCRegClass); 13853 13854 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13855 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13856 R.first = PPC::CR0; 13857 R.second = &PPC::CRRCRegClass; 13858 } 13859 13860 return R; 13861 } 13862 13863 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13864 /// vector. If it is invalid, don't add anything to Ops. 13865 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13866 std::string &Constraint, 13867 std::vector<SDValue>&Ops, 13868 SelectionDAG &DAG) const { 13869 SDValue Result; 13870 13871 // Only support length 1 constraints. 13872 if (Constraint.length() > 1) return; 13873 13874 char Letter = Constraint[0]; 13875 switch (Letter) { 13876 default: break; 13877 case 'I': 13878 case 'J': 13879 case 'K': 13880 case 'L': 13881 case 'M': 13882 case 'N': 13883 case 'O': 13884 case 'P': { 13885 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13886 if (!CST) return; // Must be an immediate to match. 13887 SDLoc dl(Op); 13888 int64_t Value = CST->getSExtValue(); 13889 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13890 // numbers are printed as such. 13891 switch (Letter) { 13892 default: llvm_unreachable("Unknown constraint letter!"); 13893 case 'I': // "I" is a signed 16-bit constant. 13894 if (isInt<16>(Value)) 13895 Result = DAG.getTargetConstant(Value, dl, TCVT); 13896 break; 13897 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13898 if (isShiftedUInt<16, 16>(Value)) 13899 Result = DAG.getTargetConstant(Value, dl, TCVT); 13900 break; 13901 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13902 if (isShiftedInt<16, 16>(Value)) 13903 Result = DAG.getTargetConstant(Value, dl, TCVT); 13904 break; 13905 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13906 if (isUInt<16>(Value)) 13907 Result = DAG.getTargetConstant(Value, dl, TCVT); 13908 break; 13909 case 'M': // "M" is a constant that is greater than 31. 13910 if (Value > 31) 13911 Result = DAG.getTargetConstant(Value, dl, TCVT); 13912 break; 13913 case 'N': // "N" is a positive constant that is an exact power of two. 13914 if (Value > 0 && isPowerOf2_64(Value)) 13915 Result = DAG.getTargetConstant(Value, dl, TCVT); 13916 break; 13917 case 'O': // "O" is the constant zero. 13918 if (Value == 0) 13919 Result = DAG.getTargetConstant(Value, dl, TCVT); 13920 break; 13921 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13922 if (isInt<16>(-Value)) 13923 Result = DAG.getTargetConstant(Value, dl, TCVT); 13924 break; 13925 } 13926 break; 13927 } 13928 } 13929 13930 if (Result.getNode()) { 13931 Ops.push_back(Result); 13932 return; 13933 } 13934 13935 // Handle standard constraint letters. 13936 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13937 } 13938 13939 // isLegalAddressingMode - Return true if the addressing mode represented 13940 // by AM is legal for this target, for a load/store of the specified type. 13941 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13942 const AddrMode &AM, Type *Ty, 13943 unsigned AS, Instruction *I) const { 13944 // PPC does not allow r+i addressing modes for vectors! 13945 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13946 return false; 13947 13948 // PPC allows a sign-extended 16-bit immediate field. 13949 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13950 return false; 13951 13952 // No global is ever allowed as a base. 13953 if (AM.BaseGV) 13954 return false; 13955 13956 // PPC only support r+r, 13957 switch (AM.Scale) { 13958 case 0: // "r+i" or just "i", depending on HasBaseReg. 13959 break; 13960 case 1: 13961 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13962 return false; 13963 // Otherwise we have r+r or r+i. 13964 break; 13965 case 2: 13966 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13967 return false; 13968 // Allow 2*r as r+r. 13969 break; 13970 default: 13971 // No other scales are supported. 13972 return false; 13973 } 13974 13975 return true; 13976 } 13977 13978 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13979 SelectionDAG &DAG) const { 13980 MachineFunction &MF = DAG.getMachineFunction(); 13981 MachineFrameInfo &MFI = MF.getFrameInfo(); 13982 MFI.setReturnAddressIsTaken(true); 13983 13984 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13985 return SDValue(); 13986 13987 SDLoc dl(Op); 13988 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13989 13990 // Make sure the function does not optimize away the store of the RA to 13991 // the stack. 13992 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13993 FuncInfo->setLRStoreRequired(); 13994 bool isPPC64 = Subtarget.isPPC64(); 13995 auto PtrVT = getPointerTy(MF.getDataLayout()); 13996 13997 if (Depth > 0) { 13998 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13999 SDValue Offset = 14000 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14001 isPPC64 ? MVT::i64 : MVT::i32); 14002 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14003 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14004 MachinePointerInfo()); 14005 } 14006 14007 // Just load the return address off the stack. 14008 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14009 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14010 MachinePointerInfo()); 14011 } 14012 14013 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14014 SelectionDAG &DAG) const { 14015 SDLoc dl(Op); 14016 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14017 14018 MachineFunction &MF = DAG.getMachineFunction(); 14019 MachineFrameInfo &MFI = MF.getFrameInfo(); 14020 MFI.setFrameAddressIsTaken(true); 14021 14022 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14023 bool isPPC64 = PtrVT == MVT::i64; 14024 14025 // Naked functions never have a frame pointer, and so we use r1. For all 14026 // other functions, this decision must be delayed until during PEI. 14027 unsigned FrameReg; 14028 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14029 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14030 else 14031 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14032 14033 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14034 PtrVT); 14035 while (Depth--) 14036 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14037 FrameAddr, MachinePointerInfo()); 14038 return FrameAddr; 14039 } 14040 14041 // FIXME? Maybe this could be a TableGen attribute on some registers and 14042 // this table could be generated automatically from RegInfo. 14043 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14044 SelectionDAG &DAG) const { 14045 bool isPPC64 = Subtarget.isPPC64(); 14046 bool isDarwinABI = Subtarget.isDarwinABI(); 14047 14048 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14049 (!isPPC64 && VT != MVT::i32)) 14050 report_fatal_error("Invalid register global variable type"); 14051 14052 bool is64Bit = isPPC64 && VT == MVT::i64; 14053 unsigned Reg = StringSwitch<unsigned>(RegName) 14054 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14055 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 14056 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 14057 (is64Bit ? PPC::X13 : PPC::R13)) 14058 .Default(0); 14059 14060 if (Reg) 14061 return Reg; 14062 report_fatal_error("Invalid register name global variable"); 14063 } 14064 14065 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14066 // 32-bit SVR4 ABI access everything as got-indirect. 14067 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 14068 return true; 14069 14070 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14071 // If it is small or large code model, module locals are accessed 14072 // indirectly by loading their address from .toc/.got. The difference 14073 // is that for large code model we have ADDISTocHa + LDtocL and for 14074 // small code model we simply have LDtoc. 14075 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14076 return true; 14077 14078 // JumpTable and BlockAddress are accessed as got-indirect. 14079 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14080 return true; 14081 14082 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 14083 const GlobalValue *GV = G->getGlobal(); 14084 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 14085 // The NLP flag indicates that a global access has to use an 14086 // extra indirection. 14087 if (GVFlags & PPCII::MO_NLP_FLAG) 14088 return true; 14089 } 14090 14091 return false; 14092 } 14093 14094 bool 14095 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14096 // The PowerPC target isn't yet aware of offsets. 14097 return false; 14098 } 14099 14100 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14101 const CallInst &I, 14102 MachineFunction &MF, 14103 unsigned Intrinsic) const { 14104 switch (Intrinsic) { 14105 case Intrinsic::ppc_qpx_qvlfd: 14106 case Intrinsic::ppc_qpx_qvlfs: 14107 case Intrinsic::ppc_qpx_qvlfcd: 14108 case Intrinsic::ppc_qpx_qvlfcs: 14109 case Intrinsic::ppc_qpx_qvlfiwa: 14110 case Intrinsic::ppc_qpx_qvlfiwz: 14111 case Intrinsic::ppc_altivec_lvx: 14112 case Intrinsic::ppc_altivec_lvxl: 14113 case Intrinsic::ppc_altivec_lvebx: 14114 case Intrinsic::ppc_altivec_lvehx: 14115 case Intrinsic::ppc_altivec_lvewx: 14116 case Intrinsic::ppc_vsx_lxvd2x: 14117 case Intrinsic::ppc_vsx_lxvw4x: { 14118 EVT VT; 14119 switch (Intrinsic) { 14120 case Intrinsic::ppc_altivec_lvebx: 14121 VT = MVT::i8; 14122 break; 14123 case Intrinsic::ppc_altivec_lvehx: 14124 VT = MVT::i16; 14125 break; 14126 case Intrinsic::ppc_altivec_lvewx: 14127 VT = MVT::i32; 14128 break; 14129 case Intrinsic::ppc_vsx_lxvd2x: 14130 VT = MVT::v2f64; 14131 break; 14132 case Intrinsic::ppc_qpx_qvlfd: 14133 VT = MVT::v4f64; 14134 break; 14135 case Intrinsic::ppc_qpx_qvlfs: 14136 VT = MVT::v4f32; 14137 break; 14138 case Intrinsic::ppc_qpx_qvlfcd: 14139 VT = MVT::v2f64; 14140 break; 14141 case Intrinsic::ppc_qpx_qvlfcs: 14142 VT = MVT::v2f32; 14143 break; 14144 default: 14145 VT = MVT::v4i32; 14146 break; 14147 } 14148 14149 Info.opc = ISD::INTRINSIC_W_CHAIN; 14150 Info.memVT = VT; 14151 Info.ptrVal = I.getArgOperand(0); 14152 Info.offset = -VT.getStoreSize()+1; 14153 Info.size = 2*VT.getStoreSize()-1; 14154 Info.align = 1; 14155 Info.flags = MachineMemOperand::MOLoad; 14156 return true; 14157 } 14158 case Intrinsic::ppc_qpx_qvlfda: 14159 case Intrinsic::ppc_qpx_qvlfsa: 14160 case Intrinsic::ppc_qpx_qvlfcda: 14161 case Intrinsic::ppc_qpx_qvlfcsa: 14162 case Intrinsic::ppc_qpx_qvlfiwaa: 14163 case Intrinsic::ppc_qpx_qvlfiwza: { 14164 EVT VT; 14165 switch (Intrinsic) { 14166 case Intrinsic::ppc_qpx_qvlfda: 14167 VT = MVT::v4f64; 14168 break; 14169 case Intrinsic::ppc_qpx_qvlfsa: 14170 VT = MVT::v4f32; 14171 break; 14172 case Intrinsic::ppc_qpx_qvlfcda: 14173 VT = MVT::v2f64; 14174 break; 14175 case Intrinsic::ppc_qpx_qvlfcsa: 14176 VT = MVT::v2f32; 14177 break; 14178 default: 14179 VT = MVT::v4i32; 14180 break; 14181 } 14182 14183 Info.opc = ISD::INTRINSIC_W_CHAIN; 14184 Info.memVT = VT; 14185 Info.ptrVal = I.getArgOperand(0); 14186 Info.offset = 0; 14187 Info.size = VT.getStoreSize(); 14188 Info.align = 1; 14189 Info.flags = MachineMemOperand::MOLoad; 14190 return true; 14191 } 14192 case Intrinsic::ppc_qpx_qvstfd: 14193 case Intrinsic::ppc_qpx_qvstfs: 14194 case Intrinsic::ppc_qpx_qvstfcd: 14195 case Intrinsic::ppc_qpx_qvstfcs: 14196 case Intrinsic::ppc_qpx_qvstfiw: 14197 case Intrinsic::ppc_altivec_stvx: 14198 case Intrinsic::ppc_altivec_stvxl: 14199 case Intrinsic::ppc_altivec_stvebx: 14200 case Intrinsic::ppc_altivec_stvehx: 14201 case Intrinsic::ppc_altivec_stvewx: 14202 case Intrinsic::ppc_vsx_stxvd2x: 14203 case Intrinsic::ppc_vsx_stxvw4x: { 14204 EVT VT; 14205 switch (Intrinsic) { 14206 case Intrinsic::ppc_altivec_stvebx: 14207 VT = MVT::i8; 14208 break; 14209 case Intrinsic::ppc_altivec_stvehx: 14210 VT = MVT::i16; 14211 break; 14212 case Intrinsic::ppc_altivec_stvewx: 14213 VT = MVT::i32; 14214 break; 14215 case Intrinsic::ppc_vsx_stxvd2x: 14216 VT = MVT::v2f64; 14217 break; 14218 case Intrinsic::ppc_qpx_qvstfd: 14219 VT = MVT::v4f64; 14220 break; 14221 case Intrinsic::ppc_qpx_qvstfs: 14222 VT = MVT::v4f32; 14223 break; 14224 case Intrinsic::ppc_qpx_qvstfcd: 14225 VT = MVT::v2f64; 14226 break; 14227 case Intrinsic::ppc_qpx_qvstfcs: 14228 VT = MVT::v2f32; 14229 break; 14230 default: 14231 VT = MVT::v4i32; 14232 break; 14233 } 14234 14235 Info.opc = ISD::INTRINSIC_VOID; 14236 Info.memVT = VT; 14237 Info.ptrVal = I.getArgOperand(1); 14238 Info.offset = -VT.getStoreSize()+1; 14239 Info.size = 2*VT.getStoreSize()-1; 14240 Info.align = 1; 14241 Info.flags = MachineMemOperand::MOStore; 14242 return true; 14243 } 14244 case Intrinsic::ppc_qpx_qvstfda: 14245 case Intrinsic::ppc_qpx_qvstfsa: 14246 case Intrinsic::ppc_qpx_qvstfcda: 14247 case Intrinsic::ppc_qpx_qvstfcsa: 14248 case Intrinsic::ppc_qpx_qvstfiwa: { 14249 EVT VT; 14250 switch (Intrinsic) { 14251 case Intrinsic::ppc_qpx_qvstfda: 14252 VT = MVT::v4f64; 14253 break; 14254 case Intrinsic::ppc_qpx_qvstfsa: 14255 VT = MVT::v4f32; 14256 break; 14257 case Intrinsic::ppc_qpx_qvstfcda: 14258 VT = MVT::v2f64; 14259 break; 14260 case Intrinsic::ppc_qpx_qvstfcsa: 14261 VT = MVT::v2f32; 14262 break; 14263 default: 14264 VT = MVT::v4i32; 14265 break; 14266 } 14267 14268 Info.opc = ISD::INTRINSIC_VOID; 14269 Info.memVT = VT; 14270 Info.ptrVal = I.getArgOperand(1); 14271 Info.offset = 0; 14272 Info.size = VT.getStoreSize(); 14273 Info.align = 1; 14274 Info.flags = MachineMemOperand::MOStore; 14275 return true; 14276 } 14277 default: 14278 break; 14279 } 14280 14281 return false; 14282 } 14283 14284 /// getOptimalMemOpType - Returns the target specific optimal type for load 14285 /// and store operations as a result of memset, memcpy, and memmove 14286 /// lowering. If DstAlign is zero that means it's safe to destination 14287 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14288 /// means there isn't a need to check it against alignment requirement, 14289 /// probably because the source does not need to be loaded. If 'IsMemset' is 14290 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14291 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14292 /// source is constant so it does not need to be loaded. 14293 /// It returns EVT::Other if the type should be determined using generic 14294 /// target-independent logic. 14295 EVT PPCTargetLowering::getOptimalMemOpType( 14296 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14297 bool ZeroMemset, bool MemcpyStrSrc, 14298 const AttributeList &FuncAttributes) const { 14299 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14300 // When expanding a memset, require at least two QPX instructions to cover 14301 // the cost of loading the value to be stored from the constant pool. 14302 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14303 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14304 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14305 return MVT::v4f64; 14306 } 14307 14308 // We should use Altivec/VSX loads and stores when available. For unaligned 14309 // addresses, unaligned VSX loads are only fast starting with the P8. 14310 if (Subtarget.hasAltivec() && Size >= 16 && 14311 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14312 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14313 return MVT::v4i32; 14314 } 14315 14316 if (Subtarget.isPPC64()) { 14317 return MVT::i64; 14318 } 14319 14320 return MVT::i32; 14321 } 14322 14323 /// Returns true if it is beneficial to convert a load of a constant 14324 /// to just the constant itself. 14325 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14326 Type *Ty) const { 14327 assert(Ty->isIntegerTy()); 14328 14329 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14330 return !(BitSize == 0 || BitSize > 64); 14331 } 14332 14333 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14334 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14335 return false; 14336 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14337 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14338 return NumBits1 == 64 && NumBits2 == 32; 14339 } 14340 14341 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14342 if (!VT1.isInteger() || !VT2.isInteger()) 14343 return false; 14344 unsigned NumBits1 = VT1.getSizeInBits(); 14345 unsigned NumBits2 = VT2.getSizeInBits(); 14346 return NumBits1 == 64 && NumBits2 == 32; 14347 } 14348 14349 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14350 // Generally speaking, zexts are not free, but they are free when they can be 14351 // folded with other operations. 14352 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14353 EVT MemVT = LD->getMemoryVT(); 14354 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14355 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14356 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14357 LD->getExtensionType() == ISD::ZEXTLOAD)) 14358 return true; 14359 } 14360 14361 // FIXME: Add other cases... 14362 // - 32-bit shifts with a zext to i64 14363 // - zext after ctlz, bswap, etc. 14364 // - zext after and by a constant mask 14365 14366 return TargetLowering::isZExtFree(Val, VT2); 14367 } 14368 14369 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14370 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14371 "invalid fpext types"); 14372 // Extending to float128 is not free. 14373 if (DestVT == MVT::f128) 14374 return false; 14375 return true; 14376 } 14377 14378 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14379 return isInt<16>(Imm) || isUInt<16>(Imm); 14380 } 14381 14382 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14383 return isInt<16>(Imm) || isUInt<16>(Imm); 14384 } 14385 14386 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14387 unsigned, 14388 unsigned, 14389 bool *Fast) const { 14390 if (DisablePPCUnaligned) 14391 return false; 14392 14393 // PowerPC supports unaligned memory access for simple non-vector types. 14394 // Although accessing unaligned addresses is not as efficient as accessing 14395 // aligned addresses, it is generally more efficient than manual expansion, 14396 // and generally only traps for software emulation when crossing page 14397 // boundaries. 14398 14399 if (!VT.isSimple()) 14400 return false; 14401 14402 if (VT.getSimpleVT().isVector()) { 14403 if (Subtarget.hasVSX()) { 14404 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14405 VT != MVT::v4f32 && VT != MVT::v4i32) 14406 return false; 14407 } else { 14408 return false; 14409 } 14410 } 14411 14412 if (VT == MVT::ppcf128) 14413 return false; 14414 14415 if (Fast) 14416 *Fast = true; 14417 14418 return true; 14419 } 14420 14421 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14422 VT = VT.getScalarType(); 14423 14424 if (!VT.isSimple()) 14425 return false; 14426 14427 switch (VT.getSimpleVT().SimpleTy) { 14428 case MVT::f32: 14429 case MVT::f64: 14430 return true; 14431 case MVT::f128: 14432 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14433 default: 14434 break; 14435 } 14436 14437 return false; 14438 } 14439 14440 const MCPhysReg * 14441 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14442 // LR is a callee-save register, but we must treat it as clobbered by any call 14443 // site. Hence we include LR in the scratch registers, which are in turn added 14444 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14445 // to CTR, which is used by any indirect call. 14446 static const MCPhysReg ScratchRegs[] = { 14447 PPC::X12, PPC::LR8, PPC::CTR8, 0 14448 }; 14449 14450 return ScratchRegs; 14451 } 14452 14453 unsigned PPCTargetLowering::getExceptionPointerRegister( 14454 const Constant *PersonalityFn) const { 14455 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14456 } 14457 14458 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14459 const Constant *PersonalityFn) const { 14460 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14461 } 14462 14463 bool 14464 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14465 EVT VT , unsigned DefinedValues) const { 14466 if (VT == MVT::v2i64) 14467 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14468 14469 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14470 return true; 14471 14472 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14473 } 14474 14475 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14476 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14477 return TargetLowering::getSchedulingPreference(N); 14478 14479 return Sched::ILP; 14480 } 14481 14482 // Create a fast isel object. 14483 FastISel * 14484 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14485 const TargetLibraryInfo *LibInfo) const { 14486 return PPC::createFastISel(FuncInfo, LibInfo); 14487 } 14488 14489 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14490 if (Subtarget.isDarwinABI()) return; 14491 if (!Subtarget.isPPC64()) return; 14492 14493 // Update IsSplitCSR in PPCFunctionInfo 14494 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14495 PFI->setIsSplitCSR(true); 14496 } 14497 14498 void PPCTargetLowering::insertCopiesSplitCSR( 14499 MachineBasicBlock *Entry, 14500 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14501 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14502 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14503 if (!IStart) 14504 return; 14505 14506 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14507 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14508 MachineBasicBlock::iterator MBBI = Entry->begin(); 14509 for (const MCPhysReg *I = IStart; *I; ++I) { 14510 const TargetRegisterClass *RC = nullptr; 14511 if (PPC::G8RCRegClass.contains(*I)) 14512 RC = &PPC::G8RCRegClass; 14513 else if (PPC::F8RCRegClass.contains(*I)) 14514 RC = &PPC::F8RCRegClass; 14515 else if (PPC::CRRCRegClass.contains(*I)) 14516 RC = &PPC::CRRCRegClass; 14517 else if (PPC::VRRCRegClass.contains(*I)) 14518 RC = &PPC::VRRCRegClass; 14519 else 14520 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14521 14522 unsigned NewVR = MRI->createVirtualRegister(RC); 14523 // Create copy from CSR to a virtual register. 14524 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14525 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14526 // nounwind. If we want to generalize this later, we may need to emit 14527 // CFI pseudo-instructions. 14528 assert(Entry->getParent()->getFunction().hasFnAttribute( 14529 Attribute::NoUnwind) && 14530 "Function should be nounwind in insertCopiesSplitCSR!"); 14531 Entry->addLiveIn(*I); 14532 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14533 .addReg(*I); 14534 14535 // Insert the copy-back instructions right before the terminator. 14536 for (auto *Exit : Exits) 14537 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14538 TII->get(TargetOpcode::COPY), *I) 14539 .addReg(NewVR); 14540 } 14541 } 14542 14543 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14544 bool PPCTargetLowering::useLoadStackGuardNode() const { 14545 if (!Subtarget.isTargetLinux()) 14546 return TargetLowering::useLoadStackGuardNode(); 14547 return true; 14548 } 14549 14550 // Override to disable global variable loading on Linux. 14551 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14552 if (!Subtarget.isTargetLinux()) 14553 return TargetLowering::insertSSPDeclarations(M); 14554 } 14555 14556 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14557 bool ForCodeSize) const { 14558 if (!VT.isSimple() || !Subtarget.hasVSX()) 14559 return false; 14560 14561 switch(VT.getSimpleVT().SimpleTy) { 14562 default: 14563 // For FP types that are currently not supported by PPC backend, return 14564 // false. Examples: f16, f80. 14565 return false; 14566 case MVT::f32: 14567 case MVT::f64: 14568 case MVT::ppcf128: 14569 return Imm.isPosZero(); 14570 } 14571 } 14572 14573 // For vector shift operation op, fold 14574 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14575 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14576 SelectionDAG &DAG) { 14577 SDValue N0 = N->getOperand(0); 14578 SDValue N1 = N->getOperand(1); 14579 EVT VT = N0.getValueType(); 14580 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14581 unsigned Opcode = N->getOpcode(); 14582 unsigned TargetOpcode; 14583 14584 switch (Opcode) { 14585 default: 14586 llvm_unreachable("Unexpected shift operation"); 14587 case ISD::SHL: 14588 TargetOpcode = PPCISD::SHL; 14589 break; 14590 case ISD::SRL: 14591 TargetOpcode = PPCISD::SRL; 14592 break; 14593 case ISD::SRA: 14594 TargetOpcode = PPCISD::SRA; 14595 break; 14596 } 14597 14598 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14599 N1->getOpcode() == ISD::AND) 14600 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14601 if (Mask->getZExtValue() == OpSizeInBits - 1) 14602 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14603 14604 return SDValue(); 14605 } 14606 14607 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14608 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14609 return Value; 14610 14611 SDValue N0 = N->getOperand(0); 14612 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14613 if (!Subtarget.isISA3_0() || 14614 N0.getOpcode() != ISD::SIGN_EXTEND || 14615 N0.getOperand(0).getValueType() != MVT::i32 || 14616 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14617 return SDValue(); 14618 14619 // We can't save an operation here if the value is already extended, and 14620 // the existing shift is easier to combine. 14621 SDValue ExtsSrc = N0.getOperand(0); 14622 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14623 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14624 return SDValue(); 14625 14626 SDLoc DL(N0); 14627 SDValue ShiftBy = SDValue(CN1, 0); 14628 // We want the shift amount to be i32 on the extswli, but the shift could 14629 // have an i64. 14630 if (ShiftBy.getValueType() == MVT::i64) 14631 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14632 14633 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14634 ShiftBy); 14635 } 14636 14637 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14638 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14639 return Value; 14640 14641 return SDValue(); 14642 } 14643 14644 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14645 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14646 return Value; 14647 14648 return SDValue(); 14649 } 14650 14651 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14652 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14653 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14654 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14655 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14656 const PPCSubtarget &Subtarget) { 14657 if (!Subtarget.isPPC64()) 14658 return SDValue(); 14659 14660 SDValue LHS = N->getOperand(0); 14661 SDValue RHS = N->getOperand(1); 14662 14663 auto isZextOfCompareWithConstant = [](SDValue Op) { 14664 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14665 Op.getValueType() != MVT::i64) 14666 return false; 14667 14668 SDValue Cmp = Op.getOperand(0); 14669 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14670 Cmp.getOperand(0).getValueType() != MVT::i64) 14671 return false; 14672 14673 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14674 int64_t NegConstant = 0 - Constant->getSExtValue(); 14675 // Due to the limitations of the addi instruction, 14676 // -C is required to be [-32768, 32767]. 14677 return isInt<16>(NegConstant); 14678 } 14679 14680 return false; 14681 }; 14682 14683 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14684 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14685 14686 // If there is a pattern, canonicalize a zext operand to the RHS. 14687 if (LHSHasPattern && !RHSHasPattern) 14688 std::swap(LHS, RHS); 14689 else if (!LHSHasPattern && !RHSHasPattern) 14690 return SDValue(); 14691 14692 SDLoc DL(N); 14693 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 14694 SDValue Cmp = RHS.getOperand(0); 14695 SDValue Z = Cmp.getOperand(0); 14696 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14697 14698 assert(Constant && "Constant Should not be a null pointer."); 14699 int64_t NegConstant = 0 - Constant->getSExtValue(); 14700 14701 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14702 default: break; 14703 case ISD::SETNE: { 14704 // when C == 0 14705 // --> addze X, (addic Z, -1).carry 14706 // / 14707 // add X, (zext(setne Z, C))-- 14708 // \ when -32768 <= -C <= 32767 && C != 0 14709 // --> addze X, (addic (addi Z, -C), -1).carry 14710 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14711 DAG.getConstant(NegConstant, DL, MVT::i64)); 14712 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14713 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14714 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14715 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14716 SDValue(Addc.getNode(), 1)); 14717 } 14718 case ISD::SETEQ: { 14719 // when C == 0 14720 // --> addze X, (subfic Z, 0).carry 14721 // / 14722 // add X, (zext(sete Z, C))-- 14723 // \ when -32768 <= -C <= 32767 && C != 0 14724 // --> addze X, (subfic (addi Z, -C), 0).carry 14725 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14726 DAG.getConstant(NegConstant, DL, MVT::i64)); 14727 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14728 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14729 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14730 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14731 SDValue(Subc.getNode(), 1)); 14732 } 14733 } 14734 14735 return SDValue(); 14736 } 14737 14738 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14739 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14740 return Value; 14741 14742 return SDValue(); 14743 } 14744 14745 // Detect TRUNCATE operations on bitcasts of float128 values. 14746 // What we are looking for here is the situtation where we extract a subset 14747 // of bits from a 128 bit float. 14748 // This can be of two forms: 14749 // 1) BITCAST of f128 feeding TRUNCATE 14750 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14751 // The reason this is required is because we do not have a legal i128 type 14752 // and so we want to prevent having to store the f128 and then reload part 14753 // of it. 14754 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14755 DAGCombinerInfo &DCI) const { 14756 // If we are using CRBits then try that first. 14757 if (Subtarget.useCRBits()) { 14758 // Check if CRBits did anything and return that if it did. 14759 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14760 return CRTruncValue; 14761 } 14762 14763 SDLoc dl(N); 14764 SDValue Op0 = N->getOperand(0); 14765 14766 // Looking for a truncate of i128 to i64. 14767 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14768 return SDValue(); 14769 14770 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14771 14772 // SRL feeding TRUNCATE. 14773 if (Op0.getOpcode() == ISD::SRL) { 14774 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14775 // The right shift has to be by 64 bits. 14776 if (!ConstNode || ConstNode->getZExtValue() != 64) 14777 return SDValue(); 14778 14779 // Switch the element number to extract. 14780 EltToExtract = EltToExtract ? 0 : 1; 14781 // Update Op0 past the SRL. 14782 Op0 = Op0.getOperand(0); 14783 } 14784 14785 // BITCAST feeding a TRUNCATE possibly via SRL. 14786 if (Op0.getOpcode() == ISD::BITCAST && 14787 Op0.getValueType() == MVT::i128 && 14788 Op0.getOperand(0).getValueType() == MVT::f128) { 14789 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14790 return DCI.DAG.getNode( 14791 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14792 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14793 } 14794 return SDValue(); 14795 } 14796 14797 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 14798 SelectionDAG &DAG = DCI.DAG; 14799 14800 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 14801 if (!ConstOpOrElement) 14802 return SDValue(); 14803 14804 // An imul is usually smaller than the alternative sequence for legal type. 14805 if (DAG.getMachineFunction().getFunction().hasMinSize() && 14806 isOperationLegal(ISD::MUL, N->getValueType(0))) 14807 return SDValue(); 14808 14809 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 14810 switch (this->Subtarget.getDarwinDirective()) { 14811 default: 14812 // TODO: enhance the condition for subtarget before pwr8 14813 return false; 14814 case PPC::DIR_PWR8: 14815 // type mul add shl 14816 // scalar 4 1 1 14817 // vector 7 2 2 14818 return true; 14819 case PPC::DIR_PWR9: 14820 // type mul add shl 14821 // scalar 5 2 2 14822 // vector 7 2 2 14823 14824 // The cycle RATIO of related operations are showed as a table above. 14825 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 14826 // scalar and vector type. For 2 instrs patterns, add/sub + shl 14827 // are 4, it is always profitable; but for 3 instrs patterns 14828 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 14829 // So we should only do it for vector type. 14830 return IsAddOne && IsNeg ? VT.isVector() : true; 14831 } 14832 }; 14833 14834 EVT VT = N->getValueType(0); 14835 SDLoc DL(N); 14836 14837 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 14838 bool IsNeg = MulAmt.isNegative(); 14839 APInt MulAmtAbs = MulAmt.abs(); 14840 14841 if ((MulAmtAbs - 1).isPowerOf2()) { 14842 // (mul x, 2^N + 1) => (add (shl x, N), x) 14843 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 14844 14845 if (!IsProfitable(IsNeg, true, VT)) 14846 return SDValue(); 14847 14848 SDValue Op0 = N->getOperand(0); 14849 SDValue Op1 = 14850 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14851 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 14852 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 14853 14854 if (!IsNeg) 14855 return Res; 14856 14857 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 14858 } else if ((MulAmtAbs + 1).isPowerOf2()) { 14859 // (mul x, 2^N - 1) => (sub (shl x, N), x) 14860 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 14861 14862 if (!IsProfitable(IsNeg, false, VT)) 14863 return SDValue(); 14864 14865 SDValue Op0 = N->getOperand(0); 14866 SDValue Op1 = 14867 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14868 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 14869 14870 if (!IsNeg) 14871 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 14872 else 14873 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 14874 14875 } else { 14876 return SDValue(); 14877 } 14878 } 14879 14880 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14881 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14882 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14883 return false; 14884 14885 // If not a tail call then no need to proceed. 14886 if (!CI->isTailCall()) 14887 return false; 14888 14889 // If tail calls are disabled for the caller then we are done. 14890 const Function *Caller = CI->getParent()->getParent(); 14891 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14892 if (Attr.getValueAsString() == "true") 14893 return false; 14894 14895 // If sibling calls have been disabled and tail-calls aren't guaranteed 14896 // there is no reason to duplicate. 14897 auto &TM = getTargetMachine(); 14898 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14899 return false; 14900 14901 // Can't tail call a function called indirectly, or if it has variadic args. 14902 const Function *Callee = CI->getCalledFunction(); 14903 if (!Callee || Callee->isVarArg()) 14904 return false; 14905 14906 // Make sure the callee and caller calling conventions are eligible for tco. 14907 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14908 CI->getCallingConv())) 14909 return false; 14910 14911 // If the function is local then we have a good chance at tail-calling it 14912 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14913 } 14914 14915 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14916 if (!Subtarget.hasVSX()) 14917 return false; 14918 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14919 return true; 14920 return VT == MVT::f32 || VT == MVT::f64 || 14921 VT == MVT::v4f32 || VT == MVT::v2f64; 14922 } 14923 14924 bool PPCTargetLowering:: 14925 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14926 const Value *Mask = AndI.getOperand(1); 14927 // If the mask is suitable for andi. or andis. we should sink the and. 14928 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14929 // Can't handle constants wider than 64-bits. 14930 if (CI->getBitWidth() > 64) 14931 return false; 14932 int64_t ConstVal = CI->getZExtValue(); 14933 return isUInt<16>(ConstVal) || 14934 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14935 } 14936 14937 // For non-constant masks, we can always use the record-form and. 14938 return true; 14939 } 14940 14941 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 14942 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 14943 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 14944 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 14945 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 14946 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 14947 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 14948 assert(Subtarget.hasP9Altivec() && 14949 "Only combine this when P9 altivec supported!"); 14950 EVT VT = N->getValueType(0); 14951 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14952 return SDValue(); 14953 14954 SelectionDAG &DAG = DCI.DAG; 14955 SDLoc dl(N); 14956 if (N->getOperand(0).getOpcode() == ISD::SUB) { 14957 // Even for signed integers, if it's known to be positive (as signed 14958 // integer) due to zero-extended inputs. 14959 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 14960 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 14961 if ((SubOpcd0 == ISD::ZERO_EXTEND || 14962 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 14963 (SubOpcd1 == ISD::ZERO_EXTEND || 14964 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 14965 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14966 N->getOperand(0)->getOperand(0), 14967 N->getOperand(0)->getOperand(1), 14968 DAG.getTargetConstant(0, dl, MVT::i32)); 14969 } 14970 14971 // For type v4i32, it can be optimized with xvnegsp + vabsduw 14972 if (N->getOperand(0).getValueType() == MVT::v4i32 && 14973 N->getOperand(0).hasOneUse()) { 14974 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14975 N->getOperand(0)->getOperand(0), 14976 N->getOperand(0)->getOperand(1), 14977 DAG.getTargetConstant(1, dl, MVT::i32)); 14978 } 14979 } 14980 14981 return SDValue(); 14982 } 14983 14984 // For type v4i32/v8ii16/v16i8, transform 14985 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 14986 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 14987 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 14988 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 14989 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 14990 DAGCombinerInfo &DCI) const { 14991 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 14992 assert(Subtarget.hasP9Altivec() && 14993 "Only combine this when P9 altivec supported!"); 14994 14995 SelectionDAG &DAG = DCI.DAG; 14996 SDLoc dl(N); 14997 SDValue Cond = N->getOperand(0); 14998 SDValue TrueOpnd = N->getOperand(1); 14999 SDValue FalseOpnd = N->getOperand(2); 15000 EVT VT = N->getOperand(1).getValueType(); 15001 15002 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15003 FalseOpnd.getOpcode() != ISD::SUB) 15004 return SDValue(); 15005 15006 // ABSD only available for type v4i32/v8i16/v16i8 15007 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15008 return SDValue(); 15009 15010 // At least to save one more dependent computation 15011 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15012 return SDValue(); 15013 15014 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15015 15016 // Can only handle unsigned comparison here 15017 switch (CC) { 15018 default: 15019 return SDValue(); 15020 case ISD::SETUGT: 15021 case ISD::SETUGE: 15022 break; 15023 case ISD::SETULT: 15024 case ISD::SETULE: 15025 std::swap(TrueOpnd, FalseOpnd); 15026 break; 15027 } 15028 15029 SDValue CmpOpnd1 = Cond.getOperand(0); 15030 SDValue CmpOpnd2 = Cond.getOperand(1); 15031 15032 // SETCC CmpOpnd1 CmpOpnd2 cond 15033 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15034 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15035 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15036 TrueOpnd.getOperand(1) == CmpOpnd2 && 15037 FalseOpnd.getOperand(0) == CmpOpnd2 && 15038 FalseOpnd.getOperand(1) == CmpOpnd1) { 15039 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15040 CmpOpnd1, CmpOpnd2, 15041 DAG.getTargetConstant(0, dl, MVT::i32)); 15042 } 15043 15044 return SDValue(); 15045 } 15046