1 //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===// 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 clang::InitializePreprocessor function. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Basic/FileManager.h" 14 #include "clang/Basic/MacroBuilder.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Basic/SyncScope.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/Version.h" 19 #include "clang/Frontend/FrontendDiagnostic.h" 20 #include "clang/Frontend/FrontendOptions.h" 21 #include "clang/Frontend/Utils.h" 22 #include "clang/Lex/HeaderSearch.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Lex/PreprocessorOptions.h" 25 #include "clang/Serialization/ASTReader.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 using namespace clang; 30 31 static bool MacroBodyEndsInBackslash(StringRef MacroBody) { 32 while (!MacroBody.empty() && isWhitespace(MacroBody.back())) 33 MacroBody = MacroBody.drop_back(); 34 return !MacroBody.empty() && MacroBody.back() == '\\'; 35 } 36 37 // Append a #define line to Buf for Macro. Macro should be of the form XXX, 38 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit 39 // "#define XXX Y z W". To get a #define with no value, use "XXX=". 40 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro, 41 DiagnosticsEngine &Diags) { 42 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 43 StringRef MacroName = MacroPair.first; 44 StringRef MacroBody = MacroPair.second; 45 if (MacroName.size() != Macro.size()) { 46 // Per GCC -D semantics, the macro ends at \n if it exists. 47 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 48 if (End != StringRef::npos) 49 Diags.Report(diag::warn_fe_macro_contains_embedded_newline) 50 << MacroName; 51 MacroBody = MacroBody.substr(0, End); 52 // We handle macro bodies which end in a backslash by appending an extra 53 // backslash+newline. This makes sure we don't accidentally treat the 54 // backslash as a line continuation marker. 55 if (MacroBodyEndsInBackslash(MacroBody)) 56 Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n"); 57 else 58 Builder.defineMacro(MacroName, MacroBody); 59 } else { 60 // Push "macroname 1". 61 Builder.defineMacro(Macro); 62 } 63 } 64 65 /// AddImplicitInclude - Add an implicit \#include of the specified file to the 66 /// predefines buffer. 67 /// As these includes are generated by -include arguments the header search 68 /// logic is going to search relatively to the current working directory. 69 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File) { 70 Builder.append(Twine("#include \"") + File + "\""); 71 } 72 73 static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) { 74 Builder.append(Twine("#__include_macros \"") + File + "\""); 75 // Marker token to stop the __include_macros fetch loop. 76 Builder.append("##"); // ##? 77 } 78 79 /// Add an implicit \#include using the original file used to generate 80 /// a PCH file. 81 static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP, 82 const PCHContainerReader &PCHContainerRdr, 83 StringRef ImplicitIncludePCH) { 84 std::string OriginalFile = ASTReader::getOriginalSourceFile( 85 std::string(ImplicitIncludePCH), PP.getFileManager(), PCHContainerRdr, 86 PP.getDiagnostics()); 87 if (OriginalFile.empty()) 88 return; 89 90 AddImplicitInclude(Builder, OriginalFile); 91 } 92 93 /// PickFP - This is used to pick a value based on the FP semantics of the 94 /// specified FP model. 95 template <typename T> 96 static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal, 97 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal, 98 T IEEEQuadVal) { 99 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEhalf()) 100 return IEEEHalfVal; 101 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle()) 102 return IEEESingleVal; 103 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble()) 104 return IEEEDoubleVal; 105 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended()) 106 return X87DoubleExtendedVal; 107 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble()) 108 return PPCDoubleDoubleVal; 109 assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad()); 110 return IEEEQuadVal; 111 } 112 113 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix, 114 const llvm::fltSemantics *Sem, StringRef Ext) { 115 const char *DenormMin, *Epsilon, *Max, *Min; 116 DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45", 117 "4.9406564584124654e-324", "3.64519953188247460253e-4951", 118 "4.94065645841246544176568792868221e-324", 119 "6.47517511943802511092443895822764655e-4966"); 120 int Digits = PickFP(Sem, 3, 6, 15, 18, 31, 33); 121 int DecimalDigits = PickFP(Sem, 5, 9, 17, 21, 33, 36); 122 Epsilon = PickFP(Sem, "9.765625e-4", "1.19209290e-7", 123 "2.2204460492503131e-16", "1.08420217248550443401e-19", 124 "4.94065645841246544176568792868221e-324", 125 "1.92592994438723585305597794258492732e-34"); 126 int MantissaDigits = PickFP(Sem, 11, 24, 53, 64, 106, 113); 127 int Min10Exp = PickFP(Sem, -4, -37, -307, -4931, -291, -4931); 128 int Max10Exp = PickFP(Sem, 4, 38, 308, 4932, 308, 4932); 129 int MinExp = PickFP(Sem, -13, -125, -1021, -16381, -968, -16381); 130 int MaxExp = PickFP(Sem, 16, 128, 1024, 16384, 1024, 16384); 131 Min = PickFP(Sem, "6.103515625e-5", "1.17549435e-38", "2.2250738585072014e-308", 132 "3.36210314311209350626e-4932", 133 "2.00416836000897277799610805135016e-292", 134 "3.36210314311209350626267781732175260e-4932"); 135 Max = PickFP(Sem, "6.5504e+4", "3.40282347e+38", "1.7976931348623157e+308", 136 "1.18973149535723176502e+4932", 137 "1.79769313486231580793728971405301e+308", 138 "1.18973149535723176508575932662800702e+4932"); 139 140 SmallString<32> DefPrefix; 141 DefPrefix = "__"; 142 DefPrefix += Prefix; 143 DefPrefix += "_"; 144 145 Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext); 146 Builder.defineMacro(DefPrefix + "HAS_DENORM__"); 147 Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits)); 148 Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits)); 149 Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext); 150 Builder.defineMacro(DefPrefix + "HAS_INFINITY__"); 151 Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__"); 152 Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits)); 153 154 Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp)); 155 Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp)); 156 Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext); 157 158 Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")"); 159 Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")"); 160 Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext); 161 } 162 163 164 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro 165 /// named MacroName with the max value for a type with width 'TypeWidth' a 166 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL). 167 static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth, 168 StringRef ValSuffix, bool isSigned, 169 MacroBuilder &Builder) { 170 llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth) 171 : llvm::APInt::getMaxValue(TypeWidth); 172 Builder.defineMacro(MacroName, toString(MaxVal, 10, isSigned) + ValSuffix); 173 } 174 175 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine 176 /// the width, suffix, and signedness of the given type 177 static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty, 178 const TargetInfo &TI, MacroBuilder &Builder) { 179 DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty), 180 TI.isTypeSigned(Ty), Builder); 181 } 182 183 static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty, 184 const TargetInfo &TI, MacroBuilder &Builder) { 185 bool IsSigned = TI.isTypeSigned(Ty); 186 StringRef FmtModifier = TI.getTypeFormatModifier(Ty); 187 for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) { 188 Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__", 189 Twine("\"") + FmtModifier + Twine(*Fmt) + "\""); 190 } 191 } 192 193 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty, 194 MacroBuilder &Builder) { 195 Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty)); 196 } 197 198 static void DefineTypeWidth(const Twine &MacroName, TargetInfo::IntType Ty, 199 const TargetInfo &TI, MacroBuilder &Builder) { 200 Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty))); 201 } 202 203 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth, 204 const TargetInfo &TI, MacroBuilder &Builder) { 205 Builder.defineMacro(MacroName, 206 Twine(BitWidth / TI.getCharWidth())); 207 } 208 209 // This will generate a macro based on the prefix with `_MAX__` as the suffix 210 // for the max value representable for the type, and a macro with a `_WIDTH__` 211 // suffix for the width of the type. 212 static void DefineTypeSizeAndWidth(const Twine &Prefix, TargetInfo::IntType Ty, 213 const TargetInfo &TI, 214 MacroBuilder &Builder) { 215 DefineTypeSize(Prefix + "_MAX__", Ty, TI, Builder); 216 DefineTypeWidth(Prefix + "_WIDTH__", Ty, TI, Builder); 217 } 218 219 static void DefineExactWidthIntType(TargetInfo::IntType Ty, 220 const TargetInfo &TI, 221 MacroBuilder &Builder) { 222 int TypeWidth = TI.getTypeWidth(Ty); 223 bool IsSigned = TI.isTypeSigned(Ty); 224 225 // Use the target specified int64 type, when appropriate, so that [u]int64_t 226 // ends up being defined in terms of the correct type. 227 if (TypeWidth == 64) 228 Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type(); 229 230 // Use the target specified int16 type when appropriate. Some MCU targets 231 // (such as AVR) have definition of [u]int16_t to [un]signed int. 232 if (TypeWidth == 16) 233 Ty = IsSigned ? TI.getInt16Type() : TI.getUInt16Type(); 234 235 const char *Prefix = IsSigned ? "__INT" : "__UINT"; 236 237 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder); 238 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder); 239 240 StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty)); 241 Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix); 242 } 243 244 static void DefineExactWidthIntTypeSize(TargetInfo::IntType Ty, 245 const TargetInfo &TI, 246 MacroBuilder &Builder) { 247 int TypeWidth = TI.getTypeWidth(Ty); 248 bool IsSigned = TI.isTypeSigned(Ty); 249 250 // Use the target specified int64 type, when appropriate, so that [u]int64_t 251 // ends up being defined in terms of the correct type. 252 if (TypeWidth == 64) 253 Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type(); 254 255 // We don't need to define a _WIDTH macro for the exact-width types because 256 // we already know the width. 257 const char *Prefix = IsSigned ? "__INT" : "__UINT"; 258 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder); 259 } 260 261 static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned, 262 const TargetInfo &TI, 263 MacroBuilder &Builder) { 264 TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned); 265 if (Ty == TargetInfo::NoInt) 266 return; 267 268 const char *Prefix = IsSigned ? "__INT_LEAST" : "__UINT_LEAST"; 269 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder); 270 // We only want the *_WIDTH macro for the signed types to avoid too many 271 // predefined macros (the unsigned width and the signed width are identical.) 272 if (IsSigned) 273 DefineTypeSizeAndWidth(Prefix + Twine(TypeWidth), Ty, TI, Builder); 274 else 275 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder); 276 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder); 277 } 278 279 static void DefineFastIntType(unsigned TypeWidth, bool IsSigned, 280 const TargetInfo &TI, MacroBuilder &Builder) { 281 // stdint.h currently defines the fast int types as equivalent to the least 282 // types. 283 TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned); 284 if (Ty == TargetInfo::NoInt) 285 return; 286 287 const char *Prefix = IsSigned ? "__INT_FAST" : "__UINT_FAST"; 288 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder); 289 // We only want the *_WIDTH macro for the signed types to avoid too many 290 // predefined macros (the unsigned width and the signed width are identical.) 291 if (IsSigned) 292 DefineTypeSizeAndWidth(Prefix + Twine(TypeWidth), Ty, TI, Builder); 293 else 294 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder); 295 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder); 296 } 297 298 299 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with 300 /// the specified properties. 301 static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign, 302 unsigned InlineWidth) { 303 // Fully-aligned, power-of-2 sizes no larger than the inline 304 // width will be inlined as lock-free operations. 305 if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 && 306 TypeWidth <= InlineWidth) 307 return "2"; // "always lock free" 308 // We cannot be certain what operations the lib calls might be 309 // able to implement as lock-free on future processors. 310 return "1"; // "sometimes lock free" 311 } 312 313 /// Add definitions required for a smooth interaction between 314 /// Objective-C++ automated reference counting and libstdc++ (4.2). 315 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts, 316 MacroBuilder &Builder) { 317 Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR"); 318 319 std::string Result; 320 { 321 // Provide specializations for the __is_scalar type trait so that 322 // lifetime-qualified objects are not considered "scalar" types, which 323 // libstdc++ uses as an indicator of the presence of trivial copy, assign, 324 // default-construct, and destruct semantics (none of which hold for 325 // lifetime-qualified objects in ARC). 326 llvm::raw_string_ostream Out(Result); 327 328 Out << "namespace std {\n" 329 << "\n" 330 << "struct __true_type;\n" 331 << "struct __false_type;\n" 332 << "\n"; 333 334 Out << "template<typename _Tp> struct __is_scalar;\n" 335 << "\n"; 336 337 if (LangOpts.ObjCAutoRefCount) { 338 Out << "template<typename _Tp>\n" 339 << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n" 340 << " enum { __value = 0 };\n" 341 << " typedef __false_type __type;\n" 342 << "};\n" 343 << "\n"; 344 } 345 346 if (LangOpts.ObjCWeak) { 347 Out << "template<typename _Tp>\n" 348 << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n" 349 << " enum { __value = 0 };\n" 350 << " typedef __false_type __type;\n" 351 << "};\n" 352 << "\n"; 353 } 354 355 if (LangOpts.ObjCAutoRefCount) { 356 Out << "template<typename _Tp>\n" 357 << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))" 358 << " _Tp> {\n" 359 << " enum { __value = 0 };\n" 360 << " typedef __false_type __type;\n" 361 << "};\n" 362 << "\n"; 363 } 364 365 Out << "}\n"; 366 } 367 Builder.append(Result); 368 } 369 370 static void InitializeStandardPredefinedMacros(const TargetInfo &TI, 371 const LangOptions &LangOpts, 372 const FrontendOptions &FEOpts, 373 MacroBuilder &Builder) { 374 // C++ [cpp.predefined]p1: 375 // The following macro names shall be defined by the implementation: 376 377 // -- __STDC__ 378 // [C++] Whether __STDC__ is predefined and if so, what its value is, 379 // are implementation-defined. 380 // (Removed in C++20.) 381 if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP) 382 Builder.defineMacro("__STDC__"); 383 // -- __STDC_HOSTED__ 384 // The integer literal 1 if the implementation is a hosted 385 // implementation or the integer literal 0 if it is not. 386 if (LangOpts.Freestanding) 387 Builder.defineMacro("__STDC_HOSTED__", "0"); 388 else 389 Builder.defineMacro("__STDC_HOSTED__"); 390 391 // -- __STDC_VERSION__ 392 // [C++] Whether __STDC_VERSION__ is predefined and if so, what its 393 // value is, are implementation-defined. 394 // (Removed in C++20.) 395 if (!LangOpts.CPlusPlus) { 396 // FIXME: Use correct value for C23. 397 if (LangOpts.C2x) 398 Builder.defineMacro("__STDC_VERSION__", "202000L"); 399 else if (LangOpts.C17) 400 Builder.defineMacro("__STDC_VERSION__", "201710L"); 401 else if (LangOpts.C11) 402 Builder.defineMacro("__STDC_VERSION__", "201112L"); 403 else if (LangOpts.C99) 404 Builder.defineMacro("__STDC_VERSION__", "199901L"); 405 else if (!LangOpts.GNUMode && LangOpts.Digraphs) 406 Builder.defineMacro("__STDC_VERSION__", "199409L"); 407 } else { 408 // -- __cplusplus 409 // FIXME: Use correct value for C++23. 410 if (LangOpts.CPlusPlus2b) 411 Builder.defineMacro("__cplusplus", "202101L"); 412 // [C++20] The integer literal 202002L. 413 else if (LangOpts.CPlusPlus20) 414 Builder.defineMacro("__cplusplus", "202002L"); 415 // [C++17] The integer literal 201703L. 416 else if (LangOpts.CPlusPlus17) 417 Builder.defineMacro("__cplusplus", "201703L"); 418 // [C++14] The name __cplusplus is defined to the value 201402L when 419 // compiling a C++ translation unit. 420 else if (LangOpts.CPlusPlus14) 421 Builder.defineMacro("__cplusplus", "201402L"); 422 // [C++11] The name __cplusplus is defined to the value 201103L when 423 // compiling a C++ translation unit. 424 else if (LangOpts.CPlusPlus11) 425 Builder.defineMacro("__cplusplus", "201103L"); 426 // [C++03] The name __cplusplus is defined to the value 199711L when 427 // compiling a C++ translation unit. 428 else 429 Builder.defineMacro("__cplusplus", "199711L"); 430 431 // -- __STDCPP_DEFAULT_NEW_ALIGNMENT__ 432 // [C++17] An integer literal of type std::size_t whose value is the 433 // alignment guaranteed by a call to operator new(std::size_t) 434 // 435 // We provide this in all language modes, since it seems generally useful. 436 Builder.defineMacro("__STDCPP_DEFAULT_NEW_ALIGNMENT__", 437 Twine(TI.getNewAlign() / TI.getCharWidth()) + 438 TI.getTypeConstantSuffix(TI.getSizeType())); 439 440 // -- __STDCPP_THREADS__ 441 // Defined, and has the value integer literal 1, if and only if a 442 // program can have more than one thread of execution. 443 if (LangOpts.getThreadModel() == LangOptions::ThreadModelKind::POSIX) 444 Builder.defineMacro("__STDCPP_THREADS__", "1"); 445 } 446 447 // In C11 these are environment macros. In C++11 they are only defined 448 // as part of <cuchar>. To prevent breakage when mixing C and C++ 449 // code, define these macros unconditionally. We can define them 450 // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit 451 // and 32-bit character literals. 452 Builder.defineMacro("__STDC_UTF_16__", "1"); 453 Builder.defineMacro("__STDC_UTF_32__", "1"); 454 455 if (LangOpts.ObjC) 456 Builder.defineMacro("__OBJC__"); 457 458 // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros. 459 if (LangOpts.OpenCL) { 460 if (LangOpts.CPlusPlus) { 461 switch (LangOpts.OpenCLCPlusPlusVersion) { 462 case 100: 463 Builder.defineMacro("__OPENCL_CPP_VERSION__", "100"); 464 break; 465 case 202100: 466 Builder.defineMacro("__OPENCL_CPP_VERSION__", "202100"); 467 break; 468 default: 469 llvm_unreachable("Unsupported C++ version for OpenCL"); 470 } 471 Builder.defineMacro("__CL_CPP_VERSION_1_0__", "100"); 472 Builder.defineMacro("__CL_CPP_VERSION_2021__", "202100"); 473 } else { 474 // OpenCL v1.0 and v1.1 do not have a predefined macro to indicate the 475 // language standard with which the program is compiled. __OPENCL_VERSION__ 476 // is for the OpenCL version supported by the OpenCL device, which is not 477 // necessarily the language standard with which the program is compiled. 478 // A shared OpenCL header file requires a macro to indicate the language 479 // standard. As a workaround, __OPENCL_C_VERSION__ is defined for 480 // OpenCL v1.0 and v1.1. 481 switch (LangOpts.OpenCLVersion) { 482 case 100: 483 Builder.defineMacro("__OPENCL_C_VERSION__", "100"); 484 break; 485 case 110: 486 Builder.defineMacro("__OPENCL_C_VERSION__", "110"); 487 break; 488 case 120: 489 Builder.defineMacro("__OPENCL_C_VERSION__", "120"); 490 break; 491 case 200: 492 Builder.defineMacro("__OPENCL_C_VERSION__", "200"); 493 break; 494 case 300: 495 Builder.defineMacro("__OPENCL_C_VERSION__", "300"); 496 break; 497 default: 498 llvm_unreachable("Unsupported OpenCL version"); 499 } 500 } 501 Builder.defineMacro("CL_VERSION_1_0", "100"); 502 Builder.defineMacro("CL_VERSION_1_1", "110"); 503 Builder.defineMacro("CL_VERSION_1_2", "120"); 504 Builder.defineMacro("CL_VERSION_2_0", "200"); 505 Builder.defineMacro("CL_VERSION_3_0", "300"); 506 507 if (TI.isLittleEndian()) 508 Builder.defineMacro("__ENDIAN_LITTLE__"); 509 510 if (LangOpts.FastRelaxedMath) 511 Builder.defineMacro("__FAST_RELAXED_MATH__"); 512 } 513 514 if (LangOpts.SYCLIsDevice || LangOpts.SYCLIsHost) { 515 // SYCL Version is set to a value when building SYCL applications 516 if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2017) 517 Builder.defineMacro("CL_SYCL_LANGUAGE_VERSION", "121"); 518 else if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2020) 519 Builder.defineMacro("SYCL_LANGUAGE_VERSION", "202001"); 520 } 521 522 // Not "standard" per se, but available even with the -undef flag. 523 if (LangOpts.AsmPreprocessor) 524 Builder.defineMacro("__ASSEMBLER__"); 525 if (LangOpts.CUDA) { 526 if (LangOpts.GPURelocatableDeviceCode) 527 Builder.defineMacro("__CLANG_RDC__"); 528 if (!LangOpts.HIP) 529 Builder.defineMacro("__CUDA__"); 530 } 531 if (LangOpts.HIP) { 532 Builder.defineMacro("__HIP__"); 533 Builder.defineMacro("__HIPCC__"); 534 Builder.defineMacro("__HIP_MEMORY_SCOPE_SINGLETHREAD", "1"); 535 Builder.defineMacro("__HIP_MEMORY_SCOPE_WAVEFRONT", "2"); 536 Builder.defineMacro("__HIP_MEMORY_SCOPE_WORKGROUP", "3"); 537 Builder.defineMacro("__HIP_MEMORY_SCOPE_AGENT", "4"); 538 Builder.defineMacro("__HIP_MEMORY_SCOPE_SYSTEM", "5"); 539 if (LangOpts.CUDAIsDevice) 540 Builder.defineMacro("__HIP_DEVICE_COMPILE__"); 541 if (LangOpts.GPUDefaultStream == 542 LangOptions::GPUDefaultStreamKind::PerThread) 543 Builder.defineMacro("HIP_API_PER_THREAD_DEFAULT_STREAM"); 544 } 545 } 546 547 /// Initialize the predefined C++ language feature test macros defined in 548 /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations". 549 static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, 550 MacroBuilder &Builder) { 551 // C++98 features. 552 if (LangOpts.RTTI) 553 Builder.defineMacro("__cpp_rtti", "199711L"); 554 if (LangOpts.CXXExceptions) 555 Builder.defineMacro("__cpp_exceptions", "199711L"); 556 557 // C++11 features. 558 if (LangOpts.CPlusPlus11) { 559 Builder.defineMacro("__cpp_unicode_characters", "200704L"); 560 Builder.defineMacro("__cpp_raw_strings", "200710L"); 561 Builder.defineMacro("__cpp_unicode_literals", "200710L"); 562 Builder.defineMacro("__cpp_user_defined_literals", "200809L"); 563 Builder.defineMacro("__cpp_lambdas", "200907L"); 564 Builder.defineMacro("__cpp_constexpr", LangOpts.CPlusPlus2b ? "202110L" 565 : LangOpts.CPlusPlus20 ? "201907L" 566 : LangOpts.CPlusPlus17 ? "201603L" 567 : LangOpts.CPlusPlus14 ? "201304L" 568 : "200704"); 569 Builder.defineMacro("__cpp_constexpr_in_decltype", "201711L"); 570 Builder.defineMacro("__cpp_range_based_for", 571 LangOpts.CPlusPlus17 ? "201603L" : "200907"); 572 Builder.defineMacro("__cpp_static_assert", 573 LangOpts.CPlusPlus17 ? "201411L" : "200410"); 574 Builder.defineMacro("__cpp_decltype", "200707L"); 575 Builder.defineMacro("__cpp_attributes", "200809L"); 576 Builder.defineMacro("__cpp_rvalue_references", "200610L"); 577 Builder.defineMacro("__cpp_variadic_templates", "200704L"); 578 Builder.defineMacro("__cpp_initializer_lists", "200806L"); 579 Builder.defineMacro("__cpp_delegating_constructors", "200604L"); 580 Builder.defineMacro("__cpp_nsdmi", "200809L"); 581 Builder.defineMacro("__cpp_inheriting_constructors", "201511L"); 582 Builder.defineMacro("__cpp_ref_qualifiers", "200710L"); 583 Builder.defineMacro("__cpp_alias_templates", "200704L"); 584 } 585 if (LangOpts.ThreadsafeStatics) 586 Builder.defineMacro("__cpp_threadsafe_static_init", "200806L"); 587 588 // C++14 features. 589 if (LangOpts.CPlusPlus14) { 590 Builder.defineMacro("__cpp_binary_literals", "201304L"); 591 Builder.defineMacro("__cpp_digit_separators", "201309L"); 592 Builder.defineMacro("__cpp_init_captures", 593 LangOpts.CPlusPlus20 ? "201803L" : "201304L"); 594 Builder.defineMacro("__cpp_generic_lambdas", 595 LangOpts.CPlusPlus20 ? "201707L" : "201304L"); 596 Builder.defineMacro("__cpp_decltype_auto", "201304L"); 597 Builder.defineMacro("__cpp_return_type_deduction", "201304L"); 598 Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L"); 599 Builder.defineMacro("__cpp_variable_templates", "201304L"); 600 } 601 if (LangOpts.SizedDeallocation) 602 Builder.defineMacro("__cpp_sized_deallocation", "201309L"); 603 604 // C++17 features. 605 if (LangOpts.CPlusPlus17) { 606 Builder.defineMacro("__cpp_hex_float", "201603L"); 607 Builder.defineMacro("__cpp_inline_variables", "201606L"); 608 Builder.defineMacro("__cpp_noexcept_function_type", "201510L"); 609 Builder.defineMacro("__cpp_capture_star_this", "201603L"); 610 Builder.defineMacro("__cpp_if_constexpr", "201606L"); 611 Builder.defineMacro("__cpp_deduction_guides", "201703L"); // (not latest) 612 Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name) 613 Builder.defineMacro("__cpp_namespace_attributes", "201411L"); 614 Builder.defineMacro("__cpp_enumerator_attributes", "201411L"); 615 Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L"); 616 Builder.defineMacro("__cpp_variadic_using", "201611L"); 617 Builder.defineMacro("__cpp_aggregate_bases", "201603L"); 618 Builder.defineMacro("__cpp_structured_bindings", "201606L"); 619 Builder.defineMacro("__cpp_nontype_template_args", 620 "201411L"); // (not latest) 621 Builder.defineMacro("__cpp_fold_expressions", "201603L"); 622 Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L"); 623 Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L"); 624 } 625 if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable) 626 Builder.defineMacro("__cpp_aligned_new", "201606L"); 627 if (LangOpts.RelaxedTemplateTemplateArgs) 628 Builder.defineMacro("__cpp_template_template_args", "201611L"); 629 630 // C++20 features. 631 if (LangOpts.CPlusPlus20) { 632 //Builder.defineMacro("__cpp_aggregate_paren_init", "201902L"); 633 Builder.defineMacro("__cpp_concepts", "201907L"); 634 Builder.defineMacro("__cpp_conditional_explicit", "201806L"); 635 //Builder.defineMacro("__cpp_consteval", "201811L"); 636 Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L"); 637 Builder.defineMacro("__cpp_constinit", "201907L"); 638 Builder.defineMacro("__cpp_impl_coroutine", "201902L"); 639 Builder.defineMacro("__cpp_designated_initializers", "201707L"); 640 Builder.defineMacro("__cpp_impl_three_way_comparison", "201907L"); 641 //Builder.defineMacro("__cpp_modules", "201907L"); 642 Builder.defineMacro("__cpp_using_enum", "201907L"); 643 } 644 // C++2b features. 645 if (LangOpts.CPlusPlus2b) { 646 Builder.defineMacro("__cpp_implicit_move", "202011L"); 647 Builder.defineMacro("__cpp_size_t_suffix", "202011L"); 648 Builder.defineMacro("__cpp_if_consteval", "202106L"); 649 Builder.defineMacro("__cpp_multidimensional_subscript", "202110L"); 650 } 651 if (LangOpts.Char8) 652 Builder.defineMacro("__cpp_char8_t", "201811L"); 653 Builder.defineMacro("__cpp_impl_destroying_delete", "201806L"); 654 655 // TS features. 656 if (LangOpts.Coroutines) 657 Builder.defineMacro("__cpp_coroutines", "201703L"); 658 } 659 660 /// InitializeOpenCLFeatureTestMacros - Define OpenCL macros based on target 661 /// settings and language version 662 void InitializeOpenCLFeatureTestMacros(const TargetInfo &TI, 663 const LangOptions &Opts, 664 MacroBuilder &Builder) { 665 const llvm::StringMap<bool> &OpenCLFeaturesMap = TI.getSupportedOpenCLOpts(); 666 // FIXME: OpenCL options which affect language semantics/syntax 667 // should be moved into LangOptions. 668 auto defineOpenCLExtMacro = [&](llvm::StringRef Name, auto... OptArgs) { 669 // Check if extension is supported by target and is available in this 670 // OpenCL version 671 if (TI.hasFeatureEnabled(OpenCLFeaturesMap, Name) && 672 OpenCLOptions::isOpenCLOptionAvailableIn(Opts, OptArgs...)) 673 Builder.defineMacro(Name); 674 }; 675 #define OPENCL_GENERIC_EXTENSION(Ext, ...) \ 676 defineOpenCLExtMacro(#Ext, __VA_ARGS__); 677 #include "clang/Basic/OpenCLExtensions.def" 678 679 // Assume compiling for FULL profile 680 Builder.defineMacro("__opencl_c_int64"); 681 } 682 683 static void InitializePredefinedMacros(const TargetInfo &TI, 684 const LangOptions &LangOpts, 685 const FrontendOptions &FEOpts, 686 const PreprocessorOptions &PPOpts, 687 MacroBuilder &Builder) { 688 // Compiler version introspection macros. 689 Builder.defineMacro("__llvm__"); // LLVM Backend 690 Builder.defineMacro("__clang__"); // Clang Frontend 691 #define TOSTR2(X) #X 692 #define TOSTR(X) TOSTR2(X) 693 Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR)); 694 Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR)); 695 Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL)); 696 #undef TOSTR 697 #undef TOSTR2 698 Builder.defineMacro("__clang_version__", 699 "\"" CLANG_VERSION_STRING " " 700 + getClangFullRepositoryVersion() + "\""); 701 702 if (LangOpts.GNUCVersion != 0) { 703 // Major, minor, patch, are given two decimal places each, so 4.2.1 becomes 704 // 40201. 705 unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100; 706 unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100; 707 unsigned GNUCPatch = LangOpts.GNUCVersion % 100; 708 Builder.defineMacro("__GNUC__", Twine(GNUCMajor)); 709 Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor)); 710 Builder.defineMacro("__GNUC_PATCHLEVEL__", Twine(GNUCPatch)); 711 Builder.defineMacro("__GXX_ABI_VERSION", "1002"); 712 713 if (LangOpts.CPlusPlus) { 714 Builder.defineMacro("__GNUG__", Twine(GNUCMajor)); 715 Builder.defineMacro("__GXX_WEAK__"); 716 } 717 } 718 719 // Define macros for the C11 / C++11 memory orderings 720 Builder.defineMacro("__ATOMIC_RELAXED", "0"); 721 Builder.defineMacro("__ATOMIC_CONSUME", "1"); 722 Builder.defineMacro("__ATOMIC_ACQUIRE", "2"); 723 Builder.defineMacro("__ATOMIC_RELEASE", "3"); 724 Builder.defineMacro("__ATOMIC_ACQ_REL", "4"); 725 Builder.defineMacro("__ATOMIC_SEQ_CST", "5"); 726 727 // Define macros for the OpenCL memory scope. 728 // The values should match AtomicScopeOpenCLModel::ID enum. 729 static_assert( 730 static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 && 731 static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 && 732 static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 && 733 static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4, 734 "Invalid OpenCL memory scope enum definition"); 735 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0"); 736 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1"); 737 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2"); 738 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3"); 739 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4"); 740 741 // Support for #pragma redefine_extname (Sun compatibility) 742 Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1"); 743 744 // Previously this macro was set to a string aiming to achieve compatibility 745 // with GCC 4.2.1. Now, just return the full Clang version 746 Builder.defineMacro("__VERSION__", "\"" + 747 Twine(getClangFullCPPVersion()) + "\""); 748 749 // Initialize language-specific preprocessor defines. 750 751 // Standard conforming mode? 752 if (!LangOpts.GNUMode && !LangOpts.MSVCCompat) 753 Builder.defineMacro("__STRICT_ANSI__"); 754 755 if (LangOpts.GNUCVersion && LangOpts.CPlusPlus11) 756 Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__"); 757 758 if (LangOpts.ObjC) { 759 if (LangOpts.ObjCRuntime.isNonFragile()) { 760 Builder.defineMacro("__OBJC2__"); 761 762 if (LangOpts.ObjCExceptions) 763 Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS"); 764 } 765 766 if (LangOpts.getGC() != LangOptions::NonGC) 767 Builder.defineMacro("__OBJC_GC__"); 768 769 if (LangOpts.ObjCRuntime.isNeXTFamily()) 770 Builder.defineMacro("__NEXT_RUNTIME__"); 771 772 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) { 773 auto version = LangOpts.ObjCRuntime.getVersion(); 774 std::string versionString = "1"; 775 // Don't rely on the tuple argument, because we can be asked to target 776 // later ABIs than we actually support, so clamp these values to those 777 // currently supported 778 if (version >= VersionTuple(2, 0)) 779 Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20"); 780 else 781 Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", 782 "1" + Twine(std::min(8U, version.getMinor().getValueOr(0)))); 783 } 784 785 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) { 786 VersionTuple tuple = LangOpts.ObjCRuntime.getVersion(); 787 788 unsigned minor = 0; 789 if (tuple.getMinor().hasValue()) 790 minor = tuple.getMinor().getValue(); 791 792 unsigned subminor = 0; 793 if (tuple.getSubminor().hasValue()) 794 subminor = tuple.getSubminor().getValue(); 795 796 Builder.defineMacro("__OBJFW_RUNTIME_ABI__", 797 Twine(tuple.getMajor() * 10000 + minor * 100 + 798 subminor)); 799 } 800 801 Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))"); 802 Builder.defineMacro("IBOutletCollection(ClassName)", 803 "__attribute__((iboutletcollection(ClassName)))"); 804 Builder.defineMacro("IBAction", "void)__attribute__((ibaction)"); 805 Builder.defineMacro("IBInspectable", ""); 806 Builder.defineMacro("IB_DESIGNABLE", ""); 807 } 808 809 // Define a macro that describes the Objective-C boolean type even for C 810 // and C++ since BOOL can be used from non Objective-C code. 811 Builder.defineMacro("__OBJC_BOOL_IS_BOOL", 812 Twine(TI.useSignedCharForObjCBool() ? "0" : "1")); 813 814 if (LangOpts.CPlusPlus) 815 InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder); 816 817 // darwin_constant_cfstrings controls this. This is also dependent 818 // on other things like the runtime I believe. This is set even for C code. 819 if (!LangOpts.NoConstantCFStrings) 820 Builder.defineMacro("__CONSTANT_CFSTRINGS__"); 821 822 if (LangOpts.ObjC) 823 Builder.defineMacro("OBJC_NEW_PROPERTIES"); 824 825 if (LangOpts.PascalStrings) 826 Builder.defineMacro("__PASCAL_STRINGS__"); 827 828 if (LangOpts.Blocks) { 829 Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))"); 830 Builder.defineMacro("__BLOCKS__"); 831 } 832 833 if (!LangOpts.MSVCCompat && LangOpts.Exceptions) 834 Builder.defineMacro("__EXCEPTIONS"); 835 if (LangOpts.GNUCVersion && LangOpts.RTTI) 836 Builder.defineMacro("__GXX_RTTI"); 837 838 if (LangOpts.hasSjLjExceptions()) 839 Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__"); 840 else if (LangOpts.hasSEHExceptions()) 841 Builder.defineMacro("__SEH__"); 842 else if (LangOpts.hasDWARFExceptions() && 843 (TI.getTriple().isThumb() || TI.getTriple().isARM())) 844 Builder.defineMacro("__ARM_DWARF_EH__"); 845 846 if (LangOpts.Deprecated) 847 Builder.defineMacro("__DEPRECATED"); 848 849 if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus) 850 Builder.defineMacro("__private_extern__", "extern"); 851 852 if (LangOpts.MicrosoftExt) { 853 if (LangOpts.WChar) { 854 // wchar_t supported as a keyword. 855 Builder.defineMacro("_WCHAR_T_DEFINED"); 856 Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED"); 857 } 858 } 859 860 // Macros to help identify the narrow and wide character sets 861 // FIXME: clang currently ignores -fexec-charset=. If this changes, 862 // then this may need to be updated. 863 Builder.defineMacro("__clang_literal_encoding__", "\"UTF-8\""); 864 if (TI.getTypeWidth(TI.getWCharType()) >= 32) { 865 // FIXME: 32-bit wchar_t signals UTF-32. This may change 866 // if -fwide-exec-charset= is ever supported. 867 Builder.defineMacro("__clang_wide_literal_encoding__", "\"UTF-32\""); 868 } else { 869 // FIXME: Less-than 32-bit wchar_t generally means UTF-16 870 // (e.g., Windows, 32-bit IBM). This may need to be 871 // updated if -fwide-exec-charset= is ever supported. 872 Builder.defineMacro("__clang_wide_literal_encoding__", "\"UTF-16\""); 873 } 874 875 if (LangOpts.Optimize) 876 Builder.defineMacro("__OPTIMIZE__"); 877 if (LangOpts.OptimizeSize) 878 Builder.defineMacro("__OPTIMIZE_SIZE__"); 879 880 if (LangOpts.FastMath) 881 Builder.defineMacro("__FAST_MATH__"); 882 883 // Initialize target-specific preprocessor defines. 884 885 // __BYTE_ORDER__ was added in GCC 4.6. It's analogous 886 // to the macro __BYTE_ORDER (no trailing underscores) 887 // from glibc's <endian.h> header. 888 // We don't support the PDP-11 as a target, but include 889 // the define so it can still be compared against. 890 Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234"); 891 Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321"); 892 Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412"); 893 if (TI.isBigEndian()) { 894 Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__"); 895 Builder.defineMacro("__BIG_ENDIAN__"); 896 } else { 897 Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__"); 898 Builder.defineMacro("__LITTLE_ENDIAN__"); 899 } 900 901 if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64 902 && TI.getIntWidth() == 32) { 903 Builder.defineMacro("_LP64"); 904 Builder.defineMacro("__LP64__"); 905 } 906 907 if (TI.getPointerWidth(0) == 32 && TI.getLongWidth() == 32 908 && TI.getIntWidth() == 32) { 909 Builder.defineMacro("_ILP32"); 910 Builder.defineMacro("__ILP32__"); 911 } 912 913 // Define type sizing macros based on the target properties. 914 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); 915 Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth())); 916 917 Builder.defineMacro("__BOOL_WIDTH__", Twine(TI.getBoolWidth())); 918 Builder.defineMacro("__SHRT_WIDTH__", Twine(TI.getShortWidth())); 919 Builder.defineMacro("__INT_WIDTH__", Twine(TI.getIntWidth())); 920 Builder.defineMacro("__LONG_WIDTH__", Twine(TI.getLongWidth())); 921 Builder.defineMacro("__LLONG_WIDTH__", Twine(TI.getLongLongWidth())); 922 923 size_t BitIntMaxWidth = TI.getMaxBitIntWidth(); 924 assert(BitIntMaxWidth <= llvm::IntegerType::MAX_INT_BITS && 925 "Target defined a max bit width larger than LLVM can support!"); 926 assert(BitIntMaxWidth >= TI.getLongLongWidth() && 927 "Target defined a max bit width smaller than the C standard allows!"); 928 Builder.defineMacro("__BITINT_MAXWIDTH__", Twine(BitIntMaxWidth)); 929 930 DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder); 931 DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder); 932 DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder); 933 DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder); 934 DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder); 935 DefineTypeSizeAndWidth("__WCHAR", TI.getWCharType(), TI, Builder); 936 DefineTypeSizeAndWidth("__WINT", TI.getWIntType(), TI, Builder); 937 DefineTypeSizeAndWidth("__INTMAX", TI.getIntMaxType(), TI, Builder); 938 DefineTypeSizeAndWidth("__SIZE", TI.getSizeType(), TI, Builder); 939 940 DefineTypeSizeAndWidth("__UINTMAX", TI.getUIntMaxType(), TI, Builder); 941 DefineTypeSizeAndWidth("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder); 942 DefineTypeSizeAndWidth("__INTPTR", TI.getIntPtrType(), TI, Builder); 943 DefineTypeSizeAndWidth("__UINTPTR", TI.getUIntPtrType(), TI, Builder); 944 945 DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder); 946 DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder); 947 DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder); 948 DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder); 949 DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder); 950 DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder); 951 DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder); 952 DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder); 953 DefineTypeSizeof("__SIZEOF_PTRDIFF_T__", 954 TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder); 955 DefineTypeSizeof("__SIZEOF_SIZE_T__", 956 TI.getTypeWidth(TI.getSizeType()), TI, Builder); 957 DefineTypeSizeof("__SIZEOF_WCHAR_T__", 958 TI.getTypeWidth(TI.getWCharType()), TI, Builder); 959 DefineTypeSizeof("__SIZEOF_WINT_T__", 960 TI.getTypeWidth(TI.getWIntType()), TI, Builder); 961 if (TI.hasInt128Type()) 962 DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder); 963 964 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder); 965 DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder); 966 Builder.defineMacro("__INTMAX_C_SUFFIX__", 967 TI.getTypeConstantSuffix(TI.getIntMaxType())); 968 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder); 969 DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder); 970 Builder.defineMacro("__UINTMAX_C_SUFFIX__", 971 TI.getTypeConstantSuffix(TI.getUIntMaxType())); 972 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder); 973 DefineFmt("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder); 974 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder); 975 DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder); 976 DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder); 977 DefineFmt("__SIZE", TI.getSizeType(), TI, Builder); 978 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder); 979 DefineType("__WINT_TYPE__", TI.getWIntType(), Builder); 980 DefineTypeSizeAndWidth("__SIG_ATOMIC", TI.getSigAtomicType(), TI, Builder); 981 DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder); 982 DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder); 983 984 DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder); 985 DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder); 986 987 // The C standard requires the width of uintptr_t and intptr_t to be the same, 988 // per 7.20.2.4p1. Same for intmax_t and uintmax_t, per 7.20.2.5p1. 989 assert(TI.getTypeWidth(TI.getUIntPtrType()) == 990 TI.getTypeWidth(TI.getIntPtrType()) && 991 "uintptr_t and intptr_t have different widths?"); 992 assert(TI.getTypeWidth(TI.getUIntMaxType()) == 993 TI.getTypeWidth(TI.getIntMaxType()) && 994 "uintmax_t and intmax_t have different widths?"); 995 996 if (TI.hasFloat16Type()) 997 DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16"); 998 DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F"); 999 DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), ""); 1000 DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L"); 1001 1002 // Define a __POINTER_WIDTH__ macro for stdint.h. 1003 Builder.defineMacro("__POINTER_WIDTH__", 1004 Twine((int)TI.getPointerWidth(0))); 1005 1006 // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc. 1007 Builder.defineMacro("__BIGGEST_ALIGNMENT__", 1008 Twine(TI.getSuitableAlign() / TI.getCharWidth()) ); 1009 1010 if (!LangOpts.CharIsSigned) 1011 Builder.defineMacro("__CHAR_UNSIGNED__"); 1012 1013 if (!TargetInfo::isTypeSigned(TI.getWCharType())) 1014 Builder.defineMacro("__WCHAR_UNSIGNED__"); 1015 1016 if (!TargetInfo::isTypeSigned(TI.getWIntType())) 1017 Builder.defineMacro("__WINT_UNSIGNED__"); 1018 1019 // Define exact-width integer types for stdint.h 1020 DefineExactWidthIntType(TargetInfo::SignedChar, TI, Builder); 1021 1022 if (TI.getShortWidth() > TI.getCharWidth()) 1023 DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder); 1024 1025 if (TI.getIntWidth() > TI.getShortWidth()) 1026 DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder); 1027 1028 if (TI.getLongWidth() > TI.getIntWidth()) 1029 DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder); 1030 1031 if (TI.getLongLongWidth() > TI.getLongWidth()) 1032 DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder); 1033 1034 DefineExactWidthIntType(TargetInfo::UnsignedChar, TI, Builder); 1035 DefineExactWidthIntTypeSize(TargetInfo::UnsignedChar, TI, Builder); 1036 DefineExactWidthIntTypeSize(TargetInfo::SignedChar, TI, Builder); 1037 1038 if (TI.getShortWidth() > TI.getCharWidth()) { 1039 DefineExactWidthIntType(TargetInfo::UnsignedShort, TI, Builder); 1040 DefineExactWidthIntTypeSize(TargetInfo::UnsignedShort, TI, Builder); 1041 DefineExactWidthIntTypeSize(TargetInfo::SignedShort, TI, Builder); 1042 } 1043 1044 if (TI.getIntWidth() > TI.getShortWidth()) { 1045 DefineExactWidthIntType(TargetInfo::UnsignedInt, TI, Builder); 1046 DefineExactWidthIntTypeSize(TargetInfo::UnsignedInt, TI, Builder); 1047 DefineExactWidthIntTypeSize(TargetInfo::SignedInt, TI, Builder); 1048 } 1049 1050 if (TI.getLongWidth() > TI.getIntWidth()) { 1051 DefineExactWidthIntType(TargetInfo::UnsignedLong, TI, Builder); 1052 DefineExactWidthIntTypeSize(TargetInfo::UnsignedLong, TI, Builder); 1053 DefineExactWidthIntTypeSize(TargetInfo::SignedLong, TI, Builder); 1054 } 1055 1056 if (TI.getLongLongWidth() > TI.getLongWidth()) { 1057 DefineExactWidthIntType(TargetInfo::UnsignedLongLong, TI, Builder); 1058 DefineExactWidthIntTypeSize(TargetInfo::UnsignedLongLong, TI, Builder); 1059 DefineExactWidthIntTypeSize(TargetInfo::SignedLongLong, TI, Builder); 1060 } 1061 1062 DefineLeastWidthIntType(8, true, TI, Builder); 1063 DefineLeastWidthIntType(8, false, TI, Builder); 1064 DefineLeastWidthIntType(16, true, TI, Builder); 1065 DefineLeastWidthIntType(16, false, TI, Builder); 1066 DefineLeastWidthIntType(32, true, TI, Builder); 1067 DefineLeastWidthIntType(32, false, TI, Builder); 1068 DefineLeastWidthIntType(64, true, TI, Builder); 1069 DefineLeastWidthIntType(64, false, TI, Builder); 1070 1071 DefineFastIntType(8, true, TI, Builder); 1072 DefineFastIntType(8, false, TI, Builder); 1073 DefineFastIntType(16, true, TI, Builder); 1074 DefineFastIntType(16, false, TI, Builder); 1075 DefineFastIntType(32, true, TI, Builder); 1076 DefineFastIntType(32, false, TI, Builder); 1077 DefineFastIntType(64, true, TI, Builder); 1078 DefineFastIntType(64, false, TI, Builder); 1079 1080 Builder.defineMacro("__USER_LABEL_PREFIX__", TI.getUserLabelPrefix()); 1081 1082 if (!LangOpts.MathErrno) 1083 Builder.defineMacro("__NO_MATH_ERRNO__"); 1084 1085 if (LangOpts.FastMath || LangOpts.FiniteMathOnly) 1086 Builder.defineMacro("__FINITE_MATH_ONLY__", "1"); 1087 else 1088 Builder.defineMacro("__FINITE_MATH_ONLY__", "0"); 1089 1090 if (LangOpts.GNUCVersion) { 1091 if (LangOpts.GNUInline || LangOpts.CPlusPlus) 1092 Builder.defineMacro("__GNUC_GNU_INLINE__"); 1093 else 1094 Builder.defineMacro("__GNUC_STDC_INLINE__"); 1095 1096 // The value written by __atomic_test_and_set. 1097 // FIXME: This is target-dependent. 1098 Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1"); 1099 } 1100 1101 auto addLockFreeMacros = [&](const llvm::Twine &Prefix) { 1102 // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE. 1103 unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth(); 1104 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \ 1105 Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", \ 1106 getLockFreeValue(TI.get##Type##Width(), \ 1107 TI.get##Type##Align(), \ 1108 InlineWidthBits)); 1109 DEFINE_LOCK_FREE_MACRO(BOOL, Bool); 1110 DEFINE_LOCK_FREE_MACRO(CHAR, Char); 1111 if (LangOpts.Char8) 1112 DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char. 1113 DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16); 1114 DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32); 1115 DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar); 1116 DEFINE_LOCK_FREE_MACRO(SHORT, Short); 1117 DEFINE_LOCK_FREE_MACRO(INT, Int); 1118 DEFINE_LOCK_FREE_MACRO(LONG, Long); 1119 DEFINE_LOCK_FREE_MACRO(LLONG, LongLong); 1120 Builder.defineMacro(Prefix + "POINTER_LOCK_FREE", 1121 getLockFreeValue(TI.getPointerWidth(0), 1122 TI.getPointerAlign(0), 1123 InlineWidthBits)); 1124 #undef DEFINE_LOCK_FREE_MACRO 1125 }; 1126 addLockFreeMacros("__CLANG_ATOMIC_"); 1127 if (LangOpts.GNUCVersion) 1128 addLockFreeMacros("__GCC_ATOMIC_"); 1129 1130 if (LangOpts.NoInlineDefine) 1131 Builder.defineMacro("__NO_INLINE__"); 1132 1133 if (unsigned PICLevel = LangOpts.PICLevel) { 1134 Builder.defineMacro("__PIC__", Twine(PICLevel)); 1135 Builder.defineMacro("__pic__", Twine(PICLevel)); 1136 if (LangOpts.PIE) { 1137 Builder.defineMacro("__PIE__", Twine(PICLevel)); 1138 Builder.defineMacro("__pie__", Twine(PICLevel)); 1139 } 1140 } 1141 1142 // Macros to control C99 numerics and <float.h> 1143 Builder.defineMacro("__FLT_RADIX__", "2"); 1144 Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__"); 1145 1146 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1147 Builder.defineMacro("__SSP__"); 1148 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1149 Builder.defineMacro("__SSP_STRONG__", "2"); 1150 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1151 Builder.defineMacro("__SSP_ALL__", "3"); 1152 1153 if (PPOpts.SetUpStaticAnalyzer) 1154 Builder.defineMacro("__clang_analyzer__"); 1155 1156 if (LangOpts.FastRelaxedMath) 1157 Builder.defineMacro("__FAST_RELAXED_MATH__"); 1158 1159 if (FEOpts.ProgramAction == frontend::RewriteObjC || 1160 LangOpts.getGC() != LangOptions::NonGC) { 1161 Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))"); 1162 Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))"); 1163 Builder.defineMacro("__autoreleasing", ""); 1164 Builder.defineMacro("__unsafe_unretained", ""); 1165 } else if (LangOpts.ObjC) { 1166 Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))"); 1167 Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))"); 1168 Builder.defineMacro("__autoreleasing", 1169 "__attribute__((objc_ownership(autoreleasing)))"); 1170 Builder.defineMacro("__unsafe_unretained", 1171 "__attribute__((objc_ownership(none)))"); 1172 } 1173 1174 // On Darwin, there are __double_underscored variants of the type 1175 // nullability qualifiers. 1176 if (TI.getTriple().isOSDarwin()) { 1177 Builder.defineMacro("__nonnull", "_Nonnull"); 1178 Builder.defineMacro("__null_unspecified", "_Null_unspecified"); 1179 Builder.defineMacro("__nullable", "_Nullable"); 1180 } 1181 1182 // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and 1183 // the corresponding simulator targets. 1184 if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment()) 1185 Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1"); 1186 1187 // OpenMP definition 1188 // OpenMP 2.2: 1189 // In implementations that support a preprocessor, the _OPENMP 1190 // macro name is defined to have the decimal value yyyymm where 1191 // yyyy and mm are the year and the month designations of the 1192 // version of the OpenMP API that the implementation support. 1193 if (!LangOpts.OpenMPSimd) { 1194 switch (LangOpts.OpenMP) { 1195 case 0: 1196 break; 1197 case 31: 1198 Builder.defineMacro("_OPENMP", "201107"); 1199 break; 1200 case 40: 1201 Builder.defineMacro("_OPENMP", "201307"); 1202 break; 1203 case 45: 1204 Builder.defineMacro("_OPENMP", "201511"); 1205 break; 1206 case 51: 1207 Builder.defineMacro("_OPENMP", "202011"); 1208 break; 1209 case 52: 1210 Builder.defineMacro("_OPENMP", "202111"); 1211 break; 1212 default: 1213 // Default version is OpenMP 5.0 1214 Builder.defineMacro("_OPENMP", "201811"); 1215 break; 1216 } 1217 } 1218 1219 // CUDA device path compilaton 1220 if (LangOpts.CUDAIsDevice && !LangOpts.HIP) { 1221 // The CUDA_ARCH value is set for the GPU target specified in the NVPTX 1222 // backend's target defines. 1223 Builder.defineMacro("__CUDA_ARCH__"); 1224 } 1225 1226 // We need to communicate this to our CUDA header wrapper, which in turn 1227 // informs the proper CUDA headers of this choice. 1228 if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) { 1229 Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__"); 1230 } 1231 1232 // Define a macro indicating that the source file is being compiled with a 1233 // SYCL device compiler which doesn't produce host binary. 1234 if (LangOpts.SYCLIsDevice) { 1235 Builder.defineMacro("__SYCL_DEVICE_ONLY__", "1"); 1236 } 1237 1238 // OpenCL definitions. 1239 if (LangOpts.OpenCL) { 1240 InitializeOpenCLFeatureTestMacros(TI, LangOpts, Builder); 1241 1242 if (TI.getTriple().isSPIR() || TI.getTriple().isSPIRV()) 1243 Builder.defineMacro("__IMAGE_SUPPORT__"); 1244 } 1245 1246 if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) { 1247 // For each extended integer type, g++ defines a macro mapping the 1248 // index of the type (0 in this case) in some list of extended types 1249 // to the type. 1250 Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128"); 1251 Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128"); 1252 } 1253 1254 // Get other target #defines. 1255 TI.getTargetDefines(LangOpts, Builder); 1256 } 1257 1258 /// InitializePreprocessor - Initialize the preprocessor getting it and the 1259 /// environment ready to process a single file. This returns true on error. 1260 /// 1261 void clang::InitializePreprocessor( 1262 Preprocessor &PP, const PreprocessorOptions &InitOpts, 1263 const PCHContainerReader &PCHContainerRdr, 1264 const FrontendOptions &FEOpts) { 1265 const LangOptions &LangOpts = PP.getLangOpts(); 1266 std::string PredefineBuffer; 1267 PredefineBuffer.reserve(4080); 1268 llvm::raw_string_ostream Predefines(PredefineBuffer); 1269 MacroBuilder Builder(Predefines); 1270 1271 // Emit line markers for various builtin sections of the file. We don't do 1272 // this in asm preprocessor mode, because "# 4" is not a line marker directive 1273 // in this mode. 1274 if (!PP.getLangOpts().AsmPreprocessor) 1275 Builder.append("# 1 \"<built-in>\" 3"); 1276 1277 // Install things like __POWERPC__, __GNUC__, etc into the macro table. 1278 if (InitOpts.UsePredefines) { 1279 // FIXME: This will create multiple definitions for most of the predefined 1280 // macros. This is not the right way to handle this. 1281 if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice || LangOpts.SYCLIsDevice) && 1282 PP.getAuxTargetInfo()) 1283 InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts, 1284 PP.getPreprocessorOpts(), Builder); 1285 1286 InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, 1287 PP.getPreprocessorOpts(), Builder); 1288 1289 // Install definitions to make Objective-C++ ARC work well with various 1290 // C++ Standard Library implementations. 1291 if (LangOpts.ObjC && LangOpts.CPlusPlus && 1292 (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) { 1293 switch (InitOpts.ObjCXXARCStandardLibrary) { 1294 case ARCXX_nolib: 1295 case ARCXX_libcxx: 1296 break; 1297 1298 case ARCXX_libstdcxx: 1299 AddObjCXXARCLibstdcxxDefines(LangOpts, Builder); 1300 break; 1301 } 1302 } 1303 } 1304 1305 // Even with predefines off, some macros are still predefined. 1306 // These should all be defined in the preprocessor according to the 1307 // current language configuration. 1308 InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(), 1309 FEOpts, Builder); 1310 1311 // Add on the predefines from the driver. Wrap in a #line directive to report 1312 // that they come from the command line. 1313 if (!PP.getLangOpts().AsmPreprocessor) 1314 Builder.append("# 1 \"<command line>\" 1"); 1315 1316 // Process #define's and #undef's in the order they are given. 1317 for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) { 1318 if (InitOpts.Macros[i].second) // isUndef 1319 Builder.undefineMacro(InitOpts.Macros[i].first); 1320 else 1321 DefineBuiltinMacro(Builder, InitOpts.Macros[i].first, 1322 PP.getDiagnostics()); 1323 } 1324 1325 // Exit the command line and go back to <built-in> (2 is LC_LEAVE). 1326 if (!PP.getLangOpts().AsmPreprocessor) 1327 Builder.append("# 1 \"<built-in>\" 2"); 1328 1329 // If -imacros are specified, include them now. These are processed before 1330 // any -include directives. 1331 for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i) 1332 AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]); 1333 1334 // Process -include-pch/-include-pth directives. 1335 if (!InitOpts.ImplicitPCHInclude.empty()) 1336 AddImplicitIncludePCH(Builder, PP, PCHContainerRdr, 1337 InitOpts.ImplicitPCHInclude); 1338 1339 // Process -include directives. 1340 for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) { 1341 const std::string &Path = InitOpts.Includes[i]; 1342 AddImplicitInclude(Builder, Path); 1343 } 1344 1345 // Instruct the preprocessor to skip the preamble. 1346 PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first, 1347 InitOpts.PrecompiledPreambleBytes.second); 1348 1349 // Copy PredefinedBuffer into the Preprocessor. 1350 PP.setPredefines(Predefines.str()); 1351 } 1352