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