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