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