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