blob: d4be3e92420e9d50255cb7119ca0efb271b400ad [file] [log] [blame]
Chris Lattnerddd6fc82006-11-10 04:58:55 +00001//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
Chris Lattner3e7bd4e2006-08-17 05:51:27 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner3e7bd4e2006-08-17 05:51:27 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerddd6fc82006-11-10 04:58:55 +00009// This file implements the actions class which performs semantic analysis and
10// builds an AST out of a parse stream.
Chris Lattner3e7bd4e2006-08-17 05:51:27 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnercb6a3822006-11-10 06:20:45 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000015#include "clang/AST/ASTDiagnostic.h"
John McCall28a0cf72010-08-25 07:42:41 +000016#include "clang/AST/DeclCXX.h"
Daniel Jasper0baec5492012-06-06 08:32:04 +000017#include "clang/AST/DeclFriend.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +000020#include "clang/AST/ExprCXX.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000021#include "clang/AST/PrettyDeclStackTrace.h"
Chris Lattnerc8e630e2011-02-17 07:39:24 +000022#include "clang/AST/StmtCXX.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssonf68079e2009-08-26 22:33:56 +000024#include "clang/Basic/PartialDiagnostic.h"
Richard Smith26a92d52019-08-26 18:18:07 +000025#include "clang/Basic/Stack.h"
Chris Lattner7d4f5c42009-04-30 06:18:40 +000026#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#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"
Richard Smith7873de02016-08-11 22:25:46 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/MultiplexExternalSemaSource.h"
34#include "clang/Sema/ObjCMethodList.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/SemaConsumer.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000038#include "clang/Sema/SemaInternal.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "clang/Sema/TemplateDeduction.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000040#include "clang/Sema/TemplateInstCallback.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/DenseMap.h"
42#include "llvm/ADT/SmallSet.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000043#include "llvm/Support/TimeProfiler.h"
44
Chris Lattnerc11438c2006-08-18 05:17:52 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Douglas Gregor9a28e842010-03-01 23:15:13 +000047
Alp Tokerb6cc5922014-05-03 03:45:55 +000048SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
49 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
50}
51
52ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
53
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +000054PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
55 const Preprocessor &PP) {
Douglas Gregor75acd922011-09-27 23:30:47 +000056 PrintingPolicy Policy = Context.getPrintingPolicy();
Joel E. Denny7bcc2102018-05-14 18:41:44 +000057 // In diagnostics, we print _Bool as bool if the latter is defined as the
58 // former.
David Blaikiebbafb8a2012-03-11 07:00:24 +000059 Policy.Bool = Context.getLangOpts().Bool;
Douglas Gregor75acd922011-09-27 23:30:47 +000060 if (!Policy.Bool) {
Richard Smith301bc212016-05-19 01:39:10 +000061 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
Michael Gottesmanbf0fd392013-01-20 01:04:14 +000062 Policy.Bool = BoolMacro->isObjectLike() &&
Richard Smith301bc212016-05-19 01:39:10 +000063 BoolMacro->getNumTokens() == 1 &&
64 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
Douglas Gregor75acd922011-09-27 23:30:47 +000065 }
66 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +000067
Douglas Gregor75acd922011-09-27 23:30:47 +000068 return Policy;
69}
70
Douglas Gregorf11096c2010-08-25 18:07:12 +000071void Sema::ActOnTranslationUnitScope(Scope *S) {
Steve Naroffc62adb62007-10-09 22:01:59 +000072 TUScope = S;
Douglas Gregor91f84212008-12-11 16:49:14 +000073 PushDeclContext(S, Context.getTranslationUnitDecl());
Steve Naroff7f549f12007-10-10 21:53:07 +000074}
75
Alex Lorenz45b40142017-07-28 14:41:21 +000076namespace clang {
77namespace sema {
78
79class SemaPPCallbacks : public PPCallbacks {
80 Sema *S = nullptr;
81 llvm::SmallVector<SourceLocation, 8> IncludeStack;
82
83public:
84 void set(Sema &S) { this->S = &S; }
85
86 void reset() { S = nullptr; }
87
88 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
89 SrcMgr::CharacteristicKind FileType,
90 FileID PrevFID) override {
91 if (!S)
92 return;
93 switch (Reason) {
94 case EnterFile: {
95 SourceManager &SM = S->getSourceManager();
96 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
97 if (IncludeLoc.isValid()) {
Anton Afanasyevd880de22019-03-30 08:42:48 +000098 if (llvm::timeTraceProfilerEnabled()) {
99 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
100 llvm::timeTraceProfilerBegin(
101 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
102 }
103
Alex Lorenz45b40142017-07-28 14:41:21 +0000104 IncludeStack.push_back(IncludeLoc);
105 S->DiagnoseNonDefaultPragmaPack(
106 Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
107 }
108 break;
109 }
110 case ExitFile:
Anton Afanasyevd880de22019-03-30 08:42:48 +0000111 if (!IncludeStack.empty()) {
112 if (llvm::timeTraceProfilerEnabled())
113 llvm::timeTraceProfilerEnd();
114
Alex Lorenz45b40142017-07-28 14:41:21 +0000115 S->DiagnoseNonDefaultPragmaPack(
116 Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
117 IncludeStack.pop_back_val());
Anton Afanasyevd880de22019-03-30 08:42:48 +0000118 }
Alex Lorenz45b40142017-07-28 14:41:21 +0000119 break;
120 default:
121 break;
122 }
123 }
124};
125
126} // end namespace sema
127} // end namespace clang
128
Douglas Gregor54feb842009-04-14 16:27:31 +0000129Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000130 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
131 : ExternalSource(nullptr), isMultiplexExternalSource(false),
132 FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
133 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
134 SourceMgr(PP.getSourceManager()), CollectStats(false),
135 CodeCompleter(CodeCompleter), CurContext(nullptr),
136 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
137 MSPointerToMemberRepresentationMethod(
138 LangOpts.getMSPointerToMemberRepresentationMethod()),
139 VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
140 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
141 CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
142 PragmaAttributeCurrentTargetDecl(nullptr),
143 IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
144 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
145 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
Brian Gesiak3e65d9a2018-07-14 18:21:44 +0000146 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
147 MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
148 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000149 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
150 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
151 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000152 TUKind(TUKind), NumSFINAEErrors(0),
153 FullyCheckedComparisonCategories(
154 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
155 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
156 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
157 CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
158 TyposCorrected(0), AnalysisWarnings(*this),
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000159 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
160 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000161 TUScope = nullptr;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +0000162 isConstantEvaluatedOverride = false;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000163
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000164 LoadedExternalKnownNamespaces = false;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000165 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
Craig Topperc3ec1492014-05-26 06:22:03 +0000166 NSNumberLiteralMethods[I] = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000167
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000168 if (getLangOpts().ObjC)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000169 NSAPIObj.reset(new NSAPI(Context));
170
David Blaikiebbafb8a2012-03-11 07:00:24 +0000171 if (getLangOpts().CPlusPlus)
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000172 FieldCollector.reset(new CXXFieldCollector());
Mike Stump11289f42009-09-09 15:08:12 +0000173
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000174 // Tell diagnostics how to render things from the AST library.
Craig Topper12126262015-11-15 17:27:57 +0000175 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
Douglas Gregorff790f12009-11-26 00:44:06 +0000176
Faisal Valid143a0c2017-04-01 21:30:49 +0000177 ExprEvalContexts.emplace_back(
178 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000179 nullptr, ExpressionEvaluationContextRecord::EK_Other);
John McCallaab3e412010-08-25 08:40:02 +0000180
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000181 // Initialization of data sharing attributes stack for OpenMP
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182 InitDataSharingAttributesStack();
Alex Lorenz45b40142017-07-28 14:41:21 +0000183
184 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000185 std::make_unique<sema::SemaPPCallbacks>();
Alex Lorenz45b40142017-07-28 14:41:21 +0000186 SemaPPCallbackHandler = Callbacks.get();
187 PP.addPPCallbacks(std::move(Callbacks));
188 SemaPPCallbackHandler->set(*this);
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000189}
190
Alp Tokerf22856a2013-12-18 15:29:05 +0000191void Sema::addImplicitTypedef(StringRef Name, QualType T) {
192 DeclarationName DN = &Context.Idents.get(Name);
193 if (IdResolver.begin(DN) == IdResolver.end())
194 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
195}
196
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000197void Sema::Initialize() {
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000198 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
199 SC->InitializeSema(*this);
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000200
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000201 // Tell the external Sema source about this Sema object.
202 if (ExternalSemaSource *ExternalSema
203 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
204 ExternalSema->InitializeSema(*this);
Douglas Gregor3ea72692011-08-12 05:46:01 +0000205
Ben Langmuirbb1c9182014-09-05 20:24:27 +0000206 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
207 // will not be able to merge any duplicate __va_list_tag decls correctly.
208 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
209
Richard Smith33e0f7e2015-07-22 02:08:40 +0000210 if (!TUScope)
211 return;
212
Douglas Gregor801c99d2011-08-12 06:49:56 +0000213 // Initialize predefined 128-bit integer types, if needed.
Alp Tokerb6cc5922014-05-03 03:45:55 +0000214 if (Context.getTargetInfo().hasInt128Type()) {
Douglas Gregor801c99d2011-08-12 06:49:56 +0000215 // If either of the 128-bit integer types are unavailable to name lookup,
216 // define them now.
217 DeclarationName Int128 = &Context.Idents.get("__int128_t");
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000218 if (IdResolver.begin(Int128) == IdResolver.end())
Douglas Gregor801c99d2011-08-12 06:49:56 +0000219 PushOnScopeChains(Context.getInt128Decl(), TUScope);
220
221 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000222 if (IdResolver.begin(UInt128) == IdResolver.end())
Douglas Gregor801c99d2011-08-12 06:49:56 +0000223 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
224 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000225
Douglas Gregor801c99d2011-08-12 06:49:56 +0000226
Douglas Gregor3ea72692011-08-12 05:46:01 +0000227 // Initialize predefined Objective-C types:
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000228 if (getLangOpts().ObjC) {
Douglas Gregor52e02802011-08-12 06:17:30 +0000229 // If 'SEL' does not yet refer to any declarations, make it refer to the
230 // predefined 'SEL'.
231 DeclarationName SEL = &Context.Idents.get("SEL");
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000232 if (IdResolver.begin(SEL) == IdResolver.end())
Douglas Gregor52e02802011-08-12 06:17:30 +0000233 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
234
Douglas Gregor3ea72692011-08-12 05:46:01 +0000235 // If 'id' does not yet refer to any declarations, make it refer to the
236 // predefined 'id'.
237 DeclarationName Id = &Context.Idents.get("id");
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000238 if (IdResolver.begin(Id) == IdResolver.end())
Douglas Gregor3ea72692011-08-12 05:46:01 +0000239 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000240
Douglas Gregor0a586182011-08-12 05:59:41 +0000241 // Create the built-in typedef for 'Class'.
242 DeclarationName Class = &Context.Idents.get("Class");
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000243 if (IdResolver.begin(Class) == IdResolver.end())
Douglas Gregor0a586182011-08-12 05:59:41 +0000244 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
Douglas Gregord53ae832012-01-17 18:09:05 +0000245
246 // Create the built-in forward declaratino for 'Protocol'.
247 DeclarationName Protocol = &Context.Idents.get("Protocol");
248 if (IdResolver.begin(Protocol) == IdResolver.end())
249 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
Douglas Gregor3ea72692011-08-12 05:46:01 +0000250 }
Meador Inge5d3fb222012-06-16 03:34:49 +0000251
Ben Langmuirf5416742016-02-04 00:55:24 +0000252 // Create the internal type for the *StringMakeConstantString builtins.
253 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
254 if (IdResolver.begin(ConstantString) == IdResolver.end())
255 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
256
Alp Tokere1fab522014-01-04 15:25:02 +0000257 // Initialize Microsoft "predefined C++ types".
Craig Topper12126262015-11-15 17:27:57 +0000258 if (getLangOpts().MSVCCompat) {
259 if (getLangOpts().CPlusPlus &&
David Majnemerbe525392015-02-18 02:28:13 +0000260 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
Alp Tokere1fab522014-01-04 15:25:02 +0000261 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
262 TUScope);
David Majnemer1de36912014-01-14 06:19:35 +0000263
264 addImplicitTypedef("size_t", Context.getSizeType());
Alp Tokere1fab522014-01-04 15:25:02 +0000265 }
266
Yaxun Liu5b746652016-12-18 05:18:55 +0000267 // Initialize predefined OpenCL types and supported extensions and (optional)
268 // core features.
Craig Topper12126262015-11-15 17:27:57 +0000269 if (getLangOpts().OpenCL) {
Anastasia Stulovae88e2b92019-02-07 17:32:37 +0000270 getOpenCLOptions().addSupport(
271 Context.getTargetInfo().getSupportedOpenCLOpts());
272 getOpenCLOptions().enableSupportedCore(getLangOpts());
Alp Tokerf22856a2013-12-18 15:29:05 +0000273 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
274 addImplicitTypedef("event_t", Context.OCLEventTy);
Anastasia Stulovae88e2b92019-02-07 17:32:37 +0000275 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) {
Alexey Bader9c8453f2015-09-15 11:18:52 +0000276 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
277 addImplicitTypedef("queue_t", Context.OCLQueueTy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000278 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
Anastasia Stulovab1152f12015-03-18 12:55:29 +0000279 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
280 addImplicitTypedef("atomic_uint",
281 Context.getAtomicType(Context.UnsignedIntTy));
Yaxun Liu5b746652016-12-18 05:18:55 +0000282 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
283 addImplicitTypedef("atomic_long", AtomicLongT);
284 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
285 addImplicitTypedef("atomic_ulong", AtomicULongT);
Anastasia Stulovab1152f12015-03-18 12:55:29 +0000286 addImplicitTypedef("atomic_float",
287 Context.getAtomicType(Context.FloatTy));
Yaxun Liu5b746652016-12-18 05:18:55 +0000288 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
289 addImplicitTypedef("atomic_double", AtomicDoubleT);
Anastasia Stulovab1152f12015-03-18 12:55:29 +0000290 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
291 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
292 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
Yaxun Liu5b746652016-12-18 05:18:55 +0000293 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
294 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
295 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
296 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
297 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
298 addImplicitTypedef("atomic_size_t", AtomicSizeT);
299 auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
300 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
301
302 // OpenCL v2.0 s6.13.11.6:
303 // - The atomic_long and atomic_ulong types are supported if the
304 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
305 // extensions are supported.
306 // - The atomic_double type is only supported if double precision
307 // is supported and the cl_khr_int64_base_atomics and
308 // cl_khr_int64_extended_atomics extensions are supported.
309 // - If the device address space is 64-bits, the data types
310 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
311 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
312 // cl_khr_int64_extended_atomics extensions are supported.
313 std::vector<QualType> Atomic64BitTypes;
314 Atomic64BitTypes.push_back(AtomicLongT);
315 Atomic64BitTypes.push_back(AtomicULongT);
316 Atomic64BitTypes.push_back(AtomicDoubleT);
317 if (Context.getTypeSize(AtomicSizeT) == 64) {
318 Atomic64BitTypes.push_back(AtomicSizeT);
319 Atomic64BitTypes.push_back(AtomicIntPtrT);
320 Atomic64BitTypes.push_back(AtomicUIntPtrT);
321 Atomic64BitTypes.push_back(AtomicPtrDiffT);
322 }
323 for (auto &I : Atomic64BitTypes)
324 setOpenCLExtensionForType(I,
325 "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
326
327 setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
Anastasia Stulovab1152f12015-03-18 12:55:29 +0000328 }
Yaxun Liu5b746652016-12-18 05:18:55 +0000329
330 setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
331
332#define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
333 setOpenCLExtensionForType(Context.Id, Ext);
334#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +0000335#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
336 addImplicitTypedef(#ExtType, Context.Id##Ty); \
337 setOpenCLExtensionForType(Context.Id##Ty, #Ext);
338#include "clang/Basic/OpenCLExtensionTypes.def"
Richard Sandifordeb485fb2019-08-09 08:52:54 +0000339 }
340
341 if (Context.getTargetInfo().hasAArch64SVETypes()) {
342#define SVE_TYPE(Name, Id, SingletonId) \
343 addImplicitTypedef(Name, Context.SingletonId);
344#include "clang/Basic/AArch64SVEACLETypes.def"
345 }
Alp Tokerf22856a2013-12-18 15:29:05 +0000346
Craig Topper12126262015-11-15 17:27:57 +0000347 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
Charles Davisc7d5c942015-09-17 20:55:33 +0000348 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
349 if (IdResolver.begin(MSVaList) == IdResolver.end())
350 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
351 }
352
Meador Inge5d3fb222012-06-16 03:34:49 +0000353 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
354 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
355 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
Steve Naroff38d31b42007-02-28 01:22:02 +0000356}
Chris Lattnercb6a3822006-11-10 06:20:45 +0000357
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000358Sema::~Sema() {
Eli Friedman570024a2010-08-05 06:57:20 +0000359 if (VisContext) FreeVisContext();
Reid Kleckner87a31802018-03-12 21:43:02 +0000360
John McCallaab3e412010-08-25 08:40:02 +0000361 // Kill all the active scopes.
Reid Kleckner87a31802018-03-12 21:43:02 +0000362 for (sema::FunctionScopeInfo *FSI : FunctionScopes)
Richard Smith2fdd95c2019-05-31 00:45:09 +0000363 delete FSI;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000364
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000365 // Tell the SemaConsumer to forget about us; we're going out of scope.
366 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
367 SC->ForgetSema();
368
369 // Detach from the external Sema source.
370 if (ExternalSemaSource *ExternalSema
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000371 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000372 ExternalSema->ForgetSema();
Axel Naumanndd433f02012-10-18 19:05:02 +0000373
374 // If Sema's ExternalSource is the multiplexer - we own it.
375 if (isMultiplexExternalSource)
376 delete ExternalSource;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000377
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000378 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
379
Alexey Bataev758e55e2013-09-06 18:03:48 +0000380 // Destroys data sharing attributes stack for OpenMP
381 DestroyDataSharingAttributesStack();
Kaelyn Takataef3e42b2014-11-21 18:48:06 +0000382
Alex Lorenz45b40142017-07-28 14:41:21 +0000383 // Detach from the PP callback handler which outlives Sema since it's owned
384 // by the preprocessor.
385 SemaPPCallbackHandler->reset();
386
Kaelyn Takataef3e42b2014-11-21 18:48:06 +0000387 assert(DelayedTypos.empty() && "Uncorrected typos!");
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000388}
389
Richard Smith26a92d52019-08-26 18:18:07 +0000390void Sema::warnStackExhausted(SourceLocation Loc) {
391 // Only warn about this once.
392 if (!WarnedStackExhausted) {
393 Diag(Loc, diag::warn_stack_exhausted);
394 WarnedStackExhausted = true;
395 }
396}
397
398void Sema::runWithSufficientStackSpace(SourceLocation Loc,
399 llvm::function_ref<void()> Fn) {
400 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
401}
402
John McCall31168b02011-06-15 23:02:42 +0000403/// makeUnavailableInSystemHeader - There is an error in the current
404/// context. If we're still in a system header, and we can plausibly
405/// make the relevant declaration unavailable instead of erroring, do
406/// so and return true.
407bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
John McCallc6af8c62015-10-28 05:03:19 +0000408 UnavailableAttr::ImplicitReason reason) {
John McCall31168b02011-06-15 23:02:42 +0000409 // If we're not in a function, it's an error.
410 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
411 if (!fn) return false;
412
413 // If we're in template instantiation, it's an error.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000414 if (inTemplateInstantiation())
John McCall31168b02011-06-15 23:02:42 +0000415 return false;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000416
John McCall31168b02011-06-15 23:02:42 +0000417 // If that function's not in a system header, it's an error.
418 if (!Context.getSourceManager().isInSystemHeader(loc))
419 return false;
420
421 // If the function is already unavailable, it's not an error.
422 if (fn->hasAttr<UnavailableAttr>()) return true;
423
John McCallc6af8c62015-10-28 05:03:19 +0000424 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
John McCall31168b02011-06-15 23:02:42 +0000425 return true;
426}
427
Sebastian Redlab238a72011-04-24 16:28:06 +0000428ASTMutationListener *Sema::getASTMutationListener() const {
429 return getASTConsumer().GetASTMutationListener();
430}
431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432///Registers an external source. If an external source already exists,
Axel Naumanndd433f02012-10-18 19:05:02 +0000433/// creates a multiplex external source and appends to it.
434///
435///\param[in] E - A non-null external sema source.
436///
437void Sema::addExternalSource(ExternalSemaSource *E) {
438 assert(E && "Cannot use with NULL ptr");
439
440 if (!ExternalSource) {
441 ExternalSource = E;
442 return;
443 }
444
445 if (isMultiplexExternalSource)
446 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
447 else {
448 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
449 isMultiplexExternalSource = true;
450 }
451}
452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000453/// Print out statistics about the semantic analysis.
Chandler Carruthb4836ea2011-07-06 16:21:37 +0000454void Sema::PrintStats() const {
455 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
456 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
457
458 BumpAlloc.PrintStats();
459 AnalysisWarnings.PrintStats();
460}
461
George Burgess IV8d141e02015-12-14 22:00:49 +0000462void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
463 QualType SrcType,
464 SourceLocation Loc) {
465 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
466 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
467 return;
468
469 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
470 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
471 return;
472
473 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
474}
475
Nico Weberd7ba86b2017-05-05 16:11:08 +0000476void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
Roman Lebedev809df342017-10-26 13:18:14 +0000477 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000478 E->getBeginLoc()))
Roman Lebedev809df342017-10-26 13:18:14 +0000479 return;
480 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
481 if (!getLangOpts().CPlusPlus11)
482 return;
483
Nico Weberd7ba86b2017-05-05 16:11:08 +0000484 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
485 return;
Erich Keane818cf5b2017-10-25 20:23:13 +0000486 if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
Nico Weberd7ba86b2017-05-05 16:11:08 +0000487 return;
Roman Lebedev809df342017-10-26 13:18:14 +0000488
489 // If it is a macro from system header, and if the macro name is not "NULL",
490 // do not warn.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000491 SourceLocation MaybeMacroLoc = E->getBeginLoc();
Roman Lebedev809df342017-10-26 13:18:14 +0000492 if (Diags.getSuppressSystemWarnings() &&
493 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
494 !findMacroSpelling(MaybeMacroLoc, "NULL"))
Nico Weberd7ba86b2017-05-05 16:11:08 +0000495 return;
496
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000497 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
Nico Weberd7ba86b2017-05-05 16:11:08 +0000498 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
499}
500
Richard Smith507840d2011-11-29 22:48:16 +0000501/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
502/// If there is already an implicit cast, merge into the existing one.
503/// The result is of the given category.
504ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
505 CastKind Kind, ExprValueKind VK,
506 const CXXCastPath *BasePath,
507 CheckedConversionKind CCK) {
Richard Smith508ebf32011-10-28 03:31:48 +0000508#ifndef NDEBUG
509 if (VK == VK_RValue && !E->isRValue()) {
510 switch (Kind) {
511 default:
Craig Topperd8d43192014-06-18 05:13:13 +0000512 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
513 "kind");
Richard Smith07ed9cf2019-06-20 19:49:13 +0000514 case CK_Dependent:
Richard Smith508ebf32011-10-28 03:31:48 +0000515 case CK_LValueToRValue:
516 case CK_ArrayToPointerDecay:
517 case CK_FunctionToPointerDecay:
518 case CK_ToVoid:
JF Bastien7d60a0f2018-07-18 18:01:41 +0000519 case CK_NonAtomicToAtomic:
Richard Smith508ebf32011-10-28 03:31:48 +0000520 break;
521 }
522 }
Richard Smith07ed9cf2019-06-20 19:49:13 +0000523 assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) &&
524 "can't cast rvalue to lvalue");
Richard Smith508ebf32011-10-28 03:31:48 +0000525#endif
526
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000527 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
Nico Weberd7ba86b2017-05-05 16:11:08 +0000528 diagnoseZeroToNullptrConversion(Kind, E);
Douglas Gregorb4866e82015-06-19 18:13:19 +0000529
John Wiegley01296292011-04-08 18:41:53 +0000530 QualType ExprTy = Context.getCanonicalType(E->getType());
Mon P Wang74b32072008-09-04 08:38:01 +0000531 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000532
Mon P Wang74b32072008-09-04 08:38:01 +0000533 if (ExprTy == TypeTy)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000534 return E;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Richard Smithb3189a12016-12-05 07:49:14 +0000536 // C++1z [conv.array]: The temporary materialization conversion is applied.
537 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
538 if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
539 E->getValueKind() == VK_RValue) {
540 // The temporary is an lvalue in C++98 and an xvalue otherwise.
541 ExprResult Materialized = CreateMaterializeTemporaryExpr(
542 E->getType(), E, !getLangOpts().CPlusPlus11);
543 if (Materialized.isInvalid())
544 return ExprError();
545 E = Materialized.get();
546 }
547
Richard Smith507840d2011-11-29 22:48:16 +0000548 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
549 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
550 ImpCast->setType(Ty);
551 ImpCast->setValueKind(VK);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000552 return E;
Richard Smith507840d2011-11-29 22:48:16 +0000553 }
554 }
555
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000556 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000557}
558
Abramo Bagnara7ccce982011-04-07 09:26:19 +0000559/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
560/// to the conversion from scalar type ScalarTy to the Boolean type.
561CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
562 switch (ScalarTy->getScalarTypeKind()) {
563 case Type::STK_Bool: return CK_NoOp;
John McCall9320b872011-09-09 05:25:32 +0000564 case Type::STK_CPointer: return CK_PointerToBoolean;
565 case Type::STK_BlockPointer: return CK_PointerToBoolean;
566 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
Abramo Bagnara7ccce982011-04-07 09:26:19 +0000567 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
568 case Type::STK_Integral: return CK_IntegralToBoolean;
569 case Type::STK_Floating: return CK_FloatingToBoolean;
570 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
571 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
Leonard Chanb4ba4672018-10-23 17:55:35 +0000572 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
Abramo Bagnara7ccce982011-04-07 09:26:19 +0000573 }
Richard Smith354abec2017-12-08 23:29:59 +0000574 llvm_unreachable("unknown scalar type kind");
Abramo Bagnara7ccce982011-04-07 09:26:19 +0000575}
576
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000577/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000578static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
Rafael Espindola820fa702013-01-08 19:43:34 +0000579 if (D->getMostRecentDecl()->isUsed())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000580 return true;
581
Rafael Espindola3ae00052013-05-13 00:12:11 +0000582 if (D->isExternallyVisible())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000583 return true;
584
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000585 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Vassil Vassilev64e1e1e2017-05-09 11:25:41 +0000586 // If this is a function template and none of its specializations is used,
587 // we should warn.
588 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
589 for (const auto *Spec : Template->specializations())
590 if (ShouldRemoveFromUnused(SemaRef, Spec))
591 return true;
592
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000593 // UnusedFileScopedDecls stores the first declaration.
594 // The declaration may have become definition so check again.
595 const FunctionDecl *DeclToCheck;
596 if (FD->hasBody(DeclToCheck))
597 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
598
599 // Later redecls may add new information resulting in not having to warn,
600 // so check again.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000601 DeclToCheck = FD->getMostRecentDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000602 if (DeclToCheck != FD)
603 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
604 }
605
606 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedmana5dfebd2013-09-10 21:10:25 +0000607 // If a variable usable in constant expressions is referenced,
608 // don't warn if it isn't used: if the value of a variable is required
609 // for the computation of a constant expression, it doesn't make sense to
610 // warn even if the variable isn't odr-used. (isReferenced doesn't
611 // precisely reflect that, but it's a decent approximation.)
612 if (VD->isReferenced() &&
Richard Smith715f7a12019-06-11 17:50:32 +0000613 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
Eli Friedmana5dfebd2013-09-10 21:10:25 +0000614 return true;
615
Vassil Vassilev64e1e1e2017-05-09 11:25:41 +0000616 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
617 // If this is a variable template and none of its specializations is used,
618 // we should warn.
619 for (const auto *Spec : Template->specializations())
620 if (ShouldRemoveFromUnused(SemaRef, Spec))
621 return true;
622
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000623 // UnusedFileScopedDecls stores the first declaration.
624 // The declaration may have become definition so check again.
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000625 const VarDecl *DeclToCheck = VD->getDefinition();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000626 if (DeclToCheck)
627 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
628
629 // Later redecls may add new information resulting in not having to warn,
630 // so check again.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000631 DeclToCheck = VD->getMostRecentDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000632 if (DeclToCheck != VD)
633 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
634 }
635
636 return false;
637}
638
Richard Smith405e2db2017-09-20 07:22:00 +0000639static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
640 if (auto *FD = dyn_cast<FunctionDecl>(ND))
641 return FD->isExternC();
642 return cast<VarDecl>(ND)->isExternC();
643}
644
645/// Determine whether ND is an external-linkage function or variable whose
646/// type has no linkage.
647bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
648 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
649 // because we also want to catch the case where its type has VisibleNoLinkage,
650 // which does not affect the linkage of VD.
651 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
652 !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
653 !isFunctionOrVarDeclExternC(VD);
654}
655
Richard Smith62f19e72016-06-25 00:15:56 +0000656/// Obtains a sorted list of functions and variables that are undefined but
657/// ODR-used.
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000658void Sema::getUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000659 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
Richard Smithd6a04d72016-03-25 21:49:43 +0000660 for (const auto &UndefinedUse : UndefinedButUsed) {
661 NamedDecl *ND = UndefinedUse.first;
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000662
663 // Ignore attributes that have become invalid.
664 if (ND->isInvalidDecl()) continue;
665
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000666 // __attribute__((weakref)) is basically a definition.
667 if (ND->hasAttr<WeakRefAttr>()) continue;
668
Richard Smith57865822017-08-03 19:24:27 +0000669 if (isa<CXXDeductionGuideDecl>(ND))
670 continue;
671
Richard Smith405e2db2017-09-20 07:22:00 +0000672 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
673 // An exported function will always be emitted when defined, so even if
674 // the function is inline, it doesn't have to be emitted in this TU. An
675 // imported function implies that it has been exported somewhere else.
676 continue;
677 }
678
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000679 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
680 if (FD->isDefined())
681 continue;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000682 if (FD->isExternallyVisible() &&
Richard Smith405e2db2017-09-20 07:22:00 +0000683 !isExternalWithNoLinkageType(FD) &&
Louis Dionned2695792018-10-04 15:49:42 +0000684 !FD->getMostRecentDecl()->isInlined() &&
685 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000686 continue;
Reid Klecknerc8ae8782018-06-20 21:12:20 +0000687 if (FD->getBuiltinID())
688 continue;
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000689 } else {
Richard Smith62f19e72016-06-25 00:15:56 +0000690 auto *VD = cast<VarDecl>(ND);
691 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000692 continue;
Richard Smith405e2db2017-09-20 07:22:00 +0000693 if (VD->isExternallyVisible() &&
694 !isExternalWithNoLinkageType(VD) &&
Louis Dionned2695792018-10-04 15:49:42 +0000695 !VD->getMostRecentDecl()->isInline() &&
696 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000697 continue;
Justin Lebar5489f852018-05-17 16:15:07 +0000698
699 // Skip VarDecls that lack formal definitions but which we know are in
700 // fact defined somewhere.
701 if (VD->isKnownToBeDefined())
702 continue;
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000703 }
704
Richard Smithd6a04d72016-03-25 21:49:43 +0000705 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000706 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000707}
708
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000709/// checkUndefinedButUsed - Check for undefined objects with internal linkage
710/// or that are inline.
711static void checkUndefinedButUsed(Sema &S) {
712 if (S.UndefinedButUsed.empty()) return;
John McCall83779672011-02-19 02:53:41 +0000713
714 // Collect all the still-undefined entities with internal linkage.
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000715 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000716 S.getUndefinedButUsed(Undefined);
Nick Lewyckyf0f56162013-01-31 03:23:57 +0000717 if (Undefined.empty()) return;
John McCall83779672011-02-19 02:53:41 +0000718
Richard Smith405e2db2017-09-20 07:22:00 +0000719 for (auto Undef : Undefined) {
720 ValueDecl *VD = cast<ValueDecl>(Undef.first);
721 SourceLocation UseLoc = Undef.second;
John McCall83779672011-02-19 02:53:41 +0000722
Richard Smith405e2db2017-09-20 07:22:00 +0000723 if (S.isExternalWithNoLinkageType(VD)) {
724 // C++ [basic.link]p8:
725 // A type without linkage shall not be used as the type of a variable
726 // or function with external linkage unless
727 // -- the entity has C language linkage
728 // -- the entity is not odr-used or is defined in the same TU
729 //
730 // As an extension, accept this in cases where the type is externally
731 // visible, since the function or variable actually can be defined in
732 // another translation unit in that case.
733 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
734 ? diag::ext_undefined_internal_type
735 : diag::err_undefined_internal_type)
736 << isa<VarDecl>(VD) << VD;
737 } else if (!VD->isExternallyVisible()) {
738 // FIXME: We can promote this to an error. The function or variable can't
739 // be defined anywhere else, so the program must necessarily violate the
740 // one definition rule.
741 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
742 << isa<VarDecl>(VD) << VD;
743 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
James Y Knight5b218ff2016-06-25 16:40:53 +0000744 (void)FD;
Richard Smith62f19e72016-06-25 00:15:56 +0000745 assert(FD->getMostRecentDecl()->isInlined() &&
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000746 "used object requires definition but isn't inline or internal?");
Richard Smith62f19e72016-06-25 00:15:56 +0000747 // FIXME: This is ill-formed; we should reject.
Richard Smith405e2db2017-09-20 07:22:00 +0000748 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
Richard Smith62f19e72016-06-25 00:15:56 +0000749 } else {
Richard Smith405e2db2017-09-20 07:22:00 +0000750 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000751 "used var requires definition but isn't inline or internal?");
Richard Smith405e2db2017-09-20 07:22:00 +0000752 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +0000753 }
Richard Smith405e2db2017-09-20 07:22:00 +0000754 if (UseLoc.isValid())
755 S.Diag(UseLoc, diag::note_used_here);
John McCall83779672011-02-19 02:53:41 +0000756 }
Richard Smithd6a04d72016-03-25 21:49:43 +0000757
758 S.UndefinedButUsed.clear();
John McCall83779672011-02-19 02:53:41 +0000759}
760
Douglas Gregor1c4bfe52011-07-28 18:09:57 +0000761void Sema::LoadExternalWeakUndeclaredIdentifiers() {
762 if (!ExternalSource)
763 return;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000764
Douglas Gregor1c4bfe52011-07-28 18:09:57 +0000765 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
766 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
Chandler Carruthf85d9822015-03-26 08:32:49 +0000767 for (auto &WeakID : WeakIDs)
768 WeakUndeclaredIdentifiers.insert(WeakID);
Douglas Gregor1c4bfe52011-07-28 18:09:57 +0000769}
770
Daniel Jasper0baec5492012-06-06 08:32:04 +0000771
772typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000774/// Returns true, if all methods and nested classes of the given
Daniel Jasper0baec5492012-06-06 08:32:04 +0000775/// CXXRecordDecl are defined in this translation unit.
776///
777/// Should only be called from ActOnEndOfTranslationUnit so that all
778/// definitions are actually read.
779static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
780 RecordCompleteMap &MNCComplete) {
781 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
782 if (Cache != MNCComplete.end())
783 return Cache->second;
784 if (!RD->isCompleteDefinition())
785 return false;
786 bool Complete = true;
787 for (DeclContext::decl_iterator I = RD->decls_begin(),
788 E = RD->decls_end();
789 I != E && Complete; ++I) {
790 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
Richard Smitha31174e2017-11-01 04:52:12 +0000791 Complete = M->isDefined() || M->isDefaulted() ||
792 (M->isPure() && !isa<CXXDestructorDecl>(M));
Daniel Jaspere99c2bf2012-06-14 20:56:06 +0000793 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
Nico Weber4bde6c22015-06-18 20:09:49 +0000794 // If the template function is marked as late template parsed at this
795 // point, it has not been instantiated and therefore we have not
796 // performed semantic analysis on it yet, so we cannot know if the type
797 // can be considered complete.
Ehsan Akhgari4b5ca9a2014-10-11 00:24:15 +0000798 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
799 F->getTemplatedDecl()->isDefined();
Daniel Jasper0baec5492012-06-06 08:32:04 +0000800 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
801 if (R->isInjectedClassName())
802 continue;
803 if (R->hasDefinition())
804 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
805 MNCComplete);
806 else
807 Complete = false;
808 }
809 }
810 MNCComplete[RD] = Complete;
811 return Complete;
812}
813
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000814/// Returns true, if the given CXXRecordDecl is fully defined in this
Daniel Jasper0baec5492012-06-06 08:32:04 +0000815/// translation unit, i.e. all methods are defined or pure virtual and all
816/// friends, friend functions and nested classes are fully defined in this
817/// translation unit.
818///
819/// Should only be called from ActOnEndOfTranslationUnit so that all
820/// definitions are actually read.
821static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
822 RecordCompleteMap &RecordsComplete,
823 RecordCompleteMap &MNCComplete) {
824 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
825 if (Cache != RecordsComplete.end())
826 return Cache->second;
827 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
828 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
829 E = RD->friend_end();
830 I != E && Complete; ++I) {
831 // Check if friend classes and methods are complete.
832 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
833 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
834 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
835 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
836 else
837 Complete = false;
838 } else {
839 // Friend functions are available through the NamedDecl of FriendDecl.
840 if (const FunctionDecl *FD =
841 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
842 Complete = FD->isDefined();
843 else
844 // This is a template friend, give up.
845 Complete = false;
846 }
847 }
848 RecordsComplete[RD] = Complete;
849 return Complete;
850}
851
Nico Weber72889432014-09-06 01:25:55 +0000852void Sema::emitAndClearUnusedLocalTypedefWarnings() {
853 if (ExternalSource)
854 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
855 UnusedLocalTypedefNameCandidates);
856 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
857 if (TD->isReferenced())
858 continue;
859 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
860 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
861 }
862 UnusedLocalTypedefNameCandidates.clear();
863}
864
Richard Smithe03a6542017-07-05 01:42:07 +0000865/// This is called before the very first declaration in the translation unit
866/// is parsed. Note that the ASTContext may have already injected some
867/// declarations.
868void Sema::ActOnStartOfTranslationUnit() {
Richard Smithac9f7fb2018-09-15 01:59:39 +0000869 if (getLangOpts().ModulesTS &&
870 (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface ||
871 getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
Richard Smithd652bdd2019-04-14 08:06:59 +0000872 // We start in an implied global module fragment.
Richard Smithdd8b5332017-09-04 05:37:53 +0000873 SourceLocation StartOfTU =
874 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Richard Smithd652bdd2019-04-14 08:06:59 +0000875 ActOnGlobalModuleFragmentDecl(StartOfTU);
876 ModuleScopes.back().ImplicitGlobalModuleFragment = true;
Richard Smithe03a6542017-07-05 01:42:07 +0000877 }
878}
879
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000880void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
881 // No explicit actions are required at the end of the global module fragment.
882 if (Kind == TUFragmentKind::Global)
Douglas Gregorc459b512012-08-17 22:17:36 +0000883 return;
884
Reid Kleckner24bd88c2018-03-26 18:22:47 +0000885 // Transfer late parsed template instantiations over to the pending template
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000886 // instantiation list. During normal compilation, the late template parser
Reid Kleckner24bd88c2018-03-26 18:22:47 +0000887 // will be installed and instantiating these templates will succeed.
888 //
889 // If we are building a TU prefix for serialization, it is also safe to
890 // transfer these over, even though they are not parsed. The end of the TU
891 // should be outside of any eager template instantiation scope, so when this
892 // AST is deserialized, these templates will not be parsed until the end of
893 // the combined TU.
894 PendingInstantiations.insert(PendingInstantiations.end(),
895 LateParsedInstantiations.begin(),
896 LateParsedInstantiations.end());
897 LateParsedInstantiations.clear();
898
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000899 // If DefinedUsedVTables ends up marking any virtual member functions it
900 // might lead to more pending template instantiations, which we then need
901 // to instantiate.
902 DefineUsedVTables();
903
904 // C++: Perform implicit template instantiations.
905 //
906 // FIXME: When we perform these implicit instantiations, we do not
907 // carefully keep track of the point of instantiation (C++ [temp.point]).
908 // This means that name lookup that occurs within the template
909 // instantiation will always happen at the end of the translation unit,
910 // so it will find some names that are not required to be found. This is
911 // valid, but we could do better by diagnosing if an instantiation uses a
912 // name that was not visible at its first point of instantiation.
913 if (ExternalSource) {
914 // Load pending instantiations from the external source.
915 SmallVector<PendingImplicitInstantiation, 4> Pending;
916 ExternalSource->ReadPendingInstantiations(Pending);
917 for (auto PII : Pending)
918 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
919 Func->setInstantiationIsPending(true);
920 PendingInstantiations.insert(PendingInstantiations.begin(),
921 Pending.begin(), Pending.end());
922 }
923
924 {
925 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations",
926 StringRef(""));
927 PerformPendingInstantiations();
928 }
929
Alexey Bataev729e2422019-08-23 16:11:14 +0000930 // Finalize analysis of OpenMP-specific constructs.
931 if (LangOpts.OpenMP)
932 finalizeOpenMPDelayedAnalysis();
933
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000934 assert(LateParsedInstantiations.empty() &&
935 "end of TU template instantiation should not create more "
936 "late-parsed templates");
937}
938
939/// ActOnEndOfTranslationUnit - This is called at the very end of the
940/// translation unit when EOF is reached and all but the top-level scope is
941/// popped.
942void Sema::ActOnEndOfTranslationUnit() {
943 assert(DelayedDiagnostics.getCurrentPool() == nullptr
944 && "reached end of translation unit with a pool attached?");
945
946 // If code completion is enabled, don't perform any end-of-translation-unit
947 // work.
948 if (PP.isCodeCompletionEnabled())
949 return;
950
Richard Smith0e5d7b82013-07-25 23:08:39 +0000951 // Complete translation units and modules define vtables and perform implicit
952 // instantiations. PCH files do not.
953 if (TUKind != TU_Prefix) {
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +0000954 DiagnoseUseOfUnimplementedSelectors();
955
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000956 ActOnEndOfTranslationUnitFragment(
957 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
958 Module::PrivateModuleFragment
959 ? TUFragmentKind::Private
960 : TUFragmentKind::Normal);
Reid Kleckner24bd88c2018-03-26 18:22:47 +0000961
Reid Kleckner89bd8d62014-10-22 17:50:19 +0000962 if (LateTemplateParserCleanup)
963 LateTemplateParserCleanup(OpaqueParser);
964
Alp Tokerae3a9442013-10-18 05:54:19 +0000965 CheckDelayedMemberExceptionSpecs();
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000966 } else {
967 // If we are building a TU prefix for serialization, it is safe to transfer
968 // these over, even though they are not parsed. The end of the TU should be
969 // outside of any eager template instantiation scope, so when this AST is
970 // deserialized, these templates will not be parsed until the end of the
971 // combined TU.
972 PendingInstantiations.insert(PendingInstantiations.end(),
973 LateParsedInstantiations.begin(),
974 LateParsedInstantiations.end());
975 LateParsedInstantiations.clear();
Nick Lewyckyef4f4562010-11-25 00:35:20 +0000976 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +0000977
Alex Lorenz45b40142017-07-28 14:41:21 +0000978 DiagnoseUnterminatedPragmaPack();
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000979 DiagnoseUnterminatedPragmaAttribute();
980
Alp Tokerae3a9442013-10-18 05:54:19 +0000981 // All delayed member exception specs should be checked or we end up accepting
982 // incompatible declarations.
Richard Smith5159bbad2018-09-05 22:30:37 +0000983 assert(DelayedOverridingExceptionSpecChecks.empty());
984 assert(DelayedEquivalentExceptionSpecChecks.empty());
Alp Tokerae3a9442013-10-18 05:54:19 +0000985
Hans Wennborg99000c22015-08-15 01:18:16 +0000986 // All dllexport classes should have been processed already.
987 assert(DelayedDllExportClasses.empty());
Hans Wennborgc5877e92019-08-01 08:01:09 +0000988 assert(DelayedDllExportMemberFunctions.empty());
Hans Wennborg99000c22015-08-15 01:18:16 +0000989
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000990 // Remove file scoped decls that turned out to be used.
Daniel Jasper9ba6f9b2013-04-30 06:43:16 +0000991 UnusedFileScopedDecls.erase(
Craig Topperc3ec1492014-05-26 06:22:03 +0000992 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
Daniel Jasper9ba6f9b2013-04-30 06:43:16 +0000993 UnusedFileScopedDecls.end(),
Richard Smith2c27df72017-03-23 23:17:58 +0000994 [this](const DeclaratorDecl *DD) {
995 return ShouldRemoveFromUnused(this, DD);
996 }),
Daniel Jasper9ba6f9b2013-04-30 06:43:16 +0000997 UnusedFileScopedDecls.end());
Douglas Gregorfb8b27d2010-04-09 17:41:13 +0000998
Douglas Gregor69f74f82011-08-25 22:30:56 +0000999 if (TUKind == TU_Prefix) {
1000 // Translation unit prefixes don't need any of the checking below.
Vassil Vassilev45bf62f2016-10-17 10:15:25 +00001001 if (!PP.isIncrementalProcessingEnabled())
1002 TUScope = nullptr;
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00001003 return;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001004 }
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00001005
Chris Lattner0c797362009-09-08 18:19:27 +00001006 // Check for #pragma weak identifiers that were never declared
Douglas Gregor1c4bfe52011-07-28 18:09:57 +00001007 LoadExternalWeakUndeclaredIdentifiers();
Chandler Carruthf85d9822015-03-26 08:32:49 +00001008 for (auto WeakID : WeakUndeclaredIdentifiers) {
1009 if (WeakID.second.getUsed())
1010 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001011
Alexander Musmanfbbc0b82015-09-18 07:40:22 +00001012 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
1013 LookupOrdinaryName);
1014 if (PrevDecl != nullptr &&
1015 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1016 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
1017 << "'weak'" << ExpectedVariableOrFunction;
1018 else
1019 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
1020 << WeakID.first;
Ryan Flynn7d470f32009-07-30 03:15:39 +00001021 }
1022
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00001023 if (LangOpts.CPlusPlus11 &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001024 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00001025 CheckDelegatingCtorCycles();
1026
Richard Smithd6a04d72016-03-25 21:49:43 +00001027 if (!Diags.hasErrorOccurred()) {
1028 if (ExternalSource)
1029 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1030 checkUndefinedButUsed(*this);
1031 }
1032
Richard Smithd652bdd2019-04-14 08:06:59 +00001033 // A global-module-fragment is only permitted within a module unit.
1034 bool DiagnosedMissingModuleDeclaration = false;
1035 if (!ModuleScopes.empty() &&
1036 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
1037 !ModuleScopes.back().ImplicitGlobalModuleFragment) {
1038 Diag(ModuleScopes.back().BeginLoc,
1039 diag::err_module_declaration_missing_after_global_module_introducer);
1040 DiagnosedMissingModuleDeclaration = true;
1041 }
1042
Douglas Gregor69f74f82011-08-25 22:30:56 +00001043 if (TUKind == TU_Module) {
Richard Smith18057cb2017-10-11 00:36:56 +00001044 // If we are building a module interface unit, we need to have seen the
1045 // module declaration by now.
1046 if (getLangOpts().getCompilingModule() ==
1047 LangOptions::CMK_ModuleInterface &&
Richard Smithd6509cf2018-09-15 01:21:15 +00001048 (ModuleScopes.empty() ||
Richard Smitha5bbbfe2019-04-18 21:12:54 +00001049 !ModuleScopes.back().Module->isModulePurview()) &&
Richard Smithd652bdd2019-04-14 08:06:59 +00001050 !DiagnosedMissingModuleDeclaration) {
Richard Smith18057cb2017-10-11 00:36:56 +00001051 // FIXME: Make a better guess as to where to put the module declaration.
1052 Diag(getSourceManager().getLocForStartOfFile(
1053 getSourceManager().getMainFileID()),
1054 diag::err_module_declaration_missing);
1055 }
1056
Douglas Gregor2b82c2a2011-12-02 01:47:07 +00001057 // If we are building a module, resolve all of the exported declarations
1058 // now.
1059 if (Module *CurrentModule = PP.getCurrentModule()) {
1060 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001061
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001062 SmallVector<Module *, 2> Stack;
Douglas Gregor2b82c2a2011-12-02 01:47:07 +00001063 Stack.push_back(CurrentModule);
1064 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001065 Module *Mod = Stack.pop_back_val();
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001066
Douglas Gregorfb912652013-03-20 21:10:35 +00001067 // Resolve the exported declarations and conflicts.
Douglas Gregor2b82c2a2011-12-02 01:47:07 +00001068 // FIXME: Actually complain, once we figure out how to teach the
Douglas Gregorfb912652013-03-20 21:10:35 +00001069 // diagnostic client to deal with complaints in the module map at this
Douglas Gregor2b82c2a2011-12-02 01:47:07 +00001070 // point.
1071 ModMap.resolveExports(Mod, /*Complain=*/false);
Daniel Jasperba7f2f72013-09-24 09:14:14 +00001072 ModMap.resolveUses(Mod, /*Complain=*/false);
Douglas Gregorfb912652013-03-20 21:10:35 +00001073 ModMap.resolveConflicts(Mod, /*Complain=*/false);
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001074
Douglas Gregor2b82c2a2011-12-02 01:47:07 +00001075 // Queue the submodules, so their exports will also be resolved.
Benjamin Kramerf367dd92015-06-12 15:31:50 +00001076 Stack.append(Mod->submodule_begin(), Mod->submodule_end());
Douglas Gregor2b82c2a2011-12-02 01:47:07 +00001077 }
1078 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001079
Nico Weber72889432014-09-06 01:25:55 +00001080 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1081 // modules when they are built, not every time they are used.
1082 emitAndClearUnusedLocalTypedefWarnings();
Douglas Gregor69f74f82011-08-25 22:30:56 +00001083 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001084
Douglas Gregor0760fa12009-03-10 23:43:53 +00001085 // C99 6.9.2p2:
1086 // A declaration of an identifier for an object that has file
1087 // scope without an initializer, and without a storage-class
1088 // specifier or with the storage-class specifier static,
1089 // constitutes a tentative definition. If a translation unit
1090 // contains one or more tentative definitions for an identifier,
1091 // and the translation unit contains no external definition for
1092 // that identifier, then the behavior is exactly as if the
1093 // translation unit contains a file scope declaration of that
1094 // identifier, with the composite type as of the end of the
1095 // translation unit, with an initializer equal to 0.
Sebastian Redl35351a92010-01-31 22:27:38 +00001096 llvm::SmallSet<VarDecl *, 32> Seen;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001097 for (TentativeDefinitionsType::iterator
Douglas Gregoreb08bd42011-07-27 20:58:46 +00001098 T = TentativeDefinitions.begin(ExternalSource),
1099 TEnd = TentativeDefinitions.end();
Richard Smithf5262c62018-06-28 01:57:04 +00001100 T != TEnd; ++T) {
Douglas Gregoreb08bd42011-07-27 20:58:46 +00001101 VarDecl *VD = (*T)->getActingDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001102
Sebastian Redl35351a92010-01-31 22:27:38 +00001103 // If the tentative definition was completed, getActingDefinition() returns
1104 // null. If we've already seen this variable before, insert()'s second
1105 // return value is false.
David Blaikie82e95a32014-11-19 07:49:47 +00001106 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
Douglas Gregorbeecd582009-04-21 17:11:58 +00001107 continue;
1108
Mike Stump11289f42009-09-09 15:08:12 +00001109 if (const IncompleteArrayType *ArrayT
Douglas Gregorbeecd582009-04-21 17:11:58 +00001110 = Context.getAsIncompleteArrayType(VD->getType())) {
Chris Lattner0c797362009-09-08 18:19:27 +00001111 // Set the length of the array to 1 (C99 6.9.2p5).
1112 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1113 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCallc5b82252009-10-16 00:14:28 +00001114 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
1115 One, ArrayType::Normal, 0);
Chris Lattner0c797362009-09-08 18:19:27 +00001116 VD->setType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001117 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorbeecd582009-04-21 17:11:58 +00001118 diag::err_tentative_def_incomplete_type))
1119 VD->setInvalidDecl();
1120
Richard Smith7873de02016-08-11 22:25:46 +00001121 // No initialization is performed for a tentative definition.
Richard Smith3997b1b2016-08-12 01:55:21 +00001122 CheckCompleteVariableDeclaration(VD);
Eli Friedman7d14b3c2012-10-23 20:19:32 +00001123
Douglas Gregorbeecd582009-04-21 17:11:58 +00001124 // Notify the consumer that we've completed a tentative definition.
1125 if (!VD->isInvalidDecl())
1126 Consumer.CompleteTentativeDefinition(VD);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001127 }
Argyrios Kyrtzidis77fd99f2011-01-31 07:04:37 +00001128
1129 // If there were errors, disable 'unused' warnings since they will mostly be
Richard Smithf5262c62018-06-28 01:57:04 +00001130 // noise. Don't warn for a use from a module: either we should warn on all
1131 // file-scope declarations in modules or not at all, but whether the
1132 // declaration is used is immaterial.
1133 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
Argyrios Kyrtzidis77fd99f2011-01-31 07:04:37 +00001134 // Output warning for unused file scoped decls.
Douglas Gregora94a1542011-07-27 21:45:57 +00001135 for (UnusedFileScopedDeclsType::iterator
1136 I = UnusedFileScopedDecls.begin(ExternalSource),
Argyrios Kyrtzidis77fd99f2011-01-31 07:04:37 +00001137 E = UnusedFileScopedDecls.end(); I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00001138 if (ShouldRemoveFromUnused(this, *I))
1139 continue;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001140
Argyrios Kyrtzidis77fd99f2011-01-31 07:04:37 +00001141 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1142 const FunctionDecl *DiagD;
1143 if (!FD->hasBody(DiagD))
1144 DiagD = FD;
Argyrios Kyrtzidise0283142011-03-03 17:47:42 +00001145 if (DiagD->isDeleted())
1146 continue; // Deleted functions are supposed to be unused.
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00001147 if (DiagD->isReferenced()) {
1148 if (isa<CXXMethodDecl>(DiagD))
1149 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1150 << DiagD->getDeclName();
Fariborz Jahanian91fc39e2012-06-27 19:43:29 +00001151 else {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001152 if (FD->getStorageClass() == SC_Static &&
Fariborz Jahanian91fc39e2012-06-27 19:43:29 +00001153 !FD->isInlineSpecified() &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00001154 !SourceMgr.isInMainFile(
Fariborz Jahanian91fc39e2012-06-27 19:43:29 +00001155 SourceMgr.getExpansionLoc(FD->getLocation())))
Nico Weber63816332014-07-26 23:20:08 +00001156 Diag(DiagD->getLocation(),
1157 diag::warn_unneeded_static_internal_decl)
1158 << DiagD->getDeclName();
Fariborz Jahanian91fc39e2012-06-27 19:43:29 +00001159 else
1160 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1161 << /*function*/0 << DiagD->getDeclName();
1162 }
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00001163 } else {
Vassil Vassilev64e1e1e2017-05-09 11:25:41 +00001164 if (FD->getDescribedFunctionTemplate())
1165 Diag(DiagD->getLocation(), diag::warn_unused_template)
1166 << /*function*/0 << DiagD->getDeclName();
1167 else
1168 Diag(DiagD->getLocation(),
1169 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
1170 : diag::warn_unused_function)
1171 << DiagD->getDeclName();
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00001172 }
Argyrios Kyrtzidis77fd99f2011-01-31 07:04:37 +00001173 } else {
1174 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1175 if (!DiagD)
1176 DiagD = cast<VarDecl>(*I);
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00001177 if (DiagD->isReferenced()) {
1178 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1179 << /*variable*/1 << DiagD->getDeclName();
Daniel Jasperc531dae2013-09-11 10:37:35 +00001180 } else if (DiagD->getType().isConstQualified()) {
Erik Verbruggen89aa7eb2016-10-28 08:28:42 +00001181 const SourceManager &SM = SourceMgr;
1182 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1183 !PP.getLangOpts().IsHeaderFile)
1184 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1185 << DiagD->getDeclName();
Eli Friedman5ef21752013-09-10 03:05:56 +00001186 } else {
Vassil Vassilev64e1e1e2017-05-09 11:25:41 +00001187 if (DiagD->getDescribedVarTemplate())
1188 Diag(DiagD->getLocation(), diag::warn_unused_template)
1189 << /*variable*/1 << DiagD->getDeclName();
1190 else
1191 Diag(DiagD->getLocation(), diag::warn_unused_variable)
Matt Beaumont-Gaye1368a12013-04-10 00:47:10 +00001192 << DiagD->getDeclName();
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00001193 }
Argyrios Kyrtzidis77fd99f2011-01-31 07:04:37 +00001194 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001195 }
John McCall83779672011-02-19 02:53:41 +00001196
Nico Weber72889432014-09-06 01:25:55 +00001197 emitAndClearUnusedLocalTypedefWarnings();
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001198 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001199
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001200 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
Richard Smithf5262c62018-06-28 01:57:04 +00001201 // FIXME: Load additional unused private field candidates from the external
1202 // source.
Daniel Jasper0baec5492012-06-06 08:32:04 +00001203 RecordCompleteMap RecordsComplete;
1204 RecordCompleteMap MNCComplete;
1205 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1206 E = UnusedPrivateFields.end(); I != E; ++I) {
1207 const NamedDecl *D = *I;
1208 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1209 if (RD && !RD->isUnion() &&
1210 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1211 Diag(D->getLocation(), diag::warn_unused_private_field)
1212 << D->getDeclName();
1213 }
1214 }
1215 }
1216
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00001217 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1218 if (ExternalSource)
1219 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1220 for (const auto &DeletedFieldInfo : DeleteExprs) {
1221 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1222 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1223 DeleteExprLoc.second);
1224 }
1225 }
1226 }
1227
Richard Smithb2bc2e62011-02-21 20:05:19 +00001228 // Check we've noticed that we're no longer parsing the initializer for every
1229 // variable. If we miss cases, then at best we have a performance issue and
1230 // at worst a rejects-valid bug.
1231 assert(ParsingInitForAutoVars.empty() &&
1232 "Didn't unmark var as having its initializer parsed");
1233
Vassil Vassilev45bf62f2016-10-17 10:15:25 +00001234 if (!PP.isIncrementalProcessingEnabled())
1235 TUScope = nullptr;
Chris Lattnerf4404402008-08-23 03:19:52 +00001236}
1237
1238
Chris Lattnerc11438c2006-08-18 05:17:52 +00001239//===----------------------------------------------------------------------===//
Chris Lattnereaafe1222006-11-10 05:17:58 +00001240// Helper functions.
1241//===----------------------------------------------------------------------===//
1242
Anders Carlssonb26ab812009-08-08 17:45:02 +00001243DeclContext *Sema::getFunctionLevelDeclContext() {
John McCallb8788012009-12-19 10:53:49 +00001244 DeclContext *DC = CurContext;
Mike Stump11289f42009-09-09 15:08:12 +00001245
Eli Friedman73a04092012-01-07 04:59:52 +00001246 while (true) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001247 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
Eli Friedman73a04092012-01-07 04:59:52 +00001248 DC = DC->getParent();
1249 } else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor1a22d282012-02-12 17:34:23 +00001250 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman73a04092012-01-07 04:59:52 +00001251 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1252 DC = DC->getParent()->getParent();
1253 }
1254 else break;
1255 }
Mike Stump11289f42009-09-09 15:08:12 +00001256
Anders Carlssonb26ab812009-08-08 17:45:02 +00001257 return DC;
1258}
1259
Chris Lattner79413952008-12-04 23:50:19 +00001260/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1261/// to the function decl for the function being parsed. If we're currently
1262/// in a 'block', this returns the containing context.
1263FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlssonb26ab812009-08-08 17:45:02 +00001264 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner79413952008-12-04 23:50:19 +00001265 return dyn_cast<FunctionDecl>(DC);
1266}
1267
Daniel Dunbar6e8aa532008-08-11 05:35:13 +00001268ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlssonb26ab812009-08-08 17:45:02 +00001269 DeclContext *DC = getFunctionLevelDeclContext();
Fariborz Jahaniandeac9ac2013-05-31 21:51:12 +00001270 while (isa<RecordDecl>(DC))
1271 DC = DC->getParent();
Steve Naroffecf2bb82008-11-17 16:28:52 +00001272 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbar6e8aa532008-08-11 05:35:13 +00001273}
Chris Lattner79413952008-12-04 23:50:19 +00001274
1275NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlssonb26ab812009-08-08 17:45:02 +00001276 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner79413952008-12-04 23:50:19 +00001277 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001278 return cast<NamedDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001279 return nullptr;
Chris Lattner79413952008-12-04 23:50:19 +00001280}
1281
Daniel Dunbard671ab92012-03-14 09:49:32 +00001282void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1283 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1284 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1285 // been made more painfully obvious by the refactor that introduced this
1286 // function, but it is possible that the incoming argument can be
Richard Smith51ec0cf2017-02-21 01:17:38 +00001287 // eliminated. If it truly cannot be (for example, there is some reentrancy
Daniel Dunbard671ab92012-03-14 09:49:32 +00001288 // issue I am not seeing yet), then there should at least be a clarifying
1289 // comment somewhere.
David Blaikie05785d12013-02-20 22:23:23 +00001290 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
Daniel Dunbard671ab92012-03-14 09:49:32 +00001291 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1292 Diags.getCurrentDiagID())) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00001293 case DiagnosticIDs::SFINAE_Report:
Richard Smith38c0e042011-10-19 00:07:01 +00001294 // We'll report the diagnostic below.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001295 break;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001296
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00001297 case DiagnosticIDs::SFINAE_SubstitutionFailure:
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001298 // Count this failure so that we know that template argument deduction
1299 // has failed.
Daniel Dunbard671ab92012-03-14 09:49:32 +00001300 ++NumSFINAEErrors;
Richard Smith9ca64612012-05-07 09:03:25 +00001301
1302 // Make a copy of this suppressed diagnostic and store it with the
1303 // template-deduction information.
1304 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1305 Diagnostic DiagInfo(&Diags);
1306 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1307 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1308 }
1309
Daniel Dunbard671ab92012-03-14 09:49:32 +00001310 Diags.setLastDiagnosticIgnored();
1311 Diags.Clear();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001312 return;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001313
Richard Smith38c0e042011-10-19 00:07:01 +00001314 case DiagnosticIDs::SFINAE_AccessControl: {
1315 // Per C++ Core Issue 1170, access control is part of SFINAE.
Daniel Dunbara25002f2012-03-13 18:30:54 +00001316 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
Richard Smith38c0e042011-10-19 00:07:01 +00001317 // make access control a part of SFINAE for the purposes of checking
1318 // type traits.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001319 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
Richard Smith38c0e042011-10-19 00:07:01 +00001320 break;
1321
Daniel Dunbard671ab92012-03-14 09:49:32 +00001322 SourceLocation Loc = Diags.getCurrentDiagLoc();
Richard Smith38c0e042011-10-19 00:07:01 +00001323
1324 // Suppress this diagnostic.
Daniel Dunbard671ab92012-03-14 09:49:32 +00001325 ++NumSFINAEErrors;
Richard Smith9ca64612012-05-07 09:03:25 +00001326
1327 // Make a copy of this suppressed diagnostic and store it with the
1328 // template-deduction information.
1329 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1330 Diagnostic DiagInfo(&Diags);
1331 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1332 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1333 }
1334
Daniel Dunbard671ab92012-03-14 09:49:32 +00001335 Diags.setLastDiagnosticIgnored();
1336 Diags.Clear();
Richard Smith38c0e042011-10-19 00:07:01 +00001337
1338 // Now the diagnostic state is clear, produce a C++98 compatibility
1339 // warning.
Daniel Dunbard671ab92012-03-14 09:49:32 +00001340 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
Richard Smith38c0e042011-10-19 00:07:01 +00001341
1342 // The last diagnostic which Sema produced was ignored. Suppress any
1343 // notes attached to it.
Daniel Dunbard671ab92012-03-14 09:49:32 +00001344 Diags.setLastDiagnosticIgnored();
Richard Smith38c0e042011-10-19 00:07:01 +00001345 return;
1346 }
1347
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00001348 case DiagnosticIDs::SFINAE_Suppress:
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001349 // Make a copy of this suppressed diagnostic and store it with the
1350 // template-deduction information;
Richard Smith9ca64612012-05-07 09:03:25 +00001351 if (*Info) {
1352 Diagnostic DiagInfo(&Diags);
Douglas Gregoredb76852011-01-27 22:31:44 +00001353 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
Richard Smith9ca64612012-05-07 09:03:25 +00001354 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1355 }
1356
1357 // Suppress this diagnostic.
Daniel Dunbard671ab92012-03-14 09:49:32 +00001358 Diags.setLastDiagnosticIgnored();
1359 Diags.Clear();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001360 return;
1361 }
1362 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001363
Joel E. Denny7bcc2102018-05-14 18:41:44 +00001364 // Copy the diagnostic printing policy over the ASTContext printing policy.
1365 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
Daniel Dunbard671ab92012-03-14 09:49:32 +00001366 Context.setPrintingPolicy(getPrintingPolicy());
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001367
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001368 // Emit the diagnostic.
Daniel Dunbard671ab92012-03-14 09:49:32 +00001369 if (!Diags.EmitCurrentDiagnostic())
Douglas Gregor33834512009-06-14 07:33:30 +00001370 return;
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregorda17bd32009-03-20 22:48:49 +00001372 // If this is not a note, and we're in a template instantiation
1373 // that is different from the last template instantiation where
1374 // we emitted an error, print a template instantiation
1375 // backtrace.
Richard Smith51ec0cf2017-02-21 01:17:38 +00001376 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1377 PrintContextStack();
Douglas Gregorda17bd32009-03-20 22:48:49 +00001378}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001379
Anders Carlssonf68079e2009-08-26 22:33:56 +00001380Sema::SemaDiagnosticBuilder
1381Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1382 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1383 PD.Emit(Builder);
Mike Stump11289f42009-09-09 15:08:12 +00001384
Anders Carlssonf68079e2009-08-26 22:33:56 +00001385 return Builder;
1386}
1387
Alexey Bataev89721332019-02-07 19:46:42 +00001388// Print notes showing how we can reach FD starting from an a priori
1389// known-callable function.
1390static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1391 auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1392 while (FnIt != S.DeviceKnownEmittedFns.end()) {
1393 DiagnosticBuilder Builder(
1394 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1395 Builder << FnIt->second.FD;
1396 Builder.setForceEmit();
1397
1398 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1399 }
1400}
1401
1402// Emit any deferred diagnostics for FD and erase them from the map in which
1403// they're stored.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001404static void emitDeferredDiags(Sema &S, FunctionDecl *FD, bool ShowCallStack) {
Alexey Bataev89721332019-02-07 19:46:42 +00001405 auto It = S.DeviceDeferredDiags.find(FD);
1406 if (It == S.DeviceDeferredDiags.end())
1407 return;
1408 bool HasWarningOrError = false;
1409 for (PartialDiagnosticAt &PDAt : It->second) {
1410 const SourceLocation &Loc = PDAt.first;
1411 const PartialDiagnostic &PD = PDAt.second;
1412 HasWarningOrError |= S.getDiagnostics().getDiagnosticLevel(
1413 PD.getDiagID(), Loc) >= DiagnosticsEngine::Warning;
1414 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1415 Builder.setForceEmit();
1416 PD.Emit(Builder);
1417 }
1418 S.DeviceDeferredDiags.erase(It);
1419
1420 // FIXME: Should this be called after every warning/error emitted in the loop
1421 // above, instead of just once per function? That would be consistent with
1422 // how we handle immediate errors, but it also seems like a bit much.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001423 if (HasWarningOrError && ShowCallStack)
Alexey Bataev89721332019-02-07 19:46:42 +00001424 emitCallStackNotes(S, FD);
1425}
1426
1427// In CUDA, there are some constructs which may appear in semantically-valid
1428// code, but trigger errors if we ever generate code for the function in which
1429// they appear. Essentially every construct you're not allowed to use on the
1430// device falls into this category, because you are allowed to use these
1431// constructs in a __host__ __device__ function, but only if that function is
1432// never codegen'ed on the device.
1433//
1434// To handle semantic checking for these constructs, we keep track of the set of
1435// functions we know will be emitted, either because we could tell a priori that
1436// they would be emitted, or because they were transitively called by a
1437// known-emitted function.
1438//
1439// We also keep a partial call graph of which not-known-emitted functions call
1440// which other not-known-emitted functions.
1441//
1442// When we see something which is illegal if the current function is emitted
1443// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1444// CheckCUDACall), we first check if the current function is known-emitted. If
1445// so, we immediately output the diagnostic.
1446//
1447// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1448// until we discover that the function is known-emitted, at which point we take
1449// it out of this map and emit the diagnostic.
1450
1451Sema::DeviceDiagBuilder::DeviceDiagBuilder(Kind K, SourceLocation Loc,
1452 unsigned DiagID, FunctionDecl *Fn,
1453 Sema &S)
1454 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1455 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1456 switch (K) {
1457 case K_Nop:
1458 break;
1459 case K_Immediate:
1460 case K_ImmediateWithCallStack:
1461 ImmediateDiag.emplace(S.Diag(Loc, DiagID));
1462 break;
1463 case K_Deferred:
1464 assert(Fn && "Must have a function to attach the deferred diag to.");
Alexey Bataev3167b302019-02-22 14:42:48 +00001465 auto &Diags = S.DeviceDeferredDiags[Fn];
1466 PartialDiagId.emplace(Diags.size());
1467 Diags.emplace_back(Loc, S.PDiag(DiagID));
Alexey Bataev89721332019-02-07 19:46:42 +00001468 break;
1469 }
1470}
1471
Alexey Bataeve69f94e2019-02-22 20:36:10 +00001472Sema::DeviceDiagBuilder::DeviceDiagBuilder(DeviceDiagBuilder &&D)
1473 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1474 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1475 PartialDiagId(D.PartialDiagId) {
1476 // Clean the previous diagnostics.
1477 D.ShowCallStack = false;
1478 D.ImmediateDiag.reset();
1479 D.PartialDiagId.reset();
1480}
1481
Alexey Bataev89721332019-02-07 19:46:42 +00001482Sema::DeviceDiagBuilder::~DeviceDiagBuilder() {
1483 if (ImmediateDiag) {
1484 // Emit our diagnostic and, if it was a warning or error, output a callstack
1485 // if Fn isn't a priori known-emitted.
1486 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1487 DiagID, Loc) >= DiagnosticsEngine::Warning;
1488 ImmediateDiag.reset(); // Emit the immediate diag.
1489 if (IsWarningOrError && ShowCallStack)
1490 emitCallStackNotes(S, Fn);
Alexey Bataev3167b302019-02-22 14:42:48 +00001491 } else {
1492 assert((!PartialDiagId || ShowCallStack) &&
1493 "Must always show call stack for deferred diags.");
Alexey Bataev89721332019-02-07 19:46:42 +00001494 }
1495}
1496
1497// Indicate that this function (and thus everything it transtively calls) will
1498// be codegen'ed, and emit any deferred diagnostics on this function and its
1499// (transitive) callees.
1500void Sema::markKnownEmitted(
1501 Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
1502 SourceLocation OrigLoc,
1503 const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted) {
1504 // Nothing to do if we already know that FD is emitted.
1505 if (IsKnownEmitted(S, OrigCallee)) {
1506 assert(!S.DeviceCallGraph.count(OrigCallee));
1507 return;
1508 }
1509
1510 // We've just discovered that OrigCallee is known-emitted. Walk our call
1511 // graph to see what else we can now discover also must be emitted.
1512
1513 struct CallInfo {
1514 FunctionDecl *Caller;
1515 FunctionDecl *Callee;
1516 SourceLocation Loc;
1517 };
1518 llvm::SmallVector<CallInfo, 4> Worklist = {{OrigCaller, OrigCallee, OrigLoc}};
1519 llvm::SmallSet<CanonicalDeclPtr<FunctionDecl>, 4> Seen;
1520 Seen.insert(OrigCallee);
1521 while (!Worklist.empty()) {
1522 CallInfo C = Worklist.pop_back_val();
1523 assert(!IsKnownEmitted(S, C.Callee) &&
1524 "Worklist should not contain known-emitted functions.");
1525 S.DeviceKnownEmittedFns[C.Callee] = {C.Caller, C.Loc};
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001526 emitDeferredDiags(S, C.Callee, C.Caller);
Alexey Bataev89721332019-02-07 19:46:42 +00001527
1528 // If this is a template instantiation, explore its callgraph as well:
1529 // Non-dependent calls are part of the template's callgraph, while dependent
1530 // calls are part of to the instantiation's call graph.
1531 if (auto *Templ = C.Callee->getPrimaryTemplate()) {
1532 FunctionDecl *TemplFD = Templ->getAsFunction();
1533 if (!Seen.count(TemplFD) && !S.DeviceKnownEmittedFns.count(TemplFD)) {
1534 Seen.insert(TemplFD);
1535 Worklist.push_back(
1536 {/* Caller = */ C.Caller, /* Callee = */ TemplFD, C.Loc});
1537 }
1538 }
1539
1540 // Add all functions called by Callee to our worklist.
1541 auto CGIt = S.DeviceCallGraph.find(C.Callee);
1542 if (CGIt == S.DeviceCallGraph.end())
1543 continue;
1544
1545 for (std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation> FDLoc :
1546 CGIt->second) {
1547 FunctionDecl *NewCallee = FDLoc.first;
1548 SourceLocation CallLoc = FDLoc.second;
1549 if (Seen.count(NewCallee) || IsKnownEmitted(S, NewCallee))
1550 continue;
1551 Seen.insert(NewCallee);
1552 Worklist.push_back(
1553 {/* Caller = */ C.Callee, /* Callee = */ NewCallee, CallLoc});
1554 }
1555
1556 // C.Callee is now known-emitted, so we no longer need to maintain its list
1557 // of callees in DeviceCallGraph.
1558 S.DeviceCallGraph.erase(CGIt);
1559 }
1560}
1561
Alexey Bataev3167b302019-02-22 14:42:48 +00001562Sema::DeviceDiagBuilder Sema::targetDiag(SourceLocation Loc, unsigned DiagID) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001563 if (LangOpts.OpenMP)
1564 return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID)
1565 : diagIfOpenMPHostCode(Loc, DiagID);
Alexey Bataev3167b302019-02-22 14:42:48 +00001566 if (getLangOpts().CUDA)
1567 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1568 : CUDADiagIfHostCode(Loc, DiagID);
Alexey Bataev5c96c1c2019-02-20 17:42:57 +00001569 return DeviceDiagBuilder(DeviceDiagBuilder::K_Immediate, Loc, DiagID,
1570 getCurFunctionDecl(), *this);
1571}
1572
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001573/// Looks through the macro-expansion chain for the given
Chandler Carruthc22845a2011-07-26 05:40:03 +00001574/// location, looking for a macro expansion with the given name.
John McCall462c0552011-03-08 07:59:04 +00001575/// If one is found, returns true and sets the location to that
Chandler Carruthc22845a2011-07-26 05:40:03 +00001576/// expansion loc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001577bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
John McCall462c0552011-03-08 07:59:04 +00001578 SourceLocation loc = locref;
1579 if (!loc.isMacroID()) return false;
1580
1581 // There's no good way right now to look at the intermediate
Chandler Carruthc22845a2011-07-26 05:40:03 +00001582 // expansions, so just jump to the expansion location.
Chandler Carruth35f53202011-07-25 16:49:02 +00001583 loc = getSourceManager().getExpansionLoc(loc);
John McCall462c0552011-03-08 07:59:04 +00001584
1585 // If that's written with the name, stop here.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001586 SmallVector<char, 16> buffer;
John McCall462c0552011-03-08 07:59:04 +00001587 if (getPreprocessor().getSpelling(loc, buffer) == name) {
1588 locref = loc;
1589 return true;
1590 }
1591 return false;
1592}
1593
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001594/// Determines the active Scope associated with the given declaration
Douglas Gregor0be31a22010-07-02 17:43:08 +00001595/// context.
1596///
1597/// This routine maps a declaration context to the active Scope object that
1598/// represents that declaration context in the parser. It is typically used
1599/// from "scope-less" code (e.g., template instantiation, lazy creation of
1600/// declarations) that injects a name for name-lookup purposes and, therefore,
1601/// must update the Scope.
1602///
1603/// \returns The scope corresponding to the given declaraion context, or NULL
1604/// if no such scope is open.
1605Scope *Sema::getScopeForContext(DeclContext *Ctx) {
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001606
Douglas Gregor0be31a22010-07-02 17:43:08 +00001607 if (!Ctx)
Craig Topperc3ec1492014-05-26 06:22:03 +00001608 return nullptr;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001609
Douglas Gregor0be31a22010-07-02 17:43:08 +00001610 Ctx = Ctx->getPrimaryContext();
1611 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcaef9ab2010-07-08 23:07:34 +00001612 // Ignore scopes that cannot have declarations. This is important for
1613 // out-of-line definitions of static class members.
1614 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
Ted Kremenekc37877d2013-10-08 17:08:03 +00001615 if (DeclContext *Entity = S->getEntity())
Sebastian Redlcaef9ab2010-07-08 23:07:34 +00001616 if (Ctx == Entity->getPrimaryContext())
1617 return S;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001618 }
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001619
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 return nullptr;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001621}
Douglas Gregor9a28e842010-03-01 23:15:13 +00001622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001623/// Enter a new function scope
Douglas Gregor9a28e842010-03-01 23:15:13 +00001624void Sema::PushFunctionScope() {
Richard Smith2fdd95c2019-05-31 00:45:09 +00001625 if (FunctionScopes.empty() && CachedFunctionScope) {
1626 // Use CachedFunctionScope to avoid allocating memory when possible.
1627 CachedFunctionScope->Clear();
1628 FunctionScopes.push_back(CachedFunctionScope.release());
Reid Kleckner87a31802018-03-12 21:43:02 +00001629 } else {
1630 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
Douglas Gregor9a28e842010-03-01 23:15:13 +00001631 }
Alexey Bataev4b465392017-04-26 15:06:24 +00001632 if (LangOpts.OpenMP)
1633 pushOpenMPFunctionRegion();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001634}
1635
1636void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
Argyrios Kyrtzidisf51ec1d2010-11-19 00:19:15 +00001637 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
Douglas Gregor9a28e842010-03-01 23:15:13 +00001638 BlockScope, Block));
1639}
1640
Faisal Vali97d8c332013-11-12 01:46:33 +00001641LambdaScopeInfo *Sema::PushLambdaScope() {
Faisal Vali524ca282013-11-12 01:40:44 +00001642 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1643 FunctionScopes.push_back(LSI);
1644 return LSI;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001645}
1646
1647void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1648 if (LambdaScopeInfo *const LSI = getCurLambda()) {
1649 LSI->AutoTemplateParameterDepth = Depth;
1650 return;
Reid Kleckner87a31802018-03-12 21:43:02 +00001651 }
1652 llvm_unreachable(
Faisal Vali2b391ab2013-09-26 19:54:12 +00001653 "Remove assertion if intentionally called in a non-lambda context.");
Eli Friedman71c80552012-01-05 03:35:19 +00001654}
1655
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001656// Check that the type of the VarDecl has an accessible copy constructor and
JF Bastienea51a8c2019-04-30 00:19:43 +00001657// resolve its destructor's exception specification.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001658static void checkEscapingByref(VarDecl *VD, Sema &S) {
1659 QualType T = VD->getType();
1660 EnterExpressionEvaluationContext scope(
1661 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1662 SourceLocation Loc = VD->getLocation();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001663 Expr *VarRef =
1664 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001665 ExprResult Result = S.PerformMoveOrCopyInitialization(
1666 InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(),
1667 VarRef, /*AllowNRVO=*/true);
1668 if (!Result.isInvalid()) {
1669 Result = S.MaybeCreateExprWithCleanups(Result);
1670 Expr *Init = Result.getAs<Expr>();
1671 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
1672 }
1673
JF Bastienea51a8c2019-04-30 00:19:43 +00001674 // The destructor's exception specification is needed when IRGen generates
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001675 // block copy/destroy functions. Resolve it here.
1676 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1677 if (CXXDestructorDecl *DD = RD->getDestructor()) {
1678 auto *FPT = DD->getType()->getAs<FunctionProtoType>();
1679 S.ResolveExceptionSpec(Loc, FPT);
1680 }
1681}
1682
1683static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
1684 // Set the EscapingByref flag of __block variables captured by
1685 // escaping blocks.
1686 for (const BlockDecl *BD : FSI.Blocks) {
Akira Hatanaka6f6156b2019-07-26 00:02:17 +00001687 if (BD->doesNotEscape())
1688 continue;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001689 for (const BlockDecl::Capture &BC : BD->captures()) {
1690 VarDecl *VD = BC.getVariable();
Akira Hatanaka6f6156b2019-07-26 00:02:17 +00001691 if (VD->hasAttr<BlocksAttr>())
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001692 VD->setEscapingByref();
1693 }
1694 }
1695
1696 for (VarDecl *VD : FSI.ByrefBlockVars) {
1697 // __block variables might require us to capture a copy-initializer.
1698 if (!VD->isEscapingByref())
1699 continue;
1700 // It's currently invalid to ever have a __block variable with an
1701 // array type; should we diagnose that here?
1702 // Regardless, we don't want to ignore array nesting when
1703 // constructing this copy.
1704 if (VD->getType()->isStructureOrClassType())
1705 checkEscapingByref(VD, S);
1706 }
1707}
1708
Richard Smith2fdd95c2019-05-31 00:45:09 +00001709/// Pop a function (or block or lambda or captured region) scope from the stack.
1710///
1711/// \param WP The warning policy to use for CFG-based warnings, or null if such
1712/// warnings should not be produced.
1713/// \param D The declaration corresponding to this function scope, if producing
1714/// CFG-based warnings.
1715/// \param BlockType The type of the block expression, if D is a BlockDecl.
1716Sema::PoppedFunctionScopePtr
1717Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1718 const Decl *D, QualType BlockType) {
Reid Kleckner8d485b82018-03-08 01:12:22 +00001719 assert(!FunctionScopes.empty() && "mismatched push/pop!");
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001720
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001721 markEscapingByrefs(*FunctionScopes.back(), *this);
1722
Richard Smith2fdd95c2019-05-31 00:45:09 +00001723 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
1724 PoppedFunctionScopeDeleter(this));
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001725
Alexey Bataev4b465392017-04-26 15:06:24 +00001726 if (LangOpts.OpenMP)
Richard Smith2fdd95c2019-05-31 00:45:09 +00001727 popOpenMPFunctionRegion(Scope.get());
Alexey Bataev4b465392017-04-26 15:06:24 +00001728
Ted Kremenek1767a272011-02-23 01:51:48 +00001729 // Issue any analysis-based warnings.
1730 if (WP && D)
Richard Smith2fdd95c2019-05-31 00:45:09 +00001731 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
Aaron Ballman130a3b02014-05-15 20:58:55 +00001732 else
1733 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1734 Diag(PUD.Loc, PUD.PD);
Ted Kremenek1767a272011-02-23 01:51:48 +00001735
Richard Smith2fdd95c2019-05-31 00:45:09 +00001736 return Scope;
1737}
1738
1739void Sema::PoppedFunctionScopeDeleter::
1740operator()(sema::FunctionScopeInfo *Scope) const {
1741 // Stash the function scope for later reuse if it's for a normal function.
1742 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
1743 Self->CachedFunctionScope.reset(Scope);
1744 else
John McCallaab3e412010-08-25 08:40:02 +00001745 delete Scope;
Douglas Gregor9a28e842010-03-01 23:15:13 +00001746}
1747
Richard Smith6eb9b9e2018-02-03 00:44:57 +00001748void Sema::PushCompoundScope(bool IsStmtExpr) {
1749 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001750}
1751
1752void Sema::PopCompoundScope() {
1753 FunctionScopeInfo *CurFunction = getCurFunction();
1754 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1755
1756 CurFunction->CompoundScopes.pop_back();
1757}
1758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001759/// Determine whether any errors occurred within this function/method/
Douglas Gregor9a28e842010-03-01 23:15:13 +00001760/// block.
John McCall31168b02011-06-15 23:02:42 +00001761bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1762 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001763}
1764
Reid Kleckner87a31802018-03-12 21:43:02 +00001765void Sema::setFunctionHasBranchIntoScope() {
1766 if (!FunctionScopes.empty())
1767 FunctionScopes.back()->setHasBranchIntoScope();
1768}
1769
1770void Sema::setFunctionHasBranchProtectedScope() {
1771 if (!FunctionScopes.empty())
1772 FunctionScopes.back()->setHasBranchProtectedScope();
1773}
1774
1775void Sema::setFunctionHasIndirectGoto() {
1776 if (!FunctionScopes.empty())
1777 FunctionScopes.back()->setHasIndirectGoto();
1778}
1779
Douglas Gregor9a28e842010-03-01 23:15:13 +00001780BlockScopeInfo *Sema::getCurBlock() {
1781 if (FunctionScopes.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001782 return nullptr;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001783
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +00001784 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1785 if (CurBSI && CurBSI->TheDecl &&
1786 !CurBSI->TheDecl->Encloses(CurContext)) {
1787 // We have switched contexts due to template instantiation.
Richard Smith696e3122017-02-23 01:43:54 +00001788 assert(!CodeSynthesisContexts.empty());
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +00001789 return nullptr;
1790 }
1791
1792 return CurBSI;
Douglas Gregor9a28e842010-03-01 23:15:13 +00001793}
John McCall75b960e2010-06-01 09:23:16 +00001794
Reid Kleckner04f9bca2018-03-07 22:48:35 +00001795FunctionScopeInfo *Sema::getEnclosingFunction() const {
1796 if (FunctionScopes.empty())
1797 return nullptr;
1798
1799 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
1800 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1801 continue;
1802 return FunctionScopes[e];
1803 }
1804 return nullptr;
1805}
1806
Akira Hatanaka7cbbb882017-03-01 06:11:25 +00001807LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
Eli Friedman4817cf72012-01-06 03:05:34 +00001808 if (FunctionScopes.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001809 return nullptr;
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001810
Alexey Bataev31939e32016-11-11 12:36:20 +00001811 auto I = FunctionScopes.rbegin();
Akira Hatanaka7cbbb882017-03-01 06:11:25 +00001812 if (IgnoreNonLambdaCapturingScope) {
Alexey Bataev31939e32016-11-11 12:36:20 +00001813 auto E = FunctionScopes.rend();
Akira Hatanaka7cbbb882017-03-01 06:11:25 +00001814 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
Alexey Bataev31939e32016-11-11 12:36:20 +00001815 ++I;
1816 if (I == E)
1817 return nullptr;
1818 }
1819 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +00001820 if (CurLSI && CurLSI->Lambda &&
1821 !CurLSI->Lambda->Encloses(CurContext)) {
1822 // We have switched contexts due to template instantiation.
Richard Smith696e3122017-02-23 01:43:54 +00001823 assert(!CodeSynthesisContexts.empty());
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +00001824 return nullptr;
1825 }
1826
1827 return CurLSI;
Eli Friedman4817cf72012-01-06 03:05:34 +00001828}
Fangrui Song6907ce22018-07-30 19:24:48 +00001829// We have a generic lambda if we parsed auto parameters, or we have
Faisal Vali2b391ab2013-09-26 19:54:12 +00001830// an associated template parameter list.
1831LambdaScopeInfo *Sema::getCurGenericLambda() {
1832 if (LambdaScopeInfo *LSI = getCurLambda()) {
Hamza Sood8205a812019-05-04 10:49:46 +00001833 return (LSI->TemplateParams.size() ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001834 LSI->GLTemplateParameterList) ? LSI : nullptr;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001835 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001836 return nullptr;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001837}
1838
Eli Friedman4817cf72012-01-06 03:05:34 +00001839
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00001840void Sema::ActOnComment(SourceRange Comment) {
Ted Kremenekb47e6bc2012-09-13 06:41:18 +00001841 if (!LangOpts.RetainCommentsFromSystemHeaders &&
1842 SourceMgr.isInSystemHeader(Comment.getBegin()))
1843 return;
David L. Jones13d5a872018-03-02 00:07:45 +00001844 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
Dmitri Gribenko052f60d2012-06-22 16:02:55 +00001845 if (RC.isAlmostTrailingComment()) {
1846 SourceRange MagicMarkerRange(Comment.getBegin(),
1847 Comment.getBegin().getLocWithOffset(3));
1848 StringRef MagicMarkerText;
1849 switch (RC.getKind()) {
Abramo Bagnarae06a8882012-07-04 07:30:26 +00001850 case RawComment::RCK_OrdinaryBCPL:
Dmitri Gribenko052f60d2012-06-22 16:02:55 +00001851 MagicMarkerText = "///<";
1852 break;
Abramo Bagnarae06a8882012-07-04 07:30:26 +00001853 case RawComment::RCK_OrdinaryC:
Dmitri Gribenko052f60d2012-06-22 16:02:55 +00001854 MagicMarkerText = "/**<";
1855 break;
1856 default:
1857 llvm_unreachable("if this is an almost Doxygen comment, "
1858 "it should be ordinary");
1859 }
1860 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1861 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1862 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00001863 Context.addComment(RC);
1864}
1865
John McCall75b960e2010-06-01 09:23:16 +00001866// Pin this vtable to this file.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00001867ExternalSemaSource::~ExternalSemaSource() {}
John McCallfaf5fb42010-08-26 23:41:50 +00001868
Douglas Gregore1716012012-01-25 00:49:42 +00001869void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
Manman Rena0f31a02016-04-29 19:04:05 +00001870void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
Sebastian Redlc1ca90a2010-09-28 20:23:00 +00001871
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001872void ExternalSemaSource::ReadKnownNamespaces(
Michael Gottesmanbf0fd392013-01-20 01:04:14 +00001873 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001874}
1875
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00001876void ExternalSemaSource::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00001877 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
Nick Lewycky8334af82013-01-26 00:35:08 +00001878
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00001879void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1880 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1881
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001882/// Figure out if an expression could be turned into a call.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001883///
1884/// Use this when trying to recover from an error where the programmer may have
1885/// written just the name of a function instead of actually calling it.
1886///
1887/// \param E - The expression to examine.
1888/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1889/// with no arguments, this parameter is set to the type returned by such a
1890/// call; otherwise, it is set to an empty QualType.
John McCall50a2c2c2011-10-11 23:14:30 +00001891/// \param OverloadSet - If the expression is an overloaded function
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001892/// name, this parameter is populated with the decls of the various overloads.
David Blaikiee5323aa2013-06-21 23:54:45 +00001893bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1894 UnresolvedSetImpl &OverloadSet) {
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001895 ZeroArgCallReturnTy = QualType();
John McCall50a2c2c2011-10-11 23:14:30 +00001896 OverloadSet.clear();
1897
Craig Topperc3ec1492014-05-26 06:22:03 +00001898 const OverloadExpr *Overloads = nullptr;
David Blaikiee5323aa2013-06-21 23:54:45 +00001899 bool IsMemExpr = false;
John McCall50a2c2c2011-10-11 23:14:30 +00001900 if (E.getType() == Context.OverloadTy) {
1901 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
John McCall50a2c2c2011-10-11 23:14:30 +00001902
David Blaikie6df859d82013-06-04 00:28:46 +00001903 // Ignore overloads that are pointer-to-member constants.
1904 if (FR.HasFormOfMemberPointer)
1905 return false;
1906
1907 Overloads = FR.Expression;
1908 } else if (E.getType() == Context.BoundMemberTy) {
1909 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
David Blaikiee5323aa2013-06-21 23:54:45 +00001910 IsMemExpr = true;
David Blaikie6df859d82013-06-04 00:28:46 +00001911 }
David Blaikiee5323aa2013-06-21 23:54:45 +00001912
1913 bool Ambiguous = false;
Erich Keane3efe0022018-07-20 14:13:28 +00001914 bool IsMV = false;
David Blaikiee5323aa2013-06-21 23:54:45 +00001915
David Blaikie6df859d82013-06-04 00:28:46 +00001916 if (Overloads) {
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001917 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1918 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
John McCall50a2c2c2011-10-11 23:14:30 +00001919 OverloadSet.addDecl(*it);
1920
David Blaikiee5323aa2013-06-21 23:54:45 +00001921 // Check whether the function is a non-template, non-member which takes no
John McCall50a2c2c2011-10-11 23:14:30 +00001922 // arguments.
David Blaikiee5323aa2013-06-21 23:54:45 +00001923 if (IsMemExpr)
1924 continue;
John McCall50a2c2c2011-10-11 23:14:30 +00001925 if (const FunctionDecl *OverloadDecl
1926 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
David Blaikie6df859d82013-06-04 00:28:46 +00001927 if (OverloadDecl->getMinRequiredArguments() == 0) {
Erich Keane3efe0022018-07-20 14:13:28 +00001928 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
1929 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
1930 OverloadDecl->isCPUSpecificMultiVersion()))) {
David Blaikie6df859d82013-06-04 00:28:46 +00001931 ZeroArgCallReturnTy = QualType();
1932 Ambiguous = true;
Erich Keane3efe0022018-07-20 14:13:28 +00001933 } else {
Alp Toker314cc812014-01-25 16:55:45 +00001934 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
Erich Keane3efe0022018-07-20 14:13:28 +00001935 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
1936 OverloadDecl->isCPUSpecificMultiVersion();
1937 }
David Blaikie6df859d82013-06-04 00:28:46 +00001938 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001939 }
1940 }
John McCall50a2c2c2011-10-11 23:14:30 +00001941
David Blaikiee5323aa2013-06-21 23:54:45 +00001942 // If it's not a member, use better machinery to try to resolve the call
1943 if (!IsMemExpr)
1944 return !ZeroArgCallReturnTy.isNull();
1945 }
1946
1947 // Attempt to call the member with no arguments - this will correctly handle
1948 // member templates with defaults/deduction of template arguments, overloads
1949 // with default arguments, etc.
Eli Friedman544c9562013-07-08 23:35:04 +00001950 if (IsMemExpr && !E.isTypeDependent()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00001951 Sema::TentativeAnalysisScope Trap(*this);
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1953 None, SourceLocation());
David Blaikiee5323aa2013-06-21 23:54:45 +00001954 if (R.isUsable()) {
1955 ZeroArgCallReturnTy = R.get()->getType();
1956 return true;
1957 }
1958 return false;
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001959 }
1960
John McCall50a2c2c2011-10-11 23:14:30 +00001961 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001962 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1963 if (Fun->getMinRequiredArguments() == 0)
Alp Toker314cc812014-01-25 16:55:45 +00001964 ZeroArgCallReturnTy = Fun->getReturnType();
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001965 return true;
1966 }
1967 }
1968
1969 // We don't have an expression that's convenient to get a FunctionDecl from,
1970 // but we can at least check if the type is "function of 0 arguments".
1971 QualType ExprTy = E.getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001972 const FunctionType *FunTy = nullptr;
Matt Beaumont-Gay330a5b42011-05-05 00:59:35 +00001973 QualType PointeeTy = ExprTy->getPointeeType();
1974 if (!PointeeTy.isNull())
1975 FunTy = PointeeTy->getAs<FunctionType>();
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001976 if (!FunTy)
1977 FunTy = ExprTy->getAs<FunctionType>();
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001978
1979 if (const FunctionProtoType *FPT =
1980 dyn_cast_or_null<FunctionProtoType>(FunTy)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001981 if (FPT->getNumParams() == 0)
Alp Toker314cc812014-01-25 16:55:45 +00001982 ZeroArgCallReturnTy = FunTy->getReturnType();
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001983 return true;
1984 }
1985 return false;
1986}
1987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001988/// Give notes for a set of overloads.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001989///
David Blaikiee5323aa2013-06-21 23:54:45 +00001990/// A companion to tryExprAsCall. In cases when the name that the programmer
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00001991/// wrote was an overloaded function, we may be able to make some guesses about
1992/// plausible overloads based on their return types; such guesses can be handed
1993/// off to this method to be emitted as notes.
1994///
1995/// \param Overloads - The overloads to note.
1996/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1997/// -fshow-overloads=best, this is the location to attach to the note about too
1998/// many candidates. Typically this will be the location of the original
1999/// ill-formed expression.
John McCall50a2c2c2011-10-11 23:14:30 +00002000static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2001 const SourceLocation FinalNoteLoc) {
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00002002 int ShownOverloads = 0;
2003 int SuppressedOverloads = 0;
2004 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2005 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2006 // FIXME: Magic number for max shown overloads stolen from
2007 // OverloadCandidateSet::NoteCandidates.
Douglas Gregor79591782012-10-23 23:11:23 +00002008 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00002009 ++SuppressedOverloads;
2010 continue;
2011 }
John McCall50a2c2c2011-10-11 23:14:30 +00002012
2013 NamedDecl *Fn = (*It)->getUnderlyingDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00002014 // Don't print overloads for non-default multiversioned functions.
2015 if (const auto *FD = Fn->getAsFunction()) {
Erich Keane3efe0022018-07-20 14:13:28 +00002016 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00002017 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2018 continue;
2019 }
Abramo Bagnaradc1646d2011-11-15 21:43:28 +00002020 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00002021 ++ShownOverloads;
2022 }
John McCall50a2c2c2011-10-11 23:14:30 +00002023
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00002024 if (SuppressedOverloads)
John McCall50a2c2c2011-10-11 23:14:30 +00002025 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2026 << SuppressedOverloads;
2027}
2028
2029static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2030 const UnresolvedSetImpl &Overloads,
2031 bool (*IsPlausibleResult)(QualType)) {
2032 if (!IsPlausibleResult)
2033 return noteOverloads(S, Overloads, Loc);
2034
2035 UnresolvedSet<2> PlausibleOverloads;
2036 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2037 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2038 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
Alp Toker314cc812014-01-25 16:55:45 +00002039 QualType OverloadResultTy = OverloadDecl->getReturnType();
John McCall50a2c2c2011-10-11 23:14:30 +00002040 if (IsPlausibleResult(OverloadResultTy))
2041 PlausibleOverloads.addDecl(It.getDecl());
2042 }
2043 noteOverloads(S, PlausibleOverloads, Loc);
2044}
2045
2046/// Determine whether the given expression can be called by just
2047/// putting parentheses after it. Notably, expressions with unary
2048/// operators can't be because the unary operator will start parsing
2049/// outside the call.
2050static bool IsCallableWithAppend(Expr *E) {
2051 E = E->IgnoreImplicit();
2052 return (!isa<CStyleCastExpr>(E) &&
2053 !isa<UnaryOperator>(E) &&
2054 !isa<BinaryOperator>(E) &&
2055 !isa<CXXOperatorCallExpr>(E));
2056}
2057
Erich Keane3efe0022018-07-20 14:13:28 +00002058static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2059 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2060 E = UO->getSubExpr();
2061
2062 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2063 if (ULE->getNumDecls() == 0)
2064 return false;
2065
2066 const NamedDecl *ND = *ULE->decls_begin();
2067 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2068 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2069 }
2070 return false;
2071}
2072
John McCall50a2c2c2011-10-11 23:14:30 +00002073bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2074 bool ForceComplain,
2075 bool (*IsPlausibleResult)(QualType)) {
2076 SourceLocation Loc = E.get()->getExprLoc();
2077 SourceRange Range = E.get()->getSourceRange();
2078
2079 QualType ZeroArgCallTy;
2080 UnresolvedSet<4> Overloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00002081 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
John McCall50a2c2c2011-10-11 23:14:30 +00002082 !ZeroArgCallTy.isNull() &&
2083 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2084 // At this point, we know E is potentially callable with 0
2085 // arguments and that it returns something of a reasonable type,
2086 // so we can emit a fixit and carry on pretending that E was
2087 // actually a CallExpr.
Craig Topper07fa1762015-11-15 02:31:46 +00002088 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
Erich Keane3efe0022018-07-20 14:13:28 +00002089 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2090 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2091 << (IsCallableWithAppend(E.get())
2092 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
2093 : FixItHint());
2094 if (!IsMV)
2095 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
John McCall50a2c2c2011-10-11 23:14:30 +00002096
2097 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2098 // while doing so.
Richard Smith255b85f2019-05-08 01:36:36 +00002099 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
Nick Lewycky1e43d952013-08-21 19:09:44 +00002100 Range.getEnd().getLocWithOffset(1));
John McCall50a2c2c2011-10-11 23:14:30 +00002101 return true;
2102 }
2103
2104 if (!ForceComplain) return false;
2105
Erich Keane3efe0022018-07-20 14:13:28 +00002106 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2107 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2108 if (!IsMV)
2109 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
John McCall50a2c2c2011-10-11 23:14:30 +00002110 E = ExprError();
2111 return true;
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00002112}
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00002113
2114IdentifierInfo *Sema::getSuperIdentifier() const {
2115 if (!Ident_super)
2116 Ident_super = &Context.Idents.get("super");
2117 return Ident_super;
2118}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002119
Nico Webere1687c52013-06-20 21:44:55 +00002120IdentifierInfo *Sema::getFloat128Identifier() const {
2121 if (!Ident___float128)
2122 Ident___float128 = &Context.Idents.get("__float128");
2123 return Ident___float128;
2124}
2125
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002126void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00002127 CapturedRegionKind K,
2128 unsigned OpenMPCaptureLevel) {
2129 auto *CSI = new CapturedRegionScopeInfo(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002130 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00002131 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2132 OpenMPCaptureLevel);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002133 CSI->ReturnType = Context.VoidTy;
2134 FunctionScopes.push_back(CSI);
2135}
2136
2137CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2138 if (FunctionScopes.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002139 return nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002140
2141 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2142}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002143
2144const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2145Sema::getMismatchingDeleteExpressions() const {
2146 return DeleteExprs;
2147}
Yaxun Liu5b746652016-12-18 05:18:55 +00002148
2149void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
2150 if (ExtStr.empty())
2151 return;
2152 llvm::SmallVector<StringRef, 1> Exts;
2153 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2154 auto CanT = T.getCanonicalType().getTypePtr();
2155 for (auto &I : Exts)
2156 OpenCLTypeExtMap[CanT].insert(I.str());
2157}
2158
2159void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
2160 llvm::SmallVector<StringRef, 1> Exts;
2161 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2162 if (Exts.empty())
2163 return;
2164 for (auto &I : Exts)
2165 OpenCLDeclExtMap[FD].insert(I.str());
2166}
2167
2168void Sema::setCurrentOpenCLExtensionForType(QualType T) {
2169 if (CurrOpenCLExtension.empty())
2170 return;
2171 setOpenCLExtensionForType(T, CurrOpenCLExtension);
2172}
2173
2174void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
2175 if (CurrOpenCLExtension.empty())
2176 return;
2177 setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
2178}
2179
Andrew Savonichev16f16992018-10-11 13:35:34 +00002180std::string Sema::getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD) {
2181 if (!OpenCLDeclExtMap.empty())
2182 return getOpenCLExtensionsFromExtMap(FD, OpenCLDeclExtMap);
2183
2184 return "";
2185}
2186
2187std::string Sema::getOpenCLExtensionsFromTypeExtMap(FunctionType *FT) {
2188 if (!OpenCLTypeExtMap.empty())
2189 return getOpenCLExtensionsFromExtMap(FT, OpenCLTypeExtMap);
2190
2191 return "";
2192}
2193
2194template <typename T, typename MapT>
2195std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) {
2196 std::string ExtensionNames = "";
2197 auto Loc = Map.find(FDT);
2198
2199 for (auto const& I : Loc->second) {
2200 ExtensionNames += I;
2201 ExtensionNames += " ";
2202 }
2203 ExtensionNames.pop_back();
2204
2205 return ExtensionNames;
2206}
2207
Yaxun Liu5b746652016-12-18 05:18:55 +00002208bool Sema::isOpenCLDisabledDecl(Decl *FD) {
2209 auto Loc = OpenCLDeclExtMap.find(FD);
2210 if (Loc == OpenCLDeclExtMap.end())
2211 return false;
2212 for (auto &I : Loc->second) {
2213 if (!getOpenCLOptions().isEnabled(I))
2214 return true;
2215 }
2216 return false;
2217}
2218
2219template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
2220bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
2221 DiagInfoT DiagInfo, MapT &Map,
2222 unsigned Selector,
2223 SourceRange SrcRange) {
2224 auto Loc = Map.find(D);
2225 if (Loc == Map.end())
2226 return false;
2227 bool Disabled = false;
2228 for (auto &I : Loc->second) {
2229 if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
2230 Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2231 << I << SrcRange;
2232 Disabled = true;
2233 }
2234 }
2235 return Disabled;
2236}
2237
2238bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
2239 // Check extensions for declared types.
2240 Decl *Decl = nullptr;
2241 if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
2242 Decl = TypedefT->getDecl();
2243 if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
2244 Decl = TagT->getDecl();
2245 auto Loc = DS.getTypeSpecTypeLoc();
Alexey Sotkin73ae7cb2018-09-03 11:43:22 +00002246
2247 // Check extensions for vector types.
2248 // e.g. double4 is not allowed when cl_khr_fp64 is absent.
2249 if (QT->isExtVectorType()) {
2250 auto TypePtr = QT->castAs<ExtVectorType>()->getElementType().getTypePtr();
2251 return checkOpenCLDisabledTypeOrDecl(TypePtr, Loc, QT, OpenCLTypeExtMap);
2252 }
2253
Yaxun Liu5b746652016-12-18 05:18:55 +00002254 if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
2255 return true;
2256
2257 // Check extensions for builtin types.
2258 return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
2259 QT, OpenCLTypeExtMap);
2260}
2261
Joey Gouly186791d2017-06-30 14:23:01 +00002262bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
2263 IdentifierInfo *FnName = D.getIdentifier();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002264 return checkOpenCLDisabledTypeOrDecl(&D, E.getBeginLoc(), FnName,
Yaxun Liu5b746652016-12-18 05:18:55 +00002265 OpenCLDeclExtMap, 1, D.getSourceRange());
2266}