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