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