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