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