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

source code of clang/lib/Basic/TargetInfo.cpp