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