1//===--- TargetInfo.cpp - Information about Target machine ----------------===//
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 file implements the TargetInfo interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Basic/TargetInfo.h"
14#include "clang/Basic/AddressSpaces.h"
15#include "clang/Basic/CharInfo.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticFrontend.h"
18#include "clang/Basic/LangOptions.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/TargetParser/TargetParser.h"
25#include "llvm/TargetParser/Triple.h"
26#include <cstdlib>
27using namespace clang;
28
29static constexpr LangASMap DefaultAddrSpaceMap;
30// The fake address space map must have a distinct entry for each
31// language-specific address space.
32static constexpr LangASMap FakeAddrSpaceMap = {
33 {LangAS::Default, 0},
34 {LangAS::opencl_global, 1},
35 {LangAS::opencl_local, 3},
36 {LangAS::opencl_constant, 2},
37 {LangAS::opencl_private, 0},
38 {LangAS::opencl_generic, 4},
39 {LangAS::opencl_global_device, 5},
40 {LangAS::opencl_global_host, 6},
41 {LangAS::cuda_device, 7},
42 {LangAS::cuda_constant, 8},
43 {LangAS::cuda_shared, 9},
44 {LangAS::sycl_global, 1},
45 {LangAS::sycl_global_device, 5},
46 {LangAS::sycl_global_host, 6},
47 {LangAS::sycl_local, 3},
48 {LangAS::sycl_private, 0},
49 {LangAS::ptr32_sptr, 10},
50 {LangAS::ptr32_uptr, 11},
51 {LangAS::ptr64, 12},
52 {LangAS::hlsl_groupshared, 13},
53 {LangAS::hlsl_constant, 14},
54 {LangAS::hlsl_private, 15},
55 {LangAS::hlsl_device, 16},
56 {LangAS::hlsl_input, 17},
57 {LangAS::hlsl_output, 18},
58 {LangAS::hlsl_push_constant, 19},
59 {LangAS::wasm_funcref, 20},
60 {LangAS::amdgpu_barrier, 21},
61};
62
63// TargetInfo Constructor.
64TargetInfo::TargetInfo(const llvm::Triple &T) : Triple(T) {
65 // Set defaults. Defaults are set for a 32-bit RISC platform, like PPC or
66 // SPARC. These should be overridden by concrete targets as needed.
67 HasMustTail = true;
68 BigEndian = !T.isLittleEndian();
69 TLSSupported = true;
70 VLASupported = true;
71 NoAsmVariants = false;
72 HasFastHalfType = false;
73 HalfArgsAndReturns = false;
74 HasFloat128 = false;
75 HasIbm128 = false;
76 HasFloat16 = false;
77 HasBFloat16 = false;
78 HasFullBFloat16 = false;
79 HasLongDouble = true;
80 HasFPReturn = true;
81 HasStrictFP = false;
82 PointerWidth = PointerAlign = 32;
83 BoolWidth = BoolAlign = 8;
84 ShortWidth = ShortAlign = 16;
85 IntWidth = IntAlign = 32;
86 LongWidth = LongAlign = 32;
87 LongLongWidth = LongLongAlign = 64;
88 Int128Align = 128;
89
90 // Fixed point default bit widths
91 ShortAccumWidth = ShortAccumAlign = 16;
92 AccumWidth = AccumAlign = 32;
93 LongAccumWidth = LongAccumAlign = 64;
94 ShortFractWidth = ShortFractAlign = 8;
95 FractWidth = FractAlign = 16;
96 LongFractWidth = LongFractAlign = 32;
97
98 // Fixed point default integral and fractional bit sizes
99 // We give the _Accum 1 fewer fractional bits than their corresponding _Fract
100 // types by default to have the same number of fractional bits between _Accum
101 // and _Fract types.
102 PaddingOnUnsignedFixedPoint = false;
103 ShortAccumScale = 7;
104 AccumScale = 15;
105 LongAccumScale = 31;
106
107 SuitableAlign = 64;
108 DefaultAlignForAttributeAligned = 128;
109 MinGlobalAlign = 0;
110 // From the glibc documentation, on GNU systems, malloc guarantees 16-byte
111 // alignment on 64-bit systems and 8-byte alignment on 32-bit systems. See
112 // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html.
113 // This alignment guarantee also applies to Windows and Android. On Darwin
114 // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit systems.
115 if (T.isGNUEnvironment() || T.isWindowsMSVCEnvironment() || T.isAndroid() ||
116 T.isOHOSFamily())
117 NewAlign = Triple.isArch64Bit() ? 128 : Triple.isArch32Bit() ? 64 : 0;
118 else if (T.isOSDarwin() || T.isOSOpenBSD())
119 NewAlign = 128;
120 else
121 NewAlign = 0; // Infer from basic type alignment.
122 HalfWidth = 16;
123 HalfAlign = 16;
124 FloatWidth = 32;
125 FloatAlign = 32;
126 DoubleWidth = 64;
127 DoubleAlign = 64;
128 LongDoubleWidth = 64;
129 LongDoubleAlign = 64;
130 Float128Align = 128;
131 Ibm128Align = 128;
132 LargeArrayMinWidth = 0;
133 LargeArrayAlign = 0;
134 MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0;
135 MaxVectorAlign = 0;
136 MaxTLSAlign = 0;
137 VectorsAreElementAligned = false;
138 SizeType = UnsignedLong;
139 PtrDiffType = SignedLong;
140 IntMaxType = SignedLongLong;
141 IntPtrType = SignedLong;
142 WCharType = SignedInt;
143 WIntType = SignedInt;
144 Char16Type = UnsignedShort;
145 Char32Type = UnsignedInt;
146 Int64Type = SignedLongLong;
147 Int16Type = SignedShort;
148 SigAtomicType = SignedInt;
149 ProcessIDType = SignedInt;
150 UseSignedCharForObjCBool = true;
151 UseBitFieldTypeAlignment = true;
152 UseZeroLengthBitfieldAlignment = false;
153 UseLeadingZeroLengthBitfield = true;
154 UseExplicitBitFieldAlignment = true;
155 ZeroLengthBitfieldBoundary = 0;
156 LargestOverSizedBitfieldContainer = 64;
157 MaxAlignedAttribute = 0;
158 HalfFormat = &llvm::APFloat::IEEEhalf();
159 FloatFormat = &llvm::APFloat::IEEEsingle();
160 DoubleFormat = &llvm::APFloat::IEEEdouble();
161 LongDoubleFormat = &llvm::APFloat::IEEEdouble();
162 Float128Format = &llvm::APFloat::IEEEquad();
163 Ibm128Format = &llvm::APFloat::PPCDoubleDouble();
164 MCountName = "mcount";
165 UserLabelPrefix = Triple.isOSBinFormatMachO() ? "_" : "";
166 RegParmMax = 0;
167 SSERegParmMax = 0;
168 HasAlignMac68kSupport = false;
169 HasBuiltinMSVaList = false;
170 HasBuiltinZOSVaList = false;
171 HasAArch64ACLETypes = false;
172 HasRISCVVTypes = false;
173 HasAMDGPUTypes = false;
174 AllowAMDGPUUnsafeFPAtomics = false;
175 HasUnalignedAccess = false;
176 ARMCDECoprocMask = 0;
177
178 // Default to no types using fpret.
179 RealTypeUsesObjCFPRetMask = 0;
180
181 // Default to not using fp2ret for __Complex long double
182 ComplexLongDoubleUsesFP2Ret = false;
183
184 // Set the C++ ABI based on the triple.
185 TheCXXABI.set(Triple.isKnownWindowsMSVCEnvironment() || Triple.isUEFI()
186 ? TargetCXXABI::Microsoft
187 : TargetCXXABI::GenericItanium);
188
189 HasMicrosoftRecordLayout = TheCXXABI.isMicrosoft();
190
191 // Default to an empty address space map.
192 AddrSpaceMap = &DefaultAddrSpaceMap;
193 UseAddrSpaceMapMangling = false;
194
195 // Default to an unknown platform name.
196 PlatformName = "unknown";
197 PlatformMinVersion = VersionTuple();
198
199 MaxOpenCLWorkGroupSize = 1024;
200
201 MaxBitIntWidth.reset();
202}
203
204// Out of line virtual dtor for TargetInfo.
205TargetInfo::~TargetInfo() {}
206
207size_t TargetInfo::getMaxBitIntWidth() const {
208 // Consider -fexperimental-max-bitint-width= first.
209 if (MaxBitIntWidth)
210 return std::min<size_t>(a: *MaxBitIntWidth, b: llvm::IntegerType::MAX_INT_BITS);
211
212 // FIXME: this value should be llvm::IntegerType::MAX_INT_BITS, which is
213 // maximum bit width that LLVM claims its IR can support. However, most
214 // backends currently have a bug where they only support float to int
215 // conversion (and vice versa) on types that are <= 128 bits and crash
216 // otherwise. We're setting the max supported value to 128 to be
217 // conservative.
218 return 128;
219}
220
221void TargetInfo::resetDataLayout(StringRef DL) { DataLayoutString = DL.str(); }
222
223void TargetInfo::resetDataLayout() {
224 DataLayoutString = Triple.computeDataLayout(ABIName: getABI());
225}
226
227bool
228TargetInfo::checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const {
229 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "cf-protection=branch";
230 return false;
231}
232
233CFBranchLabelSchemeKind TargetInfo::getDefaultCFBranchLabelScheme() const {
234 // if this hook is called, the target should override it to return a
235 // non-default scheme
236 llvm::report_fatal_error(reason: "not implemented");
237}
238
239bool TargetInfo::checkCFBranchLabelSchemeSupported(
240 const CFBranchLabelSchemeKind Scheme, DiagnosticsEngine &Diags) const {
241 if (Scheme != CFBranchLabelSchemeKind::Default)
242 Diags.Report(DiagID: diag::err_opt_not_valid_on_target)
243 << (Twine("mcf-branch-label-scheme=") +
244 getCFBranchLabelSchemeFlagVal(Scheme))
245 .str();
246 return false;
247}
248
249bool
250TargetInfo::checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const {
251 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "cf-protection=return";
252 return false;
253}
254
255/// getTypeName - Return the user string for the specified integer type enum.
256/// For example, SignedShort -> "short".
257const char *TargetInfo::getTypeName(IntType T) {
258 switch (T) {
259 default: llvm_unreachable("not an integer!");
260 case SignedChar: return "signed char";
261 case UnsignedChar: return "unsigned char";
262 case SignedShort: return "short";
263 case UnsignedShort: return "unsigned short";
264 case SignedInt: return "int";
265 case UnsignedInt: return "unsigned int";
266 case SignedLong: return "long int";
267 case UnsignedLong: return "long unsigned int";
268 case SignedLongLong: return "long long int";
269 case UnsignedLongLong: return "long long unsigned int";
270 }
271}
272
273/// getTypeConstantSuffix - Return the constant suffix for the specified
274/// integer type enum. For example, SignedLong -> "L".
275const char *TargetInfo::getTypeConstantSuffix(IntType T) const {
276 switch (T) {
277 default: llvm_unreachable("not an integer!");
278 case SignedChar:
279 case SignedShort:
280 case SignedInt: return "";
281 case SignedLong: return "L";
282 case SignedLongLong: return "LL";
283 case UnsignedChar:
284 if (getCharWidth() < getIntWidth())
285 return "";
286 [[fallthrough]];
287 case UnsignedShort:
288 if (getShortWidth() < getIntWidth())
289 return "";
290 [[fallthrough]];
291 case UnsignedInt: return "U";
292 case UnsignedLong: return "UL";
293 case UnsignedLongLong: return "ULL";
294 }
295}
296
297/// getTypeFormatModifier - Return the printf format modifier for the
298/// specified integer type enum. For example, SignedLong -> "l".
299
300const char *TargetInfo::getTypeFormatModifier(IntType T) {
301 switch (T) {
302 default: llvm_unreachable("not an integer!");
303 case SignedChar:
304 case UnsignedChar: return "hh";
305 case SignedShort:
306 case UnsignedShort: return "h";
307 case SignedInt:
308 case UnsignedInt: return "";
309 case SignedLong:
310 case UnsignedLong: return "l";
311 case SignedLongLong:
312 case UnsignedLongLong: return "ll";
313 }
314}
315
316/// getTypeWidth - Return the width (in bits) of the specified integer type
317/// enum. For example, SignedInt -> getIntWidth().
318unsigned TargetInfo::getTypeWidth(IntType T) const {
319 switch (T) {
320 default: llvm_unreachable("not an integer!");
321 case SignedChar:
322 case UnsignedChar: return getCharWidth();
323 case SignedShort:
324 case UnsignedShort: return getShortWidth();
325 case SignedInt:
326 case UnsignedInt: return getIntWidth();
327 case SignedLong:
328 case UnsignedLong: return getLongWidth();
329 case SignedLongLong:
330 case UnsignedLongLong: return getLongLongWidth();
331 };
332}
333
334TargetInfo::IntType TargetInfo::getIntTypeByWidth(
335 unsigned BitWidth, bool IsSigned) const {
336 if (getCharWidth() == BitWidth)
337 return IsSigned ? SignedChar : UnsignedChar;
338 if (getShortWidth() == BitWidth)
339 return IsSigned ? SignedShort : UnsignedShort;
340 if (getIntWidth() == BitWidth)
341 return IsSigned ? SignedInt : UnsignedInt;
342 if (getLongWidth() == BitWidth)
343 return IsSigned ? SignedLong : UnsignedLong;
344 if (getLongLongWidth() == BitWidth)
345 return IsSigned ? SignedLongLong : UnsignedLongLong;
346 return NoInt;
347}
348
349TargetInfo::IntType TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth,
350 bool IsSigned) const {
351 if (getCharWidth() >= BitWidth)
352 return IsSigned ? SignedChar : UnsignedChar;
353 if (getShortWidth() >= BitWidth)
354 return IsSigned ? SignedShort : UnsignedShort;
355 if (getIntWidth() >= BitWidth)
356 return IsSigned ? SignedInt : UnsignedInt;
357 if (getLongWidth() >= BitWidth)
358 return IsSigned ? SignedLong : UnsignedLong;
359 if (getLongLongWidth() >= BitWidth)
360 return IsSigned ? SignedLongLong : UnsignedLongLong;
361 return NoInt;
362}
363
364FloatModeKind TargetInfo::getRealTypeByWidth(unsigned BitWidth,
365 FloatModeKind ExplicitType) const {
366 if (getHalfWidth() == BitWidth)
367 return FloatModeKind::Half;
368 if (getFloatWidth() == BitWidth)
369 return FloatModeKind::Float;
370 if (getDoubleWidth() == BitWidth)
371 return FloatModeKind::Double;
372
373 switch (BitWidth) {
374 case 96:
375 if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
376 return FloatModeKind::LongDouble;
377 break;
378 case 128:
379 // The caller explicitly asked for an IEEE compliant type but we still
380 // have to check if the target supports it.
381 if (ExplicitType == FloatModeKind::Float128)
382 return hasFloat128Type() ? FloatModeKind::Float128
383 : FloatModeKind::NoFloat;
384 if (ExplicitType == FloatModeKind::Ibm128)
385 return hasIbm128Type() ? FloatModeKind::Ibm128
386 : FloatModeKind::NoFloat;
387 if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble() ||
388 &getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
389 return FloatModeKind::LongDouble;
390 if (hasFloat128Type())
391 return FloatModeKind::Float128;
392 break;
393 }
394
395 return FloatModeKind::NoFloat;
396}
397
398/// getTypeAlign - Return the alignment (in bits) of the specified integer type
399/// enum. For example, SignedInt -> getIntAlign().
400unsigned TargetInfo::getTypeAlign(IntType T) const {
401 switch (T) {
402 default: llvm_unreachable("not an integer!");
403 case SignedChar:
404 case UnsignedChar: return getCharAlign();
405 case SignedShort:
406 case UnsignedShort: return getShortAlign();
407 case SignedInt:
408 case UnsignedInt: return getIntAlign();
409 case SignedLong:
410 case UnsignedLong: return getLongAlign();
411 case SignedLongLong:
412 case UnsignedLongLong: return getLongLongAlign();
413 };
414}
415
416/// isTypeSigned - Return whether an integer types is signed. Returns true if
417/// the type is signed; false otherwise.
418bool TargetInfo::isTypeSigned(IntType T) {
419 switch (T) {
420 default: llvm_unreachable("not an integer!");
421 case SignedChar:
422 case SignedShort:
423 case SignedInt:
424 case SignedLong:
425 case SignedLongLong:
426 return true;
427 case UnsignedChar:
428 case UnsignedShort:
429 case UnsignedInt:
430 case UnsignedLong:
431 case UnsignedLongLong:
432 return false;
433 };
434}
435
436/// adjust - Set forced language options.
437/// Apply changes to the target information with respect to certain
438/// language options which change the target configuration and adjust
439/// the language based on the target options where applicable.
440void TargetInfo::adjust(DiagnosticsEngine &Diags, LangOptions &Opts,
441 const TargetInfo *Aux) {
442 if (Opts.NoBitFieldTypeAlign)
443 UseBitFieldTypeAlignment = false;
444
445 switch (Opts.WCharSize) {
446 default: llvm_unreachable("invalid wchar_t width");
447 case 0: break;
448 case 1: WCharType = Opts.WCharIsSigned ? SignedChar : UnsignedChar; break;
449 case 2: WCharType = Opts.WCharIsSigned ? SignedShort : UnsignedShort; break;
450 case 4: WCharType = Opts.WCharIsSigned ? SignedInt : UnsignedInt; break;
451 }
452
453 if (Opts.AlignDouble) {
454 DoubleAlign = LongLongAlign = 64;
455 LongDoubleAlign = 64;
456 }
457
458 // HLSL explicitly defines the sizes and formats of some data types, and we
459 // need to conform to those regardless of what architecture you are targeting.
460 if (Opts.HLSL) {
461 BoolWidth = BoolAlign = 32;
462 LongWidth = LongAlign = 64;
463 if (!Opts.NativeHalfType) {
464 HalfFormat = &llvm::APFloat::IEEEsingle();
465 HalfWidth = HalfAlign = 32;
466 }
467 }
468
469 if (Opts.OpenCL) {
470 // OpenCL C requires specific widths for types, irrespective of
471 // what these normally are for the target.
472 // We also define long long and long double here, although the
473 // OpenCL standard only mentions these as "reserved".
474 ShortWidth = ShortAlign = 16;
475 IntWidth = IntAlign = 32;
476 LongWidth = LongAlign = 64;
477 LongLongWidth = LongLongAlign = 128;
478 HalfWidth = HalfAlign = 16;
479 FloatWidth = FloatAlign = 32;
480
481 // Embedded 32-bit targets (OpenCL EP) might have double C type
482 // defined as float. Let's not override this as it might lead
483 // to generating illegal code that uses 64bit doubles.
484 if (DoubleWidth != FloatWidth) {
485 DoubleWidth = DoubleAlign = 64;
486 DoubleFormat = &llvm::APFloat::IEEEdouble();
487 }
488 LongDoubleWidth = LongDoubleAlign = 128;
489
490 unsigned MaxPointerWidth = getMaxPointerWidth();
491 assert(MaxPointerWidth == 32 || MaxPointerWidth == 64);
492 bool Is32BitArch = MaxPointerWidth == 32;
493 SizeType = Is32BitArch ? UnsignedInt : UnsignedLong;
494 PtrDiffType = Is32BitArch ? SignedInt : SignedLong;
495 IntPtrType = Is32BitArch ? SignedInt : SignedLong;
496
497 IntMaxType = SignedLongLong;
498 Int64Type = SignedLong;
499
500 HalfFormat = &llvm::APFloat::IEEEhalf();
501 FloatFormat = &llvm::APFloat::IEEEsingle();
502 LongDoubleFormat = &llvm::APFloat::IEEEquad();
503
504 // OpenCL C v3.0 s6.7.5 - The generic address space requires support for
505 // OpenCL C 2.0 or OpenCL C 3.0 with the __opencl_c_generic_address_space
506 // feature
507 // OpenCL C v3.0 s6.2.1 - OpenCL pipes require support of OpenCL C 2.0
508 // or later and __opencl_c_pipes feature
509 // FIXME: These language options are also defined in setLangDefaults()
510 // for OpenCL C 2.0 but with no access to target capabilities. Target
511 // should be immutable once created and thus these language options need
512 // to be defined only once.
513 if (Opts.getOpenCLCompatibleVersion() >= 300) {
514 const auto &OpenCLFeaturesMap = getSupportedOpenCLOpts();
515 Opts.OpenCLGenericAddressSpace = hasFeatureEnabled(
516 Features: OpenCLFeaturesMap, Name: "__opencl_c_generic_address_space");
517 Opts.OpenCLPipes =
518 hasFeatureEnabled(Features: OpenCLFeaturesMap, Name: "__opencl_c_pipes");
519 Opts.Blocks =
520 hasFeatureEnabled(Features: OpenCLFeaturesMap, Name: "__opencl_c_device_enqueue");
521 }
522 }
523
524 if (Opts.DoubleSize) {
525 if (Opts.DoubleSize == 32) {
526 DoubleWidth = 32;
527 LongDoubleWidth = 32;
528 DoubleFormat = &llvm::APFloat::IEEEsingle();
529 LongDoubleFormat = &llvm::APFloat::IEEEsingle();
530 } else if (Opts.DoubleSize == 64) {
531 DoubleWidth = 64;
532 LongDoubleWidth = 64;
533 DoubleFormat = &llvm::APFloat::IEEEdouble();
534 LongDoubleFormat = &llvm::APFloat::IEEEdouble();
535 }
536 }
537
538 if (Opts.LongDoubleSize) {
539 if (Opts.LongDoubleSize == DoubleWidth) {
540 LongDoubleWidth = DoubleWidth;
541 LongDoubleAlign = DoubleAlign;
542 LongDoubleFormat = DoubleFormat;
543 } else if (Opts.LongDoubleSize == 128) {
544 LongDoubleWidth = LongDoubleAlign = 128;
545 LongDoubleFormat = &llvm::APFloat::IEEEquad();
546 } else if (Opts.LongDoubleSize == 80) {
547 LongDoubleFormat = &llvm::APFloat::x87DoubleExtended();
548 if (getTriple().isWindowsMSVCEnvironment()) {
549 LongDoubleWidth = 128;
550 LongDoubleAlign = 128;
551 } else { // Linux
552 if (getTriple().getArch() == llvm::Triple::x86) {
553 LongDoubleWidth = 96;
554 LongDoubleAlign = 32;
555 } else {
556 LongDoubleWidth = 128;
557 LongDoubleAlign = 128;
558 }
559 }
560 }
561 }
562
563 if (Opts.NewAlignOverride)
564 NewAlign = Opts.NewAlignOverride * getCharWidth();
565
566 // Each unsigned fixed point type has the same number of fractional bits as
567 // its corresponding signed type.
568 PaddingOnUnsignedFixedPoint |= Opts.PaddingOnUnsignedFixedPoint;
569 CheckFixedPointBits();
570
571 if (Opts.ProtectParens && !checkArithmeticFenceSupported()) {
572 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "-fprotect-parens";
573 Opts.ProtectParens = false;
574 }
575
576 if (Opts.MaxBitIntWidth)
577 MaxBitIntWidth = static_cast<unsigned>(Opts.MaxBitIntWidth);
578
579 if (Opts.FakeAddressSpaceMap)
580 AddrSpaceMap = &FakeAddrSpaceMap;
581
582 // Check if it's CUDA device compilation; ensure layout consistency with host.
583 if (Opts.CUDA && Opts.CUDAIsDevice && Aux && !HasMicrosoftRecordLayout)
584 HasMicrosoftRecordLayout = Aux->getCXXABI().isMicrosoft();
585}
586
587bool TargetInfo::initFeatureMap(
588 llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
589 const std::vector<std::string> &FeatureVec) const {
590 for (StringRef Name : FeatureVec) {
591 if (Name.empty())
592 continue;
593 // Apply the feature via the target.
594 if (Name[0] != '+' && Name[0] != '-')
595 Diags.Report(DiagID: diag::warn_fe_backend_invalid_feature_flag) << Name;
596 else
597 setFeatureEnabled(Features, Name: Name.substr(Start: 1), Enabled: Name[0] == '+');
598 }
599 return true;
600}
601
602ParsedTargetAttr TargetInfo::parseTargetAttr(StringRef Features) const {
603 ParsedTargetAttr Ret;
604 if (Features == "default")
605 return Ret;
606 SmallVector<StringRef, 1> AttrFeatures;
607 Features.split(A&: AttrFeatures, Separator: ",");
608
609 // Grab the various features and prepend a "+" to turn on the feature to
610 // the backend and add them to our existing set of features.
611 for (auto &Feature : AttrFeatures) {
612 // Go ahead and trim whitespace rather than either erroring or
613 // accepting it weirdly.
614 Feature = Feature.trim();
615
616 // TODO: Support the fpmath option. It will require checking
617 // overall feature validity for the function with the rest of the
618 // attributes on the function.
619 if (Feature.starts_with(Prefix: "fpmath="))
620 continue;
621
622 if (Feature.starts_with(Prefix: "branch-protection=")) {
623 Ret.BranchProtection = Feature.split(Separator: '=').second.trim();
624 continue;
625 }
626
627 // While we're here iterating check for a different target cpu.
628 if (Feature.starts_with(Prefix: "arch=")) {
629 if (!Ret.CPU.empty())
630 Ret.Duplicate = "arch=";
631 else
632 Ret.CPU = Feature.split(Separator: "=").second.trim();
633 } else if (Feature.starts_with(Prefix: "tune=")) {
634 if (!Ret.Tune.empty())
635 Ret.Duplicate = "tune=";
636 else
637 Ret.Tune = Feature.split(Separator: "=").second.trim();
638 } else if (Feature.starts_with(Prefix: "no-"))
639 Ret.Features.push_back(x: "-" + Feature.split(Separator: "-").second.str());
640 else
641 Ret.Features.push_back(x: "+" + Feature.str());
642 }
643 return Ret;
644}
645
646TargetInfo::CallingConvKind
647TargetInfo::getCallingConvKind(bool ClangABICompat4) const {
648 if (getCXXABI() != TargetCXXABI::Microsoft &&
649 (ClangABICompat4 || getTriple().isPS4()))
650 return CCK_ClangABI4OrPS4;
651 return CCK_Default;
652}
653
654VTableUniquenessKind TargetInfo::getVTableUniqueness() const {
655 return VTableUniquenessKind::AlwaysUnique;
656}
657
658bool TargetInfo::callGlobalDeleteInDeletingDtor(
659 const LangOptions &LangOpts) const {
660 if (getCXXABI() == TargetCXXABI::Microsoft &&
661 !LangOpts.isCompatibleWith(Version: LangOptions::ClangABI::Ver21))
662 return true;
663 return false;
664}
665
666bool TargetInfo::emitVectorDeletingDtors(const LangOptions &LangOpts) const {
667 if (getCXXABI() == TargetCXXABI::Microsoft &&
668 !LangOpts.isCompatibleWith(Version: LangOptions::ClangABI::Ver21))
669 return true;
670 return false;
671}
672
673bool TargetInfo::areDefaultedSMFStillPOD(const LangOptions &LangOpts) const {
674 return !LangOpts.isCompatibleWith(Version: LangOptions::ClangABI::Ver15);
675}
676
677void TargetInfo::setDependentOpenCLOpts() {
678 auto &Opts = getSupportedOpenCLOpts();
679 if (!hasFeatureEnabled(Features: Opts, Name: "cl_khr_fp64") ||
680 !hasFeatureEnabled(Features: Opts, Name: "__opencl_c_fp64")) {
681 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_global_atomic_add", Enabled: false);
682 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_local_atomic_add", Enabled: false);
683 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_global_atomic_min_max", Enabled: false);
684 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_local_atomic_min_max", Enabled: false);
685 }
686}
687
688LangAS TargetInfo::getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const {
689 switch (TK) {
690 case OCLTK_Image:
691 case OCLTK_Pipe:
692 return LangAS::opencl_global;
693
694 case OCLTK_Sampler:
695 return LangAS::opencl_constant;
696
697 default:
698 return LangAS::Default;
699 }
700}
701
702//===----------------------------------------------------------------------===//
703
704
705static StringRef removeGCCRegisterPrefix(StringRef Name) {
706 if (Name[0] == '%' || Name[0] == '#')
707 Name = Name.substr(Start: 1);
708
709 return Name;
710}
711
712/// isValidClobber - Returns whether the passed in string is
713/// a valid clobber in an inline asm statement. This is used by
714/// Sema.
715bool TargetInfo::isValidClobber(StringRef Name) const {
716 return (isValidGCCRegisterName(Name) || Name == "memory" || Name == "cc" ||
717 Name == "unwind");
718}
719
720/// isValidGCCRegisterName - Returns whether the passed in string
721/// is a valid register name according to GCC. This is used by Sema for
722/// inline asm statements.
723bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
724 if (Name.empty())
725 return false;
726
727 // Get rid of any register prefix.
728 Name = removeGCCRegisterPrefix(Name);
729 if (Name.empty())
730 return false;
731
732 ArrayRef<const char *> Names = getGCCRegNames();
733
734 // If we have a number it maps to an entry in the register name array.
735 if (isDigit(c: Name[0])) {
736 unsigned n;
737 if (!Name.getAsInteger(Radix: 0, Result&: n))
738 return n < Names.size();
739 }
740
741 // Check register names.
742 if (llvm::is_contained(Range&: Names, Element: Name))
743 return true;
744
745 // Check any additional names that we have.
746 for (const AddlRegName &ARN : getGCCAddlRegNames())
747 for (const char *AN : ARN.Names) {
748 if (!AN)
749 break;
750 // Make sure the register that the additional name is for is within
751 // the bounds of the register names from above.
752 if (AN == Name && ARN.RegNum < Names.size())
753 return true;
754 }
755
756 // Now check aliases.
757 for (const GCCRegAlias &GRA : getGCCRegAliases())
758 for (const char *A : GRA.Aliases) {
759 if (!A)
760 break;
761 if (A == Name)
762 return true;
763 }
764
765 return false;
766}
767
768StringRef TargetInfo::getNormalizedGCCRegisterName(StringRef Name,
769 bool ReturnCanonical) const {
770 assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
771
772 // Get rid of any register prefix.
773 Name = removeGCCRegisterPrefix(Name);
774
775 ArrayRef<const char *> Names = getGCCRegNames();
776
777 // First, check if we have a number.
778 if (isDigit(c: Name[0])) {
779 unsigned n;
780 if (!Name.getAsInteger(Radix: 0, Result&: n)) {
781 assert(n < Names.size() && "Out of bounds register number!");
782 return Names[n];
783 }
784 }
785
786 // Check any additional names that we have.
787 for (const AddlRegName &ARN : getGCCAddlRegNames())
788 for (const char *AN : ARN.Names) {
789 if (!AN)
790 break;
791 // Make sure the register that the additional name is for is within
792 // the bounds of the register names from above.
793 if (AN == Name && ARN.RegNum < Names.size())
794 return ReturnCanonical ? Names[ARN.RegNum] : Name;
795 }
796
797 // Now check aliases.
798 for (const GCCRegAlias &RA : getGCCRegAliases())
799 for (const char *A : RA.Aliases) {
800 if (!A)
801 break;
802 if (A == Name)
803 return RA.Register;
804 }
805
806 return Name;
807}
808
809bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
810 const char *Name = Info.getConstraintStr().c_str();
811 // An output constraint must start with '=' or '+'
812 if (*Name != '=' && *Name != '+')
813 return false;
814
815 if (*Name == '+')
816 Info.setIsReadWrite();
817
818 Name++;
819 while (*Name) {
820 switch (*Name) {
821 default:
822 if (!validateAsmConstraint(Name, info&: Info)) {
823 // FIXME: We temporarily return false
824 // so we can add more constraints as we hit it.
825 // Eventually, an unknown constraint should just be treated as 'g'.
826 return false;
827 }
828 break;
829 case '&': // early clobber.
830 Info.setEarlyClobber();
831 break;
832 case '%': // commutative.
833 // FIXME: Check that there is a another register after this one.
834 break;
835 case 'r': // general register.
836 Info.setAllowsRegister();
837 break;
838 case 'm': // memory operand.
839 case 'o': // offsetable memory operand.
840 case 'V': // non-offsetable memory operand.
841 case '<': // autodecrement memory operand.
842 case '>': // autoincrement memory operand.
843 Info.setAllowsMemory();
844 break;
845 case 'g': // general register, memory operand or immediate integer.
846 case 'X': // any operand.
847 Info.setAllowsRegister();
848 Info.setAllowsMemory();
849 break;
850 case ',': // multiple alternative constraint. Pass it.
851 // Handle additional optional '=' or '+' modifiers.
852 if (Name[1] == '=' || Name[1] == '+')
853 Name++;
854 break;
855 case '#': // Ignore as constraint.
856 while (Name[1] && Name[1] != ',')
857 Name++;
858 break;
859 case '?': // Disparage slightly code.
860 case '!': // Disparage severely.
861 case '*': // Ignore for choosing register preferences.
862 case 'i': // Ignore i,n,E,F as output constraints (match from the other
863 // chars)
864 case 'n':
865 case 'E':
866 case 'F':
867 break; // Pass them.
868 }
869
870 Name++;
871 }
872
873 // Early clobber with a read-write constraint which doesn't permit registers
874 // is invalid.
875 if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister())
876 return false;
877
878 // If a constraint allows neither memory nor register operands it contains
879 // only modifiers. Reject it.
880 return Info.allowsMemory() || Info.allowsRegister();
881}
882
883bool TargetInfo::resolveSymbolicName(const char *&Name,
884 ArrayRef<ConstraintInfo> OutputConstraints,
885 unsigned &Index) const {
886 assert(*Name == '[' && "Symbolic name did not start with '['");
887 Name++;
888 const char *Start = Name;
889 while (*Name && *Name != ']')
890 Name++;
891
892 if (!*Name) {
893 // Missing ']'
894 return false;
895 }
896
897 std::string SymbolicName(Start, Name - Start);
898
899 for (Index = 0; Index != OutputConstraints.size(); ++Index)
900 if (SymbolicName == OutputConstraints[Index].getName())
901 return true;
902
903 return false;
904}
905
906bool TargetInfo::validateInputConstraint(
907 MutableArrayRef<ConstraintInfo> OutputConstraints,
908 ConstraintInfo &Info) const {
909 const char *Name = Info.ConstraintStr.c_str();
910
911 if (!*Name)
912 return false;
913
914 while (*Name) {
915 switch (*Name) {
916 default:
917 // Check if we have a matching constraint
918 if (*Name >= '0' && *Name <= '9') {
919 const char *DigitStart = Name;
920 while (Name[1] >= '0' && Name[1] <= '9')
921 Name++;
922 const char *DigitEnd = Name;
923 unsigned i;
924 if (StringRef(DigitStart, DigitEnd - DigitStart + 1)
925 .getAsInteger(Radix: 10, Result&: i))
926 return false;
927
928 // Check if matching constraint is out of bounds.
929 if (i >= OutputConstraints.size()) return false;
930
931 // A number must refer to an output only operand.
932 if (OutputConstraints[i].isReadWrite())
933 return false;
934
935 // If the constraint is already tied, it must be tied to the
936 // same operand referenced to by the number.
937 if (Info.hasTiedOperand() && Info.getTiedOperand() != i)
938 return false;
939
940 // The constraint should have the same info as the respective
941 // output constraint.
942 Info.setTiedOperand(N: i, Output&: OutputConstraints[i]);
943 } else if (!validateAsmConstraint(Name, info&: Info)) {
944 // FIXME: This error return is in place temporarily so we can
945 // add more constraints as we hit it. Eventually, an unknown
946 // constraint should just be treated as 'g'.
947 return false;
948 }
949 break;
950 case '[': {
951 unsigned Index = 0;
952 if (!resolveSymbolicName(Name, OutputConstraints, Index))
953 return false;
954
955 // If the constraint is already tied, it must be tied to the
956 // same operand referenced to by the number.
957 if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
958 return false;
959
960 // A number must refer to an output only operand.
961 if (OutputConstraints[Index].isReadWrite())
962 return false;
963
964 Info.setTiedOperand(N: Index, Output&: OutputConstraints[Index]);
965 break;
966 }
967 case '%': // commutative
968 // FIXME: Fail if % is used with the last operand.
969 break;
970 case 'i': // immediate integer.
971 break;
972 case 'n': // immediate integer with a known value.
973 Info.setRequiresImmediate();
974 break;
975 case 'I': // Various constant constraints with target-specific meanings.
976 case 'J':
977 case 'K':
978 case 'L':
979 case 'M':
980 case 'N':
981 case 'O':
982 case 'P':
983 if (!validateAsmConstraint(Name, info&: Info))
984 return false;
985 break;
986 case 'r': // general register.
987 Info.setAllowsRegister();
988 break;
989 case 'm': // memory operand.
990 case 'o': // offsettable memory operand.
991 case 'V': // non-offsettable memory operand.
992 case '<': // autodecrement memory operand.
993 case '>': // autoincrement memory operand.
994 Info.setAllowsMemory();
995 break;
996 case 'g': // general register, memory operand or immediate integer.
997 case 'X': // any operand.
998 Info.setAllowsRegister();
999 Info.setAllowsMemory();
1000 break;
1001 case 'E': // immediate floating point.
1002 case 'F': // immediate floating point.
1003 case 'p': // address operand.
1004 break;
1005 case ',': // multiple alternative constraint. Ignore comma.
1006 break;
1007 case '#': // Ignore as constraint.
1008 while (Name[1] && Name[1] != ',')
1009 Name++;
1010 break;
1011 case '?': // Disparage slightly code.
1012 case '!': // Disparage severely.
1013 case '*': // Ignore for choosing register preferences.
1014 break; // Pass them.
1015 }
1016
1017 Name++;
1018 }
1019
1020 return true;
1021}
1022
1023bool TargetInfo::validatePointerAuthKey(const llvm::APSInt &value) const {
1024 return false;
1025}
1026
1027void TargetInfo::CheckFixedPointBits() const {
1028 // Check that the number of fractional and integral bits (and maybe sign) can
1029 // fit into the bits given for a fixed point type.
1030 assert(ShortAccumScale + getShortAccumIBits() + 1 <= ShortAccumWidth);
1031 assert(AccumScale + getAccumIBits() + 1 <= AccumWidth);
1032 assert(LongAccumScale + getLongAccumIBits() + 1 <= LongAccumWidth);
1033 assert(getUnsignedShortAccumScale() + getUnsignedShortAccumIBits() <=
1034 ShortAccumWidth);
1035 assert(getUnsignedAccumScale() + getUnsignedAccumIBits() <= AccumWidth);
1036 assert(getUnsignedLongAccumScale() + getUnsignedLongAccumIBits() <=
1037 LongAccumWidth);
1038
1039 assert(getShortFractScale() + 1 <= ShortFractWidth);
1040 assert(getFractScale() + 1 <= FractWidth);
1041 assert(getLongFractScale() + 1 <= LongFractWidth);
1042 assert(getUnsignedShortFractScale() <= ShortFractWidth);
1043 assert(getUnsignedFractScale() <= FractWidth);
1044 assert(getUnsignedLongFractScale() <= LongFractWidth);
1045
1046 // Each unsigned fract type has either the same number of fractional bits
1047 // as, or one more fractional bit than, its corresponding signed fract type.
1048 assert(getShortFractScale() == getUnsignedShortFractScale() ||
1049 getShortFractScale() == getUnsignedShortFractScale() - 1);
1050 assert(getFractScale() == getUnsignedFractScale() ||
1051 getFractScale() == getUnsignedFractScale() - 1);
1052 assert(getLongFractScale() == getUnsignedLongFractScale() ||
1053 getLongFractScale() == getUnsignedLongFractScale() - 1);
1054
1055 // When arranged in order of increasing rank (see 6.3.1.3a), the number of
1056 // fractional bits is nondecreasing for each of the following sets of
1057 // fixed-point types:
1058 // - signed fract types
1059 // - unsigned fract types
1060 // - signed accum types
1061 // - unsigned accum types.
1062 assert(getLongFractScale() >= getFractScale() &&
1063 getFractScale() >= getShortFractScale());
1064 assert(getUnsignedLongFractScale() >= getUnsignedFractScale() &&
1065 getUnsignedFractScale() >= getUnsignedShortFractScale());
1066 assert(LongAccumScale >= AccumScale && AccumScale >= ShortAccumScale);
1067 assert(getUnsignedLongAccumScale() >= getUnsignedAccumScale() &&
1068 getUnsignedAccumScale() >= getUnsignedShortAccumScale());
1069
1070 // When arranged in order of increasing rank (see 6.3.1.3a), the number of
1071 // integral bits is nondecreasing for each of the following sets of
1072 // fixed-point types:
1073 // - signed accum types
1074 // - unsigned accum types
1075 assert(getLongAccumIBits() >= getAccumIBits() &&
1076 getAccumIBits() >= getShortAccumIBits());
1077 assert(getUnsignedLongAccumIBits() >= getUnsignedAccumIBits() &&
1078 getUnsignedAccumIBits() >= getUnsignedShortAccumIBits());
1079
1080 // Each signed accum type has at least as many integral bits as its
1081 // corresponding unsigned accum type.
1082 assert(getShortAccumIBits() >= getUnsignedShortAccumIBits());
1083 assert(getAccumIBits() >= getUnsignedAccumIBits());
1084 assert(getLongAccumIBits() >= getUnsignedLongAccumIBits());
1085}
1086
1087void TargetInfo::copyAuxTarget(const TargetInfo *Aux) {
1088 auto *Target = static_cast<TransferrableTargetInfo*>(this);
1089 auto *Src = static_cast<const TransferrableTargetInfo*>(Aux);
1090 *Target = *Src;
1091}
1092
1093std::string
1094TargetInfo::simplifyConstraint(StringRef Constraint,
1095 SmallVectorImpl<ConstraintInfo> *OutCons) const {
1096 std::string Result;
1097
1098 // Stop at '\0' to match the old behavior.
1099 Constraint = Constraint.split(Separator: '\0').first;
1100
1101 for (const char *I = Constraint.begin(), *E = Constraint.end(); I < E; I++) {
1102 switch (*I) {
1103 default:
1104 Result += convertConstraint(Constraint&: I);
1105 break;
1106 // Ignore these
1107 case '*':
1108 case '?':
1109 case '!':
1110 case '=': // Will see this and the following in mult-alt constraints.
1111 case '+':
1112 break;
1113 case '#': // Ignore the rest of the constraint alternative.
1114 while (I + 1 != E && I[1] != ',')
1115 I++;
1116 break;
1117 case '&':
1118 case '%':
1119 Result += *I;
1120 while (I + 1 != E && I[1] == *I)
1121 I++;
1122 break;
1123 case ',':
1124 Result += "|";
1125 break;
1126 case 'g':
1127 Result += "imr";
1128 break;
1129 case '[': {
1130 assert(OutCons &&
1131 "Must pass output names to constraints with a symbolic name");
1132 unsigned Index;
1133 bool ResolveResult = resolveSymbolicName(Name&: I, OutputConstraints: *OutCons, Index);
1134 assert(ResolveResult && "Could not resolve symbolic name");
1135 (void)ResolveResult;
1136 Result += llvm::utostr(X: Index);
1137 break;
1138 }
1139 }
1140 }
1141 return Result;
1142}
1143
1144unsigned clang::Microsoft64BitMinGlobalAlign(uint64_t TypeSize) {
1145 // MSVC does size based alignment for arm64 based on alignment section in
1146 // below document. Replicate that to keep alignment consistent with object
1147 // files compiled by MSVC.
1148 // https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions
1149 // The same is done for x64, but not documented.
1150
1151 if (TypeSize >= 512) // TypeSize >= 64 bytes
1152 return 128; // align type at least 16 bytes
1153 if (TypeSize >= 64) // TypeSize >= 8 bytes
1154 return 64; // align type at least 8 bytes
1155 if (TypeSize >= 16) // TypeSize >= 2 bytes
1156 return 32; // align type at least 4 bytes
1157
1158 return 0;
1159}
1160