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