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/CodeGen/Analysis.h" 21 #include "llvm/CodeGen/ISDOpcodes.h" 22 #include "llvm/CodeGen/MachineBasicBlock.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/CodeGen/MachineInstr.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineMemOperand.h" 28 #include "llvm/CodeGen/MachineOperand.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/RuntimeLibcalls.h" 31 #include "llvm/CodeGen/StackMaps.h" 32 #include "llvm/CodeGen/TargetLowering.h" 33 #include "llvm/CodeGen/TargetOpcodes.h" 34 #include "llvm/CodeGen/TargetRegisterInfo.h" 35 #include "llvm/CodeGen/ValueTypes.h" 36 #include "llvm/IR/Attributes.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/DataLayout.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalValue.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/IRBuilder.h" 44 #include "llvm/IR/Module.h" 45 #include "llvm/IR/Type.h" 46 #include "llvm/Support/BranchProbability.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Compiler.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/MachineValueType.h" 52 #include "llvm/Support/MathExtras.h" 53 #include "llvm/Target/TargetMachine.h" 54 #include <algorithm> 55 #include <cassert> 56 #include <cstddef> 57 #include <cstdint> 58 #include <cstring> 59 #include <iterator> 60 #include <string> 61 #include <tuple> 62 #include <utility> 63 64 using namespace llvm; 65 66 static cl::opt<bool> JumpIsExpensiveOverride( 67 "jump-is-expensive", cl::init(false), 68 cl::desc("Do not create extra branches to split comparison logic."), 69 cl::Hidden); 70 71 static cl::opt<unsigned> MinimumJumpTableEntries 72 ("min-jump-table-entries", cl::init(4), cl::Hidden, 73 cl::desc("Set minimum number of entries to use a jump table.")); 74 75 static cl::opt<unsigned> MaximumJumpTableSize 76 ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden, 77 cl::desc("Set maximum size of jump tables.")); 78 79 /// Minimum jump table density for normal functions. 80 static cl::opt<unsigned> 81 JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden, 82 cl::desc("Minimum density for building a jump table in " 83 "a normal function")); 84 85 /// Minimum jump table density for -Os or -Oz functions. 86 static cl::opt<unsigned> OptsizeJumpTableDensity( 87 "optsize-jump-table-density", cl::init(40), cl::Hidden, 88 cl::desc("Minimum density for building a jump table in " 89 "an optsize function")); 90 91 // FIXME: This option is only to test if the strict fp operation processed 92 // correctly by preventing mutating strict fp operation to normal fp operation 93 // during development. When the backend supports strict float operation, this 94 // option will be meaningless. 95 static cl::opt<bool> DisableStrictNodeMutation("disable-strictnode-mutation", 96 cl::desc("Don't mutate strict-float node to a legalize node"), 97 cl::init(false), cl::Hidden); 98 99 static bool darwinHasSinCos(const Triple &TT) { 100 assert(TT.isOSDarwin() && "should be called with darwin triple"); 101 // Don't bother with 32 bit x86. 102 if (TT.getArch() == Triple::x86) 103 return false; 104 // Macos < 10.9 has no sincos_stret. 105 if (TT.isMacOSX()) 106 return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit(); 107 // iOS < 7.0 has no sincos_stret. 108 if (TT.isiOS()) 109 return !TT.isOSVersionLT(7, 0); 110 // Any other darwin such as WatchOS/TvOS is new enough. 111 return true; 112 } 113 114 // Although this default value is arbitrary, it is not random. It is assumed 115 // that a condition that evaluates the same way by a higher percentage than this 116 // is best represented as control flow. Therefore, the default value N should be 117 // set such that the win from N% correct executions is greater than the loss 118 // from (100 - N)% mispredicted executions for the majority of intended targets. 119 static cl::opt<int> MinPercentageForPredictableBranch( 120 "min-predictable-branch", cl::init(99), 121 cl::desc("Minimum percentage (0-100) that a condition must be either true " 122 "or false to assume that the condition is predictable"), 123 cl::Hidden); 124 125 void TargetLoweringBase::InitLibcalls(const Triple &TT) { 126 #define HANDLE_LIBCALL(code, name) \ 127 setLibcallName(RTLIB::code, name); 128 #include "llvm/IR/RuntimeLibcalls.def" 129 #undef HANDLE_LIBCALL 130 // Initialize calling conventions to their default. 131 for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC) 132 setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C); 133 134 // For IEEE quad-precision libcall names, PPC uses "kf" instead of "tf". 135 if (TT.getArch() == Triple::ppc || TT.isPPC64()) { 136 setLibcallName(RTLIB::ADD_F128, "__addkf3"); 137 setLibcallName(RTLIB::SUB_F128, "__subkf3"); 138 setLibcallName(RTLIB::MUL_F128, "__mulkf3"); 139 setLibcallName(RTLIB::DIV_F128, "__divkf3"); 140 setLibcallName(RTLIB::FPEXT_F32_F128, "__extendsfkf2"); 141 setLibcallName(RTLIB::FPEXT_F64_F128, "__extenddfkf2"); 142 setLibcallName(RTLIB::FPROUND_F128_F32, "__trunckfsf2"); 143 setLibcallName(RTLIB::FPROUND_F128_F64, "__trunckfdf2"); 144 setLibcallName(RTLIB::FPTOSINT_F128_I32, "__fixkfsi"); 145 setLibcallName(RTLIB::FPTOSINT_F128_I64, "__fixkfdi"); 146 setLibcallName(RTLIB::FPTOUINT_F128_I32, "__fixunskfsi"); 147 setLibcallName(RTLIB::FPTOUINT_F128_I64, "__fixunskfdi"); 148 setLibcallName(RTLIB::SINTTOFP_I32_F128, "__floatsikf"); 149 setLibcallName(RTLIB::SINTTOFP_I64_F128, "__floatdikf"); 150 setLibcallName(RTLIB::UINTTOFP_I32_F128, "__floatunsikf"); 151 setLibcallName(RTLIB::UINTTOFP_I64_F128, "__floatundikf"); 152 setLibcallName(RTLIB::OEQ_F128, "__eqkf2"); 153 setLibcallName(RTLIB::UNE_F128, "__nekf2"); 154 setLibcallName(RTLIB::OGE_F128, "__gekf2"); 155 setLibcallName(RTLIB::OLT_F128, "__ltkf2"); 156 setLibcallName(RTLIB::OLE_F128, "__lekf2"); 157 setLibcallName(RTLIB::OGT_F128, "__gtkf2"); 158 setLibcallName(RTLIB::UO_F128, "__unordkf2"); 159 setLibcallName(RTLIB::O_F128, "__unordkf2"); 160 } 161 162 // A few names are different on particular architectures or environments. 163 if (TT.isOSDarwin()) { 164 // For f16/f32 conversions, Darwin uses the standard naming scheme, instead 165 // of the gnueabi-style __gnu_*_ieee. 166 // FIXME: What about other targets? 167 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 168 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 169 170 // Some darwins have an optimized __bzero/bzero function. 171 switch (TT.getArch()) { 172 case Triple::x86: 173 case Triple::x86_64: 174 if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6)) 175 setLibcallName(RTLIB::BZERO, "__bzero"); 176 break; 177 case Triple::aarch64: 178 case Triple::aarch64_32: 179 setLibcallName(RTLIB::BZERO, "bzero"); 180 break; 181 default: 182 break; 183 } 184 185 if (darwinHasSinCos(TT)) { 186 setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret"); 187 setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret"); 188 if (TT.isWatchABI()) { 189 setLibcallCallingConv(RTLIB::SINCOS_STRET_F32, 190 CallingConv::ARM_AAPCS_VFP); 191 setLibcallCallingConv(RTLIB::SINCOS_STRET_F64, 192 CallingConv::ARM_AAPCS_VFP); 193 } 194 } 195 } else { 196 setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee"); 197 setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee"); 198 } 199 200 if (TT.isGNUEnvironment() || TT.isOSFuchsia() || 201 (TT.isAndroid() && !TT.isAndroidVersionLT(9))) { 202 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 203 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 204 setLibcallName(RTLIB::SINCOS_F80, "sincosl"); 205 setLibcallName(RTLIB::SINCOS_F128, "sincosl"); 206 setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl"); 207 } 208 209 if (TT.isPS4CPU()) { 210 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 211 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 212 } 213 214 if (TT.isOSOpenBSD()) { 215 setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr); 216 } 217 } 218 219 /// getFPEXT - Return the FPEXT_*_* value for the given types, or 220 /// UNKNOWN_LIBCALL if there is none. 221 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) { 222 if (OpVT == MVT::f16) { 223 if (RetVT == MVT::f32) 224 return FPEXT_F16_F32; 225 } else if (OpVT == MVT::f32) { 226 if (RetVT == MVT::f64) 227 return FPEXT_F32_F64; 228 if (RetVT == MVT::f128) 229 return FPEXT_F32_F128; 230 if (RetVT == MVT::ppcf128) 231 return FPEXT_F32_PPCF128; 232 } else if (OpVT == MVT::f64) { 233 if (RetVT == MVT::f128) 234 return FPEXT_F64_F128; 235 else if (RetVT == MVT::ppcf128) 236 return FPEXT_F64_PPCF128; 237 } else if (OpVT == MVT::f80) { 238 if (RetVT == MVT::f128) 239 return FPEXT_F80_F128; 240 } 241 242 return UNKNOWN_LIBCALL; 243 } 244 245 /// getFPROUND - Return the FPROUND_*_* value for the given types, or 246 /// UNKNOWN_LIBCALL if there is none. 247 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) { 248 if (RetVT == MVT::f16) { 249 if (OpVT == MVT::f32) 250 return FPROUND_F32_F16; 251 if (OpVT == MVT::f64) 252 return FPROUND_F64_F16; 253 if (OpVT == MVT::f80) 254 return FPROUND_F80_F16; 255 if (OpVT == MVT::f128) 256 return FPROUND_F128_F16; 257 if (OpVT == MVT::ppcf128) 258 return FPROUND_PPCF128_F16; 259 } else if (RetVT == MVT::f32) { 260 if (OpVT == MVT::f64) 261 return FPROUND_F64_F32; 262 if (OpVT == MVT::f80) 263 return FPROUND_F80_F32; 264 if (OpVT == MVT::f128) 265 return FPROUND_F128_F32; 266 if (OpVT == MVT::ppcf128) 267 return FPROUND_PPCF128_F32; 268 } else if (RetVT == MVT::f64) { 269 if (OpVT == MVT::f80) 270 return FPROUND_F80_F64; 271 if (OpVT == MVT::f128) 272 return FPROUND_F128_F64; 273 if (OpVT == MVT::ppcf128) 274 return FPROUND_PPCF128_F64; 275 } else if (RetVT == MVT::f80) { 276 if (OpVT == MVT::f128) 277 return FPROUND_F128_F80; 278 } 279 280 return UNKNOWN_LIBCALL; 281 } 282 283 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or 284 /// UNKNOWN_LIBCALL if there is none. 285 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) { 286 if (OpVT == MVT::f32) { 287 if (RetVT == MVT::i32) 288 return FPTOSINT_F32_I32; 289 if (RetVT == MVT::i64) 290 return FPTOSINT_F32_I64; 291 if (RetVT == MVT::i128) 292 return FPTOSINT_F32_I128; 293 } else if (OpVT == MVT::f64) { 294 if (RetVT == MVT::i32) 295 return FPTOSINT_F64_I32; 296 if (RetVT == MVT::i64) 297 return FPTOSINT_F64_I64; 298 if (RetVT == MVT::i128) 299 return FPTOSINT_F64_I128; 300 } else if (OpVT == MVT::f80) { 301 if (RetVT == MVT::i32) 302 return FPTOSINT_F80_I32; 303 if (RetVT == MVT::i64) 304 return FPTOSINT_F80_I64; 305 if (RetVT == MVT::i128) 306 return FPTOSINT_F80_I128; 307 } else if (OpVT == MVT::f128) { 308 if (RetVT == MVT::i32) 309 return FPTOSINT_F128_I32; 310 if (RetVT == MVT::i64) 311 return FPTOSINT_F128_I64; 312 if (RetVT == MVT::i128) 313 return FPTOSINT_F128_I128; 314 } else if (OpVT == MVT::ppcf128) { 315 if (RetVT == MVT::i32) 316 return FPTOSINT_PPCF128_I32; 317 if (RetVT == MVT::i64) 318 return FPTOSINT_PPCF128_I64; 319 if (RetVT == MVT::i128) 320 return FPTOSINT_PPCF128_I128; 321 } 322 return UNKNOWN_LIBCALL; 323 } 324 325 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or 326 /// UNKNOWN_LIBCALL if there is none. 327 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) { 328 if (OpVT == MVT::f32) { 329 if (RetVT == MVT::i32) 330 return FPTOUINT_F32_I32; 331 if (RetVT == MVT::i64) 332 return FPTOUINT_F32_I64; 333 if (RetVT == MVT::i128) 334 return FPTOUINT_F32_I128; 335 } else if (OpVT == MVT::f64) { 336 if (RetVT == MVT::i32) 337 return FPTOUINT_F64_I32; 338 if (RetVT == MVT::i64) 339 return FPTOUINT_F64_I64; 340 if (RetVT == MVT::i128) 341 return FPTOUINT_F64_I128; 342 } else if (OpVT == MVT::f80) { 343 if (RetVT == MVT::i32) 344 return FPTOUINT_F80_I32; 345 if (RetVT == MVT::i64) 346 return FPTOUINT_F80_I64; 347 if (RetVT == MVT::i128) 348 return FPTOUINT_F80_I128; 349 } else if (OpVT == MVT::f128) { 350 if (RetVT == MVT::i32) 351 return FPTOUINT_F128_I32; 352 if (RetVT == MVT::i64) 353 return FPTOUINT_F128_I64; 354 if (RetVT == MVT::i128) 355 return FPTOUINT_F128_I128; 356 } else if (OpVT == MVT::ppcf128) { 357 if (RetVT == MVT::i32) 358 return FPTOUINT_PPCF128_I32; 359 if (RetVT == MVT::i64) 360 return FPTOUINT_PPCF128_I64; 361 if (RetVT == MVT::i128) 362 return FPTOUINT_PPCF128_I128; 363 } 364 return UNKNOWN_LIBCALL; 365 } 366 367 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or 368 /// UNKNOWN_LIBCALL if there is none. 369 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) { 370 if (OpVT == MVT::i32) { 371 if (RetVT == MVT::f32) 372 return SINTTOFP_I32_F32; 373 if (RetVT == MVT::f64) 374 return SINTTOFP_I32_F64; 375 if (RetVT == MVT::f80) 376 return SINTTOFP_I32_F80; 377 if (RetVT == MVT::f128) 378 return SINTTOFP_I32_F128; 379 if (RetVT == MVT::ppcf128) 380 return SINTTOFP_I32_PPCF128; 381 } else if (OpVT == MVT::i64) { 382 if (RetVT == MVT::f32) 383 return SINTTOFP_I64_F32; 384 if (RetVT == MVT::f64) 385 return SINTTOFP_I64_F64; 386 if (RetVT == MVT::f80) 387 return SINTTOFP_I64_F80; 388 if (RetVT == MVT::f128) 389 return SINTTOFP_I64_F128; 390 if (RetVT == MVT::ppcf128) 391 return SINTTOFP_I64_PPCF128; 392 } else if (OpVT == MVT::i128) { 393 if (RetVT == MVT::f32) 394 return SINTTOFP_I128_F32; 395 if (RetVT == MVT::f64) 396 return SINTTOFP_I128_F64; 397 if (RetVT == MVT::f80) 398 return SINTTOFP_I128_F80; 399 if (RetVT == MVT::f128) 400 return SINTTOFP_I128_F128; 401 if (RetVT == MVT::ppcf128) 402 return SINTTOFP_I128_PPCF128; 403 } 404 return UNKNOWN_LIBCALL; 405 } 406 407 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or 408 /// UNKNOWN_LIBCALL if there is none. 409 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) { 410 if (OpVT == MVT::i32) { 411 if (RetVT == MVT::f32) 412 return UINTTOFP_I32_F32; 413 if (RetVT == MVT::f64) 414 return UINTTOFP_I32_F64; 415 if (RetVT == MVT::f80) 416 return UINTTOFP_I32_F80; 417 if (RetVT == MVT::f128) 418 return UINTTOFP_I32_F128; 419 if (RetVT == MVT::ppcf128) 420 return UINTTOFP_I32_PPCF128; 421 } else if (OpVT == MVT::i64) { 422 if (RetVT == MVT::f32) 423 return UINTTOFP_I64_F32; 424 if (RetVT == MVT::f64) 425 return UINTTOFP_I64_F64; 426 if (RetVT == MVT::f80) 427 return UINTTOFP_I64_F80; 428 if (RetVT == MVT::f128) 429 return UINTTOFP_I64_F128; 430 if (RetVT == MVT::ppcf128) 431 return UINTTOFP_I64_PPCF128; 432 } else if (OpVT == MVT::i128) { 433 if (RetVT == MVT::f32) 434 return UINTTOFP_I128_F32; 435 if (RetVT == MVT::f64) 436 return UINTTOFP_I128_F64; 437 if (RetVT == MVT::f80) 438 return UINTTOFP_I128_F80; 439 if (RetVT == MVT::f128) 440 return UINTTOFP_I128_F128; 441 if (RetVT == MVT::ppcf128) 442 return UINTTOFP_I128_PPCF128; 443 } 444 return UNKNOWN_LIBCALL; 445 } 446 447 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) { 448 #define OP_TO_LIBCALL(Name, Enum) \ 449 case Name: \ 450 switch (VT.SimpleTy) { \ 451 default: \ 452 return UNKNOWN_LIBCALL; \ 453 case MVT::i8: \ 454 return Enum##_1; \ 455 case MVT::i16: \ 456 return Enum##_2; \ 457 case MVT::i32: \ 458 return Enum##_4; \ 459 case MVT::i64: \ 460 return Enum##_8; \ 461 case MVT::i128: \ 462 return Enum##_16; \ 463 } 464 465 switch (Opc) { 466 OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET) 467 OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP) 468 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD) 469 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB) 470 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND) 471 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR) 472 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR) 473 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND) 474 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX) 475 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX) 476 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN) 477 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN) 478 } 479 480 #undef OP_TO_LIBCALL 481 482 return UNKNOWN_LIBCALL; 483 } 484 485 RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 486 switch (ElementSize) { 487 case 1: 488 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1; 489 case 2: 490 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2; 491 case 4: 492 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4; 493 case 8: 494 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8; 495 case 16: 496 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16; 497 default: 498 return UNKNOWN_LIBCALL; 499 } 500 } 501 502 RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 503 switch (ElementSize) { 504 case 1: 505 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1; 506 case 2: 507 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2; 508 case 4: 509 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4; 510 case 8: 511 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8; 512 case 16: 513 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16; 514 default: 515 return UNKNOWN_LIBCALL; 516 } 517 } 518 519 RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 520 switch (ElementSize) { 521 case 1: 522 return MEMSET_ELEMENT_UNORDERED_ATOMIC_1; 523 case 2: 524 return MEMSET_ELEMENT_UNORDERED_ATOMIC_2; 525 case 4: 526 return MEMSET_ELEMENT_UNORDERED_ATOMIC_4; 527 case 8: 528 return MEMSET_ELEMENT_UNORDERED_ATOMIC_8; 529 case 16: 530 return MEMSET_ELEMENT_UNORDERED_ATOMIC_16; 531 default: 532 return UNKNOWN_LIBCALL; 533 } 534 } 535 536 /// InitCmpLibcallCCs - Set default comparison libcall CC. 537 static void InitCmpLibcallCCs(ISD::CondCode *CCs) { 538 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL); 539 CCs[RTLIB::OEQ_F32] = ISD::SETEQ; 540 CCs[RTLIB::OEQ_F64] = ISD::SETEQ; 541 CCs[RTLIB::OEQ_F128] = ISD::SETEQ; 542 CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ; 543 CCs[RTLIB::UNE_F32] = ISD::SETNE; 544 CCs[RTLIB::UNE_F64] = ISD::SETNE; 545 CCs[RTLIB::UNE_F128] = ISD::SETNE; 546 CCs[RTLIB::UNE_PPCF128] = ISD::SETNE; 547 CCs[RTLIB::OGE_F32] = ISD::SETGE; 548 CCs[RTLIB::OGE_F64] = ISD::SETGE; 549 CCs[RTLIB::OGE_F128] = ISD::SETGE; 550 CCs[RTLIB::OGE_PPCF128] = ISD::SETGE; 551 CCs[RTLIB::OLT_F32] = ISD::SETLT; 552 CCs[RTLIB::OLT_F64] = ISD::SETLT; 553 CCs[RTLIB::OLT_F128] = ISD::SETLT; 554 CCs[RTLIB::OLT_PPCF128] = ISD::SETLT; 555 CCs[RTLIB::OLE_F32] = ISD::SETLE; 556 CCs[RTLIB::OLE_F64] = ISD::SETLE; 557 CCs[RTLIB::OLE_F128] = ISD::SETLE; 558 CCs[RTLIB::OLE_PPCF128] = ISD::SETLE; 559 CCs[RTLIB::OGT_F32] = ISD::SETGT; 560 CCs[RTLIB::OGT_F64] = ISD::SETGT; 561 CCs[RTLIB::OGT_F128] = ISD::SETGT; 562 CCs[RTLIB::OGT_PPCF128] = ISD::SETGT; 563 CCs[RTLIB::UO_F32] = ISD::SETNE; 564 CCs[RTLIB::UO_F64] = ISD::SETNE; 565 CCs[RTLIB::UO_F128] = ISD::SETNE; 566 CCs[RTLIB::UO_PPCF128] = ISD::SETNE; 567 CCs[RTLIB::O_F32] = ISD::SETEQ; 568 CCs[RTLIB::O_F64] = ISD::SETEQ; 569 CCs[RTLIB::O_F128] = ISD::SETEQ; 570 CCs[RTLIB::O_PPCF128] = ISD::SETEQ; 571 } 572 573 /// NOTE: The TargetMachine owns TLOF. 574 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) { 575 initActions(); 576 577 // Perform these initializations only once. 578 MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove = 579 MaxLoadsPerMemcmp = 8; 580 MaxGluedStoresPerMemcpy = 0; 581 MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize = 582 MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4; 583 HasMultipleConditionRegisters = false; 584 HasExtractBitsInsn = false; 585 JumpIsExpensive = JumpIsExpensiveOverride; 586 PredictableSelectIsExpensive = false; 587 EnableExtLdPromotion = false; 588 StackPointerRegisterToSaveRestore = 0; 589 BooleanContents = UndefinedBooleanContent; 590 BooleanFloatContents = UndefinedBooleanContent; 591 BooleanVectorContents = UndefinedBooleanContent; 592 SchedPreferenceInfo = Sched::ILP; 593 GatherAllAliasesMaxDepth = 18; 594 IsStrictFPEnabled = DisableStrictNodeMutation; 595 // TODO: the default will be switched to 0 in the next commit, along 596 // with the Target-specific changes necessary. 597 MaxAtomicSizeInBitsSupported = 1024; 598 599 MinCmpXchgSizeInBits = 0; 600 SupportsUnalignedAtomics = false; 601 602 std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr); 603 604 InitLibcalls(TM.getTargetTriple()); 605 InitCmpLibcallCCs(CmpLibcallCCs); 606 } 607 608 void TargetLoweringBase::initActions() { 609 // All operations default to being supported. 610 memset(OpActions, 0, sizeof(OpActions)); 611 memset(LoadExtActions, 0, sizeof(LoadExtActions)); 612 memset(TruncStoreActions, 0, sizeof(TruncStoreActions)); 613 memset(IndexedModeActions, 0, sizeof(IndexedModeActions)); 614 memset(CondCodeActions, 0, sizeof(CondCodeActions)); 615 std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr); 616 std::fill(std::begin(TargetDAGCombineArray), 617 std::end(TargetDAGCombineArray), 0); 618 619 for (MVT VT : MVT::fp_valuetypes()) { 620 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits()); 621 if (IntVT.isValid()) { 622 setOperationAction(ISD::ATOMIC_SWAP, VT, Promote); 623 AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT); 624 } 625 } 626 627 // Set default actions for various operations. 628 for (MVT VT : MVT::all_valuetypes()) { 629 // Default all indexed load / store to expand. 630 for (unsigned IM = (unsigned)ISD::PRE_INC; 631 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) { 632 setIndexedLoadAction(IM, VT, Expand); 633 setIndexedStoreAction(IM, VT, Expand); 634 setIndexedMaskedLoadAction(IM, VT, Expand); 635 setIndexedMaskedStoreAction(IM, VT, Expand); 636 } 637 638 // Most backends expect to see the node which just returns the value loaded. 639 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand); 640 641 // These operations default to expand. 642 setOperationAction(ISD::FGETSIGN, VT, Expand); 643 setOperationAction(ISD::CONCAT_VECTORS, VT, Expand); 644 setOperationAction(ISD::FMINNUM, VT, Expand); 645 setOperationAction(ISD::FMAXNUM, VT, Expand); 646 setOperationAction(ISD::FMINNUM_IEEE, VT, Expand); 647 setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand); 648 setOperationAction(ISD::FMINIMUM, VT, Expand); 649 setOperationAction(ISD::FMAXIMUM, VT, Expand); 650 setOperationAction(ISD::FMAD, VT, Expand); 651 setOperationAction(ISD::SMIN, VT, Expand); 652 setOperationAction(ISD::SMAX, VT, Expand); 653 setOperationAction(ISD::UMIN, VT, Expand); 654 setOperationAction(ISD::UMAX, VT, Expand); 655 setOperationAction(ISD::ABS, VT, Expand); 656 setOperationAction(ISD::FSHL, VT, Expand); 657 setOperationAction(ISD::FSHR, VT, Expand); 658 setOperationAction(ISD::SADDSAT, VT, Expand); 659 setOperationAction(ISD::UADDSAT, VT, Expand); 660 setOperationAction(ISD::SSUBSAT, VT, Expand); 661 setOperationAction(ISD::USUBSAT, VT, Expand); 662 setOperationAction(ISD::SMULFIX, VT, Expand); 663 setOperationAction(ISD::SMULFIXSAT, VT, Expand); 664 setOperationAction(ISD::UMULFIX, VT, Expand); 665 setOperationAction(ISD::UMULFIXSAT, VT, Expand); 666 setOperationAction(ISD::SDIVFIX, VT, Expand); 667 setOperationAction(ISD::UDIVFIX, VT, Expand); 668 669 // Overflow operations default to expand 670 setOperationAction(ISD::SADDO, VT, Expand); 671 setOperationAction(ISD::SSUBO, VT, Expand); 672 setOperationAction(ISD::UADDO, VT, Expand); 673 setOperationAction(ISD::USUBO, VT, Expand); 674 setOperationAction(ISD::SMULO, VT, Expand); 675 setOperationAction(ISD::UMULO, VT, Expand); 676 677 // ADDCARRY operations default to expand 678 setOperationAction(ISD::ADDCARRY, VT, Expand); 679 setOperationAction(ISD::SUBCARRY, VT, Expand); 680 setOperationAction(ISD::SETCCCARRY, VT, Expand); 681 682 // ADDC/ADDE/SUBC/SUBE default to expand. 683 setOperationAction(ISD::ADDC, VT, Expand); 684 setOperationAction(ISD::ADDE, VT, Expand); 685 setOperationAction(ISD::SUBC, VT, Expand); 686 setOperationAction(ISD::SUBE, VT, Expand); 687 688 // These default to Expand so they will be expanded to CTLZ/CTTZ by default. 689 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 691 692 setOperationAction(ISD::BITREVERSE, VT, Expand); 693 694 // These library functions default to expand. 695 setOperationAction(ISD::FROUND, VT, Expand); 696 setOperationAction(ISD::FPOWI, VT, Expand); 697 698 // These operations default to expand for vector types. 699 if (VT.isVector()) { 700 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 701 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 702 setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand); 703 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand); 704 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand); 705 setOperationAction(ISD::SPLAT_VECTOR, VT, Expand); 706 } 707 708 // Constrained floating-point operations default to expand. 709 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 710 setOperationAction(ISD::STRICT_##DAGN, VT, Expand); 711 #include "llvm/IR/ConstrainedOps.def" 712 713 // For most targets @llvm.get.dynamic.area.offset just returns 0. 714 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand); 715 716 // Vector reduction default to expand. 717 setOperationAction(ISD::VECREDUCE_FADD, VT, Expand); 718 setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand); 719 setOperationAction(ISD::VECREDUCE_ADD, VT, Expand); 720 setOperationAction(ISD::VECREDUCE_MUL, VT, Expand); 721 setOperationAction(ISD::VECREDUCE_AND, VT, Expand); 722 setOperationAction(ISD::VECREDUCE_OR, VT, Expand); 723 setOperationAction(ISD::VECREDUCE_XOR, VT, Expand); 724 setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand); 725 setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand); 726 setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand); 727 setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand); 728 setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand); 729 setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand); 730 } 731 732 // Most targets ignore the @llvm.prefetch intrinsic. 733 setOperationAction(ISD::PREFETCH, MVT::Other, Expand); 734 735 // Most targets also ignore the @llvm.readcyclecounter intrinsic. 736 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand); 737 738 // ConstantFP nodes default to expand. Targets can either change this to 739 // Legal, in which case all fp constants are legal, or use isFPImmLegal() 740 // to optimize expansions for certain constants. 741 setOperationAction(ISD::ConstantFP, MVT::f16, Expand); 742 setOperationAction(ISD::ConstantFP, MVT::f32, Expand); 743 setOperationAction(ISD::ConstantFP, MVT::f64, Expand); 744 setOperationAction(ISD::ConstantFP, MVT::f80, Expand); 745 setOperationAction(ISD::ConstantFP, MVT::f128, Expand); 746 747 // These library functions default to expand. 748 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) { 749 setOperationAction(ISD::FCBRT, VT, Expand); 750 setOperationAction(ISD::FLOG , VT, Expand); 751 setOperationAction(ISD::FLOG2, VT, Expand); 752 setOperationAction(ISD::FLOG10, VT, Expand); 753 setOperationAction(ISD::FEXP , VT, Expand); 754 setOperationAction(ISD::FEXP2, VT, Expand); 755 setOperationAction(ISD::FFLOOR, VT, Expand); 756 setOperationAction(ISD::FNEARBYINT, VT, Expand); 757 setOperationAction(ISD::FCEIL, VT, Expand); 758 setOperationAction(ISD::FRINT, VT, Expand); 759 setOperationAction(ISD::FTRUNC, VT, Expand); 760 setOperationAction(ISD::FROUND, VT, Expand); 761 setOperationAction(ISD::LROUND, VT, Expand); 762 setOperationAction(ISD::LLROUND, VT, Expand); 763 setOperationAction(ISD::LRINT, VT, Expand); 764 setOperationAction(ISD::LLRINT, VT, Expand); 765 } 766 767 // Default ISD::TRAP to expand (which turns it into abort). 768 setOperationAction(ISD::TRAP, MVT::Other, Expand); 769 770 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand" 771 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP. 772 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand); 773 } 774 775 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL, 776 EVT) const { 777 return MVT::getIntegerVT(DL.getPointerSizeInBits(0)); 778 } 779 780 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL, 781 bool LegalTypes) const { 782 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 783 if (LHSTy.isVector()) 784 return LHSTy; 785 return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy) 786 : getPointerTy(DL); 787 } 788 789 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const { 790 assert(isTypeLegal(VT)); 791 switch (Op) { 792 default: 793 return false; 794 case ISD::SDIV: 795 case ISD::UDIV: 796 case ISD::SREM: 797 case ISD::UREM: 798 return true; 799 } 800 } 801 802 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) { 803 // If the command-line option was specified, ignore this request. 804 if (!JumpIsExpensiveOverride.getNumOccurrences()) 805 JumpIsExpensive = isExpensive; 806 } 807 808 TargetLoweringBase::LegalizeKind 809 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const { 810 // If this is a simple type, use the ComputeRegisterProp mechanism. 811 if (VT.isSimple()) { 812 MVT SVT = VT.getSimpleVT(); 813 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType)); 814 MVT NVT = TransformToType[SVT.SimpleTy]; 815 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT); 816 817 assert((LA == TypeLegal || LA == TypeSoftenFloat || 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 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32]; 1237 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32]; 1238 TransformToType[MVT::f16] = MVT::f32; 1239 ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat); 1240 } 1241 1242 // Loop over all of the vector value types to see which need transformations. 1243 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE; 1244 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1245 MVT VT = (MVT::SimpleValueType) i; 1246 if (isTypeLegal(VT)) 1247 continue; 1248 1249 MVT EltVT = VT.getVectorElementType(); 1250 unsigned NElts = VT.getVectorNumElements(); 1251 bool IsLegalWiderType = false; 1252 bool IsScalable = VT.isScalableVector(); 1253 LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT); 1254 switch (PreferredAction) { 1255 case TypePromoteInteger: { 1256 MVT::SimpleValueType EndVT = IsScalable ? 1257 MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE : 1258 MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE; 1259 // Try to promote the elements of integer vectors. If no legal 1260 // promotion was found, fall through to the widen-vector method. 1261 for (unsigned nVT = i + 1; 1262 (MVT::SimpleValueType)nVT <= EndVT; ++nVT) { 1263 MVT SVT = (MVT::SimpleValueType) nVT; 1264 // Promote vectors of integers to vectors with the same number 1265 // of elements, with a wider element type. 1266 if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() && 1267 SVT.getVectorNumElements() == NElts && 1268 SVT.isScalableVector() == IsScalable && isTypeLegal(SVT)) { 1269 TransformToType[i] = SVT; 1270 RegisterTypeForVT[i] = SVT; 1271 NumRegistersForVT[i] = 1; 1272 ValueTypeActions.setTypeAction(VT, TypePromoteInteger); 1273 IsLegalWiderType = true; 1274 break; 1275 } 1276 } 1277 if (IsLegalWiderType) 1278 break; 1279 LLVM_FALLTHROUGH; 1280 } 1281 1282 case TypeWidenVector: 1283 if (isPowerOf2_32(NElts)) { 1284 // Try to widen the vector. 1285 for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) { 1286 MVT SVT = (MVT::SimpleValueType) nVT; 1287 if (SVT.getVectorElementType() == EltVT 1288 && SVT.getVectorNumElements() > NElts 1289 && SVT.isScalableVector() == IsScalable && isTypeLegal(SVT)) { 1290 TransformToType[i] = SVT; 1291 RegisterTypeForVT[i] = SVT; 1292 NumRegistersForVT[i] = 1; 1293 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1294 IsLegalWiderType = true; 1295 break; 1296 } 1297 } 1298 if (IsLegalWiderType) 1299 break; 1300 } else { 1301 // Only widen to the next power of 2 to keep consistency with EVT. 1302 MVT NVT = VT.getPow2VectorType(); 1303 if (isTypeLegal(NVT)) { 1304 TransformToType[i] = NVT; 1305 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1306 RegisterTypeForVT[i] = NVT; 1307 NumRegistersForVT[i] = 1; 1308 break; 1309 } 1310 } 1311 LLVM_FALLTHROUGH; 1312 1313 case TypeSplitVector: 1314 case TypeScalarizeVector: { 1315 MVT IntermediateVT; 1316 MVT RegisterVT; 1317 unsigned NumIntermediates; 1318 unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT, 1319 NumIntermediates, RegisterVT, this); 1320 NumRegistersForVT[i] = NumRegisters; 1321 assert(NumRegistersForVT[i] == NumRegisters && 1322 "NumRegistersForVT size cannot represent NumRegisters!"); 1323 RegisterTypeForVT[i] = RegisterVT; 1324 1325 MVT NVT = VT.getPow2VectorType(); 1326 if (NVT == VT) { 1327 // Type is already a power of 2. The default action is to split. 1328 TransformToType[i] = MVT::Other; 1329 if (PreferredAction == TypeScalarizeVector) 1330 ValueTypeActions.setTypeAction(VT, TypeScalarizeVector); 1331 else if (PreferredAction == TypeSplitVector) 1332 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1333 else 1334 // Set type action according to the number of elements. 1335 ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector 1336 : TypeSplitVector); 1337 } else { 1338 TransformToType[i] = NVT; 1339 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1340 } 1341 break; 1342 } 1343 default: 1344 llvm_unreachable("Unknown vector legalization action!"); 1345 } 1346 } 1347 1348 // Determine the 'representative' register class for each value type. 1349 // An representative register class is the largest (meaning one which is 1350 // not a sub-register class / subreg register class) legal register class for 1351 // a group of value types. For example, on i386, i8, i16, and i32 1352 // representative would be GR32; while on x86_64 it's GR64. 1353 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) { 1354 const TargetRegisterClass* RRC; 1355 uint8_t Cost; 1356 std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i); 1357 RepRegClassForVT[i] = RRC; 1358 RepRegClassCostForVT[i] = Cost; 1359 } 1360 } 1361 1362 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1363 EVT VT) const { 1364 assert(!VT.isVector() && "No default SetCC type for vectors!"); 1365 return getPointerTy(DL).SimpleTy; 1366 } 1367 1368 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const { 1369 return MVT::i32; // return the default value 1370 } 1371 1372 /// getVectorTypeBreakdown - Vector types are broken down into some number of 1373 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32 1374 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack. 1375 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86. 1376 /// 1377 /// This method returns the number of registers needed, and the VT for each 1378 /// register. It also returns the VT and quantity of the intermediate values 1379 /// before they are promoted/expanded. 1380 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT, 1381 EVT &IntermediateVT, 1382 unsigned &NumIntermediates, 1383 MVT &RegisterVT) const { 1384 unsigned NumElts = VT.getVectorNumElements(); 1385 1386 // If there is a wider vector type with the same element type as this one, 1387 // or a promoted vector type that has the same number of elements which 1388 // are wider, then we should convert to that legal vector type. 1389 // This handles things like <2 x float> -> <4 x float> and 1390 // <4 x i1> -> <4 x i32>. 1391 LegalizeTypeAction TA = getTypeAction(Context, VT); 1392 if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) { 1393 EVT RegisterEVT = getTypeToTransformTo(Context, VT); 1394 if (isTypeLegal(RegisterEVT)) { 1395 IntermediateVT = RegisterEVT; 1396 RegisterVT = RegisterEVT.getSimpleVT(); 1397 NumIntermediates = 1; 1398 return 1; 1399 } 1400 } 1401 1402 // Figure out the right, legal destination reg to copy into. 1403 EVT EltTy = VT.getVectorElementType(); 1404 1405 unsigned NumVectorRegs = 1; 1406 1407 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we 1408 // could break down into LHS/RHS like LegalizeDAG does. 1409 if (!isPowerOf2_32(NumElts)) { 1410 NumVectorRegs = NumElts; 1411 NumElts = 1; 1412 } 1413 1414 // Divide the input until we get to a supported size. This will always 1415 // end with a scalar if the target doesn't support vectors. 1416 while (NumElts > 1 && !isTypeLegal( 1417 EVT::getVectorVT(Context, EltTy, NumElts))) { 1418 NumElts >>= 1; 1419 NumVectorRegs <<= 1; 1420 } 1421 1422 NumIntermediates = NumVectorRegs; 1423 1424 EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts); 1425 if (!isTypeLegal(NewVT)) 1426 NewVT = EltTy; 1427 IntermediateVT = NewVT; 1428 1429 MVT DestVT = getRegisterType(Context, NewVT); 1430 RegisterVT = DestVT; 1431 unsigned NewVTSize = NewVT.getSizeInBits(); 1432 1433 // Convert sizes such as i33 to i64. 1434 if (!isPowerOf2_32(NewVTSize)) 1435 NewVTSize = NextPowerOf2(NewVTSize); 1436 1437 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16. 1438 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits()); 1439 1440 // Otherwise, promotion or legal types use the same number of registers as 1441 // the vector decimated to the appropriate level. 1442 return NumVectorRegs; 1443 } 1444 1445 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI, 1446 uint64_t NumCases, 1447 uint64_t Range, 1448 ProfileSummaryInfo *PSI, 1449 BlockFrequencyInfo *BFI) const { 1450 // FIXME: This function check the maximum table size and density, but the 1451 // minimum size is not checked. It would be nice if the minimum size is 1452 // also combined within this function. Currently, the minimum size check is 1453 // performed in findJumpTable() in SelectionDAGBuiler and 1454 // getEstimatedNumberOfCaseClusters() in BasicTTIImpl. 1455 const bool OptForSize = 1456 SI->getParent()->getParent()->hasOptSize() || 1457 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI); 1458 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize); 1459 const unsigned MaxJumpTableSize = getMaximumJumpTableSize(); 1460 1461 // Check whether the number of cases is small enough and 1462 // the range is dense enough for a jump table. 1463 return (OptForSize || Range <= MaxJumpTableSize) && 1464 (NumCases * 100 >= Range * MinDensity); 1465 } 1466 1467 /// Get the EVTs and ArgFlags collections that represent the legalized return 1468 /// type of the given function. This does not require a DAG or a return value, 1469 /// and is suitable for use before any DAGs for the function are constructed. 1470 /// TODO: Move this out of TargetLowering.cpp. 1471 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType, 1472 AttributeList attr, 1473 SmallVectorImpl<ISD::OutputArg> &Outs, 1474 const TargetLowering &TLI, const DataLayout &DL) { 1475 SmallVector<EVT, 4> ValueVTs; 1476 ComputeValueVTs(TLI, DL, ReturnType, ValueVTs); 1477 unsigned NumValues = ValueVTs.size(); 1478 if (NumValues == 0) return; 1479 1480 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1481 EVT VT = ValueVTs[j]; 1482 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1483 1484 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 1485 ExtendKind = ISD::SIGN_EXTEND; 1486 else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt)) 1487 ExtendKind = ISD::ZERO_EXTEND; 1488 1489 // FIXME: C calling convention requires the return type to be promoted to 1490 // at least 32-bit. But this is not necessary for non-C calling 1491 // conventions. The frontend should mark functions whose return values 1492 // require promoting with signext or zeroext attributes. 1493 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 1494 MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32); 1495 if (VT.bitsLT(MinVT)) 1496 VT = MinVT; 1497 } 1498 1499 unsigned NumParts = 1500 TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT); 1501 MVT PartVT = 1502 TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT); 1503 1504 // 'inreg' on function refers to return value 1505 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1506 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg)) 1507 Flags.setInReg(); 1508 1509 // Propagate extension type if any 1510 if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 1511 Flags.setSExt(); 1512 else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt)) 1513 Flags.setZExt(); 1514 1515 for (unsigned i = 0; i < NumParts; ++i) 1516 Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isfixed=*/true, 0, 0)); 1517 } 1518 } 1519 1520 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1521 /// function arguments in the caller parameter area. This is the actual 1522 /// alignment, not its logarithm. 1523 unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty, 1524 const DataLayout &DL) const { 1525 return DL.getABITypeAlignment(Ty); 1526 } 1527 1528 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1529 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, 1530 unsigned Alignment, MachineMemOperand::Flags Flags, bool *Fast) const { 1531 // Check if the specified alignment is sufficient based on the data layout. 1532 // TODO: While using the data layout works in practice, a better solution 1533 // would be to implement this check directly (make this a virtual function). 1534 // For example, the ABI alignment may change based on software platform while 1535 // this function should only be affected by hardware implementation. 1536 Type *Ty = VT.getTypeForEVT(Context); 1537 if (Alignment >= DL.getABITypeAlignment(Ty)) { 1538 // Assume that an access that meets the ABI-specified alignment is fast. 1539 if (Fast != nullptr) 1540 *Fast = true; 1541 return true; 1542 } 1543 1544 // This is a misaligned access. 1545 return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast); 1546 } 1547 1548 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1549 LLVMContext &Context, const DataLayout &DL, EVT VT, 1550 const MachineMemOperand &MMO, bool *Fast) const { 1551 return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(), 1552 MMO.getAlignment(), MMO.getFlags(), 1553 Fast); 1554 } 1555 1556 bool TargetLoweringBase::allowsMemoryAccess( 1557 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, 1558 unsigned Alignment, MachineMemOperand::Flags Flags, bool *Fast) const { 1559 return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment, 1560 Flags, Fast); 1561 } 1562 1563 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1564 const DataLayout &DL, EVT VT, 1565 const MachineMemOperand &MMO, 1566 bool *Fast) const { 1567 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), 1568 MMO.getAlignment(), MMO.getFlags(), Fast); 1569 } 1570 1571 BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const { 1572 return BranchProbability(MinPercentageForPredictableBranch, 100); 1573 } 1574 1575 //===----------------------------------------------------------------------===// 1576 // TargetTransformInfo Helpers 1577 //===----------------------------------------------------------------------===// 1578 1579 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const { 1580 enum InstructionOpcodes { 1581 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM, 1582 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM 1583 #include "llvm/IR/Instruction.def" 1584 }; 1585 switch (static_cast<InstructionOpcodes>(Opcode)) { 1586 case Ret: return 0; 1587 case Br: return 0; 1588 case Switch: return 0; 1589 case IndirectBr: return 0; 1590 case Invoke: return 0; 1591 case CallBr: return 0; 1592 case Resume: return 0; 1593 case Unreachable: return 0; 1594 case CleanupRet: return 0; 1595 case CatchRet: return 0; 1596 case CatchPad: return 0; 1597 case CatchSwitch: return 0; 1598 case CleanupPad: return 0; 1599 case FNeg: return ISD::FNEG; 1600 case Add: return ISD::ADD; 1601 case FAdd: return ISD::FADD; 1602 case Sub: return ISD::SUB; 1603 case FSub: return ISD::FSUB; 1604 case Mul: return ISD::MUL; 1605 case FMul: return ISD::FMUL; 1606 case UDiv: return ISD::UDIV; 1607 case SDiv: return ISD::SDIV; 1608 case FDiv: return ISD::FDIV; 1609 case URem: return ISD::UREM; 1610 case SRem: return ISD::SREM; 1611 case FRem: return ISD::FREM; 1612 case Shl: return ISD::SHL; 1613 case LShr: return ISD::SRL; 1614 case AShr: return ISD::SRA; 1615 case And: return ISD::AND; 1616 case Or: return ISD::OR; 1617 case Xor: return ISD::XOR; 1618 case Alloca: return 0; 1619 case Load: return ISD::LOAD; 1620 case Store: return ISD::STORE; 1621 case GetElementPtr: return 0; 1622 case Fence: return 0; 1623 case AtomicCmpXchg: return 0; 1624 case AtomicRMW: return 0; 1625 case Trunc: return ISD::TRUNCATE; 1626 case ZExt: return ISD::ZERO_EXTEND; 1627 case SExt: return ISD::SIGN_EXTEND; 1628 case FPToUI: return ISD::FP_TO_UINT; 1629 case FPToSI: return ISD::FP_TO_SINT; 1630 case UIToFP: return ISD::UINT_TO_FP; 1631 case SIToFP: return ISD::SINT_TO_FP; 1632 case FPTrunc: return ISD::FP_ROUND; 1633 case FPExt: return ISD::FP_EXTEND; 1634 case PtrToInt: return ISD::BITCAST; 1635 case IntToPtr: return ISD::BITCAST; 1636 case BitCast: return ISD::BITCAST; 1637 case AddrSpaceCast: return ISD::ADDRSPACECAST; 1638 case ICmp: return ISD::SETCC; 1639 case FCmp: return ISD::SETCC; 1640 case PHI: return 0; 1641 case Call: return 0; 1642 case Select: return ISD::SELECT; 1643 case UserOp1: return 0; 1644 case UserOp2: return 0; 1645 case VAArg: return 0; 1646 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT; 1647 case InsertElement: return ISD::INSERT_VECTOR_ELT; 1648 case ShuffleVector: return ISD::VECTOR_SHUFFLE; 1649 case ExtractValue: return ISD::MERGE_VALUES; 1650 case InsertValue: return ISD::MERGE_VALUES; 1651 case LandingPad: return 0; 1652 case Freeze: return 0; 1653 } 1654 1655 llvm_unreachable("Unknown instruction type encountered!"); 1656 } 1657 1658 std::pair<int, MVT> 1659 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL, 1660 Type *Ty) const { 1661 LLVMContext &C = Ty->getContext(); 1662 EVT MTy = getValueType(DL, Ty); 1663 1664 int Cost = 1; 1665 // We keep legalizing the type until we find a legal kind. We assume that 1666 // the only operation that costs anything is the split. After splitting 1667 // we need to handle two types. 1668 while (true) { 1669 LegalizeKind LK = getTypeConversion(C, MTy); 1670 1671 if (LK.first == TypeLegal) 1672 return std::make_pair(Cost, MTy.getSimpleVT()); 1673 1674 if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger) 1675 Cost *= 2; 1676 1677 // Do not loop with f128 type. 1678 if (MTy == LK.second) 1679 return std::make_pair(Cost, MTy.getSimpleVT()); 1680 1681 // Keep legalizing the type. 1682 MTy = LK.second; 1683 } 1684 } 1685 1686 Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB, 1687 bool UseTLS) const { 1688 // compiler-rt provides a variable with a magic name. Targets that do not 1689 // link with compiler-rt may also provide such a variable. 1690 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 1691 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; 1692 auto UnsafeStackPtr = 1693 dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar)); 1694 1695 Type *StackPtrTy = Type::getInt8PtrTy(M->getContext()); 1696 1697 if (!UnsafeStackPtr) { 1698 auto TLSModel = UseTLS ? 1699 GlobalValue::InitialExecTLSModel : 1700 GlobalValue::NotThreadLocal; 1701 // The global variable is not defined yet, define it ourselves. 1702 // We use the initial-exec TLS model because we do not support the 1703 // variable living anywhere other than in the main executable. 1704 UnsafeStackPtr = new GlobalVariable( 1705 *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr, 1706 UnsafeStackPtrVar, nullptr, TLSModel); 1707 } else { 1708 // The variable exists, check its type and attributes. 1709 if (UnsafeStackPtr->getValueType() != StackPtrTy) 1710 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type"); 1711 if (UseTLS != UnsafeStackPtr->isThreadLocal()) 1712 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " + 1713 (UseTLS ? "" : "not ") + "be thread-local"); 1714 } 1715 return UnsafeStackPtr; 1716 } 1717 1718 Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 1719 if (!TM.getTargetTriple().isAndroid()) 1720 return getDefaultSafeStackPointerLocation(IRB, true); 1721 1722 // Android provides a libc function to retrieve the address of the current 1723 // thread's unsafe stack pointer. 1724 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 1725 Type *StackPtrTy = Type::getInt8PtrTy(M->getContext()); 1726 FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address", 1727 StackPtrTy->getPointerTo(0)); 1728 return IRB.CreateCall(Fn); 1729 } 1730 1731 //===----------------------------------------------------------------------===// 1732 // Loop Strength Reduction hooks 1733 //===----------------------------------------------------------------------===// 1734 1735 /// isLegalAddressingMode - Return true if the addressing mode represented 1736 /// by AM is legal for this target, for a load/store of the specified type. 1737 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL, 1738 const AddrMode &AM, Type *Ty, 1739 unsigned AS, Instruction *I) const { 1740 // The default implementation of this implements a conservative RISCy, r+r and 1741 // r+i addr mode. 1742 1743 // Allows a sign-extended 16-bit immediate field. 1744 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 1745 return false; 1746 1747 // No global is ever allowed as a base. 1748 if (AM.BaseGV) 1749 return false; 1750 1751 // Only support r+r, 1752 switch (AM.Scale) { 1753 case 0: // "r+i" or just "i", depending on HasBaseReg. 1754 break; 1755 case 1: 1756 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 1757 return false; 1758 // Otherwise we have r+r or r+i. 1759 break; 1760 case 2: 1761 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 1762 return false; 1763 // Allow 2*r as r+r. 1764 break; 1765 default: // Don't allow n * r 1766 return false; 1767 } 1768 1769 return true; 1770 } 1771 1772 //===----------------------------------------------------------------------===// 1773 // Stack Protector 1774 //===----------------------------------------------------------------------===// 1775 1776 // For OpenBSD return its special guard variable. Otherwise return nullptr, 1777 // so that SelectionDAG handle SSP. 1778 Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const { 1779 if (getTargetMachine().getTargetTriple().isOSOpenBSD()) { 1780 Module &M = *IRB.GetInsertBlock()->getParent()->getParent(); 1781 PointerType *PtrTy = Type::getInt8PtrTy(M.getContext()); 1782 return M.getOrInsertGlobal("__guard_local", PtrTy); 1783 } 1784 return nullptr; 1785 } 1786 1787 // Currently only support "standard" __stack_chk_guard. 1788 // TODO: add LOAD_STACK_GUARD support. 1789 void TargetLoweringBase::insertSSPDeclarations(Module &M) const { 1790 if (!M.getNamedValue("__stack_chk_guard")) 1791 new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false, 1792 GlobalVariable::ExternalLinkage, 1793 nullptr, "__stack_chk_guard"); 1794 } 1795 1796 // Currently only support "standard" __stack_chk_guard. 1797 // TODO: add LOAD_STACK_GUARD support. 1798 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const { 1799 return M.getNamedValue("__stack_chk_guard"); 1800 } 1801 1802 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const { 1803 return nullptr; 1804 } 1805 1806 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const { 1807 return MinimumJumpTableEntries; 1808 } 1809 1810 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) { 1811 MinimumJumpTableEntries = Val; 1812 } 1813 1814 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const { 1815 return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity; 1816 } 1817 1818 unsigned TargetLoweringBase::getMaximumJumpTableSize() const { 1819 return MaximumJumpTableSize; 1820 } 1821 1822 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) { 1823 MaximumJumpTableSize = Val; 1824 } 1825 1826 //===----------------------------------------------------------------------===// 1827 // Reciprocal Estimates 1828 //===----------------------------------------------------------------------===// 1829 1830 /// Get the reciprocal estimate attribute string for a function that will 1831 /// override the target defaults. 1832 static StringRef getRecipEstimateForFunc(MachineFunction &MF) { 1833 const Function &F = MF.getFunction(); 1834 return F.getFnAttribute("reciprocal-estimates").getValueAsString(); 1835 } 1836 1837 /// Construct a string for the given reciprocal operation of the given type. 1838 /// This string should match the corresponding option to the front-end's 1839 /// "-mrecip" flag assuming those strings have been passed through in an 1840 /// attribute string. For example, "vec-divf" for a division of a vXf32. 1841 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) { 1842 std::string Name = VT.isVector() ? "vec-" : ""; 1843 1844 Name += IsSqrt ? "sqrt" : "div"; 1845 1846 // TODO: Handle "half" or other float types? 1847 if (VT.getScalarType() == MVT::f64) { 1848 Name += "d"; 1849 } else { 1850 assert(VT.getScalarType() == MVT::f32 && 1851 "Unexpected FP type for reciprocal estimate"); 1852 Name += "f"; 1853 } 1854 1855 return Name; 1856 } 1857 1858 /// Return the character position and value (a single numeric character) of a 1859 /// customized refinement operation in the input string if it exists. Return 1860 /// false if there is no customized refinement step count. 1861 static bool parseRefinementStep(StringRef In, size_t &Position, 1862 uint8_t &Value) { 1863 const char RefStepToken = ':'; 1864 Position = In.find(RefStepToken); 1865 if (Position == StringRef::npos) 1866 return false; 1867 1868 StringRef RefStepString = In.substr(Position + 1); 1869 // Allow exactly one numeric character for the additional refinement 1870 // step parameter. 1871 if (RefStepString.size() == 1) { 1872 char RefStepChar = RefStepString[0]; 1873 if (RefStepChar >= '0' && RefStepChar <= '9') { 1874 Value = RefStepChar - '0'; 1875 return true; 1876 } 1877 } 1878 report_fatal_error("Invalid refinement step for -recip."); 1879 } 1880 1881 /// For the input attribute string, return one of the ReciprocalEstimate enum 1882 /// status values (enabled, disabled, or not specified) for this operation on 1883 /// the specified data type. 1884 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) { 1885 if (Override.empty()) 1886 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 1887 1888 SmallVector<StringRef, 4> OverrideVector; 1889 Override.split(OverrideVector, ','); 1890 unsigned NumArgs = OverrideVector.size(); 1891 1892 // Check if "all", "none", or "default" was specified. 1893 if (NumArgs == 1) { 1894 // Look for an optional setting of the number of refinement steps needed 1895 // for this type of reciprocal operation. 1896 size_t RefPos; 1897 uint8_t RefSteps; 1898 if (parseRefinementStep(Override, RefPos, RefSteps)) { 1899 // Split the string for further processing. 1900 Override = Override.substr(0, RefPos); 1901 } 1902 1903 // All reciprocal types are enabled. 1904 if (Override == "all") 1905 return TargetLoweringBase::ReciprocalEstimate::Enabled; 1906 1907 // All reciprocal types are disabled. 1908 if (Override == "none") 1909 return TargetLoweringBase::ReciprocalEstimate::Disabled; 1910 1911 // Target defaults for enablement are used. 1912 if (Override == "default") 1913 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 1914 } 1915 1916 // The attribute string may omit the size suffix ('f'/'d'). 1917 std::string VTName = getReciprocalOpName(IsSqrt, VT); 1918 std::string VTNameNoSize = VTName; 1919 VTNameNoSize.pop_back(); 1920 static const char DisabledPrefix = '!'; 1921 1922 for (StringRef RecipType : OverrideVector) { 1923 size_t RefPos; 1924 uint8_t RefSteps; 1925 if (parseRefinementStep(RecipType, RefPos, RefSteps)) 1926 RecipType = RecipType.substr(0, RefPos); 1927 1928 // Ignore the disablement token for string matching. 1929 bool IsDisabled = RecipType[0] == DisabledPrefix; 1930 if (IsDisabled) 1931 RecipType = RecipType.substr(1); 1932 1933 if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize)) 1934 return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled 1935 : TargetLoweringBase::ReciprocalEstimate::Enabled; 1936 } 1937 1938 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 1939 } 1940 1941 /// For the input attribute string, return the customized refinement step count 1942 /// for this operation on the specified data type. If the step count does not 1943 /// exist, return the ReciprocalEstimate enum value for unspecified. 1944 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) { 1945 if (Override.empty()) 1946 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 1947 1948 SmallVector<StringRef, 4> OverrideVector; 1949 Override.split(OverrideVector, ','); 1950 unsigned NumArgs = OverrideVector.size(); 1951 1952 // Check if "all", "default", or "none" was specified. 1953 if (NumArgs == 1) { 1954 // Look for an optional setting of the number of refinement steps needed 1955 // for this type of reciprocal operation. 1956 size_t RefPos; 1957 uint8_t RefSteps; 1958 if (!parseRefinementStep(Override, RefPos, RefSteps)) 1959 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 1960 1961 // Split the string for further processing. 1962 Override = Override.substr(0, RefPos); 1963 assert(Override != "none" && 1964 "Disabled reciprocals, but specifed refinement steps?"); 1965 1966 // If this is a general override, return the specified number of steps. 1967 if (Override == "all" || Override == "default") 1968 return RefSteps; 1969 } 1970 1971 // The attribute string may omit the size suffix ('f'/'d'). 1972 std::string VTName = getReciprocalOpName(IsSqrt, VT); 1973 std::string VTNameNoSize = VTName; 1974 VTNameNoSize.pop_back(); 1975 1976 for (StringRef RecipType : OverrideVector) { 1977 size_t RefPos; 1978 uint8_t RefSteps; 1979 if (!parseRefinementStep(RecipType, RefPos, RefSteps)) 1980 continue; 1981 1982 RecipType = RecipType.substr(0, RefPos); 1983 if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize)) 1984 return RefSteps; 1985 } 1986 1987 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 1988 } 1989 1990 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT, 1991 MachineFunction &MF) const { 1992 return getOpEnabled(true, VT, getRecipEstimateForFunc(MF)); 1993 } 1994 1995 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT, 1996 MachineFunction &MF) const { 1997 return getOpEnabled(false, VT, getRecipEstimateForFunc(MF)); 1998 } 1999 2000 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT, 2001 MachineFunction &MF) const { 2002 return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF)); 2003 } 2004 2005 int TargetLoweringBase::getDivRefinementSteps(EVT VT, 2006 MachineFunction &MF) const { 2007 return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF)); 2008 } 2009 2010 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const { 2011 MF.getRegInfo().freezeReservedRegs(MF); 2012 } 2013