1 //===- TargetLoweringBase.cpp - Implement the TargetLoweringBase class ----===// 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 implements the TargetLoweringBase class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/BitVector.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/StringExtras.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/Analysis/Loads.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/ISDOpcodes.h" 24 #include "llvm/CodeGen/MachineBasicBlock.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineInstr.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineMemOperand.h" 30 #include "llvm/CodeGen/MachineOperand.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/RuntimeLibcalls.h" 33 #include "llvm/CodeGen/StackMaps.h" 34 #include "llvm/CodeGen/TargetLowering.h" 35 #include "llvm/CodeGen/TargetOpcodes.h" 36 #include "llvm/CodeGen/TargetRegisterInfo.h" 37 #include "llvm/CodeGen/ValueTypes.h" 38 #include "llvm/IR/Attributes.h" 39 #include "llvm/IR/CallingConv.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DerivedTypes.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/GlobalValue.h" 44 #include "llvm/IR/GlobalVariable.h" 45 #include "llvm/IR/IRBuilder.h" 46 #include "llvm/IR/Module.h" 47 #include "llvm/IR/Type.h" 48 #include "llvm/Support/BranchProbability.h" 49 #include "llvm/Support/Casting.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Compiler.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/MachineValueType.h" 54 #include "llvm/Support/MathExtras.h" 55 #include "llvm/Target/TargetMachine.h" 56 #include "llvm/Transforms/Utils/SizeOpts.h" 57 #include <algorithm> 58 #include <cassert> 59 #include <cstddef> 60 #include <cstdint> 61 #include <cstring> 62 #include <iterator> 63 #include <string> 64 #include <tuple> 65 #include <utility> 66 67 using namespace llvm; 68 69 static cl::opt<bool> JumpIsExpensiveOverride( 70 "jump-is-expensive", cl::init(false), 71 cl::desc("Do not create extra branches to split comparison logic."), 72 cl::Hidden); 73 74 static cl::opt<unsigned> MinimumJumpTableEntries 75 ("min-jump-table-entries", cl::init(4), cl::Hidden, 76 cl::desc("Set minimum number of entries to use a jump table.")); 77 78 static cl::opt<unsigned> MaximumJumpTableSize 79 ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden, 80 cl::desc("Set maximum size of jump tables.")); 81 82 /// Minimum jump table density for normal functions. 83 static cl::opt<unsigned> 84 JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden, 85 cl::desc("Minimum density for building a jump table in " 86 "a normal function")); 87 88 /// Minimum jump table density for -Os or -Oz functions. 89 static cl::opt<unsigned> OptsizeJumpTableDensity( 90 "optsize-jump-table-density", cl::init(40), cl::Hidden, 91 cl::desc("Minimum density for building a jump table in " 92 "an optsize function")); 93 94 // FIXME: This option is only to test if the strict fp operation processed 95 // correctly by preventing mutating strict fp operation to normal fp operation 96 // during development. When the backend supports strict float operation, this 97 // option will be meaningless. 98 static cl::opt<bool> DisableStrictNodeMutation("disable-strictnode-mutation", 99 cl::desc("Don't mutate strict-float node to a legalize node"), 100 cl::init(false), cl::Hidden); 101 102 static bool darwinHasSinCos(const Triple &TT) { 103 assert(TT.isOSDarwin() && "should be called with darwin triple"); 104 // Don't bother with 32 bit x86. 105 if (TT.getArch() == Triple::x86) 106 return false; 107 // Macos < 10.9 has no sincos_stret. 108 if (TT.isMacOSX()) 109 return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit(); 110 // iOS < 7.0 has no sincos_stret. 111 if (TT.isiOS()) 112 return !TT.isOSVersionLT(7, 0); 113 // Any other darwin such as WatchOS/TvOS is new enough. 114 return true; 115 } 116 117 // Although this default value is arbitrary, it is not random. It is assumed 118 // that a condition that evaluates the same way by a higher percentage than this 119 // is best represented as control flow. Therefore, the default value N should be 120 // set such that the win from N% correct executions is greater than the loss 121 // from (100 - N)% mispredicted executions for the majority of intended targets. 122 static cl::opt<int> MinPercentageForPredictableBranch( 123 "min-predictable-branch", cl::init(99), 124 cl::desc("Minimum percentage (0-100) that a condition must be either true " 125 "or false to assume that the condition is predictable"), 126 cl::Hidden); 127 128 void TargetLoweringBase::InitLibcalls(const Triple &TT) { 129 #define HANDLE_LIBCALL(code, name) \ 130 setLibcallName(RTLIB::code, name); 131 #include "llvm/IR/RuntimeLibcalls.def" 132 #undef HANDLE_LIBCALL 133 // Initialize calling conventions to their default. 134 for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC) 135 setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C); 136 137 // For IEEE quad-precision libcall names, PPC uses "kf" instead of "tf". 138 if (TT.getArch() == Triple::ppc || TT.isPPC64()) { 139 setLibcallName(RTLIB::ADD_F128, "__addkf3"); 140 setLibcallName(RTLIB::SUB_F128, "__subkf3"); 141 setLibcallName(RTLIB::MUL_F128, "__mulkf3"); 142 setLibcallName(RTLIB::DIV_F128, "__divkf3"); 143 setLibcallName(RTLIB::FPEXT_F32_F128, "__extendsfkf2"); 144 setLibcallName(RTLIB::FPEXT_F64_F128, "__extenddfkf2"); 145 setLibcallName(RTLIB::FPROUND_F128_F32, "__trunckfsf2"); 146 setLibcallName(RTLIB::FPROUND_F128_F64, "__trunckfdf2"); 147 setLibcallName(RTLIB::FPTOSINT_F128_I32, "__fixkfsi"); 148 setLibcallName(RTLIB::FPTOSINT_F128_I64, "__fixkfdi"); 149 setLibcallName(RTLIB::FPTOUINT_F128_I32, "__fixunskfsi"); 150 setLibcallName(RTLIB::FPTOUINT_F128_I64, "__fixunskfdi"); 151 setLibcallName(RTLIB::SINTTOFP_I32_F128, "__floatsikf"); 152 setLibcallName(RTLIB::SINTTOFP_I64_F128, "__floatdikf"); 153 setLibcallName(RTLIB::UINTTOFP_I32_F128, "__floatunsikf"); 154 setLibcallName(RTLIB::UINTTOFP_I64_F128, "__floatundikf"); 155 setLibcallName(RTLIB::OEQ_F128, "__eqkf2"); 156 setLibcallName(RTLIB::UNE_F128, "__nekf2"); 157 setLibcallName(RTLIB::OGE_F128, "__gekf2"); 158 setLibcallName(RTLIB::OLT_F128, "__ltkf2"); 159 setLibcallName(RTLIB::OLE_F128, "__lekf2"); 160 setLibcallName(RTLIB::OGT_F128, "__gtkf2"); 161 setLibcallName(RTLIB::UO_F128, "__unordkf2"); 162 } 163 164 // A few names are different on particular architectures or environments. 165 if (TT.isOSDarwin()) { 166 // For f16/f32 conversions, Darwin uses the standard naming scheme, instead 167 // of the gnueabi-style __gnu_*_ieee. 168 // FIXME: What about other targets? 169 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 170 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 171 172 // Some darwins have an optimized __bzero/bzero function. 173 switch (TT.getArch()) { 174 case Triple::x86: 175 case Triple::x86_64: 176 if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6)) 177 setLibcallName(RTLIB::BZERO, "__bzero"); 178 break; 179 case Triple::aarch64: 180 case Triple::aarch64_32: 181 setLibcallName(RTLIB::BZERO, "bzero"); 182 break; 183 default: 184 break; 185 } 186 187 if (darwinHasSinCos(TT)) { 188 setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret"); 189 setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret"); 190 if (TT.isWatchABI()) { 191 setLibcallCallingConv(RTLIB::SINCOS_STRET_F32, 192 CallingConv::ARM_AAPCS_VFP); 193 setLibcallCallingConv(RTLIB::SINCOS_STRET_F64, 194 CallingConv::ARM_AAPCS_VFP); 195 } 196 } 197 } else { 198 setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee"); 199 setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee"); 200 } 201 202 if (TT.isGNUEnvironment() || TT.isOSFuchsia() || 203 (TT.isAndroid() && !TT.isAndroidVersionLT(9))) { 204 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 205 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 206 setLibcallName(RTLIB::SINCOS_F80, "sincosl"); 207 setLibcallName(RTLIB::SINCOS_F128, "sincosl"); 208 setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl"); 209 } 210 211 if (TT.isPS4CPU()) { 212 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 213 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 214 } 215 216 if (TT.isOSOpenBSD()) { 217 setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr); 218 } 219 } 220 221 /// getFPEXT - Return the FPEXT_*_* value for the given types, or 222 /// UNKNOWN_LIBCALL if there is none. 223 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) { 224 if (OpVT == MVT::f16) { 225 if (RetVT == MVT::f32) 226 return FPEXT_F16_F32; 227 if (RetVT == MVT::f128) 228 return FPEXT_F16_F128; 229 } else if (OpVT == MVT::f32) { 230 if (RetVT == MVT::f64) 231 return FPEXT_F32_F64; 232 if (RetVT == MVT::f128) 233 return FPEXT_F32_F128; 234 if (RetVT == MVT::ppcf128) 235 return FPEXT_F32_PPCF128; 236 } else if (OpVT == MVT::f64) { 237 if (RetVT == MVT::f128) 238 return FPEXT_F64_F128; 239 else if (RetVT == MVT::ppcf128) 240 return FPEXT_F64_PPCF128; 241 } else if (OpVT == MVT::f80) { 242 if (RetVT == MVT::f128) 243 return FPEXT_F80_F128; 244 } 245 246 return UNKNOWN_LIBCALL; 247 } 248 249 /// getFPROUND - Return the FPROUND_*_* value for the given types, or 250 /// UNKNOWN_LIBCALL if there is none. 251 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) { 252 if (RetVT == MVT::f16) { 253 if (OpVT == MVT::f32) 254 return FPROUND_F32_F16; 255 if (OpVT == MVT::f64) 256 return FPROUND_F64_F16; 257 if (OpVT == MVT::f80) 258 return FPROUND_F80_F16; 259 if (OpVT == MVT::f128) 260 return FPROUND_F128_F16; 261 if (OpVT == MVT::ppcf128) 262 return FPROUND_PPCF128_F16; 263 } else if (RetVT == MVT::f32) { 264 if (OpVT == MVT::f64) 265 return FPROUND_F64_F32; 266 if (OpVT == MVT::f80) 267 return FPROUND_F80_F32; 268 if (OpVT == MVT::f128) 269 return FPROUND_F128_F32; 270 if (OpVT == MVT::ppcf128) 271 return FPROUND_PPCF128_F32; 272 } else if (RetVT == MVT::f64) { 273 if (OpVT == MVT::f80) 274 return FPROUND_F80_F64; 275 if (OpVT == MVT::f128) 276 return FPROUND_F128_F64; 277 if (OpVT == MVT::ppcf128) 278 return FPROUND_PPCF128_F64; 279 } else if (RetVT == MVT::f80) { 280 if (OpVT == MVT::f128) 281 return FPROUND_F128_F80; 282 } 283 284 return UNKNOWN_LIBCALL; 285 } 286 287 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or 288 /// UNKNOWN_LIBCALL if there is none. 289 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) { 290 if (OpVT == MVT::f32) { 291 if (RetVT == MVT::i32) 292 return FPTOSINT_F32_I32; 293 if (RetVT == MVT::i64) 294 return FPTOSINT_F32_I64; 295 if (RetVT == MVT::i128) 296 return FPTOSINT_F32_I128; 297 } else if (OpVT == MVT::f64) { 298 if (RetVT == MVT::i32) 299 return FPTOSINT_F64_I32; 300 if (RetVT == MVT::i64) 301 return FPTOSINT_F64_I64; 302 if (RetVT == MVT::i128) 303 return FPTOSINT_F64_I128; 304 } else if (OpVT == MVT::f80) { 305 if (RetVT == MVT::i32) 306 return FPTOSINT_F80_I32; 307 if (RetVT == MVT::i64) 308 return FPTOSINT_F80_I64; 309 if (RetVT == MVT::i128) 310 return FPTOSINT_F80_I128; 311 } else if (OpVT == MVT::f128) { 312 if (RetVT == MVT::i32) 313 return FPTOSINT_F128_I32; 314 if (RetVT == MVT::i64) 315 return FPTOSINT_F128_I64; 316 if (RetVT == MVT::i128) 317 return FPTOSINT_F128_I128; 318 } else if (OpVT == MVT::ppcf128) { 319 if (RetVT == MVT::i32) 320 return FPTOSINT_PPCF128_I32; 321 if (RetVT == MVT::i64) 322 return FPTOSINT_PPCF128_I64; 323 if (RetVT == MVT::i128) 324 return FPTOSINT_PPCF128_I128; 325 } 326 return UNKNOWN_LIBCALL; 327 } 328 329 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or 330 /// UNKNOWN_LIBCALL if there is none. 331 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) { 332 if (OpVT == MVT::f32) { 333 if (RetVT == MVT::i32) 334 return FPTOUINT_F32_I32; 335 if (RetVT == MVT::i64) 336 return FPTOUINT_F32_I64; 337 if (RetVT == MVT::i128) 338 return FPTOUINT_F32_I128; 339 } else if (OpVT == MVT::f64) { 340 if (RetVT == MVT::i32) 341 return FPTOUINT_F64_I32; 342 if (RetVT == MVT::i64) 343 return FPTOUINT_F64_I64; 344 if (RetVT == MVT::i128) 345 return FPTOUINT_F64_I128; 346 } else if (OpVT == MVT::f80) { 347 if (RetVT == MVT::i32) 348 return FPTOUINT_F80_I32; 349 if (RetVT == MVT::i64) 350 return FPTOUINT_F80_I64; 351 if (RetVT == MVT::i128) 352 return FPTOUINT_F80_I128; 353 } else if (OpVT == MVT::f128) { 354 if (RetVT == MVT::i32) 355 return FPTOUINT_F128_I32; 356 if (RetVT == MVT::i64) 357 return FPTOUINT_F128_I64; 358 if (RetVT == MVT::i128) 359 return FPTOUINT_F128_I128; 360 } else if (OpVT == MVT::ppcf128) { 361 if (RetVT == MVT::i32) 362 return FPTOUINT_PPCF128_I32; 363 if (RetVT == MVT::i64) 364 return FPTOUINT_PPCF128_I64; 365 if (RetVT == MVT::i128) 366 return FPTOUINT_PPCF128_I128; 367 } 368 return UNKNOWN_LIBCALL; 369 } 370 371 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or 372 /// UNKNOWN_LIBCALL if there is none. 373 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) { 374 if (OpVT == MVT::i32) { 375 if (RetVT == MVT::f32) 376 return SINTTOFP_I32_F32; 377 if (RetVT == MVT::f64) 378 return SINTTOFP_I32_F64; 379 if (RetVT == MVT::f80) 380 return SINTTOFP_I32_F80; 381 if (RetVT == MVT::f128) 382 return SINTTOFP_I32_F128; 383 if (RetVT == MVT::ppcf128) 384 return SINTTOFP_I32_PPCF128; 385 } else if (OpVT == MVT::i64) { 386 if (RetVT == MVT::f32) 387 return SINTTOFP_I64_F32; 388 if (RetVT == MVT::f64) 389 return SINTTOFP_I64_F64; 390 if (RetVT == MVT::f80) 391 return SINTTOFP_I64_F80; 392 if (RetVT == MVT::f128) 393 return SINTTOFP_I64_F128; 394 if (RetVT == MVT::ppcf128) 395 return SINTTOFP_I64_PPCF128; 396 } else if (OpVT == MVT::i128) { 397 if (RetVT == MVT::f32) 398 return SINTTOFP_I128_F32; 399 if (RetVT == MVT::f64) 400 return SINTTOFP_I128_F64; 401 if (RetVT == MVT::f80) 402 return SINTTOFP_I128_F80; 403 if (RetVT == MVT::f128) 404 return SINTTOFP_I128_F128; 405 if (RetVT == MVT::ppcf128) 406 return SINTTOFP_I128_PPCF128; 407 } 408 return UNKNOWN_LIBCALL; 409 } 410 411 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or 412 /// UNKNOWN_LIBCALL if there is none. 413 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) { 414 if (OpVT == MVT::i32) { 415 if (RetVT == MVT::f32) 416 return UINTTOFP_I32_F32; 417 if (RetVT == MVT::f64) 418 return UINTTOFP_I32_F64; 419 if (RetVT == MVT::f80) 420 return UINTTOFP_I32_F80; 421 if (RetVT == MVT::f128) 422 return UINTTOFP_I32_F128; 423 if (RetVT == MVT::ppcf128) 424 return UINTTOFP_I32_PPCF128; 425 } else if (OpVT == MVT::i64) { 426 if (RetVT == MVT::f32) 427 return UINTTOFP_I64_F32; 428 if (RetVT == MVT::f64) 429 return UINTTOFP_I64_F64; 430 if (RetVT == MVT::f80) 431 return UINTTOFP_I64_F80; 432 if (RetVT == MVT::f128) 433 return UINTTOFP_I64_F128; 434 if (RetVT == MVT::ppcf128) 435 return UINTTOFP_I64_PPCF128; 436 } else if (OpVT == MVT::i128) { 437 if (RetVT == MVT::f32) 438 return UINTTOFP_I128_F32; 439 if (RetVT == MVT::f64) 440 return UINTTOFP_I128_F64; 441 if (RetVT == MVT::f80) 442 return UINTTOFP_I128_F80; 443 if (RetVT == MVT::f128) 444 return UINTTOFP_I128_F128; 445 if (RetVT == MVT::ppcf128) 446 return UINTTOFP_I128_PPCF128; 447 } 448 return UNKNOWN_LIBCALL; 449 } 450 451 RTLIB::Libcall RTLIB::getOUTLINE_ATOMIC(unsigned Opc, AtomicOrdering Order, 452 MVT VT) { 453 unsigned ModeN, ModelN; 454 switch (VT.SimpleTy) { 455 case MVT::i8: 456 ModeN = 0; 457 break; 458 case MVT::i16: 459 ModeN = 1; 460 break; 461 case MVT::i32: 462 ModeN = 2; 463 break; 464 case MVT::i64: 465 ModeN = 3; 466 break; 467 case MVT::i128: 468 ModeN = 4; 469 break; 470 default: 471 return UNKNOWN_LIBCALL; 472 } 473 474 switch (Order) { 475 case AtomicOrdering::Monotonic: 476 ModelN = 0; 477 break; 478 case AtomicOrdering::Acquire: 479 ModelN = 1; 480 break; 481 case AtomicOrdering::Release: 482 ModelN = 2; 483 break; 484 case AtomicOrdering::AcquireRelease: 485 case AtomicOrdering::SequentiallyConsistent: 486 ModelN = 3; 487 break; 488 default: 489 return UNKNOWN_LIBCALL; 490 } 491 492 #define LCALLS(A, B) \ 493 { A##B##_RELAX, A##B##_ACQ, A##B##_REL, A##B##_ACQ_REL } 494 #define LCALL5(A) \ 495 LCALLS(A, 1), LCALLS(A, 2), LCALLS(A, 4), LCALLS(A, 8), LCALLS(A, 16) 496 switch (Opc) { 497 case ISD::ATOMIC_CMP_SWAP: { 498 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_CAS)}; 499 return LC[ModeN][ModelN]; 500 } 501 case ISD::ATOMIC_SWAP: { 502 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_SWP)}; 503 return LC[ModeN][ModelN]; 504 } 505 case ISD::ATOMIC_LOAD_ADD: { 506 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDADD)}; 507 return LC[ModeN][ModelN]; 508 } 509 case ISD::ATOMIC_LOAD_OR: { 510 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDSET)}; 511 return LC[ModeN][ModelN]; 512 } 513 case ISD::ATOMIC_LOAD_CLR: { 514 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDCLR)}; 515 return LC[ModeN][ModelN]; 516 } 517 case ISD::ATOMIC_LOAD_XOR: { 518 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDEOR)}; 519 return LC[ModeN][ModelN]; 520 } 521 default: 522 return UNKNOWN_LIBCALL; 523 } 524 #undef LCALLS 525 #undef LCALL5 526 } 527 528 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) { 529 #define OP_TO_LIBCALL(Name, Enum) \ 530 case Name: \ 531 switch (VT.SimpleTy) { \ 532 default: \ 533 return UNKNOWN_LIBCALL; \ 534 case MVT::i8: \ 535 return Enum##_1; \ 536 case MVT::i16: \ 537 return Enum##_2; \ 538 case MVT::i32: \ 539 return Enum##_4; \ 540 case MVT::i64: \ 541 return Enum##_8; \ 542 case MVT::i128: \ 543 return Enum##_16; \ 544 } 545 546 switch (Opc) { 547 OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET) 548 OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP) 549 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD) 550 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB) 551 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND) 552 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR) 553 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR) 554 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND) 555 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX) 556 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX) 557 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN) 558 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN) 559 } 560 561 #undef OP_TO_LIBCALL 562 563 return UNKNOWN_LIBCALL; 564 } 565 566 RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 567 switch (ElementSize) { 568 case 1: 569 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1; 570 case 2: 571 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2; 572 case 4: 573 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4; 574 case 8: 575 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8; 576 case 16: 577 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16; 578 default: 579 return UNKNOWN_LIBCALL; 580 } 581 } 582 583 RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 584 switch (ElementSize) { 585 case 1: 586 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1; 587 case 2: 588 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2; 589 case 4: 590 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4; 591 case 8: 592 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8; 593 case 16: 594 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16; 595 default: 596 return UNKNOWN_LIBCALL; 597 } 598 } 599 600 RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 601 switch (ElementSize) { 602 case 1: 603 return MEMSET_ELEMENT_UNORDERED_ATOMIC_1; 604 case 2: 605 return MEMSET_ELEMENT_UNORDERED_ATOMIC_2; 606 case 4: 607 return MEMSET_ELEMENT_UNORDERED_ATOMIC_4; 608 case 8: 609 return MEMSET_ELEMENT_UNORDERED_ATOMIC_8; 610 case 16: 611 return MEMSET_ELEMENT_UNORDERED_ATOMIC_16; 612 default: 613 return UNKNOWN_LIBCALL; 614 } 615 } 616 617 /// InitCmpLibcallCCs - Set default comparison libcall CC. 618 static void InitCmpLibcallCCs(ISD::CondCode *CCs) { 619 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL); 620 CCs[RTLIB::OEQ_F32] = ISD::SETEQ; 621 CCs[RTLIB::OEQ_F64] = ISD::SETEQ; 622 CCs[RTLIB::OEQ_F128] = ISD::SETEQ; 623 CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ; 624 CCs[RTLIB::UNE_F32] = ISD::SETNE; 625 CCs[RTLIB::UNE_F64] = ISD::SETNE; 626 CCs[RTLIB::UNE_F128] = ISD::SETNE; 627 CCs[RTLIB::UNE_PPCF128] = ISD::SETNE; 628 CCs[RTLIB::OGE_F32] = ISD::SETGE; 629 CCs[RTLIB::OGE_F64] = ISD::SETGE; 630 CCs[RTLIB::OGE_F128] = ISD::SETGE; 631 CCs[RTLIB::OGE_PPCF128] = ISD::SETGE; 632 CCs[RTLIB::OLT_F32] = ISD::SETLT; 633 CCs[RTLIB::OLT_F64] = ISD::SETLT; 634 CCs[RTLIB::OLT_F128] = ISD::SETLT; 635 CCs[RTLIB::OLT_PPCF128] = ISD::SETLT; 636 CCs[RTLIB::OLE_F32] = ISD::SETLE; 637 CCs[RTLIB::OLE_F64] = ISD::SETLE; 638 CCs[RTLIB::OLE_F128] = ISD::SETLE; 639 CCs[RTLIB::OLE_PPCF128] = ISD::SETLE; 640 CCs[RTLIB::OGT_F32] = ISD::SETGT; 641 CCs[RTLIB::OGT_F64] = ISD::SETGT; 642 CCs[RTLIB::OGT_F128] = ISD::SETGT; 643 CCs[RTLIB::OGT_PPCF128] = ISD::SETGT; 644 CCs[RTLIB::UO_F32] = ISD::SETNE; 645 CCs[RTLIB::UO_F64] = ISD::SETNE; 646 CCs[RTLIB::UO_F128] = ISD::SETNE; 647 CCs[RTLIB::UO_PPCF128] = ISD::SETNE; 648 } 649 650 /// NOTE: The TargetMachine owns TLOF. 651 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) { 652 initActions(); 653 654 // Perform these initializations only once. 655 MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove = 656 MaxLoadsPerMemcmp = 8; 657 MaxGluedStoresPerMemcpy = 0; 658 MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize = 659 MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4; 660 HasMultipleConditionRegisters = false; 661 HasExtractBitsInsn = false; 662 JumpIsExpensive = JumpIsExpensiveOverride; 663 PredictableSelectIsExpensive = false; 664 EnableExtLdPromotion = false; 665 StackPointerRegisterToSaveRestore = 0; 666 BooleanContents = UndefinedBooleanContent; 667 BooleanFloatContents = UndefinedBooleanContent; 668 BooleanVectorContents = UndefinedBooleanContent; 669 SchedPreferenceInfo = Sched::ILP; 670 GatherAllAliasesMaxDepth = 18; 671 IsStrictFPEnabled = DisableStrictNodeMutation; 672 // TODO: the default will be switched to 0 in the next commit, along 673 // with the Target-specific changes necessary. 674 MaxAtomicSizeInBitsSupported = 1024; 675 676 MinCmpXchgSizeInBits = 0; 677 SupportsUnalignedAtomics = false; 678 679 std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr); 680 681 InitLibcalls(TM.getTargetTriple()); 682 InitCmpLibcallCCs(CmpLibcallCCs); 683 } 684 685 void TargetLoweringBase::initActions() { 686 // All operations default to being supported. 687 memset(OpActions, 0, sizeof(OpActions)); 688 memset(LoadExtActions, 0, sizeof(LoadExtActions)); 689 memset(TruncStoreActions, 0, sizeof(TruncStoreActions)); 690 memset(IndexedModeActions, 0, sizeof(IndexedModeActions)); 691 memset(CondCodeActions, 0, sizeof(CondCodeActions)); 692 std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr); 693 std::fill(std::begin(TargetDAGCombineArray), 694 std::end(TargetDAGCombineArray), 0); 695 696 for (MVT VT : MVT::fp_valuetypes()) { 697 MVT IntVT = MVT::getIntegerVT(VT.getFixedSizeInBits()); 698 if (IntVT.isValid()) { 699 setOperationAction(ISD::ATOMIC_SWAP, VT, Promote); 700 AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT); 701 } 702 } 703 704 // Set default actions for various operations. 705 for (MVT VT : MVT::all_valuetypes()) { 706 // Default all indexed load / store to expand. 707 for (unsigned IM = (unsigned)ISD::PRE_INC; 708 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) { 709 setIndexedLoadAction(IM, VT, Expand); 710 setIndexedStoreAction(IM, VT, Expand); 711 setIndexedMaskedLoadAction(IM, VT, Expand); 712 setIndexedMaskedStoreAction(IM, VT, Expand); 713 } 714 715 // Most backends expect to see the node which just returns the value loaded. 716 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand); 717 718 // These operations default to expand. 719 setOperationAction(ISD::FGETSIGN, VT, Expand); 720 setOperationAction(ISD::CONCAT_VECTORS, VT, Expand); 721 setOperationAction(ISD::FMINNUM, VT, Expand); 722 setOperationAction(ISD::FMAXNUM, VT, Expand); 723 setOperationAction(ISD::FMINNUM_IEEE, VT, Expand); 724 setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand); 725 setOperationAction(ISD::FMINIMUM, VT, Expand); 726 setOperationAction(ISD::FMAXIMUM, VT, Expand); 727 setOperationAction(ISD::FMAD, VT, Expand); 728 setOperationAction(ISD::SMIN, VT, Expand); 729 setOperationAction(ISD::SMAX, VT, Expand); 730 setOperationAction(ISD::UMIN, VT, Expand); 731 setOperationAction(ISD::UMAX, VT, Expand); 732 setOperationAction(ISD::ABS, VT, Expand); 733 setOperationAction(ISD::FSHL, VT, Expand); 734 setOperationAction(ISD::FSHR, VT, Expand); 735 setOperationAction(ISD::SADDSAT, VT, Expand); 736 setOperationAction(ISD::UADDSAT, VT, Expand); 737 setOperationAction(ISD::SSUBSAT, VT, Expand); 738 setOperationAction(ISD::USUBSAT, VT, Expand); 739 setOperationAction(ISD::SSHLSAT, VT, Expand); 740 setOperationAction(ISD::USHLSAT, VT, Expand); 741 setOperationAction(ISD::SMULFIX, VT, Expand); 742 setOperationAction(ISD::SMULFIXSAT, VT, Expand); 743 setOperationAction(ISD::UMULFIX, VT, Expand); 744 setOperationAction(ISD::UMULFIXSAT, VT, Expand); 745 setOperationAction(ISD::SDIVFIX, VT, Expand); 746 setOperationAction(ISD::SDIVFIXSAT, VT, Expand); 747 setOperationAction(ISD::UDIVFIX, VT, Expand); 748 setOperationAction(ISD::UDIVFIXSAT, VT, Expand); 749 750 // Overflow operations default to expand 751 setOperationAction(ISD::SADDO, VT, Expand); 752 setOperationAction(ISD::SSUBO, VT, Expand); 753 setOperationAction(ISD::UADDO, VT, Expand); 754 setOperationAction(ISD::USUBO, VT, Expand); 755 setOperationAction(ISD::SMULO, VT, Expand); 756 setOperationAction(ISD::UMULO, VT, Expand); 757 758 // ADDCARRY operations default to expand 759 setOperationAction(ISD::ADDCARRY, VT, Expand); 760 setOperationAction(ISD::SUBCARRY, VT, Expand); 761 setOperationAction(ISD::SETCCCARRY, VT, Expand); 762 setOperationAction(ISD::SADDO_CARRY, VT, Expand); 763 setOperationAction(ISD::SSUBO_CARRY, VT, Expand); 764 765 // ADDC/ADDE/SUBC/SUBE default to expand. 766 setOperationAction(ISD::ADDC, VT, Expand); 767 setOperationAction(ISD::ADDE, VT, Expand); 768 setOperationAction(ISD::SUBC, VT, Expand); 769 setOperationAction(ISD::SUBE, VT, Expand); 770 771 // These default to Expand so they will be expanded to CTLZ/CTTZ by default. 772 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 773 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 774 775 setOperationAction(ISD::BITREVERSE, VT, Expand); 776 setOperationAction(ISD::PARITY, VT, Expand); 777 778 // These library functions default to expand. 779 setOperationAction(ISD::FROUND, VT, Expand); 780 setOperationAction(ISD::FROUNDEVEN, VT, Expand); 781 setOperationAction(ISD::FPOWI, VT, Expand); 782 783 // These operations default to expand for vector types. 784 if (VT.isVector()) { 785 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 786 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 787 setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand); 788 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand); 789 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand); 790 setOperationAction(ISD::SPLAT_VECTOR, VT, Expand); 791 } 792 793 // Constrained floating-point operations default to expand. 794 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 795 setOperationAction(ISD::STRICT_##DAGN, VT, Expand); 796 #include "llvm/IR/ConstrainedOps.def" 797 798 // For most targets @llvm.get.dynamic.area.offset just returns 0. 799 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand); 800 801 // Vector reduction default to expand. 802 setOperationAction(ISD::VECREDUCE_FADD, VT, Expand); 803 setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand); 804 setOperationAction(ISD::VECREDUCE_ADD, VT, Expand); 805 setOperationAction(ISD::VECREDUCE_MUL, VT, Expand); 806 setOperationAction(ISD::VECREDUCE_AND, VT, Expand); 807 setOperationAction(ISD::VECREDUCE_OR, VT, Expand); 808 setOperationAction(ISD::VECREDUCE_XOR, VT, Expand); 809 setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand); 810 setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand); 811 setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand); 812 setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand); 813 setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand); 814 setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand); 815 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Expand); 816 setOperationAction(ISD::VECREDUCE_SEQ_FMUL, VT, Expand); 817 } 818 819 // Most targets ignore the @llvm.prefetch intrinsic. 820 setOperationAction(ISD::PREFETCH, MVT::Other, Expand); 821 822 // Most targets also ignore the @llvm.readcyclecounter intrinsic. 823 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand); 824 825 // ConstantFP nodes default to expand. Targets can either change this to 826 // Legal, in which case all fp constants are legal, or use isFPImmLegal() 827 // to optimize expansions for certain constants. 828 setOperationAction(ISD::ConstantFP, MVT::f16, Expand); 829 setOperationAction(ISD::ConstantFP, MVT::f32, Expand); 830 setOperationAction(ISD::ConstantFP, MVT::f64, Expand); 831 setOperationAction(ISD::ConstantFP, MVT::f80, Expand); 832 setOperationAction(ISD::ConstantFP, MVT::f128, Expand); 833 834 // These library functions default to expand. 835 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) { 836 setOperationAction(ISD::FCBRT, VT, Expand); 837 setOperationAction(ISD::FLOG , VT, Expand); 838 setOperationAction(ISD::FLOG2, VT, Expand); 839 setOperationAction(ISD::FLOG10, VT, Expand); 840 setOperationAction(ISD::FEXP , VT, Expand); 841 setOperationAction(ISD::FEXP2, VT, Expand); 842 setOperationAction(ISD::FFLOOR, VT, Expand); 843 setOperationAction(ISD::FNEARBYINT, VT, Expand); 844 setOperationAction(ISD::FCEIL, VT, Expand); 845 setOperationAction(ISD::FRINT, VT, Expand); 846 setOperationAction(ISD::FTRUNC, VT, Expand); 847 setOperationAction(ISD::FROUND, VT, Expand); 848 setOperationAction(ISD::FROUNDEVEN, VT, Expand); 849 setOperationAction(ISD::LROUND, VT, Expand); 850 setOperationAction(ISD::LLROUND, VT, Expand); 851 setOperationAction(ISD::LRINT, VT, Expand); 852 setOperationAction(ISD::LLRINT, VT, Expand); 853 } 854 855 // Default ISD::TRAP to expand (which turns it into abort). 856 setOperationAction(ISD::TRAP, MVT::Other, Expand); 857 858 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand" 859 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP. 860 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand); 861 } 862 863 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL, 864 EVT) const { 865 return MVT::getIntegerVT(DL.getPointerSizeInBits(0)); 866 } 867 868 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL, 869 bool LegalTypes) const { 870 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 871 if (LHSTy.isVector()) 872 return LHSTy; 873 return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy) 874 : getPointerTy(DL); 875 } 876 877 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const { 878 assert(isTypeLegal(VT)); 879 switch (Op) { 880 default: 881 return false; 882 case ISD::SDIV: 883 case ISD::UDIV: 884 case ISD::SREM: 885 case ISD::UREM: 886 return true; 887 } 888 } 889 890 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS, 891 unsigned DestAS) const { 892 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 893 } 894 895 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) { 896 // If the command-line option was specified, ignore this request. 897 if (!JumpIsExpensiveOverride.getNumOccurrences()) 898 JumpIsExpensive = isExpensive; 899 } 900 901 TargetLoweringBase::LegalizeKind 902 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const { 903 // If this is a simple type, use the ComputeRegisterProp mechanism. 904 if (VT.isSimple()) { 905 MVT SVT = VT.getSimpleVT(); 906 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType)); 907 MVT NVT = TransformToType[SVT.SimpleTy]; 908 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT); 909 910 assert((LA == TypeLegal || LA == TypeSoftenFloat || 911 LA == TypeSoftPromoteHalf || 912 (NVT.isVector() || 913 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) && 914 "Promote may not follow Expand or Promote"); 915 916 if (LA == TypeSplitVector) 917 return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context)); 918 if (LA == TypeScalarizeVector) 919 return LegalizeKind(LA, SVT.getVectorElementType()); 920 return LegalizeKind(LA, NVT); 921 } 922 923 // Handle Extended Scalar Types. 924 if (!VT.isVector()) { 925 assert(VT.isInteger() && "Float types must be simple"); 926 unsigned BitSize = VT.getSizeInBits(); 927 // First promote to a power-of-two size, then expand if necessary. 928 if (BitSize < 8 || !isPowerOf2_32(BitSize)) { 929 EVT NVT = VT.getRoundIntegerType(Context); 930 assert(NVT != VT && "Unable to round integer VT"); 931 LegalizeKind NextStep = getTypeConversion(Context, NVT); 932 // Avoid multi-step promotion. 933 if (NextStep.first == TypePromoteInteger) 934 return NextStep; 935 // Return rounded integer type. 936 return LegalizeKind(TypePromoteInteger, NVT); 937 } 938 939 return LegalizeKind(TypeExpandInteger, 940 EVT::getIntegerVT(Context, VT.getSizeInBits() / 2)); 941 } 942 943 // Handle vector types. 944 ElementCount NumElts = VT.getVectorElementCount(); 945 EVT EltVT = VT.getVectorElementType(); 946 947 // Vectors with only one element are always scalarized. 948 if (NumElts.isScalar()) 949 return LegalizeKind(TypeScalarizeVector, EltVT); 950 951 if (VT.getVectorElementCount() == ElementCount::getScalable(1)) 952 report_fatal_error("Cannot legalize this vector"); 953 954 // Try to widen vector elements until the element type is a power of two and 955 // promote it to a legal type later on, for example: 956 // <3 x i8> -> <4 x i8> -> <4 x i32> 957 if (EltVT.isInteger()) { 958 // Vectors with a number of elements that is not a power of two are always 959 // widened, for example <3 x i8> -> <4 x i8>. 960 if (!VT.isPow2VectorType()) { 961 NumElts = NumElts.coefficientNextPowerOf2(); 962 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts); 963 return LegalizeKind(TypeWidenVector, NVT); 964 } 965 966 // Examine the element type. 967 LegalizeKind LK = getTypeConversion(Context, EltVT); 968 969 // If type is to be expanded, split the vector. 970 // <4 x i140> -> <2 x i140> 971 if (LK.first == TypeExpandInteger) 972 return LegalizeKind(TypeSplitVector, 973 VT.getHalfNumVectorElementsVT(Context)); 974 975 // Promote the integer element types until a legal vector type is found 976 // or until the element integer type is too big. If a legal type was not 977 // found, fallback to the usual mechanism of widening/splitting the 978 // vector. 979 EVT OldEltVT = EltVT; 980 while (true) { 981 // Increase the bitwidth of the element to the next pow-of-two 982 // (which is greater than 8 bits). 983 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()) 984 .getRoundIntegerType(Context); 985 986 // Stop trying when getting a non-simple element type. 987 // Note that vector elements may be greater than legal vector element 988 // types. Example: X86 XMM registers hold 64bit element on 32bit 989 // systems. 990 if (!EltVT.isSimple()) 991 break; 992 993 // Build a new vector type and check if it is legal. 994 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 995 // Found a legal promoted vector type. 996 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal) 997 return LegalizeKind(TypePromoteInteger, 998 EVT::getVectorVT(Context, EltVT, NumElts)); 999 } 1000 1001 // Reset the type to the unexpanded type if we did not find a legal vector 1002 // type with a promoted vector element type. 1003 EltVT = OldEltVT; 1004 } 1005 1006 // Try to widen the vector until a legal type is found. 1007 // If there is no wider legal type, split the vector. 1008 while (true) { 1009 // Round up to the next power of 2. 1010 NumElts = NumElts.coefficientNextPowerOf2(); 1011 1012 // If there is no simple vector type with this many elements then there 1013 // cannot be a larger legal vector type. Note that this assumes that 1014 // there are no skipped intermediate vector types in the simple types. 1015 if (!EltVT.isSimple()) 1016 break; 1017 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1018 if (LargerVector == MVT()) 1019 break; 1020 1021 // If this type is legal then widen the vector. 1022 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal) 1023 return LegalizeKind(TypeWidenVector, LargerVector); 1024 } 1025 1026 // Widen odd vectors to next power of two. 1027 if (!VT.isPow2VectorType()) { 1028 EVT NVT = VT.getPow2VectorType(Context); 1029 return LegalizeKind(TypeWidenVector, NVT); 1030 } 1031 1032 // Vectors with illegal element types are expanded. 1033 EVT NVT = EVT::getVectorVT(Context, EltVT, 1034 VT.getVectorElementCount().divideCoefficientBy(2)); 1035 return LegalizeKind(TypeSplitVector, NVT); 1036 } 1037 1038 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT, 1039 unsigned &NumIntermediates, 1040 MVT &RegisterVT, 1041 TargetLoweringBase *TLI) { 1042 // Figure out the right, legal destination reg to copy into. 1043 ElementCount EC = VT.getVectorElementCount(); 1044 MVT EltTy = VT.getVectorElementType(); 1045 1046 unsigned NumVectorRegs = 1; 1047 1048 // Scalable vectors cannot be scalarized, so splitting or widening is 1049 // required. 1050 if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue())) 1051 llvm_unreachable( 1052 "Splitting or widening of non-power-of-2 MVTs is not implemented."); 1053 1054 // FIXME: We don't support non-power-of-2-sized vectors for now. 1055 // Ideally we could break down into LHS/RHS like LegalizeDAG does. 1056 if (!isPowerOf2_32(EC.getKnownMinValue())) { 1057 // Split EC to unit size (scalable property is preserved). 1058 NumVectorRegs = EC.getKnownMinValue(); 1059 EC = ElementCount::getFixed(1); 1060 } 1061 1062 // Divide the input until we get to a supported size. This will 1063 // always end up with an EC that represent a scalar or a scalable 1064 // scalar. 1065 while (EC.getKnownMinValue() > 1 && 1066 !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) { 1067 EC = EC.divideCoefficientBy(2); 1068 NumVectorRegs <<= 1; 1069 } 1070 1071 NumIntermediates = NumVectorRegs; 1072 1073 MVT NewVT = MVT::getVectorVT(EltTy, EC); 1074 if (!TLI->isTypeLegal(NewVT)) 1075 NewVT = EltTy; 1076 IntermediateVT = NewVT; 1077 1078 unsigned LaneSizeInBits = NewVT.getScalarSizeInBits(); 1079 1080 // Convert sizes such as i33 to i64. 1081 if (!isPowerOf2_32(LaneSizeInBits)) 1082 LaneSizeInBits = NextPowerOf2(LaneSizeInBits); 1083 1084 MVT DestVT = TLI->getRegisterType(NewVT); 1085 RegisterVT = DestVT; 1086 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16. 1087 return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits()); 1088 1089 // Otherwise, promotion or legal types use the same number of registers as 1090 // the vector decimated to the appropriate level. 1091 return NumVectorRegs; 1092 } 1093 1094 /// isLegalRC - Return true if the value types that can be represented by the 1095 /// specified register class are all legal. 1096 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI, 1097 const TargetRegisterClass &RC) const { 1098 for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I) 1099 if (isTypeLegal(*I)) 1100 return true; 1101 return false; 1102 } 1103 1104 /// Replace/modify any TargetFrameIndex operands with a targte-dependent 1105 /// sequence of memory operands that is recognized by PrologEpilogInserter. 1106 MachineBasicBlock * 1107 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI, 1108 MachineBasicBlock *MBB) const { 1109 MachineInstr *MI = &InitialMI; 1110 MachineFunction &MF = *MI->getMF(); 1111 MachineFrameInfo &MFI = MF.getFrameInfo(); 1112 1113 // We're handling multiple types of operands here: 1114 // PATCHPOINT MetaArgs - live-in, read only, direct 1115 // STATEPOINT Deopt Spill - live-through, read only, indirect 1116 // STATEPOINT Deopt Alloca - live-through, read only, direct 1117 // (We're currently conservative and mark the deopt slots read/write in 1118 // practice.) 1119 // STATEPOINT GC Spill - live-through, read/write, indirect 1120 // STATEPOINT GC Alloca - live-through, read/write, direct 1121 // The live-in vs live-through is handled already (the live through ones are 1122 // all stack slots), but we need to handle the different type of stackmap 1123 // operands and memory effects here. 1124 1125 if (!llvm::any_of(MI->operands(), 1126 [](MachineOperand &Operand) { return Operand.isFI(); })) 1127 return MBB; 1128 1129 MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc()); 1130 1131 // Inherit previous memory operands. 1132 MIB.cloneMemRefs(*MI); 1133 1134 for (unsigned i = 0; i < MI->getNumOperands(); ++i) { 1135 MachineOperand &MO = MI->getOperand(i); 1136 if (!MO.isFI()) { 1137 // Index of Def operand this Use it tied to. 1138 // Since Defs are coming before Uses, if Use is tied, then 1139 // index of Def must be smaller that index of that Use. 1140 // Also, Defs preserve their position in new MI. 1141 unsigned TiedTo = i; 1142 if (MO.isReg() && MO.isTied()) 1143 TiedTo = MI->findTiedOperandIdx(i); 1144 MIB.add(MO); 1145 if (TiedTo < i) 1146 MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1); 1147 continue; 1148 } 1149 1150 // foldMemoryOperand builds a new MI after replacing a single FI operand 1151 // with the canonical set of five x86 addressing-mode operands. 1152 int FI = MO.getIndex(); 1153 1154 // Add frame index operands recognized by stackmaps.cpp 1155 if (MFI.isStatepointSpillSlotObjectIndex(FI)) { 1156 // indirect-mem-ref tag, size, #FI, offset. 1157 // Used for spills inserted by StatepointLowering. This codepath is not 1158 // used for patchpoints/stackmaps at all, for these spilling is done via 1159 // foldMemoryOperand callback only. 1160 assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity"); 1161 MIB.addImm(StackMaps::IndirectMemRefOp); 1162 MIB.addImm(MFI.getObjectSize(FI)); 1163 MIB.add(MO); 1164 MIB.addImm(0); 1165 } else { 1166 // direct-mem-ref tag, #FI, offset. 1167 // Used by patchpoint, and direct alloca arguments to statepoints 1168 MIB.addImm(StackMaps::DirectMemRefOp); 1169 MIB.add(MO); 1170 MIB.addImm(0); 1171 } 1172 1173 assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!"); 1174 1175 // Add a new memory operand for this FI. 1176 assert(MFI.getObjectOffset(FI) != -1); 1177 1178 // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and 1179 // PATCHPOINT should be updated to do the same. (TODO) 1180 if (MI->getOpcode() != TargetOpcode::STATEPOINT) { 1181 auto Flags = MachineMemOperand::MOLoad; 1182 MachineMemOperand *MMO = MF.getMachineMemOperand( 1183 MachinePointerInfo::getFixedStack(MF, FI), Flags, 1184 MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI)); 1185 MIB->addMemOperand(MF, MMO); 1186 } 1187 } 1188 MBB->insert(MachineBasicBlock::iterator(MI), MIB); 1189 MI->eraseFromParent(); 1190 return MBB; 1191 } 1192 1193 MachineBasicBlock * 1194 TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI, 1195 MachineBasicBlock *MBB) const { 1196 assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL && 1197 "Called emitXRayCustomEvent on the wrong MI!"); 1198 auto &MF = *MI.getMF(); 1199 auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc()); 1200 for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx) 1201 MIB.add(MI.getOperand(OpIdx)); 1202 1203 MBB->insert(MachineBasicBlock::iterator(MI), MIB); 1204 MI.eraseFromParent(); 1205 return MBB; 1206 } 1207 1208 MachineBasicBlock * 1209 TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI, 1210 MachineBasicBlock *MBB) const { 1211 assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL && 1212 "Called emitXRayTypedEvent on the wrong MI!"); 1213 auto &MF = *MI.getMF(); 1214 auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc()); 1215 for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx) 1216 MIB.add(MI.getOperand(OpIdx)); 1217 1218 MBB->insert(MachineBasicBlock::iterator(MI), MIB); 1219 MI.eraseFromParent(); 1220 return MBB; 1221 } 1222 1223 /// findRepresentativeClass - Return the largest legal super-reg register class 1224 /// of the register class for the specified type and its associated "cost". 1225 // This function is in TargetLowering because it uses RegClassForVT which would 1226 // need to be moved to TargetRegisterInfo and would necessitate moving 1227 // isTypeLegal over as well - a massive change that would just require 1228 // TargetLowering having a TargetRegisterInfo class member that it would use. 1229 std::pair<const TargetRegisterClass *, uint8_t> 1230 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI, 1231 MVT VT) const { 1232 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy]; 1233 if (!RC) 1234 return std::make_pair(RC, 0); 1235 1236 // Compute the set of all super-register classes. 1237 BitVector SuperRegRC(TRI->getNumRegClasses()); 1238 for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI) 1239 SuperRegRC.setBitsInMask(RCI.getMask()); 1240 1241 // Find the first legal register class with the largest spill size. 1242 const TargetRegisterClass *BestRC = RC; 1243 for (unsigned i : SuperRegRC.set_bits()) { 1244 const TargetRegisterClass *SuperRC = TRI->getRegClass(i); 1245 // We want the largest possible spill size. 1246 if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC)) 1247 continue; 1248 if (!isLegalRC(*TRI, *SuperRC)) 1249 continue; 1250 BestRC = SuperRC; 1251 } 1252 return std::make_pair(BestRC, 1); 1253 } 1254 1255 /// computeRegisterProperties - Once all of the register classes are added, 1256 /// this allows us to compute derived properties we expose. 1257 void TargetLoweringBase::computeRegisterProperties( 1258 const TargetRegisterInfo *TRI) { 1259 static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE, 1260 "Too many value types for ValueTypeActions to hold!"); 1261 1262 // Everything defaults to needing one register. 1263 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) { 1264 NumRegistersForVT[i] = 1; 1265 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i; 1266 } 1267 // ...except isVoid, which doesn't need any registers. 1268 NumRegistersForVT[MVT::isVoid] = 0; 1269 1270 // Find the largest integer register class. 1271 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE; 1272 for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg) 1273 assert(LargestIntReg != MVT::i1 && "No integer registers defined!"); 1274 1275 // Every integer value type larger than this largest register takes twice as 1276 // many registers to represent as the previous ValueType. 1277 for (unsigned ExpandedReg = LargestIntReg + 1; 1278 ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) { 1279 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1]; 1280 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg; 1281 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1); 1282 ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg, 1283 TypeExpandInteger); 1284 } 1285 1286 // Inspect all of the ValueType's smaller than the largest integer 1287 // register to see which ones need promotion. 1288 unsigned LegalIntReg = LargestIntReg; 1289 for (unsigned IntReg = LargestIntReg - 1; 1290 IntReg >= (unsigned)MVT::i1; --IntReg) { 1291 MVT IVT = (MVT::SimpleValueType)IntReg; 1292 if (isTypeLegal(IVT)) { 1293 LegalIntReg = IntReg; 1294 } else { 1295 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = 1296 (MVT::SimpleValueType)LegalIntReg; 1297 ValueTypeActions.setTypeAction(IVT, TypePromoteInteger); 1298 } 1299 } 1300 1301 // ppcf128 type is really two f64's. 1302 if (!isTypeLegal(MVT::ppcf128)) { 1303 if (isTypeLegal(MVT::f64)) { 1304 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64]; 1305 RegisterTypeForVT[MVT::ppcf128] = MVT::f64; 1306 TransformToType[MVT::ppcf128] = MVT::f64; 1307 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat); 1308 } else { 1309 NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128]; 1310 RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128]; 1311 TransformToType[MVT::ppcf128] = MVT::i128; 1312 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat); 1313 } 1314 } 1315 1316 // Decide how to handle f128. If the target does not have native f128 support, 1317 // expand it to i128 and we will be generating soft float library calls. 1318 if (!isTypeLegal(MVT::f128)) { 1319 NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128]; 1320 RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128]; 1321 TransformToType[MVT::f128] = MVT::i128; 1322 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat); 1323 } 1324 1325 // Decide how to handle f64. If the target does not have native f64 support, 1326 // expand it to i64 and we will be generating soft float library calls. 1327 if (!isTypeLegal(MVT::f64)) { 1328 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64]; 1329 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64]; 1330 TransformToType[MVT::f64] = MVT::i64; 1331 ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat); 1332 } 1333 1334 // Decide how to handle f32. If the target does not have native f32 support, 1335 // expand it to i32 and we will be generating soft float library calls. 1336 if (!isTypeLegal(MVT::f32)) { 1337 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32]; 1338 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32]; 1339 TransformToType[MVT::f32] = MVT::i32; 1340 ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat); 1341 } 1342 1343 // Decide how to handle f16. If the target does not have native f16 support, 1344 // promote it to f32, because there are no f16 library calls (except for 1345 // conversions). 1346 if (!isTypeLegal(MVT::f16)) { 1347 // Allow targets to control how we legalize half. 1348 if (softPromoteHalfType()) { 1349 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16]; 1350 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16]; 1351 TransformToType[MVT::f16] = MVT::f32; 1352 ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf); 1353 } else { 1354 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32]; 1355 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32]; 1356 TransformToType[MVT::f16] = MVT::f32; 1357 ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat); 1358 } 1359 } 1360 1361 // Loop over all of the vector value types to see which need transformations. 1362 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE; 1363 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1364 MVT VT = (MVT::SimpleValueType) i; 1365 if (isTypeLegal(VT)) 1366 continue; 1367 1368 MVT EltVT = VT.getVectorElementType(); 1369 ElementCount EC = VT.getVectorElementCount(); 1370 bool IsLegalWiderType = false; 1371 bool IsScalable = VT.isScalableVector(); 1372 LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT); 1373 switch (PreferredAction) { 1374 case TypePromoteInteger: { 1375 MVT::SimpleValueType EndVT = IsScalable ? 1376 MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE : 1377 MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE; 1378 // Try to promote the elements of integer vectors. If no legal 1379 // promotion was found, fall through to the widen-vector method. 1380 for (unsigned nVT = i + 1; 1381 (MVT::SimpleValueType)nVT <= EndVT; ++nVT) { 1382 MVT SVT = (MVT::SimpleValueType) nVT; 1383 // Promote vectors of integers to vectors with the same number 1384 // of elements, with a wider element type. 1385 if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() && 1386 SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) { 1387 TransformToType[i] = SVT; 1388 RegisterTypeForVT[i] = SVT; 1389 NumRegistersForVT[i] = 1; 1390 ValueTypeActions.setTypeAction(VT, TypePromoteInteger); 1391 IsLegalWiderType = true; 1392 break; 1393 } 1394 } 1395 if (IsLegalWiderType) 1396 break; 1397 LLVM_FALLTHROUGH; 1398 } 1399 1400 case TypeWidenVector: 1401 if (isPowerOf2_32(EC.getKnownMinValue())) { 1402 // Try to widen the vector. 1403 for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) { 1404 MVT SVT = (MVT::SimpleValueType) nVT; 1405 if (SVT.getVectorElementType() == EltVT && 1406 SVT.isScalableVector() == IsScalable && 1407 SVT.getVectorElementCount().getKnownMinValue() > 1408 EC.getKnownMinValue() && 1409 isTypeLegal(SVT)) { 1410 TransformToType[i] = SVT; 1411 RegisterTypeForVT[i] = SVT; 1412 NumRegistersForVT[i] = 1; 1413 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1414 IsLegalWiderType = true; 1415 break; 1416 } 1417 } 1418 if (IsLegalWiderType) 1419 break; 1420 } else { 1421 // Only widen to the next power of 2 to keep consistency with EVT. 1422 MVT NVT = VT.getPow2VectorType(); 1423 if (isTypeLegal(NVT)) { 1424 TransformToType[i] = NVT; 1425 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1426 RegisterTypeForVT[i] = NVT; 1427 NumRegistersForVT[i] = 1; 1428 break; 1429 } 1430 } 1431 LLVM_FALLTHROUGH; 1432 1433 case TypeSplitVector: 1434 case TypeScalarizeVector: { 1435 MVT IntermediateVT; 1436 MVT RegisterVT; 1437 unsigned NumIntermediates; 1438 unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT, 1439 NumIntermediates, RegisterVT, this); 1440 NumRegistersForVT[i] = NumRegisters; 1441 assert(NumRegistersForVT[i] == NumRegisters && 1442 "NumRegistersForVT size cannot represent NumRegisters!"); 1443 RegisterTypeForVT[i] = RegisterVT; 1444 1445 MVT NVT = VT.getPow2VectorType(); 1446 if (NVT == VT) { 1447 // Type is already a power of 2. The default action is to split. 1448 TransformToType[i] = MVT::Other; 1449 if (PreferredAction == TypeScalarizeVector) 1450 ValueTypeActions.setTypeAction(VT, TypeScalarizeVector); 1451 else if (PreferredAction == TypeSplitVector) 1452 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1453 else if (EC.getKnownMinValue() > 1) 1454 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1455 else 1456 ValueTypeActions.setTypeAction(VT, EC.isScalable() 1457 ? TypeScalarizeScalableVector 1458 : TypeScalarizeVector); 1459 } else { 1460 TransformToType[i] = NVT; 1461 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1462 } 1463 break; 1464 } 1465 default: 1466 llvm_unreachable("Unknown vector legalization action!"); 1467 } 1468 } 1469 1470 // Determine the 'representative' register class for each value type. 1471 // An representative register class is the largest (meaning one which is 1472 // not a sub-register class / subreg register class) legal register class for 1473 // a group of value types. For example, on i386, i8, i16, and i32 1474 // representative would be GR32; while on x86_64 it's GR64. 1475 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) { 1476 const TargetRegisterClass* RRC; 1477 uint8_t Cost; 1478 std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i); 1479 RepRegClassForVT[i] = RRC; 1480 RepRegClassCostForVT[i] = Cost; 1481 } 1482 } 1483 1484 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1485 EVT VT) const { 1486 assert(!VT.isVector() && "No default SetCC type for vectors!"); 1487 return getPointerTy(DL).SimpleTy; 1488 } 1489 1490 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const { 1491 return MVT::i32; // return the default value 1492 } 1493 1494 /// getVectorTypeBreakdown - Vector types are broken down into some number of 1495 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32 1496 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack. 1497 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86. 1498 /// 1499 /// This method returns the number of registers needed, and the VT for each 1500 /// register. It also returns the VT and quantity of the intermediate values 1501 /// before they are promoted/expanded. 1502 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT, 1503 EVT &IntermediateVT, 1504 unsigned &NumIntermediates, 1505 MVT &RegisterVT) const { 1506 ElementCount EltCnt = VT.getVectorElementCount(); 1507 1508 // If there is a wider vector type with the same element type as this one, 1509 // or a promoted vector type that has the same number of elements which 1510 // are wider, then we should convert to that legal vector type. 1511 // This handles things like <2 x float> -> <4 x float> and 1512 // <4 x i1> -> <4 x i32>. 1513 LegalizeTypeAction TA = getTypeAction(Context, VT); 1514 if (EltCnt.getKnownMinValue() != 1 && 1515 (TA == TypeWidenVector || TA == TypePromoteInteger)) { 1516 EVT RegisterEVT = getTypeToTransformTo(Context, VT); 1517 if (isTypeLegal(RegisterEVT)) { 1518 IntermediateVT = RegisterEVT; 1519 RegisterVT = RegisterEVT.getSimpleVT(); 1520 NumIntermediates = 1; 1521 return 1; 1522 } 1523 } 1524 1525 // Figure out the right, legal destination reg to copy into. 1526 EVT EltTy = VT.getVectorElementType(); 1527 1528 unsigned NumVectorRegs = 1; 1529 1530 // Scalable vectors cannot be scalarized, so handle the legalisation of the 1531 // types like done elsewhere in SelectionDAG. 1532 if (VT.isScalableVector() && !isPowerOf2_32(EltCnt.getKnownMinValue())) { 1533 LegalizeKind LK; 1534 EVT PartVT = VT; 1535 do { 1536 // Iterate until we've found a legal (part) type to hold VT. 1537 LK = getTypeConversion(Context, PartVT); 1538 PartVT = LK.second; 1539 } while (LK.first != TypeLegal); 1540 1541 NumIntermediates = VT.getVectorElementCount().getKnownMinValue() / 1542 PartVT.getVectorElementCount().getKnownMinValue(); 1543 1544 // FIXME: This code needs to be extended to handle more complex vector 1545 // breakdowns, like nxv7i64 -> nxv8i64 -> 4 x nxv2i64. Currently the only 1546 // supported cases are vectors that are broken down into equal parts 1547 // such as nxv6i64 -> 3 x nxv2i64. 1548 assert((PartVT.getVectorElementCount() * NumIntermediates) == 1549 VT.getVectorElementCount() && 1550 "Expected an integer multiple of PartVT"); 1551 IntermediateVT = PartVT; 1552 RegisterVT = getRegisterType(Context, IntermediateVT); 1553 return NumIntermediates; 1554 } 1555 1556 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally 1557 // we could break down into LHS/RHS like LegalizeDAG does. 1558 if (!isPowerOf2_32(EltCnt.getKnownMinValue())) { 1559 NumVectorRegs = EltCnt.getKnownMinValue(); 1560 EltCnt = ElementCount::getFixed(1); 1561 } 1562 1563 // Divide the input until we get to a supported size. This will always 1564 // end with a scalar if the target doesn't support vectors. 1565 while (EltCnt.getKnownMinValue() > 1 && 1566 !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) { 1567 EltCnt = EltCnt.divideCoefficientBy(2); 1568 NumVectorRegs <<= 1; 1569 } 1570 1571 NumIntermediates = NumVectorRegs; 1572 1573 EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt); 1574 if (!isTypeLegal(NewVT)) 1575 NewVT = EltTy; 1576 IntermediateVT = NewVT; 1577 1578 MVT DestVT = getRegisterType(Context, NewVT); 1579 RegisterVT = DestVT; 1580 1581 if (EVT(DestVT).bitsLT(NewVT)) { // Value is expanded, e.g. i64 -> i16. 1582 TypeSize NewVTSize = NewVT.getSizeInBits(); 1583 // Convert sizes such as i33 to i64. 1584 if (!isPowerOf2_32(NewVTSize.getKnownMinSize())) 1585 NewVTSize = NewVTSize.coefficientNextPowerOf2(); 1586 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits()); 1587 } 1588 1589 // Otherwise, promotion or legal types use the same number of registers as 1590 // the vector decimated to the appropriate level. 1591 return NumVectorRegs; 1592 } 1593 1594 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI, 1595 uint64_t NumCases, 1596 uint64_t Range, 1597 ProfileSummaryInfo *PSI, 1598 BlockFrequencyInfo *BFI) const { 1599 // FIXME: This function check the maximum table size and density, but the 1600 // minimum size is not checked. It would be nice if the minimum size is 1601 // also combined within this function. Currently, the minimum size check is 1602 // performed in findJumpTable() in SelectionDAGBuiler and 1603 // getEstimatedNumberOfCaseClusters() in BasicTTIImpl. 1604 const bool OptForSize = 1605 SI->getParent()->getParent()->hasOptSize() || 1606 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI); 1607 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize); 1608 const unsigned MaxJumpTableSize = getMaximumJumpTableSize(); 1609 1610 // Check whether the number of cases is small enough and 1611 // the range is dense enough for a jump table. 1612 return (OptForSize || Range <= MaxJumpTableSize) && 1613 (NumCases * 100 >= Range * MinDensity); 1614 } 1615 1616 /// Get the EVTs and ArgFlags collections that represent the legalized return 1617 /// type of the given function. This does not require a DAG or a return value, 1618 /// and is suitable for use before any DAGs for the function are constructed. 1619 /// TODO: Move this out of TargetLowering.cpp. 1620 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType, 1621 AttributeList attr, 1622 SmallVectorImpl<ISD::OutputArg> &Outs, 1623 const TargetLowering &TLI, const DataLayout &DL) { 1624 SmallVector<EVT, 4> ValueVTs; 1625 ComputeValueVTs(TLI, DL, ReturnType, ValueVTs); 1626 unsigned NumValues = ValueVTs.size(); 1627 if (NumValues == 0) return; 1628 1629 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1630 EVT VT = ValueVTs[j]; 1631 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1632 1633 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 1634 ExtendKind = ISD::SIGN_EXTEND; 1635 else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt)) 1636 ExtendKind = ISD::ZERO_EXTEND; 1637 1638 // FIXME: C calling convention requires the return type to be promoted to 1639 // at least 32-bit. But this is not necessary for non-C calling 1640 // conventions. The frontend should mark functions whose return values 1641 // require promoting with signext or zeroext attributes. 1642 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 1643 MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32); 1644 if (VT.bitsLT(MinVT)) 1645 VT = MinVT; 1646 } 1647 1648 unsigned NumParts = 1649 TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT); 1650 MVT PartVT = 1651 TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT); 1652 1653 // 'inreg' on function refers to return value 1654 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1655 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg)) 1656 Flags.setInReg(); 1657 1658 // Propagate extension type if any 1659 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 1660 Flags.setSExt(); 1661 else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt)) 1662 Flags.setZExt(); 1663 1664 for (unsigned i = 0; i < NumParts; ++i) 1665 Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isfixed=*/true, 0, 0)); 1666 } 1667 } 1668 1669 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1670 /// function arguments in the caller parameter area. This is the actual 1671 /// alignment, not its logarithm. 1672 unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty, 1673 const DataLayout &DL) const { 1674 return DL.getABITypeAlign(Ty).value(); 1675 } 1676 1677 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1678 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, 1679 Align Alignment, MachineMemOperand::Flags Flags, bool *Fast) const { 1680 // Check if the specified alignment is sufficient based on the data layout. 1681 // TODO: While using the data layout works in practice, a better solution 1682 // would be to implement this check directly (make this a virtual function). 1683 // For example, the ABI alignment may change based on software platform while 1684 // this function should only be affected by hardware implementation. 1685 Type *Ty = VT.getTypeForEVT(Context); 1686 if (Alignment >= DL.getABITypeAlign(Ty)) { 1687 // Assume that an access that meets the ABI-specified alignment is fast. 1688 if (Fast != nullptr) 1689 *Fast = true; 1690 return true; 1691 } 1692 1693 // This is a misaligned access. 1694 return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment.value(), Flags, 1695 Fast); 1696 } 1697 1698 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1699 LLVMContext &Context, const DataLayout &DL, EVT VT, 1700 const MachineMemOperand &MMO, bool *Fast) const { 1701 return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(), 1702 MMO.getAlign(), MMO.getFlags(), Fast); 1703 } 1704 1705 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1706 const DataLayout &DL, EVT VT, 1707 unsigned AddrSpace, Align Alignment, 1708 MachineMemOperand::Flags Flags, 1709 bool *Fast) const { 1710 return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment, 1711 Flags, Fast); 1712 } 1713 1714 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1715 const DataLayout &DL, EVT VT, 1716 const MachineMemOperand &MMO, 1717 bool *Fast) const { 1718 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(), 1719 MMO.getFlags(), Fast); 1720 } 1721 1722 BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const { 1723 return BranchProbability(MinPercentageForPredictableBranch, 100); 1724 } 1725 1726 //===----------------------------------------------------------------------===// 1727 // TargetTransformInfo Helpers 1728 //===----------------------------------------------------------------------===// 1729 1730 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const { 1731 enum InstructionOpcodes { 1732 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM, 1733 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM 1734 #include "llvm/IR/Instruction.def" 1735 }; 1736 switch (static_cast<InstructionOpcodes>(Opcode)) { 1737 case Ret: return 0; 1738 case Br: return 0; 1739 case Switch: return 0; 1740 case IndirectBr: return 0; 1741 case Invoke: return 0; 1742 case CallBr: return 0; 1743 case Resume: return 0; 1744 case Unreachable: return 0; 1745 case CleanupRet: return 0; 1746 case CatchRet: return 0; 1747 case CatchPad: return 0; 1748 case CatchSwitch: return 0; 1749 case CleanupPad: return 0; 1750 case FNeg: return ISD::FNEG; 1751 case Add: return ISD::ADD; 1752 case FAdd: return ISD::FADD; 1753 case Sub: return ISD::SUB; 1754 case FSub: return ISD::FSUB; 1755 case Mul: return ISD::MUL; 1756 case FMul: return ISD::FMUL; 1757 case UDiv: return ISD::UDIV; 1758 case SDiv: return ISD::SDIV; 1759 case FDiv: return ISD::FDIV; 1760 case URem: return ISD::UREM; 1761 case SRem: return ISD::SREM; 1762 case FRem: return ISD::FREM; 1763 case Shl: return ISD::SHL; 1764 case LShr: return ISD::SRL; 1765 case AShr: return ISD::SRA; 1766 case And: return ISD::AND; 1767 case Or: return ISD::OR; 1768 case Xor: return ISD::XOR; 1769 case Alloca: return 0; 1770 case Load: return ISD::LOAD; 1771 case Store: return ISD::STORE; 1772 case GetElementPtr: return 0; 1773 case Fence: return 0; 1774 case AtomicCmpXchg: return 0; 1775 case AtomicRMW: return 0; 1776 case Trunc: return ISD::TRUNCATE; 1777 case ZExt: return ISD::ZERO_EXTEND; 1778 case SExt: return ISD::SIGN_EXTEND; 1779 case FPToUI: return ISD::FP_TO_UINT; 1780 case FPToSI: return ISD::FP_TO_SINT; 1781 case UIToFP: return ISD::UINT_TO_FP; 1782 case SIToFP: return ISD::SINT_TO_FP; 1783 case FPTrunc: return ISD::FP_ROUND; 1784 case FPExt: return ISD::FP_EXTEND; 1785 case PtrToInt: return ISD::BITCAST; 1786 case IntToPtr: return ISD::BITCAST; 1787 case BitCast: return ISD::BITCAST; 1788 case AddrSpaceCast: return ISD::ADDRSPACECAST; 1789 case ICmp: return ISD::SETCC; 1790 case FCmp: return ISD::SETCC; 1791 case PHI: return 0; 1792 case Call: return 0; 1793 case Select: return ISD::SELECT; 1794 case UserOp1: return 0; 1795 case UserOp2: return 0; 1796 case VAArg: return 0; 1797 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT; 1798 case InsertElement: return ISD::INSERT_VECTOR_ELT; 1799 case ShuffleVector: return ISD::VECTOR_SHUFFLE; 1800 case ExtractValue: return ISD::MERGE_VALUES; 1801 case InsertValue: return ISD::MERGE_VALUES; 1802 case LandingPad: return 0; 1803 case Freeze: return ISD::FREEZE; 1804 } 1805 1806 llvm_unreachable("Unknown instruction type encountered!"); 1807 } 1808 1809 std::pair<int, MVT> 1810 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL, 1811 Type *Ty) const { 1812 LLVMContext &C = Ty->getContext(); 1813 EVT MTy = getValueType(DL, Ty); 1814 1815 int Cost = 1; 1816 // We keep legalizing the type until we find a legal kind. We assume that 1817 // the only operation that costs anything is the split. After splitting 1818 // we need to handle two types. 1819 while (true) { 1820 LegalizeKind LK = getTypeConversion(C, MTy); 1821 1822 if (LK.first == TypeLegal) 1823 return std::make_pair(Cost, MTy.getSimpleVT()); 1824 1825 if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger) 1826 Cost *= 2; 1827 1828 // Do not loop with f128 type. 1829 if (MTy == LK.second) 1830 return std::make_pair(Cost, MTy.getSimpleVT()); 1831 1832 // Keep legalizing the type. 1833 MTy = LK.second; 1834 } 1835 } 1836 1837 Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB, 1838 bool UseTLS) const { 1839 // compiler-rt provides a variable with a magic name. Targets that do not 1840 // link with compiler-rt may also provide such a variable. 1841 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 1842 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; 1843 auto UnsafeStackPtr = 1844 dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar)); 1845 1846 Type *StackPtrTy = Type::getInt8PtrTy(M->getContext()); 1847 1848 if (!UnsafeStackPtr) { 1849 auto TLSModel = UseTLS ? 1850 GlobalValue::InitialExecTLSModel : 1851 GlobalValue::NotThreadLocal; 1852 // The global variable is not defined yet, define it ourselves. 1853 // We use the initial-exec TLS model because we do not support the 1854 // variable living anywhere other than in the main executable. 1855 UnsafeStackPtr = new GlobalVariable( 1856 *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr, 1857 UnsafeStackPtrVar, nullptr, TLSModel); 1858 } else { 1859 // The variable exists, check its type and attributes. 1860 if (UnsafeStackPtr->getValueType() != StackPtrTy) 1861 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type"); 1862 if (UseTLS != UnsafeStackPtr->isThreadLocal()) 1863 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " + 1864 (UseTLS ? "" : "not ") + "be thread-local"); 1865 } 1866 return UnsafeStackPtr; 1867 } 1868 1869 Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 1870 if (!TM.getTargetTriple().isAndroid()) 1871 return getDefaultSafeStackPointerLocation(IRB, true); 1872 1873 // Android provides a libc function to retrieve the address of the current 1874 // thread's unsafe stack pointer. 1875 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 1876 Type *StackPtrTy = Type::getInt8PtrTy(M->getContext()); 1877 FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address", 1878 StackPtrTy->getPointerTo(0)); 1879 return IRB.CreateCall(Fn); 1880 } 1881 1882 //===----------------------------------------------------------------------===// 1883 // Loop Strength Reduction hooks 1884 //===----------------------------------------------------------------------===// 1885 1886 /// isLegalAddressingMode - Return true if the addressing mode represented 1887 /// by AM is legal for this target, for a load/store of the specified type. 1888 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL, 1889 const AddrMode &AM, Type *Ty, 1890 unsigned AS, Instruction *I) const { 1891 // The default implementation of this implements a conservative RISCy, r+r and 1892 // r+i addr mode. 1893 1894 // Allows a sign-extended 16-bit immediate field. 1895 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 1896 return false; 1897 1898 // No global is ever allowed as a base. 1899 if (AM.BaseGV) 1900 return false; 1901 1902 // Only support r+r, 1903 switch (AM.Scale) { 1904 case 0: // "r+i" or just "i", depending on HasBaseReg. 1905 break; 1906 case 1: 1907 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 1908 return false; 1909 // Otherwise we have r+r or r+i. 1910 break; 1911 case 2: 1912 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 1913 return false; 1914 // Allow 2*r as r+r. 1915 break; 1916 default: // Don't allow n * r 1917 return false; 1918 } 1919 1920 return true; 1921 } 1922 1923 //===----------------------------------------------------------------------===// 1924 // Stack Protector 1925 //===----------------------------------------------------------------------===// 1926 1927 // For OpenBSD return its special guard variable. Otherwise return nullptr, 1928 // so that SelectionDAG handle SSP. 1929 Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const { 1930 if (getTargetMachine().getTargetTriple().isOSOpenBSD()) { 1931 Module &M = *IRB.GetInsertBlock()->getParent()->getParent(); 1932 PointerType *PtrTy = Type::getInt8PtrTy(M.getContext()); 1933 Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy); 1934 if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C)) 1935 G->setVisibility(GlobalValue::HiddenVisibility); 1936 return C; 1937 } 1938 return nullptr; 1939 } 1940 1941 // Currently only support "standard" __stack_chk_guard. 1942 // TODO: add LOAD_STACK_GUARD support. 1943 void TargetLoweringBase::insertSSPDeclarations(Module &M) const { 1944 if (!M.getNamedValue("__stack_chk_guard")) 1945 new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false, 1946 GlobalVariable::ExternalLinkage, 1947 nullptr, "__stack_chk_guard"); 1948 } 1949 1950 // Currently only support "standard" __stack_chk_guard. 1951 // TODO: add LOAD_STACK_GUARD support. 1952 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const { 1953 return M.getNamedValue("__stack_chk_guard"); 1954 } 1955 1956 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const { 1957 return nullptr; 1958 } 1959 1960 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const { 1961 return MinimumJumpTableEntries; 1962 } 1963 1964 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) { 1965 MinimumJumpTableEntries = Val; 1966 } 1967 1968 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const { 1969 return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity; 1970 } 1971 1972 unsigned TargetLoweringBase::getMaximumJumpTableSize() const { 1973 return MaximumJumpTableSize; 1974 } 1975 1976 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) { 1977 MaximumJumpTableSize = Val; 1978 } 1979 1980 bool TargetLoweringBase::isJumpTableRelative() const { 1981 return getTargetMachine().isPositionIndependent(); 1982 } 1983 1984 //===----------------------------------------------------------------------===// 1985 // Reciprocal Estimates 1986 //===----------------------------------------------------------------------===// 1987 1988 /// Get the reciprocal estimate attribute string for a function that will 1989 /// override the target defaults. 1990 static StringRef getRecipEstimateForFunc(MachineFunction &MF) { 1991 const Function &F = MF.getFunction(); 1992 return F.getFnAttribute("reciprocal-estimates").getValueAsString(); 1993 } 1994 1995 /// Construct a string for the given reciprocal operation of the given type. 1996 /// This string should match the corresponding option to the front-end's 1997 /// "-mrecip" flag assuming those strings have been passed through in an 1998 /// attribute string. For example, "vec-divf" for a division of a vXf32. 1999 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) { 2000 std::string Name = VT.isVector() ? "vec-" : ""; 2001 2002 Name += IsSqrt ? "sqrt" : "div"; 2003 2004 // TODO: Handle "half" or other float types? 2005 if (VT.getScalarType() == MVT::f64) { 2006 Name += "d"; 2007 } else { 2008 assert(VT.getScalarType() == MVT::f32 && 2009 "Unexpected FP type for reciprocal estimate"); 2010 Name += "f"; 2011 } 2012 2013 return Name; 2014 } 2015 2016 /// Return the character position and value (a single numeric character) of a 2017 /// customized refinement operation in the input string if it exists. Return 2018 /// false if there is no customized refinement step count. 2019 static bool parseRefinementStep(StringRef In, size_t &Position, 2020 uint8_t &Value) { 2021 const char RefStepToken = ':'; 2022 Position = In.find(RefStepToken); 2023 if (Position == StringRef::npos) 2024 return false; 2025 2026 StringRef RefStepString = In.substr(Position + 1); 2027 // Allow exactly one numeric character for the additional refinement 2028 // step parameter. 2029 if (RefStepString.size() == 1) { 2030 char RefStepChar = RefStepString[0]; 2031 if (RefStepChar >= '0' && RefStepChar <= '9') { 2032 Value = RefStepChar - '0'; 2033 return true; 2034 } 2035 } 2036 report_fatal_error("Invalid refinement step for -recip."); 2037 } 2038 2039 /// For the input attribute string, return one of the ReciprocalEstimate enum 2040 /// status values (enabled, disabled, or not specified) for this operation on 2041 /// the specified data type. 2042 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) { 2043 if (Override.empty()) 2044 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2045 2046 SmallVector<StringRef, 4> OverrideVector; 2047 Override.split(OverrideVector, ','); 2048 unsigned NumArgs = OverrideVector.size(); 2049 2050 // Check if "all", "none", or "default" was specified. 2051 if (NumArgs == 1) { 2052 // Look for an optional setting of the number of refinement steps needed 2053 // for this type of reciprocal operation. 2054 size_t RefPos; 2055 uint8_t RefSteps; 2056 if (parseRefinementStep(Override, RefPos, RefSteps)) { 2057 // Split the string for further processing. 2058 Override = Override.substr(0, RefPos); 2059 } 2060 2061 // All reciprocal types are enabled. 2062 if (Override == "all") 2063 return TargetLoweringBase::ReciprocalEstimate::Enabled; 2064 2065 // All reciprocal types are disabled. 2066 if (Override == "none") 2067 return TargetLoweringBase::ReciprocalEstimate::Disabled; 2068 2069 // Target defaults for enablement are used. 2070 if (Override == "default") 2071 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2072 } 2073 2074 // The attribute string may omit the size suffix ('f'/'d'). 2075 std::string VTName = getReciprocalOpName(IsSqrt, VT); 2076 std::string VTNameNoSize = VTName; 2077 VTNameNoSize.pop_back(); 2078 static const char DisabledPrefix = '!'; 2079 2080 for (StringRef RecipType : OverrideVector) { 2081 size_t RefPos; 2082 uint8_t RefSteps; 2083 if (parseRefinementStep(RecipType, RefPos, RefSteps)) 2084 RecipType = RecipType.substr(0, RefPos); 2085 2086 // Ignore the disablement token for string matching. 2087 bool IsDisabled = RecipType[0] == DisabledPrefix; 2088 if (IsDisabled) 2089 RecipType = RecipType.substr(1); 2090 2091 if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize)) 2092 return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled 2093 : TargetLoweringBase::ReciprocalEstimate::Enabled; 2094 } 2095 2096 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2097 } 2098 2099 /// For the input attribute string, return the customized refinement step count 2100 /// for this operation on the specified data type. If the step count does not 2101 /// exist, return the ReciprocalEstimate enum value for unspecified. 2102 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) { 2103 if (Override.empty()) 2104 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2105 2106 SmallVector<StringRef, 4> OverrideVector; 2107 Override.split(OverrideVector, ','); 2108 unsigned NumArgs = OverrideVector.size(); 2109 2110 // Check if "all", "default", or "none" was specified. 2111 if (NumArgs == 1) { 2112 // Look for an optional setting of the number of refinement steps needed 2113 // for this type of reciprocal operation. 2114 size_t RefPos; 2115 uint8_t RefSteps; 2116 if (!parseRefinementStep(Override, RefPos, RefSteps)) 2117 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2118 2119 // Split the string for further processing. 2120 Override = Override.substr(0, RefPos); 2121 assert(Override != "none" && 2122 "Disabled reciprocals, but specifed refinement steps?"); 2123 2124 // If this is a general override, return the specified number of steps. 2125 if (Override == "all" || Override == "default") 2126 return RefSteps; 2127 } 2128 2129 // The attribute string may omit the size suffix ('f'/'d'). 2130 std::string VTName = getReciprocalOpName(IsSqrt, VT); 2131 std::string VTNameNoSize = VTName; 2132 VTNameNoSize.pop_back(); 2133 2134 for (StringRef RecipType : OverrideVector) { 2135 size_t RefPos; 2136 uint8_t RefSteps; 2137 if (!parseRefinementStep(RecipType, RefPos, RefSteps)) 2138 continue; 2139 2140 RecipType = RecipType.substr(0, RefPos); 2141 if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize)) 2142 return RefSteps; 2143 } 2144 2145 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2146 } 2147 2148 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT, 2149 MachineFunction &MF) const { 2150 return getOpEnabled(true, VT, getRecipEstimateForFunc(MF)); 2151 } 2152 2153 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT, 2154 MachineFunction &MF) const { 2155 return getOpEnabled(false, VT, getRecipEstimateForFunc(MF)); 2156 } 2157 2158 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT, 2159 MachineFunction &MF) const { 2160 return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF)); 2161 } 2162 2163 int TargetLoweringBase::getDivRefinementSteps(EVT VT, 2164 MachineFunction &MF) const { 2165 return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF)); 2166 } 2167 2168 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const { 2169 MF.getRegInfo().freezeReservedRegs(MF); 2170 } 2171 2172 MachineMemOperand::Flags 2173 TargetLoweringBase::getLoadMemOperandFlags(const LoadInst &LI, 2174 const DataLayout &DL) const { 2175 MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad; 2176 if (LI.isVolatile()) 2177 Flags |= MachineMemOperand::MOVolatile; 2178 2179 if (LI.hasMetadata(LLVMContext::MD_nontemporal)) 2180 Flags |= MachineMemOperand::MONonTemporal; 2181 2182 if (LI.hasMetadata(LLVMContext::MD_invariant_load)) 2183 Flags |= MachineMemOperand::MOInvariant; 2184 2185 if (isDereferenceablePointer(LI.getPointerOperand(), LI.getType(), DL)) 2186 Flags |= MachineMemOperand::MODereferenceable; 2187 2188 Flags |= getTargetMMOFlags(LI); 2189 return Flags; 2190 } 2191 2192 MachineMemOperand::Flags 2193 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI, 2194 const DataLayout &DL) const { 2195 MachineMemOperand::Flags Flags = MachineMemOperand::MOStore; 2196 2197 if (SI.isVolatile()) 2198 Flags |= MachineMemOperand::MOVolatile; 2199 2200 if (SI.hasMetadata(LLVMContext::MD_nontemporal)) 2201 Flags |= MachineMemOperand::MONonTemporal; 2202 2203 // FIXME: Not preserving dereferenceable 2204 Flags |= getTargetMMOFlags(SI); 2205 return Flags; 2206 } 2207 2208 MachineMemOperand::Flags 2209 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI, 2210 const DataLayout &DL) const { 2211 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 2212 2213 if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) { 2214 if (RMW->isVolatile()) 2215 Flags |= MachineMemOperand::MOVolatile; 2216 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) { 2217 if (CmpX->isVolatile()) 2218 Flags |= MachineMemOperand::MOVolatile; 2219 } else 2220 llvm_unreachable("not an atomic instruction"); 2221 2222 // FIXME: Not preserving dereferenceable 2223 Flags |= getTargetMMOFlags(AI); 2224 return Flags; 2225 } 2226 2227 //===----------------------------------------------------------------------===// 2228 // GlobalISel Hooks 2229 //===----------------------------------------------------------------------===// 2230 2231 bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI, 2232 const TargetTransformInfo *TTI) const { 2233 auto &MF = *MI.getMF(); 2234 auto &MRI = MF.getRegInfo(); 2235 // Assuming a spill and reload of a value has a cost of 1 instruction each, 2236 // this helper function computes the maximum number of uses we should consider 2237 // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We 2238 // break even in terms of code size when the original MI has 2 users vs 2239 // choosing to potentially spill. Any more than 2 users we we have a net code 2240 // size increase. This doesn't take into account register pressure though. 2241 auto maxUses = [](unsigned RematCost) { 2242 // A cost of 1 means remats are basically free. 2243 if (RematCost == 1) 2244 return UINT_MAX; 2245 if (RematCost == 2) 2246 return 2U; 2247 2248 // Remat is too expensive, only sink if there's one user. 2249 if (RematCost > 2) 2250 return 1U; 2251 llvm_unreachable("Unexpected remat cost"); 2252 }; 2253 2254 // Helper to walk through uses and terminate if we've reached a limit. Saves 2255 // us spending time traversing uses if all we want to know is if it's >= min. 2256 auto isUsesAtMost = [&](unsigned Reg, unsigned MaxUses) { 2257 unsigned NumUses = 0; 2258 auto UI = MRI.use_instr_nodbg_begin(Reg), UE = MRI.use_instr_nodbg_end(); 2259 for (; UI != UE && NumUses < MaxUses; ++UI) { 2260 NumUses++; 2261 } 2262 // If we haven't reached the end yet then there are more than MaxUses users. 2263 return UI == UE; 2264 }; 2265 2266 switch (MI.getOpcode()) { 2267 default: 2268 return false; 2269 // Constants-like instructions should be close to their users. 2270 // We don't want long live-ranges for them. 2271 case TargetOpcode::G_CONSTANT: 2272 case TargetOpcode::G_FCONSTANT: 2273 case TargetOpcode::G_FRAME_INDEX: 2274 case TargetOpcode::G_INTTOPTR: 2275 return true; 2276 case TargetOpcode::G_GLOBAL_VALUE: { 2277 unsigned RematCost = TTI->getGISelRematGlobalCost(); 2278 Register Reg = MI.getOperand(0).getReg(); 2279 unsigned MaxUses = maxUses(RematCost); 2280 if (MaxUses == UINT_MAX) 2281 return true; // Remats are "free" so always localize. 2282 bool B = isUsesAtMost(Reg, MaxUses); 2283 return B; 2284 } 2285 } 2286 } 2287