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