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