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