1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 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 actions class which performs semantic analysis and 10 // builds an AST out of a parse stream. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTDiagnostic.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclFriend.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/PrettyDeclStackTrace.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/Stack.h" 26 #include "clang/Basic/TargetInfo.h" 27 #include "clang/Lex/HeaderSearch.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/CXXFieldCollector.h" 30 #include "clang/Sema/DelayedDiagnostic.h" 31 #include "clang/Sema/ExternalSemaSource.h" 32 #include "clang/Sema/Initialization.h" 33 #include "clang/Sema/MultiplexExternalSemaSource.h" 34 #include "clang/Sema/ObjCMethodList.h" 35 #include "clang/Sema/Scope.h" 36 #include "clang/Sema/ScopeInfo.h" 37 #include "clang/Sema/SemaConsumer.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/TemplateDeduction.h" 40 #include "clang/Sema/TemplateInstCallback.h" 41 #include "clang/Sema/TypoCorrection.h" 42 #include "llvm/ADT/DenseMap.h" 43 #include "llvm/ADT/SmallSet.h" 44 #include "llvm/Support/TimeProfiler.h" 45 46 using namespace clang; 47 using namespace sema; 48 49 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { 50 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); 51 } 52 53 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); } 54 55 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, 56 const Preprocessor &PP) { 57 PrintingPolicy Policy = Context.getPrintingPolicy(); 58 // In diagnostics, we print _Bool as bool if the latter is defined as the 59 // former. 60 Policy.Bool = Context.getLangOpts().Bool; 61 if (!Policy.Bool) { 62 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) { 63 Policy.Bool = BoolMacro->isObjectLike() && 64 BoolMacro->getNumTokens() == 1 && 65 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 66 } 67 } 68 69 return Policy; 70 } 71 72 void Sema::ActOnTranslationUnitScope(Scope *S) { 73 TUScope = S; 74 PushDeclContext(S, Context.getTranslationUnitDecl()); 75 } 76 77 namespace clang { 78 namespace sema { 79 80 class SemaPPCallbacks : public PPCallbacks { 81 Sema *S = nullptr; 82 llvm::SmallVector<SourceLocation, 8> IncludeStack; 83 84 public: 85 void set(Sema &S) { this->S = &S; } 86 87 void reset() { S = nullptr; } 88 89 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 90 SrcMgr::CharacteristicKind FileType, 91 FileID PrevFID) override { 92 if (!S) 93 return; 94 switch (Reason) { 95 case EnterFile: { 96 SourceManager &SM = S->getSourceManager(); 97 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc)); 98 if (IncludeLoc.isValid()) { 99 if (llvm::timeTraceProfilerEnabled()) { 100 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc)); 101 llvm::timeTraceProfilerBegin( 102 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>")); 103 } 104 105 IncludeStack.push_back(IncludeLoc); 106 S->DiagnoseNonDefaultPragmaPack( 107 Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc); 108 } 109 break; 110 } 111 case ExitFile: 112 if (!IncludeStack.empty()) { 113 if (llvm::timeTraceProfilerEnabled()) 114 llvm::timeTraceProfilerEnd(); 115 116 S->DiagnoseNonDefaultPragmaPack( 117 Sema::PragmaPackDiagnoseKind::ChangedStateAtExit, 118 IncludeStack.pop_back_val()); 119 } 120 break; 121 default: 122 break; 123 } 124 } 125 }; 126 127 } // end namespace sema 128 } // end namespace clang 129 130 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 131 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter) 132 : ExternalSource(nullptr), isMultiplexExternalSource(false), 133 FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp), 134 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()), 135 SourceMgr(PP.getSourceManager()), CollectStats(false), 136 CodeCompleter(CodeCompleter), CurContext(nullptr), 137 OriginalLexicalContext(nullptr), MSStructPragmaOn(false), 138 MSPointerToMemberRepresentationMethod( 139 LangOpts.getMSPointerToMemberRepresentationMethod()), 140 VtorDispStack(LangOpts.getVtorDispMode()), PackStack(0), 141 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr), 142 CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr), 143 PragmaAttributeCurrentTargetDecl(nullptr), 144 IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr), 145 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp), 146 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr), 147 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr), 148 MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr), 149 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr), 150 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr), 151 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr), 152 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false), 153 TUKind(TUKind), NumSFINAEErrors(0), 154 FullyCheckedComparisonCategories( 155 static_cast<unsigned>(ComparisonCategoryType::Last) + 1), 156 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false), 157 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1), 158 CurrentInstantiationScope(nullptr), DisableTypoCorrection(false), 159 TyposCorrected(0), AnalysisWarnings(*this), 160 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr), 161 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) { 162 TUScope = nullptr; 163 isConstantEvaluatedOverride = false; 164 165 LoadedExternalKnownNamespaces = false; 166 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) 167 NSNumberLiteralMethods[I] = nullptr; 168 169 if (getLangOpts().ObjC) 170 NSAPIObj.reset(new NSAPI(Context)); 171 172 if (getLangOpts().CPlusPlus) 173 FieldCollector.reset(new CXXFieldCollector()); 174 175 // Tell diagnostics how to render things from the AST library. 176 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context); 177 178 ExprEvalContexts.emplace_back( 179 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{}, 180 nullptr, ExpressionEvaluationContextRecord::EK_Other); 181 182 // Initialization of data sharing attributes stack for OpenMP 183 InitDataSharingAttributesStack(); 184 185 std::unique_ptr<sema::SemaPPCallbacks> Callbacks = 186 std::make_unique<sema::SemaPPCallbacks>(); 187 SemaPPCallbackHandler = Callbacks.get(); 188 PP.addPPCallbacks(std::move(Callbacks)); 189 SemaPPCallbackHandler->set(*this); 190 } 191 192 // Anchor Sema's type info to this TU. 193 void Sema::anchor() {} 194 195 void Sema::addImplicitTypedef(StringRef Name, QualType T) { 196 DeclarationName DN = &Context.Idents.get(Name); 197 if (IdResolver.begin(DN) == IdResolver.end()) 198 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope); 199 } 200 201 void Sema::Initialize() { 202 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 203 SC->InitializeSema(*this); 204 205 // Tell the external Sema source about this Sema object. 206 if (ExternalSemaSource *ExternalSema 207 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 208 ExternalSema->InitializeSema(*this); 209 210 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we 211 // will not be able to merge any duplicate __va_list_tag decls correctly. 212 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 213 214 if (!TUScope) 215 return; 216 217 // Initialize predefined 128-bit integer types, if needed. 218 if (Context.getTargetInfo().hasInt128Type()) { 219 // If either of the 128-bit integer types are unavailable to name lookup, 220 // define them now. 221 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 222 if (IdResolver.begin(Int128) == IdResolver.end()) 223 PushOnScopeChains(Context.getInt128Decl(), TUScope); 224 225 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 226 if (IdResolver.begin(UInt128) == IdResolver.end()) 227 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 228 } 229 230 231 // Initialize predefined Objective-C types: 232 if (getLangOpts().ObjC) { 233 // If 'SEL' does not yet refer to any declarations, make it refer to the 234 // predefined 'SEL'. 235 DeclarationName SEL = &Context.Idents.get("SEL"); 236 if (IdResolver.begin(SEL) == IdResolver.end()) 237 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 238 239 // If 'id' does not yet refer to any declarations, make it refer to the 240 // predefined 'id'. 241 DeclarationName Id = &Context.Idents.get("id"); 242 if (IdResolver.begin(Id) == IdResolver.end()) 243 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 244 245 // Create the built-in typedef for 'Class'. 246 DeclarationName Class = &Context.Idents.get("Class"); 247 if (IdResolver.begin(Class) == IdResolver.end()) 248 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 249 250 // Create the built-in forward declaratino for 'Protocol'. 251 DeclarationName Protocol = &Context.Idents.get("Protocol"); 252 if (IdResolver.begin(Protocol) == IdResolver.end()) 253 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope); 254 } 255 256 // Create the internal type for the *StringMakeConstantString builtins. 257 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString"); 258 if (IdResolver.begin(ConstantString) == IdResolver.end()) 259 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope); 260 261 // Initialize Microsoft "predefined C++ types". 262 if (getLangOpts().MSVCCompat) { 263 if (getLangOpts().CPlusPlus && 264 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()) 265 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class), 266 TUScope); 267 268 addImplicitTypedef("size_t", Context.getSizeType()); 269 } 270 271 // Initialize predefined OpenCL types and supported extensions and (optional) 272 // core features. 273 if (getLangOpts().OpenCL) { 274 getOpenCLOptions().addSupport( 275 Context.getTargetInfo().getSupportedOpenCLOpts()); 276 getOpenCLOptions().enableSupportedCore(getLangOpts()); 277 addImplicitTypedef("sampler_t", Context.OCLSamplerTy); 278 addImplicitTypedef("event_t", Context.OCLEventTy); 279 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) { 280 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy); 281 addImplicitTypedef("queue_t", Context.OCLQueueTy); 282 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy); 283 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy)); 284 addImplicitTypedef("atomic_uint", 285 Context.getAtomicType(Context.UnsignedIntTy)); 286 auto AtomicLongT = Context.getAtomicType(Context.LongTy); 287 addImplicitTypedef("atomic_long", AtomicLongT); 288 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy); 289 addImplicitTypedef("atomic_ulong", AtomicULongT); 290 addImplicitTypedef("atomic_float", 291 Context.getAtomicType(Context.FloatTy)); 292 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy); 293 addImplicitTypedef("atomic_double", AtomicDoubleT); 294 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as 295 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide. 296 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy)); 297 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType()); 298 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT); 299 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType()); 300 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT); 301 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType()); 302 addImplicitTypedef("atomic_size_t", AtomicSizeT); 303 auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType()); 304 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT); 305 306 // OpenCL v2.0 s6.13.11.6: 307 // - The atomic_long and atomic_ulong types are supported if the 308 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics 309 // extensions are supported. 310 // - The atomic_double type is only supported if double precision 311 // is supported and the cl_khr_int64_base_atomics and 312 // cl_khr_int64_extended_atomics extensions are supported. 313 // - If the device address space is 64-bits, the data types 314 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and 315 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and 316 // cl_khr_int64_extended_atomics extensions are supported. 317 std::vector<QualType> Atomic64BitTypes; 318 Atomic64BitTypes.push_back(AtomicLongT); 319 Atomic64BitTypes.push_back(AtomicULongT); 320 Atomic64BitTypes.push_back(AtomicDoubleT); 321 if (Context.getTypeSize(AtomicSizeT) == 64) { 322 Atomic64BitTypes.push_back(AtomicSizeT); 323 Atomic64BitTypes.push_back(AtomicIntPtrT); 324 Atomic64BitTypes.push_back(AtomicUIntPtrT); 325 Atomic64BitTypes.push_back(AtomicPtrDiffT); 326 } 327 for (auto &I : Atomic64BitTypes) 328 setOpenCLExtensionForType(I, 329 "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics"); 330 331 setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64"); 332 } 333 334 setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64"); 335 336 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \ 337 setOpenCLExtensionForType(Context.Id, Ext); 338 #include "clang/Basic/OpenCLImageTypes.def" 339 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 340 addImplicitTypedef(#ExtType, Context.Id##Ty); \ 341 setOpenCLExtensionForType(Context.Id##Ty, #Ext); 342 #include "clang/Basic/OpenCLExtensionTypes.def" 343 } 344 345 if (Context.getTargetInfo().hasAArch64SVETypes()) { 346 #define SVE_TYPE(Name, Id, SingletonId) \ 347 addImplicitTypedef(Name, Context.SingletonId); 348 #include "clang/Basic/AArch64SVEACLETypes.def" 349 } 350 351 if (Context.getTargetInfo().hasBuiltinMSVaList()) { 352 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list"); 353 if (IdResolver.begin(MSVaList) == IdResolver.end()) 354 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope); 355 } 356 357 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list"); 358 if (IdResolver.begin(BuiltinVaList) == IdResolver.end()) 359 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope); 360 } 361 362 Sema::~Sema() { 363 if (VisContext) FreeVisContext(); 364 365 // Kill all the active scopes. 366 for (sema::FunctionScopeInfo *FSI : FunctionScopes) 367 delete FSI; 368 369 // Tell the SemaConsumer to forget about us; we're going out of scope. 370 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 371 SC->ForgetSema(); 372 373 // Detach from the external Sema source. 374 if (ExternalSemaSource *ExternalSema 375 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 376 ExternalSema->ForgetSema(); 377 378 // If Sema's ExternalSource is the multiplexer - we own it. 379 if (isMultiplexExternalSource) 380 delete ExternalSource; 381 382 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache); 383 384 // Destroys data sharing attributes stack for OpenMP 385 DestroyDataSharingAttributesStack(); 386 387 // Detach from the PP callback handler which outlives Sema since it's owned 388 // by the preprocessor. 389 SemaPPCallbackHandler->reset(); 390 } 391 392 void Sema::warnStackExhausted(SourceLocation Loc) { 393 // Only warn about this once. 394 if (!WarnedStackExhausted) { 395 Diag(Loc, diag::warn_stack_exhausted); 396 WarnedStackExhausted = true; 397 } 398 } 399 400 void Sema::runWithSufficientStackSpace(SourceLocation Loc, 401 llvm::function_ref<void()> Fn) { 402 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn); 403 } 404 405 /// makeUnavailableInSystemHeader - There is an error in the current 406 /// context. If we're still in a system header, and we can plausibly 407 /// make the relevant declaration unavailable instead of erroring, do 408 /// so and return true. 409 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 410 UnavailableAttr::ImplicitReason reason) { 411 // If we're not in a function, it's an error. 412 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 413 if (!fn) return false; 414 415 // If we're in template instantiation, it's an error. 416 if (inTemplateInstantiation()) 417 return false; 418 419 // If that function's not in a system header, it's an error. 420 if (!Context.getSourceManager().isInSystemHeader(loc)) 421 return false; 422 423 // If the function is already unavailable, it's not an error. 424 if (fn->hasAttr<UnavailableAttr>()) return true; 425 426 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc)); 427 return true; 428 } 429 430 ASTMutationListener *Sema::getASTMutationListener() const { 431 return getASTConsumer().GetASTMutationListener(); 432 } 433 434 ///Registers an external source. If an external source already exists, 435 /// creates a multiplex external source and appends to it. 436 /// 437 ///\param[in] E - A non-null external sema source. 438 /// 439 void Sema::addExternalSource(ExternalSemaSource *E) { 440 assert(E && "Cannot use with NULL ptr"); 441 442 if (!ExternalSource) { 443 ExternalSource = E; 444 return; 445 } 446 447 if (isMultiplexExternalSource) 448 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E); 449 else { 450 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E); 451 isMultiplexExternalSource = true; 452 } 453 } 454 455 /// Print out statistics about the semantic analysis. 456 void Sema::PrintStats() const { 457 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 458 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 459 460 BumpAlloc.PrintStats(); 461 AnalysisWarnings.PrintStats(); 462 } 463 464 void Sema::diagnoseNullableToNonnullConversion(QualType DstType, 465 QualType SrcType, 466 SourceLocation Loc) { 467 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context); 468 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable) 469 return; 470 471 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context); 472 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) 473 return; 474 475 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType; 476 } 477 478 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) { 479 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant, 480 E->getBeginLoc())) 481 return; 482 // nullptr only exists from C++11 on, so don't warn on its absence earlier. 483 if (!getLangOpts().CPlusPlus11) 484 return; 485 486 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer) 487 return; 488 if (E->IgnoreParenImpCasts()->getType()->isNullPtrType()) 489 return; 490 491 // If it is a macro from system header, and if the macro name is not "NULL", 492 // do not warn. 493 SourceLocation MaybeMacroLoc = E->getBeginLoc(); 494 if (Diags.getSuppressSystemWarnings() && 495 SourceMgr.isInSystemMacro(MaybeMacroLoc) && 496 !findMacroSpelling(MaybeMacroLoc, "NULL")) 497 return; 498 499 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant) 500 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr"); 501 } 502 503 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 504 /// If there is already an implicit cast, merge into the existing one. 505 /// The result is of the given category. 506 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 507 CastKind Kind, ExprValueKind VK, 508 const CXXCastPath *BasePath, 509 CheckedConversionKind CCK) { 510 #ifndef NDEBUG 511 if (VK == VK_RValue && !E->isRValue()) { 512 switch (Kind) { 513 default: 514 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast " 515 "kind"); 516 case CK_Dependent: 517 case CK_LValueToRValue: 518 case CK_ArrayToPointerDecay: 519 case CK_FunctionToPointerDecay: 520 case CK_ToVoid: 521 case CK_NonAtomicToAtomic: 522 break; 523 } 524 } 525 assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) && 526 "can't cast rvalue to lvalue"); 527 #endif 528 529 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc()); 530 diagnoseZeroToNullptrConversion(Kind, E); 531 532 QualType ExprTy = Context.getCanonicalType(E->getType()); 533 QualType TypeTy = Context.getCanonicalType(Ty); 534 535 if (ExprTy == TypeTy) 536 return E; 537 538 // C++1z [conv.array]: The temporary materialization conversion is applied. 539 // We also use this to fuel C++ DR1213, which applies to C++11 onwards. 540 if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus && 541 E->getValueKind() == VK_RValue) { 542 // The temporary is an lvalue in C++98 and an xvalue otherwise. 543 ExprResult Materialized = CreateMaterializeTemporaryExpr( 544 E->getType(), E, !getLangOpts().CPlusPlus11); 545 if (Materialized.isInvalid()) 546 return ExprError(); 547 E = Materialized.get(); 548 } 549 550 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 551 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 552 ImpCast->setType(Ty); 553 ImpCast->setValueKind(VK); 554 return E; 555 } 556 } 557 558 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK); 559 } 560 561 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 562 /// to the conversion from scalar type ScalarTy to the Boolean type. 563 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 564 switch (ScalarTy->getScalarTypeKind()) { 565 case Type::STK_Bool: return CK_NoOp; 566 case Type::STK_CPointer: return CK_PointerToBoolean; 567 case Type::STK_BlockPointer: return CK_PointerToBoolean; 568 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 569 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 570 case Type::STK_Integral: return CK_IntegralToBoolean; 571 case Type::STK_Floating: return CK_FloatingToBoolean; 572 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 573 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 574 case Type::STK_FixedPoint: return CK_FixedPointToBoolean; 575 } 576 llvm_unreachable("unknown scalar type kind"); 577 } 578 579 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector. 580 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 581 if (D->getMostRecentDecl()->isUsed()) 582 return true; 583 584 if (D->isExternallyVisible()) 585 return true; 586 587 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 588 // If this is a function template and none of its specializations is used, 589 // we should warn. 590 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate()) 591 for (const auto *Spec : Template->specializations()) 592 if (ShouldRemoveFromUnused(SemaRef, Spec)) 593 return true; 594 595 // UnusedFileScopedDecls stores the first declaration. 596 // The declaration may have become definition so check again. 597 const FunctionDecl *DeclToCheck; 598 if (FD->hasBody(DeclToCheck)) 599 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 600 601 // Later redecls may add new information resulting in not having to warn, 602 // so check again. 603 DeclToCheck = FD->getMostRecentDecl(); 604 if (DeclToCheck != FD) 605 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 606 } 607 608 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 609 // If a variable usable in constant expressions is referenced, 610 // don't warn if it isn't used: if the value of a variable is required 611 // for the computation of a constant expression, it doesn't make sense to 612 // warn even if the variable isn't odr-used. (isReferenced doesn't 613 // precisely reflect that, but it's a decent approximation.) 614 if (VD->isReferenced() && 615 VD->mightBeUsableInConstantExpressions(SemaRef->Context)) 616 return true; 617 618 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate()) 619 // If this is a variable template and none of its specializations is used, 620 // we should warn. 621 for (const auto *Spec : Template->specializations()) 622 if (ShouldRemoveFromUnused(SemaRef, Spec)) 623 return true; 624 625 // UnusedFileScopedDecls stores the first declaration. 626 // The declaration may have become definition so check again. 627 const VarDecl *DeclToCheck = VD->getDefinition(); 628 if (DeclToCheck) 629 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 630 631 // Later redecls may add new information resulting in not having to warn, 632 // so check again. 633 DeclToCheck = VD->getMostRecentDecl(); 634 if (DeclToCheck != VD) 635 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 636 } 637 638 return false; 639 } 640 641 static bool isFunctionOrVarDeclExternC(NamedDecl *ND) { 642 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 643 return FD->isExternC(); 644 return cast<VarDecl>(ND)->isExternC(); 645 } 646 647 /// Determine whether ND is an external-linkage function or variable whose 648 /// type has no linkage. 649 bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) { 650 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage, 651 // because we also want to catch the case where its type has VisibleNoLinkage, 652 // which does not affect the linkage of VD. 653 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() && 654 !isExternalFormalLinkage(VD->getType()->getLinkage()) && 655 !isFunctionOrVarDeclExternC(VD); 656 } 657 658 /// Obtains a sorted list of functions and variables that are undefined but 659 /// ODR-used. 660 void Sema::getUndefinedButUsed( 661 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { 662 for (const auto &UndefinedUse : UndefinedButUsed) { 663 NamedDecl *ND = UndefinedUse.first; 664 665 // Ignore attributes that have become invalid. 666 if (ND->isInvalidDecl()) continue; 667 668 // __attribute__((weakref)) is basically a definition. 669 if (ND->hasAttr<WeakRefAttr>()) continue; 670 671 if (isa<CXXDeductionGuideDecl>(ND)) 672 continue; 673 674 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { 675 // An exported function will always be emitted when defined, so even if 676 // the function is inline, it doesn't have to be emitted in this TU. An 677 // imported function implies that it has been exported somewhere else. 678 continue; 679 } 680 681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 682 if (FD->isDefined()) 683 continue; 684 if (FD->isExternallyVisible() && 685 !isExternalWithNoLinkageType(FD) && 686 !FD->getMostRecentDecl()->isInlined() && 687 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 688 continue; 689 if (FD->getBuiltinID()) 690 continue; 691 } else { 692 auto *VD = cast<VarDecl>(ND); 693 if (VD->hasDefinition() != VarDecl::DeclarationOnly) 694 continue; 695 if (VD->isExternallyVisible() && 696 !isExternalWithNoLinkageType(VD) && 697 !VD->getMostRecentDecl()->isInline() && 698 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 699 continue; 700 701 // Skip VarDecls that lack formal definitions but which we know are in 702 // fact defined somewhere. 703 if (VD->isKnownToBeDefined()) 704 continue; 705 } 706 707 Undefined.push_back(std::make_pair(ND, UndefinedUse.second)); 708 } 709 } 710 711 /// checkUndefinedButUsed - Check for undefined objects with internal linkage 712 /// or that are inline. 713 static void checkUndefinedButUsed(Sema &S) { 714 if (S.UndefinedButUsed.empty()) return; 715 716 // Collect all the still-undefined entities with internal linkage. 717 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 718 S.getUndefinedButUsed(Undefined); 719 if (Undefined.empty()) return; 720 721 for (auto Undef : Undefined) { 722 ValueDecl *VD = cast<ValueDecl>(Undef.first); 723 SourceLocation UseLoc = Undef.second; 724 725 if (S.isExternalWithNoLinkageType(VD)) { 726 // C++ [basic.link]p8: 727 // A type without linkage shall not be used as the type of a variable 728 // or function with external linkage unless 729 // -- the entity has C language linkage 730 // -- the entity is not odr-used or is defined in the same TU 731 // 732 // As an extension, accept this in cases where the type is externally 733 // visible, since the function or variable actually can be defined in 734 // another translation unit in that case. 735 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage()) 736 ? diag::ext_undefined_internal_type 737 : diag::err_undefined_internal_type) 738 << isa<VarDecl>(VD) << VD; 739 } else if (!VD->isExternallyVisible()) { 740 // FIXME: We can promote this to an error. The function or variable can't 741 // be defined anywhere else, so the program must necessarily violate the 742 // one definition rule. 743 S.Diag(VD->getLocation(), diag::warn_undefined_internal) 744 << isa<VarDecl>(VD) << VD; 745 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 746 (void)FD; 747 assert(FD->getMostRecentDecl()->isInlined() && 748 "used object requires definition but isn't inline or internal?"); 749 // FIXME: This is ill-formed; we should reject. 750 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD; 751 } else { 752 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() && 753 "used var requires definition but isn't inline or internal?"); 754 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD; 755 } 756 if (UseLoc.isValid()) 757 S.Diag(UseLoc, diag::note_used_here); 758 } 759 760 S.UndefinedButUsed.clear(); 761 } 762 763 void Sema::LoadExternalWeakUndeclaredIdentifiers() { 764 if (!ExternalSource) 765 return; 766 767 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 768 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 769 for (auto &WeakID : WeakIDs) 770 WeakUndeclaredIdentifiers.insert(WeakID); 771 } 772 773 774 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 775 776 /// Returns true, if all methods and nested classes of the given 777 /// CXXRecordDecl are defined in this translation unit. 778 /// 779 /// Should only be called from ActOnEndOfTranslationUnit so that all 780 /// definitions are actually read. 781 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 782 RecordCompleteMap &MNCComplete) { 783 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 784 if (Cache != MNCComplete.end()) 785 return Cache->second; 786 if (!RD->isCompleteDefinition()) 787 return false; 788 bool Complete = true; 789 for (DeclContext::decl_iterator I = RD->decls_begin(), 790 E = RD->decls_end(); 791 I != E && Complete; ++I) { 792 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 793 Complete = M->isDefined() || M->isDefaulted() || 794 (M->isPure() && !isa<CXXDestructorDecl>(M)); 795 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 796 // If the template function is marked as late template parsed at this 797 // point, it has not been instantiated and therefore we have not 798 // performed semantic analysis on it yet, so we cannot know if the type 799 // can be considered complete. 800 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && 801 F->getTemplatedDecl()->isDefined(); 802 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 803 if (R->isInjectedClassName()) 804 continue; 805 if (R->hasDefinition()) 806 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 807 MNCComplete); 808 else 809 Complete = false; 810 } 811 } 812 MNCComplete[RD] = Complete; 813 return Complete; 814 } 815 816 /// Returns true, if the given CXXRecordDecl is fully defined in this 817 /// translation unit, i.e. all methods are defined or pure virtual and all 818 /// friends, friend functions and nested classes are fully defined in this 819 /// translation unit. 820 /// 821 /// Should only be called from ActOnEndOfTranslationUnit so that all 822 /// definitions are actually read. 823 static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 824 RecordCompleteMap &RecordsComplete, 825 RecordCompleteMap &MNCComplete) { 826 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 827 if (Cache != RecordsComplete.end()) 828 return Cache->second; 829 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 830 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 831 E = RD->friend_end(); 832 I != E && Complete; ++I) { 833 // Check if friend classes and methods are complete. 834 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 835 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 836 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 837 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 838 else 839 Complete = false; 840 } else { 841 // Friend functions are available through the NamedDecl of FriendDecl. 842 if (const FunctionDecl *FD = 843 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 844 Complete = FD->isDefined(); 845 else 846 // This is a template friend, give up. 847 Complete = false; 848 } 849 } 850 RecordsComplete[RD] = Complete; 851 return Complete; 852 } 853 854 void Sema::emitAndClearUnusedLocalTypedefWarnings() { 855 if (ExternalSource) 856 ExternalSource->ReadUnusedLocalTypedefNameCandidates( 857 UnusedLocalTypedefNameCandidates); 858 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { 859 if (TD->isReferenced()) 860 continue; 861 Diag(TD->getLocation(), diag::warn_unused_local_typedef) 862 << isa<TypeAliasDecl>(TD) << TD->getDeclName(); 863 } 864 UnusedLocalTypedefNameCandidates.clear(); 865 } 866 867 /// This is called before the very first declaration in the translation unit 868 /// is parsed. Note that the ASTContext may have already injected some 869 /// declarations. 870 void Sema::ActOnStartOfTranslationUnit() { 871 if (getLangOpts().ModulesTS && 872 (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface || 873 getLangOpts().getCompilingModule() == LangOptions::CMK_None)) { 874 // We start in an implied global module fragment. 875 SourceLocation StartOfTU = 876 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 877 ActOnGlobalModuleFragmentDecl(StartOfTU); 878 ModuleScopes.back().ImplicitGlobalModuleFragment = true; 879 } 880 } 881 882 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) { 883 // No explicit actions are required at the end of the global module fragment. 884 if (Kind == TUFragmentKind::Global) 885 return; 886 887 // Transfer late parsed template instantiations over to the pending template 888 // instantiation list. During normal compilation, the late template parser 889 // will be installed and instantiating these templates will succeed. 890 // 891 // If we are building a TU prefix for serialization, it is also safe to 892 // transfer these over, even though they are not parsed. The end of the TU 893 // should be outside of any eager template instantiation scope, so when this 894 // AST is deserialized, these templates will not be parsed until the end of 895 // the combined TU. 896 PendingInstantiations.insert(PendingInstantiations.end(), 897 LateParsedInstantiations.begin(), 898 LateParsedInstantiations.end()); 899 LateParsedInstantiations.clear(); 900 901 // If DefinedUsedVTables ends up marking any virtual member functions it 902 // might lead to more pending template instantiations, which we then need 903 // to instantiate. 904 DefineUsedVTables(); 905 906 // C++: Perform implicit template instantiations. 907 // 908 // FIXME: When we perform these implicit instantiations, we do not 909 // carefully keep track of the point of instantiation (C++ [temp.point]). 910 // This means that name lookup that occurs within the template 911 // instantiation will always happen at the end of the translation unit, 912 // so it will find some names that are not required to be found. This is 913 // valid, but we could do better by diagnosing if an instantiation uses a 914 // name that was not visible at its first point of instantiation. 915 if (ExternalSource) { 916 // Load pending instantiations from the external source. 917 SmallVector<PendingImplicitInstantiation, 4> Pending; 918 ExternalSource->ReadPendingInstantiations(Pending); 919 for (auto PII : Pending) 920 if (auto Func = dyn_cast<FunctionDecl>(PII.first)) 921 Func->setInstantiationIsPending(true); 922 PendingInstantiations.insert(PendingInstantiations.begin(), 923 Pending.begin(), Pending.end()); 924 } 925 926 { 927 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations"); 928 PerformPendingInstantiations(); 929 } 930 931 // Finalize analysis of OpenMP-specific constructs. 932 if (LangOpts.OpenMP) 933 finalizeOpenMPDelayedAnalysis(); 934 935 assert(LateParsedInstantiations.empty() && 936 "end of TU template instantiation should not create more " 937 "late-parsed templates"); 938 939 // Report diagnostics for uncorrected delayed typos. Ideally all of them 940 // should have been corrected by that time, but it is very hard to cover all 941 // cases in practice. 942 for (const auto &Typo : DelayedTypos) { 943 // We pass an empty TypoCorrection to indicate no correction was performed. 944 Typo.second.DiagHandler(TypoCorrection()); 945 } 946 DelayedTypos.clear(); 947 } 948 949 /// ActOnEndOfTranslationUnit - This is called at the very end of the 950 /// translation unit when EOF is reached and all but the top-level scope is 951 /// popped. 952 void Sema::ActOnEndOfTranslationUnit() { 953 assert(DelayedDiagnostics.getCurrentPool() == nullptr 954 && "reached end of translation unit with a pool attached?"); 955 956 // If code completion is enabled, don't perform any end-of-translation-unit 957 // work. 958 if (PP.isCodeCompletionEnabled()) 959 return; 960 961 // Complete translation units and modules define vtables and perform implicit 962 // instantiations. PCH files do not. 963 if (TUKind != TU_Prefix) { 964 DiagnoseUseOfUnimplementedSelectors(); 965 966 ActOnEndOfTranslationUnitFragment( 967 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind == 968 Module::PrivateModuleFragment 969 ? TUFragmentKind::Private 970 : TUFragmentKind::Normal); 971 972 if (LateTemplateParserCleanup) 973 LateTemplateParserCleanup(OpaqueParser); 974 975 CheckDelayedMemberExceptionSpecs(); 976 } else { 977 // If we are building a TU prefix for serialization, it is safe to transfer 978 // these over, even though they are not parsed. The end of the TU should be 979 // outside of any eager template instantiation scope, so when this AST is 980 // deserialized, these templates will not be parsed until the end of the 981 // combined TU. 982 PendingInstantiations.insert(PendingInstantiations.end(), 983 LateParsedInstantiations.begin(), 984 LateParsedInstantiations.end()); 985 LateParsedInstantiations.clear(); 986 } 987 988 DiagnoseUnterminatedPragmaPack(); 989 DiagnoseUnterminatedPragmaAttribute(); 990 991 // All delayed member exception specs should be checked or we end up accepting 992 // incompatible declarations. 993 assert(DelayedOverridingExceptionSpecChecks.empty()); 994 assert(DelayedEquivalentExceptionSpecChecks.empty()); 995 996 // All dllexport classes should have been processed already. 997 assert(DelayedDllExportClasses.empty()); 998 assert(DelayedDllExportMemberFunctions.empty()); 999 1000 // Remove file scoped decls that turned out to be used. 1001 UnusedFileScopedDecls.erase( 1002 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true), 1003 UnusedFileScopedDecls.end(), 1004 [this](const DeclaratorDecl *DD) { 1005 return ShouldRemoveFromUnused(this, DD); 1006 }), 1007 UnusedFileScopedDecls.end()); 1008 1009 if (TUKind == TU_Prefix) { 1010 // Translation unit prefixes don't need any of the checking below. 1011 if (!PP.isIncrementalProcessingEnabled()) 1012 TUScope = nullptr; 1013 return; 1014 } 1015 1016 // Check for #pragma weak identifiers that were never declared 1017 LoadExternalWeakUndeclaredIdentifiers(); 1018 for (auto WeakID : WeakUndeclaredIdentifiers) { 1019 if (WeakID.second.getUsed()) 1020 continue; 1021 1022 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(), 1023 LookupOrdinaryName); 1024 if (PrevDecl != nullptr && 1025 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) 1026 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type) 1027 << "'weak'" << ExpectedVariableOrFunction; 1028 else 1029 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared) 1030 << WeakID.first; 1031 } 1032 1033 if (LangOpts.CPlusPlus11 && 1034 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())) 1035 CheckDelegatingCtorCycles(); 1036 1037 if (!Diags.hasErrorOccurred()) { 1038 if (ExternalSource) 1039 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed); 1040 checkUndefinedButUsed(*this); 1041 } 1042 1043 // A global-module-fragment is only permitted within a module unit. 1044 bool DiagnosedMissingModuleDeclaration = false; 1045 if (!ModuleScopes.empty() && 1046 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment && 1047 !ModuleScopes.back().ImplicitGlobalModuleFragment) { 1048 Diag(ModuleScopes.back().BeginLoc, 1049 diag::err_module_declaration_missing_after_global_module_introducer); 1050 DiagnosedMissingModuleDeclaration = true; 1051 } 1052 1053 if (TUKind == TU_Module) { 1054 // If we are building a module interface unit, we need to have seen the 1055 // module declaration by now. 1056 if (getLangOpts().getCompilingModule() == 1057 LangOptions::CMK_ModuleInterface && 1058 (ModuleScopes.empty() || 1059 !ModuleScopes.back().Module->isModulePurview()) && 1060 !DiagnosedMissingModuleDeclaration) { 1061 // FIXME: Make a better guess as to where to put the module declaration. 1062 Diag(getSourceManager().getLocForStartOfFile( 1063 getSourceManager().getMainFileID()), 1064 diag::err_module_declaration_missing); 1065 } 1066 1067 // If we are building a module, resolve all of the exported declarations 1068 // now. 1069 if (Module *CurrentModule = PP.getCurrentModule()) { 1070 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 1071 1072 SmallVector<Module *, 2> Stack; 1073 Stack.push_back(CurrentModule); 1074 while (!Stack.empty()) { 1075 Module *Mod = Stack.pop_back_val(); 1076 1077 // Resolve the exported declarations and conflicts. 1078 // FIXME: Actually complain, once we figure out how to teach the 1079 // diagnostic client to deal with complaints in the module map at this 1080 // point. 1081 ModMap.resolveExports(Mod, /*Complain=*/false); 1082 ModMap.resolveUses(Mod, /*Complain=*/false); 1083 ModMap.resolveConflicts(Mod, /*Complain=*/false); 1084 1085 // Queue the submodules, so their exports will also be resolved. 1086 Stack.append(Mod->submodule_begin(), Mod->submodule_end()); 1087 } 1088 } 1089 1090 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for 1091 // modules when they are built, not every time they are used. 1092 emitAndClearUnusedLocalTypedefWarnings(); 1093 } 1094 1095 // C99 6.9.2p2: 1096 // A declaration of an identifier for an object that has file 1097 // scope without an initializer, and without a storage-class 1098 // specifier or with the storage-class specifier static, 1099 // constitutes a tentative definition. If a translation unit 1100 // contains one or more tentative definitions for an identifier, 1101 // and the translation unit contains no external definition for 1102 // that identifier, then the behavior is exactly as if the 1103 // translation unit contains a file scope declaration of that 1104 // identifier, with the composite type as of the end of the 1105 // translation unit, with an initializer equal to 0. 1106 llvm::SmallSet<VarDecl *, 32> Seen; 1107 for (TentativeDefinitionsType::iterator 1108 T = TentativeDefinitions.begin(ExternalSource), 1109 TEnd = TentativeDefinitions.end(); 1110 T != TEnd; ++T) { 1111 VarDecl *VD = (*T)->getActingDefinition(); 1112 1113 // If the tentative definition was completed, getActingDefinition() returns 1114 // null. If we've already seen this variable before, insert()'s second 1115 // return value is false. 1116 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second) 1117 continue; 1118 1119 if (const IncompleteArrayType *ArrayT 1120 = Context.getAsIncompleteArrayType(VD->getType())) { 1121 // Set the length of the array to 1 (C99 6.9.2p5). 1122 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 1123 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 1124 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One, 1125 nullptr, ArrayType::Normal, 0); 1126 VD->setType(T); 1127 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 1128 diag::err_tentative_def_incomplete_type)) 1129 VD->setInvalidDecl(); 1130 1131 // No initialization is performed for a tentative definition. 1132 CheckCompleteVariableDeclaration(VD); 1133 1134 // Notify the consumer that we've completed a tentative definition. 1135 if (!VD->isInvalidDecl()) 1136 Consumer.CompleteTentativeDefinition(VD); 1137 } 1138 1139 for (auto D : ExternalDeclarations) { 1140 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed()) 1141 continue; 1142 1143 Consumer.CompleteExternalDeclaration(D); 1144 } 1145 1146 // If there were errors, disable 'unused' warnings since they will mostly be 1147 // noise. Don't warn for a use from a module: either we should warn on all 1148 // file-scope declarations in modules or not at all, but whether the 1149 // declaration is used is immaterial. 1150 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) { 1151 // Output warning for unused file scoped decls. 1152 for (UnusedFileScopedDeclsType::iterator 1153 I = UnusedFileScopedDecls.begin(ExternalSource), 1154 E = UnusedFileScopedDecls.end(); I != E; ++I) { 1155 if (ShouldRemoveFromUnused(this, *I)) 1156 continue; 1157 1158 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 1159 const FunctionDecl *DiagD; 1160 if (!FD->hasBody(DiagD)) 1161 DiagD = FD; 1162 if (DiagD->isDeleted()) 1163 continue; // Deleted functions are supposed to be unused. 1164 if (DiagD->isReferenced()) { 1165 if (isa<CXXMethodDecl>(DiagD)) 1166 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 1167 << DiagD->getDeclName(); 1168 else { 1169 if (FD->getStorageClass() == SC_Static && 1170 !FD->isInlineSpecified() && 1171 !SourceMgr.isInMainFile( 1172 SourceMgr.getExpansionLoc(FD->getLocation()))) 1173 Diag(DiagD->getLocation(), 1174 diag::warn_unneeded_static_internal_decl) 1175 << DiagD->getDeclName(); 1176 else 1177 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1178 << /*function*/0 << DiagD->getDeclName(); 1179 } 1180 } else { 1181 if (FD->getDescribedFunctionTemplate()) 1182 Diag(DiagD->getLocation(), diag::warn_unused_template) 1183 << /*function*/0 << DiagD->getDeclName(); 1184 else 1185 Diag(DiagD->getLocation(), 1186 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 1187 : diag::warn_unused_function) 1188 << DiagD->getDeclName(); 1189 } 1190 } else { 1191 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 1192 if (!DiagD) 1193 DiagD = cast<VarDecl>(*I); 1194 if (DiagD->isReferenced()) { 1195 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1196 << /*variable*/1 << DiagD->getDeclName(); 1197 } else if (DiagD->getType().isConstQualified()) { 1198 const SourceManager &SM = SourceMgr; 1199 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) || 1200 !PP.getLangOpts().IsHeaderFile) 1201 Diag(DiagD->getLocation(), diag::warn_unused_const_variable) 1202 << DiagD->getDeclName(); 1203 } else { 1204 if (DiagD->getDescribedVarTemplate()) 1205 Diag(DiagD->getLocation(), diag::warn_unused_template) 1206 << /*variable*/1 << DiagD->getDeclName(); 1207 else 1208 Diag(DiagD->getLocation(), diag::warn_unused_variable) 1209 << DiagD->getDeclName(); 1210 } 1211 } 1212 } 1213 1214 emitAndClearUnusedLocalTypedefWarnings(); 1215 } 1216 1217 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) { 1218 // FIXME: Load additional unused private field candidates from the external 1219 // source. 1220 RecordCompleteMap RecordsComplete; 1221 RecordCompleteMap MNCComplete; 1222 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 1223 E = UnusedPrivateFields.end(); I != E; ++I) { 1224 const NamedDecl *D = *I; 1225 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 1226 if (RD && !RD->isUnion() && 1227 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 1228 Diag(D->getLocation(), diag::warn_unused_private_field) 1229 << D->getDeclName(); 1230 } 1231 } 1232 } 1233 1234 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) { 1235 if (ExternalSource) 1236 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); 1237 for (const auto &DeletedFieldInfo : DeleteExprs) { 1238 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { 1239 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first, 1240 DeleteExprLoc.second); 1241 } 1242 } 1243 } 1244 1245 // Check we've noticed that we're no longer parsing the initializer for every 1246 // variable. If we miss cases, then at best we have a performance issue and 1247 // at worst a rejects-valid bug. 1248 assert(ParsingInitForAutoVars.empty() && 1249 "Didn't unmark var as having its initializer parsed"); 1250 1251 if (!PP.isIncrementalProcessingEnabled()) 1252 TUScope = nullptr; 1253 } 1254 1255 1256 //===----------------------------------------------------------------------===// 1257 // Helper functions. 1258 //===----------------------------------------------------------------------===// 1259 1260 DeclContext *Sema::getFunctionLevelDeclContext() { 1261 DeclContext *DC = CurContext; 1262 1263 while (true) { 1264 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) { 1265 DC = DC->getParent(); 1266 } else if (isa<CXXMethodDecl>(DC) && 1267 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 1268 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 1269 DC = DC->getParent()->getParent(); 1270 } 1271 else break; 1272 } 1273 1274 return DC; 1275 } 1276 1277 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1278 /// to the function decl for the function being parsed. If we're currently 1279 /// in a 'block', this returns the containing context. 1280 FunctionDecl *Sema::getCurFunctionDecl() { 1281 DeclContext *DC = getFunctionLevelDeclContext(); 1282 return dyn_cast<FunctionDecl>(DC); 1283 } 1284 1285 ObjCMethodDecl *Sema::getCurMethodDecl() { 1286 DeclContext *DC = getFunctionLevelDeclContext(); 1287 while (isa<RecordDecl>(DC)) 1288 DC = DC->getParent(); 1289 return dyn_cast<ObjCMethodDecl>(DC); 1290 } 1291 1292 NamedDecl *Sema::getCurFunctionOrMethodDecl() { 1293 DeclContext *DC = getFunctionLevelDeclContext(); 1294 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 1295 return cast<NamedDecl>(DC); 1296 return nullptr; 1297 } 1298 1299 LangAS Sema::getDefaultCXXMethodAddrSpace() const { 1300 if (getLangOpts().OpenCL) 1301 return LangAS::opencl_generic; 1302 return LangAS::Default; 1303 } 1304 1305 void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 1306 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 1307 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 1308 // been made more painfully obvious by the refactor that introduced this 1309 // function, but it is possible that the incoming argument can be 1310 // eliminated. If it truly cannot be (for example, there is some reentrancy 1311 // issue I am not seeing yet), then there should at least be a clarifying 1312 // comment somewhere. 1313 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 1314 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 1315 Diags.getCurrentDiagID())) { 1316 case DiagnosticIDs::SFINAE_Report: 1317 // We'll report the diagnostic below. 1318 break; 1319 1320 case DiagnosticIDs::SFINAE_SubstitutionFailure: 1321 // Count this failure so that we know that template argument deduction 1322 // has failed. 1323 ++NumSFINAEErrors; 1324 1325 // Make a copy of this suppressed diagnostic and store it with the 1326 // template-deduction information. 1327 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1328 Diagnostic DiagInfo(&Diags); 1329 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1330 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1331 } 1332 1333 Diags.setLastDiagnosticIgnored(true); 1334 Diags.Clear(); 1335 return; 1336 1337 case DiagnosticIDs::SFINAE_AccessControl: { 1338 // Per C++ Core Issue 1170, access control is part of SFINAE. 1339 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 1340 // make access control a part of SFINAE for the purposes of checking 1341 // type traits. 1342 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) 1343 break; 1344 1345 SourceLocation Loc = Diags.getCurrentDiagLoc(); 1346 1347 // Suppress this diagnostic. 1348 ++NumSFINAEErrors; 1349 1350 // Make a copy of this suppressed diagnostic and store it with the 1351 // template-deduction information. 1352 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1353 Diagnostic DiagInfo(&Diags); 1354 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1355 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1356 } 1357 1358 Diags.setLastDiagnosticIgnored(true); 1359 Diags.Clear(); 1360 1361 // Now the diagnostic state is clear, produce a C++98 compatibility 1362 // warning. 1363 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 1364 1365 // The last diagnostic which Sema produced was ignored. Suppress any 1366 // notes attached to it. 1367 Diags.setLastDiagnosticIgnored(true); 1368 return; 1369 } 1370 1371 case DiagnosticIDs::SFINAE_Suppress: 1372 // Make a copy of this suppressed diagnostic and store it with the 1373 // template-deduction information; 1374 if (*Info) { 1375 Diagnostic DiagInfo(&Diags); 1376 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 1377 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1378 } 1379 1380 // Suppress this diagnostic. 1381 Diags.setLastDiagnosticIgnored(true); 1382 Diags.Clear(); 1383 return; 1384 } 1385 } 1386 1387 // Copy the diagnostic printing policy over the ASTContext printing policy. 1388 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292 1389 Context.setPrintingPolicy(getPrintingPolicy()); 1390 1391 // Emit the diagnostic. 1392 if (!Diags.EmitCurrentDiagnostic()) 1393 return; 1394 1395 // If this is not a note, and we're in a template instantiation 1396 // that is different from the last template instantiation where 1397 // we emitted an error, print a template instantiation 1398 // backtrace. 1399 if (!DiagnosticIDs::isBuiltinNote(DiagID)) 1400 PrintContextStack(); 1401 } 1402 1403 Sema::SemaDiagnosticBuilder 1404 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 1405 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 1406 PD.Emit(Builder); 1407 1408 return Builder; 1409 } 1410 1411 // Print notes showing how we can reach FD starting from an a priori 1412 // known-callable function. 1413 static void emitCallStackNotes(Sema &S, FunctionDecl *FD) { 1414 auto FnIt = S.DeviceKnownEmittedFns.find(FD); 1415 while (FnIt != S.DeviceKnownEmittedFns.end()) { 1416 DiagnosticBuilder Builder( 1417 S.Diags.Report(FnIt->second.Loc, diag::note_called_by)); 1418 Builder << FnIt->second.FD; 1419 Builder.setForceEmit(); 1420 1421 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD); 1422 } 1423 } 1424 1425 // Emit any deferred diagnostics for FD and erase them from the map in which 1426 // they're stored. 1427 static void emitDeferredDiags(Sema &S, FunctionDecl *FD, bool ShowCallStack) { 1428 auto It = S.DeviceDeferredDiags.find(FD); 1429 if (It == S.DeviceDeferredDiags.end()) 1430 return; 1431 bool HasWarningOrError = false; 1432 for (PartialDiagnosticAt &PDAt : It->second) { 1433 const SourceLocation &Loc = PDAt.first; 1434 const PartialDiagnostic &PD = PDAt.second; 1435 HasWarningOrError |= S.getDiagnostics().getDiagnosticLevel( 1436 PD.getDiagID(), Loc) >= DiagnosticsEngine::Warning; 1437 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID())); 1438 Builder.setForceEmit(); 1439 PD.Emit(Builder); 1440 } 1441 S.DeviceDeferredDiags.erase(It); 1442 1443 // FIXME: Should this be called after every warning/error emitted in the loop 1444 // above, instead of just once per function? That would be consistent with 1445 // how we handle immediate errors, but it also seems like a bit much. 1446 if (HasWarningOrError && ShowCallStack) 1447 emitCallStackNotes(S, FD); 1448 } 1449 1450 // In CUDA, there are some constructs which may appear in semantically-valid 1451 // code, but trigger errors if we ever generate code for the function in which 1452 // they appear. Essentially every construct you're not allowed to use on the 1453 // device falls into this category, because you are allowed to use these 1454 // constructs in a __host__ __device__ function, but only if that function is 1455 // never codegen'ed on the device. 1456 // 1457 // To handle semantic checking for these constructs, we keep track of the set of 1458 // functions we know will be emitted, either because we could tell a priori that 1459 // they would be emitted, or because they were transitively called by a 1460 // known-emitted function. 1461 // 1462 // We also keep a partial call graph of which not-known-emitted functions call 1463 // which other not-known-emitted functions. 1464 // 1465 // When we see something which is illegal if the current function is emitted 1466 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or 1467 // CheckCUDACall), we first check if the current function is known-emitted. If 1468 // so, we immediately output the diagnostic. 1469 // 1470 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags 1471 // until we discover that the function is known-emitted, at which point we take 1472 // it out of this map and emit the diagnostic. 1473 1474 Sema::DeviceDiagBuilder::DeviceDiagBuilder(Kind K, SourceLocation Loc, 1475 unsigned DiagID, FunctionDecl *Fn, 1476 Sema &S) 1477 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn), 1478 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) { 1479 switch (K) { 1480 case K_Nop: 1481 break; 1482 case K_Immediate: 1483 case K_ImmediateWithCallStack: 1484 ImmediateDiag.emplace(S.Diag(Loc, DiagID)); 1485 break; 1486 case K_Deferred: 1487 assert(Fn && "Must have a function to attach the deferred diag to."); 1488 auto &Diags = S.DeviceDeferredDiags[Fn]; 1489 PartialDiagId.emplace(Diags.size()); 1490 Diags.emplace_back(Loc, S.PDiag(DiagID)); 1491 break; 1492 } 1493 } 1494 1495 Sema::DeviceDiagBuilder::DeviceDiagBuilder(DeviceDiagBuilder &&D) 1496 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn), 1497 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag), 1498 PartialDiagId(D.PartialDiagId) { 1499 // Clean the previous diagnostics. 1500 D.ShowCallStack = false; 1501 D.ImmediateDiag.reset(); 1502 D.PartialDiagId.reset(); 1503 } 1504 1505 Sema::DeviceDiagBuilder::~DeviceDiagBuilder() { 1506 if (ImmediateDiag) { 1507 // Emit our diagnostic and, if it was a warning or error, output a callstack 1508 // if Fn isn't a priori known-emitted. 1509 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel( 1510 DiagID, Loc) >= DiagnosticsEngine::Warning; 1511 ImmediateDiag.reset(); // Emit the immediate diag. 1512 if (IsWarningOrError && ShowCallStack) 1513 emitCallStackNotes(S, Fn); 1514 } else { 1515 assert((!PartialDiagId || ShowCallStack) && 1516 "Must always show call stack for deferred diags."); 1517 } 1518 } 1519 1520 // Indicate that this function (and thus everything it transtively calls) will 1521 // be codegen'ed, and emit any deferred diagnostics on this function and its 1522 // (transitive) callees. 1523 void Sema::markKnownEmitted( 1524 Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, 1525 SourceLocation OrigLoc, 1526 const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted) { 1527 // Nothing to do if we already know that FD is emitted. 1528 if (IsKnownEmitted(S, OrigCallee)) { 1529 assert(!S.DeviceCallGraph.count(OrigCallee)); 1530 return; 1531 } 1532 1533 // We've just discovered that OrigCallee is known-emitted. Walk our call 1534 // graph to see what else we can now discover also must be emitted. 1535 1536 struct CallInfo { 1537 FunctionDecl *Caller; 1538 FunctionDecl *Callee; 1539 SourceLocation Loc; 1540 }; 1541 llvm::SmallVector<CallInfo, 4> Worklist = {{OrigCaller, OrigCallee, OrigLoc}}; 1542 llvm::SmallSet<CanonicalDeclPtr<FunctionDecl>, 4> Seen; 1543 Seen.insert(OrigCallee); 1544 while (!Worklist.empty()) { 1545 CallInfo C = Worklist.pop_back_val(); 1546 assert(!IsKnownEmitted(S, C.Callee) && 1547 "Worklist should not contain known-emitted functions."); 1548 S.DeviceKnownEmittedFns[C.Callee] = {C.Caller, C.Loc}; 1549 emitDeferredDiags(S, C.Callee, C.Caller); 1550 1551 // If this is a template instantiation, explore its callgraph as well: 1552 // Non-dependent calls are part of the template's callgraph, while dependent 1553 // calls are part of to the instantiation's call graph. 1554 if (auto *Templ = C.Callee->getPrimaryTemplate()) { 1555 FunctionDecl *TemplFD = Templ->getAsFunction(); 1556 if (!Seen.count(TemplFD) && !S.DeviceKnownEmittedFns.count(TemplFD)) { 1557 Seen.insert(TemplFD); 1558 Worklist.push_back( 1559 {/* Caller = */ C.Caller, /* Callee = */ TemplFD, C.Loc}); 1560 } 1561 } 1562 1563 // Add all functions called by Callee to our worklist. 1564 auto CGIt = S.DeviceCallGraph.find(C.Callee); 1565 if (CGIt == S.DeviceCallGraph.end()) 1566 continue; 1567 1568 for (std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation> FDLoc : 1569 CGIt->second) { 1570 FunctionDecl *NewCallee = FDLoc.first; 1571 SourceLocation CallLoc = FDLoc.second; 1572 if (Seen.count(NewCallee) || IsKnownEmitted(S, NewCallee)) 1573 continue; 1574 Seen.insert(NewCallee); 1575 Worklist.push_back( 1576 {/* Caller = */ C.Callee, /* Callee = */ NewCallee, CallLoc}); 1577 } 1578 1579 // C.Callee is now known-emitted, so we no longer need to maintain its list 1580 // of callees in DeviceCallGraph. 1581 S.DeviceCallGraph.erase(CGIt); 1582 } 1583 } 1584 1585 Sema::DeviceDiagBuilder Sema::targetDiag(SourceLocation Loc, unsigned DiagID) { 1586 if (LangOpts.OpenMP) 1587 return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID) 1588 : diagIfOpenMPHostCode(Loc, DiagID); 1589 if (getLangOpts().CUDA) 1590 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID) 1591 : CUDADiagIfHostCode(Loc, DiagID); 1592 return DeviceDiagBuilder(DeviceDiagBuilder::K_Immediate, Loc, DiagID, 1593 getCurFunctionDecl(), *this); 1594 } 1595 1596 /// Looks through the macro-expansion chain for the given 1597 /// location, looking for a macro expansion with the given name. 1598 /// If one is found, returns true and sets the location to that 1599 /// expansion loc. 1600 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 1601 SourceLocation loc = locref; 1602 if (!loc.isMacroID()) return false; 1603 1604 // There's no good way right now to look at the intermediate 1605 // expansions, so just jump to the expansion location. 1606 loc = getSourceManager().getExpansionLoc(loc); 1607 1608 // If that's written with the name, stop here. 1609 SmallVector<char, 16> buffer; 1610 if (getPreprocessor().getSpelling(loc, buffer) == name) { 1611 locref = loc; 1612 return true; 1613 } 1614 return false; 1615 } 1616 1617 /// Determines the active Scope associated with the given declaration 1618 /// context. 1619 /// 1620 /// This routine maps a declaration context to the active Scope object that 1621 /// represents that declaration context in the parser. It is typically used 1622 /// from "scope-less" code (e.g., template instantiation, lazy creation of 1623 /// declarations) that injects a name for name-lookup purposes and, therefore, 1624 /// must update the Scope. 1625 /// 1626 /// \returns The scope corresponding to the given declaraion context, or NULL 1627 /// if no such scope is open. 1628 Scope *Sema::getScopeForContext(DeclContext *Ctx) { 1629 1630 if (!Ctx) 1631 return nullptr; 1632 1633 Ctx = Ctx->getPrimaryContext(); 1634 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1635 // Ignore scopes that cannot have declarations. This is important for 1636 // out-of-line definitions of static class members. 1637 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 1638 if (DeclContext *Entity = S->getEntity()) 1639 if (Ctx == Entity->getPrimaryContext()) 1640 return S; 1641 } 1642 1643 return nullptr; 1644 } 1645 1646 /// Enter a new function scope 1647 void Sema::PushFunctionScope() { 1648 if (FunctionScopes.empty() && CachedFunctionScope) { 1649 // Use CachedFunctionScope to avoid allocating memory when possible. 1650 CachedFunctionScope->Clear(); 1651 FunctionScopes.push_back(CachedFunctionScope.release()); 1652 } else { 1653 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 1654 } 1655 if (LangOpts.OpenMP) 1656 pushOpenMPFunctionRegion(); 1657 } 1658 1659 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 1660 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 1661 BlockScope, Block)); 1662 } 1663 1664 LambdaScopeInfo *Sema::PushLambdaScope() { 1665 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); 1666 FunctionScopes.push_back(LSI); 1667 return LSI; 1668 } 1669 1670 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { 1671 if (LambdaScopeInfo *const LSI = getCurLambda()) { 1672 LSI->AutoTemplateParameterDepth = Depth; 1673 return; 1674 } 1675 llvm_unreachable( 1676 "Remove assertion if intentionally called in a non-lambda context."); 1677 } 1678 1679 // Check that the type of the VarDecl has an accessible copy constructor and 1680 // resolve its destructor's exception specification. 1681 static void checkEscapingByref(VarDecl *VD, Sema &S) { 1682 QualType T = VD->getType(); 1683 EnterExpressionEvaluationContext scope( 1684 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 1685 SourceLocation Loc = VD->getLocation(); 1686 Expr *VarRef = 1687 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc); 1688 ExprResult Result = S.PerformMoveOrCopyInitialization( 1689 InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(), 1690 VarRef, /*AllowNRVO=*/true); 1691 if (!Result.isInvalid()) { 1692 Result = S.MaybeCreateExprWithCleanups(Result); 1693 Expr *Init = Result.getAs<Expr>(); 1694 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init)); 1695 } 1696 1697 // The destructor's exception specification is needed when IRGen generates 1698 // block copy/destroy functions. Resolve it here. 1699 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1700 if (CXXDestructorDecl *DD = RD->getDestructor()) { 1701 auto *FPT = DD->getType()->getAs<FunctionProtoType>(); 1702 S.ResolveExceptionSpec(Loc, FPT); 1703 } 1704 } 1705 1706 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) { 1707 // Set the EscapingByref flag of __block variables captured by 1708 // escaping blocks. 1709 for (const BlockDecl *BD : FSI.Blocks) { 1710 for (const BlockDecl::Capture &BC : BD->captures()) { 1711 VarDecl *VD = BC.getVariable(); 1712 if (VD->hasAttr<BlocksAttr>()) { 1713 // Nothing to do if this is a __block variable captured by a 1714 // non-escaping block. 1715 if (BD->doesNotEscape()) 1716 continue; 1717 VD->setEscapingByref(); 1718 } 1719 // Check whether the captured variable is or contains an object of 1720 // non-trivial C union type. 1721 QualType CapType = BC.getVariable()->getType(); 1722 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() || 1723 CapType.hasNonTrivialToPrimitiveCopyCUnion()) 1724 S.checkNonTrivialCUnion(BC.getVariable()->getType(), 1725 BD->getCaretLocation(), 1726 Sema::NTCUC_BlockCapture, 1727 Sema::NTCUK_Destruct|Sema::NTCUK_Copy); 1728 } 1729 } 1730 1731 for (VarDecl *VD : FSI.ByrefBlockVars) { 1732 // __block variables might require us to capture a copy-initializer. 1733 if (!VD->isEscapingByref()) 1734 continue; 1735 // It's currently invalid to ever have a __block variable with an 1736 // array type; should we diagnose that here? 1737 // Regardless, we don't want to ignore array nesting when 1738 // constructing this copy. 1739 if (VD->getType()->isStructureOrClassType()) 1740 checkEscapingByref(VD, S); 1741 } 1742 } 1743 1744 /// Pop a function (or block or lambda or captured region) scope from the stack. 1745 /// 1746 /// \param WP The warning policy to use for CFG-based warnings, or null if such 1747 /// warnings should not be produced. 1748 /// \param D The declaration corresponding to this function scope, if producing 1749 /// CFG-based warnings. 1750 /// \param BlockType The type of the block expression, if D is a BlockDecl. 1751 Sema::PoppedFunctionScopePtr 1752 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 1753 const Decl *D, QualType BlockType) { 1754 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 1755 1756 markEscapingByrefs(*FunctionScopes.back(), *this); 1757 1758 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(), 1759 PoppedFunctionScopeDeleter(this)); 1760 1761 if (LangOpts.OpenMP) 1762 popOpenMPFunctionRegion(Scope.get()); 1763 1764 // Issue any analysis-based warnings. 1765 if (WP && D) 1766 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType); 1767 else 1768 for (const auto &PUD : Scope->PossiblyUnreachableDiags) 1769 Diag(PUD.Loc, PUD.PD); 1770 1771 return Scope; 1772 } 1773 1774 void Sema::PoppedFunctionScopeDeleter:: 1775 operator()(sema::FunctionScopeInfo *Scope) const { 1776 // Stash the function scope for later reuse if it's for a normal function. 1777 if (Scope->isPlainFunction() && !Self->CachedFunctionScope) 1778 Self->CachedFunctionScope.reset(Scope); 1779 else 1780 delete Scope; 1781 } 1782 1783 void Sema::PushCompoundScope(bool IsStmtExpr) { 1784 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr)); 1785 } 1786 1787 void Sema::PopCompoundScope() { 1788 FunctionScopeInfo *CurFunction = getCurFunction(); 1789 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 1790 1791 CurFunction->CompoundScopes.pop_back(); 1792 } 1793 1794 /// Determine whether any errors occurred within this function/method/ 1795 /// block. 1796 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 1797 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 1798 } 1799 1800 void Sema::setFunctionHasBranchIntoScope() { 1801 if (!FunctionScopes.empty()) 1802 FunctionScopes.back()->setHasBranchIntoScope(); 1803 } 1804 1805 void Sema::setFunctionHasBranchProtectedScope() { 1806 if (!FunctionScopes.empty()) 1807 FunctionScopes.back()->setHasBranchProtectedScope(); 1808 } 1809 1810 void Sema::setFunctionHasIndirectGoto() { 1811 if (!FunctionScopes.empty()) 1812 FunctionScopes.back()->setHasIndirectGoto(); 1813 } 1814 1815 BlockScopeInfo *Sema::getCurBlock() { 1816 if (FunctionScopes.empty()) 1817 return nullptr; 1818 1819 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 1820 if (CurBSI && CurBSI->TheDecl && 1821 !CurBSI->TheDecl->Encloses(CurContext)) { 1822 // We have switched contexts due to template instantiation. 1823 assert(!CodeSynthesisContexts.empty()); 1824 return nullptr; 1825 } 1826 1827 return CurBSI; 1828 } 1829 1830 FunctionScopeInfo *Sema::getEnclosingFunction() const { 1831 if (FunctionScopes.empty()) 1832 return nullptr; 1833 1834 for (int e = FunctionScopes.size() - 1; e >= 0; --e) { 1835 if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) 1836 continue; 1837 return FunctionScopes[e]; 1838 } 1839 return nullptr; 1840 } 1841 1842 LambdaScopeInfo *Sema::getEnclosingLambda() const { 1843 for (auto *Scope : llvm::reverse(FunctionScopes)) { 1844 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) { 1845 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) { 1846 // We have switched contexts due to template instantiation. 1847 // FIXME: We should swap out the FunctionScopes during code synthesis 1848 // so that we don't need to check for this. 1849 assert(!CodeSynthesisContexts.empty()); 1850 return nullptr; 1851 } 1852 return LSI; 1853 } 1854 } 1855 return nullptr; 1856 } 1857 1858 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { 1859 if (FunctionScopes.empty()) 1860 return nullptr; 1861 1862 auto I = FunctionScopes.rbegin(); 1863 if (IgnoreNonLambdaCapturingScope) { 1864 auto E = FunctionScopes.rend(); 1865 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I)) 1866 ++I; 1867 if (I == E) 1868 return nullptr; 1869 } 1870 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I); 1871 if (CurLSI && CurLSI->Lambda && 1872 !CurLSI->Lambda->Encloses(CurContext)) { 1873 // We have switched contexts due to template instantiation. 1874 assert(!CodeSynthesisContexts.empty()); 1875 return nullptr; 1876 } 1877 1878 return CurLSI; 1879 } 1880 1881 // We have a generic lambda if we parsed auto parameters, or we have 1882 // an associated template parameter list. 1883 LambdaScopeInfo *Sema::getCurGenericLambda() { 1884 if (LambdaScopeInfo *LSI = getCurLambda()) { 1885 return (LSI->TemplateParams.size() || 1886 LSI->GLTemplateParameterList) ? LSI : nullptr; 1887 } 1888 return nullptr; 1889 } 1890 1891 1892 void Sema::ActOnComment(SourceRange Comment) { 1893 if (!LangOpts.RetainCommentsFromSystemHeaders && 1894 SourceMgr.isInSystemHeader(Comment.getBegin())) 1895 return; 1896 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false); 1897 if (RC.isAlmostTrailingComment()) { 1898 SourceRange MagicMarkerRange(Comment.getBegin(), 1899 Comment.getBegin().getLocWithOffset(3)); 1900 StringRef MagicMarkerText; 1901 switch (RC.getKind()) { 1902 case RawComment::RCK_OrdinaryBCPL: 1903 MagicMarkerText = "///<"; 1904 break; 1905 case RawComment::RCK_OrdinaryC: 1906 MagicMarkerText = "/**<"; 1907 break; 1908 default: 1909 llvm_unreachable("if this is an almost Doxygen comment, " 1910 "it should be ordinary"); 1911 } 1912 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 1913 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 1914 } 1915 Context.addComment(RC); 1916 } 1917 1918 // Pin this vtable to this file. 1919 ExternalSemaSource::~ExternalSemaSource() {} 1920 char ExternalSemaSource::ID; 1921 1922 void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 1923 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } 1924 1925 void ExternalSemaSource::ReadKnownNamespaces( 1926 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 1927 } 1928 1929 void ExternalSemaSource::ReadUndefinedButUsed( 1930 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} 1931 1932 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< 1933 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} 1934 1935 /// Figure out if an expression could be turned into a call. 1936 /// 1937 /// Use this when trying to recover from an error where the programmer may have 1938 /// written just the name of a function instead of actually calling it. 1939 /// 1940 /// \param E - The expression to examine. 1941 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 1942 /// with no arguments, this parameter is set to the type returned by such a 1943 /// call; otherwise, it is set to an empty QualType. 1944 /// \param OverloadSet - If the expression is an overloaded function 1945 /// name, this parameter is populated with the decls of the various overloads. 1946 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 1947 UnresolvedSetImpl &OverloadSet) { 1948 ZeroArgCallReturnTy = QualType(); 1949 OverloadSet.clear(); 1950 1951 const OverloadExpr *Overloads = nullptr; 1952 bool IsMemExpr = false; 1953 if (E.getType() == Context.OverloadTy) { 1954 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 1955 1956 // Ignore overloads that are pointer-to-member constants. 1957 if (FR.HasFormOfMemberPointer) 1958 return false; 1959 1960 Overloads = FR.Expression; 1961 } else if (E.getType() == Context.BoundMemberTy) { 1962 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens()); 1963 IsMemExpr = true; 1964 } 1965 1966 bool Ambiguous = false; 1967 bool IsMV = false; 1968 1969 if (Overloads) { 1970 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 1971 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 1972 OverloadSet.addDecl(*it); 1973 1974 // Check whether the function is a non-template, non-member which takes no 1975 // arguments. 1976 if (IsMemExpr) 1977 continue; 1978 if (const FunctionDecl *OverloadDecl 1979 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 1980 if (OverloadDecl->getMinRequiredArguments() == 0) { 1981 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous && 1982 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() || 1983 OverloadDecl->isCPUSpecificMultiVersion()))) { 1984 ZeroArgCallReturnTy = QualType(); 1985 Ambiguous = true; 1986 } else { 1987 ZeroArgCallReturnTy = OverloadDecl->getReturnType(); 1988 IsMV = OverloadDecl->isCPUDispatchMultiVersion() || 1989 OverloadDecl->isCPUSpecificMultiVersion(); 1990 } 1991 } 1992 } 1993 } 1994 1995 // If it's not a member, use better machinery to try to resolve the call 1996 if (!IsMemExpr) 1997 return !ZeroArgCallReturnTy.isNull(); 1998 } 1999 2000 // Attempt to call the member with no arguments - this will correctly handle 2001 // member templates with defaults/deduction of template arguments, overloads 2002 // with default arguments, etc. 2003 if (IsMemExpr && !E.isTypeDependent()) { 2004 Sema::TentativeAnalysisScope Trap(*this); 2005 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), 2006 None, SourceLocation()); 2007 if (R.isUsable()) { 2008 ZeroArgCallReturnTy = R.get()->getType(); 2009 return true; 2010 } 2011 return false; 2012 } 2013 2014 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 2015 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 2016 if (Fun->getMinRequiredArguments() == 0) 2017 ZeroArgCallReturnTy = Fun->getReturnType(); 2018 return true; 2019 } 2020 } 2021 2022 // We don't have an expression that's convenient to get a FunctionDecl from, 2023 // but we can at least check if the type is "function of 0 arguments". 2024 QualType ExprTy = E.getType(); 2025 const FunctionType *FunTy = nullptr; 2026 QualType PointeeTy = ExprTy->getPointeeType(); 2027 if (!PointeeTy.isNull()) 2028 FunTy = PointeeTy->getAs<FunctionType>(); 2029 if (!FunTy) 2030 FunTy = ExprTy->getAs<FunctionType>(); 2031 2032 if (const FunctionProtoType *FPT = 2033 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 2034 if (FPT->getNumParams() == 0) 2035 ZeroArgCallReturnTy = FunTy->getReturnType(); 2036 return true; 2037 } 2038 return false; 2039 } 2040 2041 /// Give notes for a set of overloads. 2042 /// 2043 /// A companion to tryExprAsCall. In cases when the name that the programmer 2044 /// wrote was an overloaded function, we may be able to make some guesses about 2045 /// plausible overloads based on their return types; such guesses can be handed 2046 /// off to this method to be emitted as notes. 2047 /// 2048 /// \param Overloads - The overloads to note. 2049 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to 2050 /// -fshow-overloads=best, this is the location to attach to the note about too 2051 /// many candidates. Typically this will be the location of the original 2052 /// ill-formed expression. 2053 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 2054 const SourceLocation FinalNoteLoc) { 2055 int ShownOverloads = 0; 2056 int SuppressedOverloads = 0; 2057 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 2058 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 2059 // FIXME: Magic number for max shown overloads stolen from 2060 // OverloadCandidateSet::NoteCandidates. 2061 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) { 2062 ++SuppressedOverloads; 2063 continue; 2064 } 2065 2066 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 2067 // Don't print overloads for non-default multiversioned functions. 2068 if (const auto *FD = Fn->getAsFunction()) { 2069 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() && 2070 !FD->getAttr<TargetAttr>()->isDefaultVersion()) 2071 continue; 2072 } 2073 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 2074 ++ShownOverloads; 2075 } 2076 2077 if (SuppressedOverloads) 2078 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 2079 << SuppressedOverloads; 2080 } 2081 2082 static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 2083 const UnresolvedSetImpl &Overloads, 2084 bool (*IsPlausibleResult)(QualType)) { 2085 if (!IsPlausibleResult) 2086 return noteOverloads(S, Overloads, Loc); 2087 2088 UnresolvedSet<2> PlausibleOverloads; 2089 for (OverloadExpr::decls_iterator It = Overloads.begin(), 2090 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 2091 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 2092 QualType OverloadResultTy = OverloadDecl->getReturnType(); 2093 if (IsPlausibleResult(OverloadResultTy)) 2094 PlausibleOverloads.addDecl(It.getDecl()); 2095 } 2096 noteOverloads(S, PlausibleOverloads, Loc); 2097 } 2098 2099 /// Determine whether the given expression can be called by just 2100 /// putting parentheses after it. Notably, expressions with unary 2101 /// operators can't be because the unary operator will start parsing 2102 /// outside the call. 2103 static bool IsCallableWithAppend(Expr *E) { 2104 E = E->IgnoreImplicit(); 2105 return (!isa<CStyleCastExpr>(E) && 2106 !isa<UnaryOperator>(E) && 2107 !isa<BinaryOperator>(E) && 2108 !isa<CXXOperatorCallExpr>(E)); 2109 } 2110 2111 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) { 2112 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 2113 E = UO->getSubExpr(); 2114 2115 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2116 if (ULE->getNumDecls() == 0) 2117 return false; 2118 2119 const NamedDecl *ND = *ULE->decls_begin(); 2120 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2121 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion(); 2122 } 2123 return false; 2124 } 2125 2126 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2127 bool ForceComplain, 2128 bool (*IsPlausibleResult)(QualType)) { 2129 SourceLocation Loc = E.get()->getExprLoc(); 2130 SourceRange Range = E.get()->getSourceRange(); 2131 2132 QualType ZeroArgCallTy; 2133 UnresolvedSet<4> Overloads; 2134 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) && 2135 !ZeroArgCallTy.isNull() && 2136 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 2137 // At this point, we know E is potentially callable with 0 2138 // arguments and that it returns something of a reasonable type, 2139 // so we can emit a fixit and carry on pretending that E was 2140 // actually a CallExpr. 2141 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd()); 2142 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get()); 2143 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range 2144 << (IsCallableWithAppend(E.get()) 2145 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 2146 : FixItHint()); 2147 if (!IsMV) 2148 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 2149 2150 // FIXME: Try this before emitting the fixit, and suppress diagnostics 2151 // while doing so. 2152 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None, 2153 Range.getEnd().getLocWithOffset(1)); 2154 return true; 2155 } 2156 2157 if (!ForceComplain) return false; 2158 2159 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get()); 2160 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range; 2161 if (!IsMV) 2162 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 2163 E = ExprError(); 2164 return true; 2165 } 2166 2167 IdentifierInfo *Sema::getSuperIdentifier() const { 2168 if (!Ident_super) 2169 Ident_super = &Context.Idents.get("super"); 2170 return Ident_super; 2171 } 2172 2173 IdentifierInfo *Sema::getFloat128Identifier() const { 2174 if (!Ident___float128) 2175 Ident___float128 = &Context.Idents.get("__float128"); 2176 return Ident___float128; 2177 } 2178 2179 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, 2180 CapturedRegionKind K, 2181 unsigned OpenMPCaptureLevel) { 2182 auto *CSI = new CapturedRegionScopeInfo( 2183 getDiagnostics(), S, CD, RD, CD->getContextParam(), K, 2184 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0, 2185 OpenMPCaptureLevel); 2186 CSI->ReturnType = Context.VoidTy; 2187 FunctionScopes.push_back(CSI); 2188 } 2189 2190 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { 2191 if (FunctionScopes.empty()) 2192 return nullptr; 2193 2194 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back()); 2195 } 2196 2197 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & 2198 Sema::getMismatchingDeleteExpressions() const { 2199 return DeleteExprs; 2200 } 2201 2202 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) { 2203 if (ExtStr.empty()) 2204 return; 2205 llvm::SmallVector<StringRef, 1> Exts; 2206 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false); 2207 auto CanT = T.getCanonicalType().getTypePtr(); 2208 for (auto &I : Exts) 2209 OpenCLTypeExtMap[CanT].insert(I.str()); 2210 } 2211 2212 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) { 2213 llvm::SmallVector<StringRef, 1> Exts; 2214 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false); 2215 if (Exts.empty()) 2216 return; 2217 for (auto &I : Exts) 2218 OpenCLDeclExtMap[FD].insert(I.str()); 2219 } 2220 2221 void Sema::setCurrentOpenCLExtensionForType(QualType T) { 2222 if (CurrOpenCLExtension.empty()) 2223 return; 2224 setOpenCLExtensionForType(T, CurrOpenCLExtension); 2225 } 2226 2227 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) { 2228 if (CurrOpenCLExtension.empty()) 2229 return; 2230 setOpenCLExtensionForDecl(D, CurrOpenCLExtension); 2231 } 2232 2233 std::string Sema::getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD) { 2234 if (!OpenCLDeclExtMap.empty()) 2235 return getOpenCLExtensionsFromExtMap(FD, OpenCLDeclExtMap); 2236 2237 return ""; 2238 } 2239 2240 std::string Sema::getOpenCLExtensionsFromTypeExtMap(FunctionType *FT) { 2241 if (!OpenCLTypeExtMap.empty()) 2242 return getOpenCLExtensionsFromExtMap(FT, OpenCLTypeExtMap); 2243 2244 return ""; 2245 } 2246 2247 template <typename T, typename MapT> 2248 std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) { 2249 std::string ExtensionNames = ""; 2250 auto Loc = Map.find(FDT); 2251 2252 for (auto const& I : Loc->second) { 2253 ExtensionNames += I; 2254 ExtensionNames += " "; 2255 } 2256 ExtensionNames.pop_back(); 2257 2258 return ExtensionNames; 2259 } 2260 2261 bool Sema::isOpenCLDisabledDecl(Decl *FD) { 2262 auto Loc = OpenCLDeclExtMap.find(FD); 2263 if (Loc == OpenCLDeclExtMap.end()) 2264 return false; 2265 for (auto &I : Loc->second) { 2266 if (!getOpenCLOptions().isEnabled(I)) 2267 return true; 2268 } 2269 return false; 2270 } 2271 2272 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> 2273 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, 2274 DiagInfoT DiagInfo, MapT &Map, 2275 unsigned Selector, 2276 SourceRange SrcRange) { 2277 auto Loc = Map.find(D); 2278 if (Loc == Map.end()) 2279 return false; 2280 bool Disabled = false; 2281 for (auto &I : Loc->second) { 2282 if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) { 2283 Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo 2284 << I << SrcRange; 2285 Disabled = true; 2286 } 2287 } 2288 return Disabled; 2289 } 2290 2291 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) { 2292 // Check extensions for declared types. 2293 Decl *Decl = nullptr; 2294 if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr())) 2295 Decl = TypedefT->getDecl(); 2296 if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr())) 2297 Decl = TagT->getDecl(); 2298 auto Loc = DS.getTypeSpecTypeLoc(); 2299 2300 // Check extensions for vector types. 2301 // e.g. double4 is not allowed when cl_khr_fp64 is absent. 2302 if (QT->isExtVectorType()) { 2303 auto TypePtr = QT->castAs<ExtVectorType>()->getElementType().getTypePtr(); 2304 return checkOpenCLDisabledTypeOrDecl(TypePtr, Loc, QT, OpenCLTypeExtMap); 2305 } 2306 2307 if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap)) 2308 return true; 2309 2310 // Check extensions for builtin types. 2311 return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc, 2312 QT, OpenCLTypeExtMap); 2313 } 2314 2315 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) { 2316 IdentifierInfo *FnName = D.getIdentifier(); 2317 return checkOpenCLDisabledTypeOrDecl(&D, E.getBeginLoc(), FnName, 2318 OpenCLDeclExtMap, 1, D.getSourceRange()); 2319 } 2320