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