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