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