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