File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 9287, column 27 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// | ||||||||
2 | // | ||||||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||||||
6 | // | ||||||||
7 | //===----------------------------------------------------------------------===// | ||||||||
8 | // | ||||||||
9 | // This file implements semantic analysis for expressions. | ||||||||
10 | // | ||||||||
11 | //===----------------------------------------------------------------------===// | ||||||||
12 | |||||||||
13 | #include "TreeTransform.h" | ||||||||
14 | #include "UsedDeclVisitor.h" | ||||||||
15 | #include "clang/AST/ASTConsumer.h" | ||||||||
16 | #include "clang/AST/ASTContext.h" | ||||||||
17 | #include "clang/AST/ASTLambda.h" | ||||||||
18 | #include "clang/AST/ASTMutationListener.h" | ||||||||
19 | #include "clang/AST/CXXInheritance.h" | ||||||||
20 | #include "clang/AST/DeclObjC.h" | ||||||||
21 | #include "clang/AST/DeclTemplate.h" | ||||||||
22 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||||||
23 | #include "clang/AST/Expr.h" | ||||||||
24 | #include "clang/AST/ExprCXX.h" | ||||||||
25 | #include "clang/AST/ExprObjC.h" | ||||||||
26 | #include "clang/AST/ExprOpenMP.h" | ||||||||
27 | #include "clang/AST/OperationKinds.h" | ||||||||
28 | #include "clang/AST/RecursiveASTVisitor.h" | ||||||||
29 | #include "clang/AST/TypeLoc.h" | ||||||||
30 | #include "clang/Basic/Builtins.h" | ||||||||
31 | #include "clang/Basic/PartialDiagnostic.h" | ||||||||
32 | #include "clang/Basic/SourceManager.h" | ||||||||
33 | #include "clang/Basic/TargetInfo.h" | ||||||||
34 | #include "clang/Lex/LiteralSupport.h" | ||||||||
35 | #include "clang/Lex/Preprocessor.h" | ||||||||
36 | #include "clang/Sema/AnalysisBasedWarnings.h" | ||||||||
37 | #include "clang/Sema/DeclSpec.h" | ||||||||
38 | #include "clang/Sema/DelayedDiagnostic.h" | ||||||||
39 | #include "clang/Sema/Designator.h" | ||||||||
40 | #include "clang/Sema/Initialization.h" | ||||||||
41 | #include "clang/Sema/Lookup.h" | ||||||||
42 | #include "clang/Sema/Overload.h" | ||||||||
43 | #include "clang/Sema/ParsedTemplate.h" | ||||||||
44 | #include "clang/Sema/Scope.h" | ||||||||
45 | #include "clang/Sema/ScopeInfo.h" | ||||||||
46 | #include "clang/Sema/SemaFixItUtils.h" | ||||||||
47 | #include "clang/Sema/SemaInternal.h" | ||||||||
48 | #include "clang/Sema/Template.h" | ||||||||
49 | #include "llvm/ADT/STLExtras.h" | ||||||||
50 | #include "llvm/Support/ConvertUTF.h" | ||||||||
51 | #include "llvm/Support/SaveAndRestore.h" | ||||||||
52 | using namespace clang; | ||||||||
53 | using namespace sema; | ||||||||
54 | using llvm::RoundingMode; | ||||||||
55 | |||||||||
56 | /// Determine whether the use of this declaration is valid, without | ||||||||
57 | /// emitting diagnostics. | ||||||||
58 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||||||
59 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||||||
60 | if (ParsingInitForAutoVars.count(D)) | ||||||||
61 | return false; | ||||||||
62 | |||||||||
63 | // See if this is a deleted function. | ||||||||
64 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
65 | if (FD->isDeleted()) | ||||||||
66 | return false; | ||||||||
67 | |||||||||
68 | // If the function has a deduced return type, and we can't deduce it, | ||||||||
69 | // then we can't use it either. | ||||||||
70 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||||||
71 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||||||
72 | return false; | ||||||||
73 | |||||||||
74 | // See if this is an aligned allocation/deallocation function that is | ||||||||
75 | // unavailable. | ||||||||
76 | if (TreatUnavailableAsInvalid && | ||||||||
77 | isUnavailableAlignedAllocationFunction(*FD)) | ||||||||
78 | return false; | ||||||||
79 | } | ||||||||
80 | |||||||||
81 | // See if this function is unavailable. | ||||||||
82 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||||||
83 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||||||
84 | return false; | ||||||||
85 | |||||||||
86 | return true; | ||||||||
87 | } | ||||||||
88 | |||||||||
89 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||||||
90 | // Warn if this is used but marked unused. | ||||||||
91 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||||||
92 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||||||
93 | // should diagnose them. | ||||||||
94 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||||||
95 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||||||
96 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||||||
97 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||||||
98 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||||||
99 | } | ||||||||
100 | } | ||||||||
101 | } | ||||||||
102 | |||||||||
103 | /// Emit a note explaining that this function is deleted. | ||||||||
104 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||||||
105 | assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void > (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 105, __PRETTY_FUNCTION__)); | ||||||||
106 | |||||||||
107 | if (Decl->isDefaulted()) { | ||||||||
108 | // If the method was explicitly defaulted, point at that declaration. | ||||||||
109 | if (!Decl->isImplicit()) | ||||||||
110 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||||||
111 | |||||||||
112 | // Try to diagnose why this special member function was implicitly | ||||||||
113 | // deleted. This might fail, if that reason no longer applies. | ||||||||
114 | DiagnoseDeletedDefaultedFunction(Decl); | ||||||||
115 | return; | ||||||||
116 | } | ||||||||
117 | |||||||||
118 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||||||
119 | if (Ctor && Ctor->isInheritingConstructor()) | ||||||||
120 | return NoteDeletedInheritingConstructor(Ctor); | ||||||||
121 | |||||||||
122 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||||||
123 | << Decl << 1; | ||||||||
124 | } | ||||||||
125 | |||||||||
126 | /// Determine whether a FunctionDecl was ever declared with an | ||||||||
127 | /// explicit storage class. | ||||||||
128 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||||||
129 | for (auto I : D->redecls()) { | ||||||||
130 | if (I->getStorageClass() != SC_None) | ||||||||
131 | return true; | ||||||||
132 | } | ||||||||
133 | return false; | ||||||||
134 | } | ||||||||
135 | |||||||||
136 | /// Check whether we're in an extern inline function and referring to a | ||||||||
137 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||||||
138 | /// | ||||||||
139 | /// This is only a warning because we used to silently accept this code, but | ||||||||
140 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||||||
141 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||||||
142 | /// and so while there may still be user mistakes, most of the time we can't | ||||||||
143 | /// prove that there are errors. | ||||||||
144 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||||||
145 | const NamedDecl *D, | ||||||||
146 | SourceLocation Loc) { | ||||||||
147 | // This is disabled under C++; there are too many ways for this to fire in | ||||||||
148 | // contexts where the warning is a false positive, or where it is technically | ||||||||
149 | // correct but benign. | ||||||||
150 | if (S.getLangOpts().CPlusPlus) | ||||||||
151 | return; | ||||||||
152 | |||||||||
153 | // Check if this is an inlined function or method. | ||||||||
154 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||||||
155 | if (!Current) | ||||||||
156 | return; | ||||||||
157 | if (!Current->isInlined()) | ||||||||
158 | return; | ||||||||
159 | if (!Current->isExternallyVisible()) | ||||||||
160 | return; | ||||||||
161 | |||||||||
162 | // Check if the decl has internal linkage. | ||||||||
163 | if (D->getFormalLinkage() != InternalLinkage) | ||||||||
164 | return; | ||||||||
165 | |||||||||
166 | // Downgrade from ExtWarn to Extension if | ||||||||
167 | // (1) the supposedly external inline function is in the main file, | ||||||||
168 | // and probably won't be included anywhere else. | ||||||||
169 | // (2) the thing we're referencing is a pure function. | ||||||||
170 | // (3) the thing we're referencing is another inline function. | ||||||||
171 | // This last can give us false negatives, but it's better than warning on | ||||||||
172 | // wrappers for simple C library functions. | ||||||||
173 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||||||
174 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||||||
175 | if (!DowngradeWarning && UsedFn) | ||||||||
176 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||||||
177 | |||||||||
178 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||||||
179 | : diag::ext_internal_in_extern_inline) | ||||||||
180 | << /*IsVar=*/!UsedFn << D; | ||||||||
181 | |||||||||
182 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||||||
183 | |||||||||
184 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||||||
185 | << D; | ||||||||
186 | } | ||||||||
187 | |||||||||
188 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||||||
189 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||||||
190 | |||||||||
191 | // Suggest "static" on the function, if possible. | ||||||||
192 | if (!hasAnyExplicitStorageClass(First)) { | ||||||||
193 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||||||
194 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||||||
195 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||||||
196 | } | ||||||||
197 | } | ||||||||
198 | |||||||||
199 | /// Determine whether the use of this declaration is valid, and | ||||||||
200 | /// emit any corresponding diagnostics. | ||||||||
201 | /// | ||||||||
202 | /// This routine diagnoses various problems with referencing | ||||||||
203 | /// declarations that can occur when using a declaration. For example, | ||||||||
204 | /// it might warn if a deprecated or unavailable declaration is being | ||||||||
205 | /// used, or produce an error (and return true) if a C++0x deleted | ||||||||
206 | /// function is being used. | ||||||||
207 | /// | ||||||||
208 | /// \returns true if there was an error (this declaration cannot be | ||||||||
209 | /// referenced), false otherwise. | ||||||||
210 | /// | ||||||||
211 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||||||
212 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||||||
213 | bool ObjCPropertyAccess, | ||||||||
214 | bool AvoidPartialAvailabilityChecks, | ||||||||
215 | ObjCInterfaceDecl *ClassReceiver) { | ||||||||
216 | SourceLocation Loc = Locs.front(); | ||||||||
217 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||||||
218 | // If there were any diagnostics suppressed by template argument deduction, | ||||||||
219 | // emit them now. | ||||||||
220 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||||||
221 | if (Pos != SuppressedDiagnostics.end()) { | ||||||||
222 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||||||
223 | Diag(Suppressed.first, Suppressed.second); | ||||||||
224 | |||||||||
225 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||||||
226 | // them again for this specialization. However, we don't obsolete this | ||||||||
227 | // entry from the table, because we want to avoid ever emitting these | ||||||||
228 | // diagnostics again. | ||||||||
229 | Pos->second.clear(); | ||||||||
230 | } | ||||||||
231 | |||||||||
232 | // C++ [basic.start.main]p3: | ||||||||
233 | // The function 'main' shall not be used within a program. | ||||||||
234 | if (cast<FunctionDecl>(D)->isMain()) | ||||||||
235 | Diag(Loc, diag::ext_main_used); | ||||||||
236 | |||||||||
237 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||||||
238 | } | ||||||||
239 | |||||||||
240 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||||||
241 | if (ParsingInitForAutoVars.count(D)) { | ||||||||
242 | if (isa<BindingDecl>(D)) { | ||||||||
243 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||||||
244 | << D->getDeclName(); | ||||||||
245 | } else { | ||||||||
246 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||||||
247 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||||||
248 | } | ||||||||
249 | return true; | ||||||||
250 | } | ||||||||
251 | |||||||||
252 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
253 | // See if this is a deleted function. | ||||||||
254 | if (FD->isDeleted()) { | ||||||||
255 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||||||
256 | if (Ctor && Ctor->isInheritingConstructor()) | ||||||||
257 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||||||
258 | << Ctor->getParent() | ||||||||
259 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||||||
260 | else | ||||||||
261 | Diag(Loc, diag::err_deleted_function_use); | ||||||||
262 | NoteDeletedFunction(FD); | ||||||||
263 | return true; | ||||||||
264 | } | ||||||||
265 | |||||||||
266 | // [expr.prim.id]p4 | ||||||||
267 | // A program that refers explicitly or implicitly to a function with a | ||||||||
268 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||||||
269 | // other than to declare it, is ill-formed. [...] | ||||||||
270 | // | ||||||||
271 | // See if this is a function with constraints that need to be satisfied. | ||||||||
272 | // Check this before deducing the return type, as it might instantiate the | ||||||||
273 | // definition. | ||||||||
274 | if (FD->getTrailingRequiresClause()) { | ||||||||
275 | ConstraintSatisfaction Satisfaction; | ||||||||
276 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | ||||||||
277 | // A diagnostic will have already been generated (non-constant | ||||||||
278 | // constraint expression, for example) | ||||||||
279 | return true; | ||||||||
280 | if (!Satisfaction.IsSatisfied) { | ||||||||
281 | Diag(Loc, | ||||||||
282 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||||||
283 | << D; | ||||||||
284 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||||||
285 | return true; | ||||||||
286 | } | ||||||||
287 | } | ||||||||
288 | |||||||||
289 | // If the function has a deduced return type, and we can't deduce it, | ||||||||
290 | // then we can't use it either. | ||||||||
291 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||||||
292 | DeduceReturnType(FD, Loc)) | ||||||||
293 | return true; | ||||||||
294 | |||||||||
295 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||||||
296 | return true; | ||||||||
297 | |||||||||
298 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||||||
299 | return true; | ||||||||
300 | } | ||||||||
301 | |||||||||
302 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||||||
303 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||||||
304 | if (MD->getParent()->isLambda() && | ||||||||
305 | ((isa<CXXConstructorDecl>(MD) && | ||||||||
306 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||||||
307 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||||||
308 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||||||
309 | << !isa<CXXConstructorDecl>(MD); | ||||||||
310 | } | ||||||||
311 | } | ||||||||
312 | |||||||||
313 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||||||
314 | const ObjCPropertyDecl * { | ||||||||
315 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||||||
316 | return MD->findPropertyDecl(); | ||||||||
317 | return nullptr; | ||||||||
318 | }; | ||||||||
319 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||||||
320 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||||||
321 | return true; | ||||||||
322 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||||||
323 | return true; | ||||||||
324 | } | ||||||||
325 | |||||||||
326 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||||||
327 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||||||
328 | // Only the variables omp_priv and omp_orig are allowed in the | ||||||||
329 | // initializer-clause. | ||||||||
330 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||||||
331 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||||||
332 | isa<VarDecl>(D)) { | ||||||||
333 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||||||
334 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||||||
335 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
336 | return true; | ||||||||
337 | } | ||||||||
338 | |||||||||
339 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||||||
340 | // List-items in map clauses on this construct may only refer to the declared | ||||||||
341 | // variable var and entities that could be referenced by a procedure defined | ||||||||
342 | // at the same location | ||||||||
343 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||||||
344 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||||||
345 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||||||
346 | << getOpenMPDeclareMapperVarName(); | ||||||||
347 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
348 | return true; | ||||||||
349 | } | ||||||||
350 | |||||||||
351 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||||||
352 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||||||
353 | |||||||||
354 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||||||
355 | |||||||||
356 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||||||
357 | |||||||||
358 | // CUDA/HIP: Diagnose invalid references of host global variables in device | ||||||||
359 | // functions. Reference of device global variables in host functions is | ||||||||
360 | // allowed through shadow variables therefore it is not diagnosed. | ||||||||
361 | if (LangOpts.CUDAIsDevice) { | ||||||||
362 | auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); | ||||||||
363 | auto Target = IdentifyCUDATarget(FD); | ||||||||
364 | if (FD && Target != CFT_Host) { | ||||||||
365 | const auto *VD = dyn_cast<VarDecl>(D); | ||||||||
366 | if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && | ||||||||
367 | !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && | ||||||||
368 | !VD->getType()->isCUDADeviceBuiltinSurfaceType() && | ||||||||
369 | !VD->getType()->isCUDADeviceBuiltinTextureType() && | ||||||||
370 | !VD->isConstexpr() && !VD->getType().isConstQualified()) | ||||||||
371 | targetDiag(*Locs.begin(), diag::err_ref_bad_target) | ||||||||
372 | << /*host*/ 2 << /*variable*/ 1 << VD << Target; | ||||||||
373 | } | ||||||||
374 | } | ||||||||
375 | |||||||||
376 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||||||
377 | if (auto *VD = dyn_cast<ValueDecl>(D)) | ||||||||
378 | checkDeviceDecl(VD, Loc); | ||||||||
379 | |||||||||
380 | if (!Context.getTargetInfo().isTLSSupported()) | ||||||||
381 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||||||
382 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||||||
383 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||||||
384 | } | ||||||||
385 | |||||||||
386 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||||||
387 | !isUnevaluatedContext()) { | ||||||||
388 | // C++ [expr.prim.req.nested] p3 | ||||||||
389 | // A local parameter shall only appear as an unevaluated operand | ||||||||
390 | // (Clause 8) within the constraint-expression. | ||||||||
391 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||||||
392 | << D; | ||||||||
393 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
394 | return true; | ||||||||
395 | } | ||||||||
396 | |||||||||
397 | return false; | ||||||||
398 | } | ||||||||
399 | |||||||||
400 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||||||
401 | /// message-send is to a declaration with the sentinel attribute, and | ||||||||
402 | /// if so, it checks that the requirements of the sentinel are | ||||||||
403 | /// satisfied. | ||||||||
404 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||||||
405 | ArrayRef<Expr *> Args) { | ||||||||
406 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||||||
407 | if (!attr) | ||||||||
408 | return; | ||||||||
409 | |||||||||
410 | // The number of formal parameters of the declaration. | ||||||||
411 | unsigned numFormalParams; | ||||||||
412 | |||||||||
413 | // The kind of declaration. This is also an index into a %select in | ||||||||
414 | // the diagnostic. | ||||||||
415 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||||||
416 | |||||||||
417 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||||||
418 | numFormalParams = MD->param_size(); | ||||||||
419 | calleeType = CT_Method; | ||||||||
420 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
421 | numFormalParams = FD->param_size(); | ||||||||
422 | calleeType = CT_Function; | ||||||||
423 | } else if (isa<VarDecl>(D)) { | ||||||||
424 | QualType type = cast<ValueDecl>(D)->getType(); | ||||||||
425 | const FunctionType *fn = nullptr; | ||||||||
426 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||||||
427 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||||||
428 | if (!fn) return; | ||||||||
429 | calleeType = CT_Function; | ||||||||
430 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||||||
431 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||||||
432 | calleeType = CT_Block; | ||||||||
433 | } else { | ||||||||
434 | return; | ||||||||
435 | } | ||||||||
436 | |||||||||
437 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||||||
438 | numFormalParams = proto->getNumParams(); | ||||||||
439 | } else { | ||||||||
440 | numFormalParams = 0; | ||||||||
441 | } | ||||||||
442 | } else { | ||||||||
443 | return; | ||||||||
444 | } | ||||||||
445 | |||||||||
446 | // "nullPos" is the number of formal parameters at the end which | ||||||||
447 | // effectively count as part of the variadic arguments. This is | ||||||||
448 | // useful if you would prefer to not have *any* formal parameters, | ||||||||
449 | // but the language forces you to have at least one. | ||||||||
450 | unsigned nullPos = attr->getNullPos(); | ||||||||
451 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel" ) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 451, __PRETTY_FUNCTION__)); | ||||||||
452 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||||||
453 | |||||||||
454 | // The number of arguments which should follow the sentinel. | ||||||||
455 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||||||
456 | |||||||||
457 | // If there aren't enough arguments for all the formal parameters, | ||||||||
458 | // the sentinel, and the args after the sentinel, complain. | ||||||||
459 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||||||
460 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||||||
461 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||||||
462 | return; | ||||||||
463 | } | ||||||||
464 | |||||||||
465 | // Otherwise, find the sentinel expression. | ||||||||
466 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||||||
467 | if (!sentinelExpr) return; | ||||||||
468 | if (sentinelExpr->isValueDependent()) return; | ||||||||
469 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||||||
470 | |||||||||
471 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||||||
472 | // or 'NULL' if those are actually defined in the context. Only use | ||||||||
473 | // 'nil' for ObjC methods, where it's much more likely that the | ||||||||
474 | // variadic arguments form a list of object pointers. | ||||||||
475 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||||||
476 | std::string NullValue; | ||||||||
477 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||||||
478 | NullValue = "nil"; | ||||||||
479 | else if (getLangOpts().CPlusPlus11) | ||||||||
480 | NullValue = "nullptr"; | ||||||||
481 | else if (PP.isMacroDefined("NULL")) | ||||||||
482 | NullValue = "NULL"; | ||||||||
483 | else | ||||||||
484 | NullValue = "(void*) 0"; | ||||||||
485 | |||||||||
486 | if (MissingNilLoc.isInvalid()) | ||||||||
487 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||||||
488 | else | ||||||||
489 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||||||
490 | << int(calleeType) | ||||||||
491 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||||||
492 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||||||
493 | } | ||||||||
494 | |||||||||
495 | SourceRange Sema::getExprRange(Expr *E) const { | ||||||||
496 | return E ? E->getSourceRange() : SourceRange(); | ||||||||
497 | } | ||||||||
498 | |||||||||
499 | //===----------------------------------------------------------------------===// | ||||||||
500 | // Standard Promotions and Conversions | ||||||||
501 | //===----------------------------------------------------------------------===// | ||||||||
502 | |||||||||
503 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||||||
504 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||||||
505 | // Handle any placeholder expressions which made it here. | ||||||||
506 | if (E->getType()->isPlaceholderType()) { | ||||||||
507 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
508 | if (result.isInvalid()) return ExprError(); | ||||||||
509 | E = result.get(); | ||||||||
510 | } | ||||||||
511 | |||||||||
512 | QualType Ty = E->getType(); | ||||||||
513 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 513, __PRETTY_FUNCTION__)); | ||||||||
514 | |||||||||
515 | if (Ty->isFunctionType()) { | ||||||||
516 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||||||
517 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||||||
518 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||||||
519 | return ExprError(); | ||||||||
520 | |||||||||
521 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||||||
522 | CK_FunctionToPointerDecay).get(); | ||||||||
523 | } else if (Ty->isArrayType()) { | ||||||||
524 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||||||
525 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||||||
526 | // type 'array of type' is converted to an expression that has type 'pointer | ||||||||
527 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||||||
528 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||||||
529 | // (C90) to "an expression" (C99). | ||||||||
530 | // | ||||||||
531 | // C++ 4.2p1: | ||||||||
532 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||||||
533 | // T" can be converted to an rvalue of type "pointer to T". | ||||||||
534 | // | ||||||||
535 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | ||||||||
536 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||||||
537 | CK_ArrayToPointerDecay).get(); | ||||||||
538 | } | ||||||||
539 | return E; | ||||||||
540 | } | ||||||||
541 | |||||||||
542 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||||||
543 | // Check to see if we are dereferencing a null pointer. If so, | ||||||||
544 | // and if not volatile-qualified, this is undefined behavior that the | ||||||||
545 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||||||
546 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||||||
547 | // only handles the pattern "*null", which is a very syntactic check. | ||||||||
548 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||||||
549 | if (UO && UO->getOpcode() == UO_Deref && | ||||||||
550 | UO->getSubExpr()->getType()->isPointerType()) { | ||||||||
551 | const LangAS AS = | ||||||||
552 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||||||
553 | if ((!isTargetAddressSpace(AS) || | ||||||||
554 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||||||
555 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||||||
556 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||||||
557 | !UO->getType().isVolatileQualified()) { | ||||||||
558 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||
559 | S.PDiag(diag::warn_indirection_through_null) | ||||||||
560 | << UO->getSubExpr()->getSourceRange()); | ||||||||
561 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||
562 | S.PDiag(diag::note_indirection_through_null)); | ||||||||
563 | } | ||||||||
564 | } | ||||||||
565 | } | ||||||||
566 | |||||||||
567 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||||||
568 | SourceLocation AssignLoc, | ||||||||
569 | const Expr* RHS) { | ||||||||
570 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||||||
571 | if (!IV) | ||||||||
572 | return; | ||||||||
573 | |||||||||
574 | DeclarationName MemberName = IV->getDeclName(); | ||||||||
575 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||||||
576 | if (!Member || !Member->isStr("isa")) | ||||||||
577 | return; | ||||||||
578 | |||||||||
579 | const Expr *Base = OIRE->getBase(); | ||||||||
580 | QualType BaseType = Base->getType(); | ||||||||
581 | if (OIRE->isArrow()) | ||||||||
582 | BaseType = BaseType->getPointeeType(); | ||||||||
583 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||||||
584 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||||||
585 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||||||
586 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||||||
587 | if (!ClassDeclared->getSuperClass() | ||||||||
588 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||||||
589 | if (RHS) { | ||||||||
590 | NamedDecl *ObjectSetClass = | ||||||||
591 | S.LookupSingleName(S.TUScope, | ||||||||
592 | &S.Context.Idents.get("object_setClass"), | ||||||||
593 | SourceLocation(), S.LookupOrdinaryName); | ||||||||
594 | if (ObjectSetClass) { | ||||||||
595 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||||||
596 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||||||
597 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||||||
598 | "object_setClass(") | ||||||||
599 | << FixItHint::CreateReplacement( | ||||||||
600 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||||||
601 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||||||
602 | } | ||||||||
603 | else | ||||||||
604 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||||||
605 | } else { | ||||||||
606 | NamedDecl *ObjectGetClass = | ||||||||
607 | S.LookupSingleName(S.TUScope, | ||||||||
608 | &S.Context.Idents.get("object_getClass"), | ||||||||
609 | SourceLocation(), S.LookupOrdinaryName); | ||||||||
610 | if (ObjectGetClass) | ||||||||
611 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||||||
612 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||||||
613 | "object_getClass(") | ||||||||
614 | << FixItHint::CreateReplacement( | ||||||||
615 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||||||
616 | else | ||||||||
617 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||||||
618 | } | ||||||||
619 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||||||
620 | } | ||||||||
621 | } | ||||||||
622 | } | ||||||||
623 | |||||||||
624 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||||||
625 | // Handle any placeholder expressions which made it here. | ||||||||
626 | if (E->getType()->isPlaceholderType()) { | ||||||||
627 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
628 | if (result.isInvalid()) return ExprError(); | ||||||||
629 | E = result.get(); | ||||||||
630 | } | ||||||||
631 | |||||||||
632 | // C++ [conv.lval]p1: | ||||||||
633 | // A glvalue of a non-function, non-array type T can be | ||||||||
634 | // converted to a prvalue. | ||||||||
635 | if (!E->isGLValue()) return E; | ||||||||
636 | |||||||||
637 | QualType T = E->getType(); | ||||||||
638 | assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 638, __PRETTY_FUNCTION__)); | ||||||||
639 | |||||||||
640 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||||||
641 | if (T->isFunctionType() || T->isArrayType()) | ||||||||
642 | return E; | ||||||||
643 | |||||||||
644 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||||||
645 | // expressions of certain types in C++. | ||||||||
646 | if (getLangOpts().CPlusPlus && | ||||||||
647 | (E->getType() == Context.OverloadTy || | ||||||||
648 | T->isDependentType() || | ||||||||
649 | T->isRecordType())) | ||||||||
650 | return E; | ||||||||
651 | |||||||||
652 | // The C standard is actually really unclear on this point, and | ||||||||
653 | // DR106 tells us what the result should be but not why. It's | ||||||||
654 | // generally best to say that void types just doesn't undergo | ||||||||
655 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||||||
656 | // 'void' type are never l-values, but qualified void can be. | ||||||||
657 | if (T->isVoidType()) | ||||||||
658 | return E; | ||||||||
659 | |||||||||
660 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||||||
661 | if (getLangOpts().OpenCL && | ||||||||
662 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||||||
663 | T->isHalfType()) { | ||||||||
664 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||||||
665 | << 0 << T; | ||||||||
666 | return ExprError(); | ||||||||
667 | } | ||||||||
668 | |||||||||
669 | CheckForNullPointerDereference(*this, E); | ||||||||
670 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||||||
671 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||||||
672 | &Context.Idents.get("object_getClass"), | ||||||||
673 | SourceLocation(), LookupOrdinaryName); | ||||||||
674 | if (ObjectGetClass) | ||||||||
675 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||||||
676 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||||||
677 | << FixItHint::CreateReplacement( | ||||||||
678 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||||||
679 | else | ||||||||
680 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||||||
681 | } | ||||||||
682 | else if (const ObjCIvarRefExpr *OIRE = | ||||||||
683 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||||||
684 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||||||
685 | |||||||||
686 | // C++ [conv.lval]p1: | ||||||||
687 | // [...] If T is a non-class type, the type of the prvalue is the | ||||||||
688 | // cv-unqualified version of T. Otherwise, the type of the | ||||||||
689 | // rvalue is T. | ||||||||
690 | // | ||||||||
691 | // C99 6.3.2.1p2: | ||||||||
692 | // If the lvalue has qualified type, the value has the unqualified | ||||||||
693 | // version of the type of the lvalue; otherwise, the value has the | ||||||||
694 | // type of the lvalue. | ||||||||
695 | if (T.hasQualifiers()) | ||||||||
696 | T = T.getUnqualifiedType(); | ||||||||
697 | |||||||||
698 | // Under the MS ABI, lock down the inheritance model now. | ||||||||
699 | if (T->isMemberPointerType() && | ||||||||
700 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||||||
701 | (void)isCompleteType(E->getExprLoc(), T); | ||||||||
702 | |||||||||
703 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||||||
704 | if (Res.isInvalid()) | ||||||||
705 | return Res; | ||||||||
706 | E = Res.get(); | ||||||||
707 | |||||||||
708 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||||||
709 | // balance that. | ||||||||
710 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||||
711 | Cleanup.setExprNeedsCleanups(true); | ||||||||
712 | |||||||||
713 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
714 | Cleanup.setExprNeedsCleanups(true); | ||||||||
715 | |||||||||
716 | // C++ [conv.lval]p3: | ||||||||
717 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||||||
718 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||||||
719 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, | ||||||||
720 | CurFPFeatureOverrides()); | ||||||||
721 | |||||||||
722 | // C11 6.3.2.1p2: | ||||||||
723 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||||||
724 | // of the type of the lvalue ... | ||||||||
725 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||||||
726 | T = Atomic->getValueType().getUnqualifiedType(); | ||||||||
727 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||||||
728 | nullptr, VK_RValue, FPOptionsOverride()); | ||||||||
729 | } | ||||||||
730 | |||||||||
731 | return Res; | ||||||||
732 | } | ||||||||
733 | |||||||||
734 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||||||
735 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||||||
736 | if (Res.isInvalid()) | ||||||||
737 | return ExprError(); | ||||||||
738 | Res = DefaultLvalueConversion(Res.get()); | ||||||||
739 | if (Res.isInvalid()) | ||||||||
740 | return ExprError(); | ||||||||
741 | return Res; | ||||||||
742 | } | ||||||||
743 | |||||||||
744 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||||||
745 | /// performed on a function designator of a call expression. | ||||||||
746 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||||||
747 | QualType Ty = E->getType(); | ||||||||
748 | ExprResult Res = E; | ||||||||
749 | // Only do implicit cast for a function type, but not for a pointer | ||||||||
750 | // to function type. | ||||||||
751 | if (Ty->isFunctionType()) { | ||||||||
752 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||||||
753 | CK_FunctionToPointerDecay); | ||||||||
754 | if (Res.isInvalid()) | ||||||||
755 | return ExprError(); | ||||||||
756 | } | ||||||||
757 | Res = DefaultLvalueConversion(Res.get()); | ||||||||
758 | if (Res.isInvalid()) | ||||||||
759 | return ExprError(); | ||||||||
760 | return Res.get(); | ||||||||
761 | } | ||||||||
762 | |||||||||
763 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||||||
764 | /// operators (C99 6.3). The conversions of array and function types are | ||||||||
765 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||||||
766 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||||||
767 | /// In these instances, this routine should *not* be called. | ||||||||
768 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||||||
769 | // First, convert to an r-value. | ||||||||
770 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||||||
771 | if (Res.isInvalid()) | ||||||||
772 | return ExprError(); | ||||||||
773 | E = Res.get(); | ||||||||
774 | |||||||||
775 | QualType Ty = E->getType(); | ||||||||
776 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 776, __PRETTY_FUNCTION__)); | ||||||||
777 | |||||||||
778 | // Half FP have to be promoted to float unless it is natively supported | ||||||||
779 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||||||
780 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||||||
781 | |||||||||
782 | // Try to perform integral promotions if the object has a theoretically | ||||||||
783 | // promotable type. | ||||||||
784 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||||||
785 | // C99 6.3.1.1p2: | ||||||||
786 | // | ||||||||
787 | // The following may be used in an expression wherever an int or | ||||||||
788 | // unsigned int may be used: | ||||||||
789 | // - an object or expression with an integer type whose integer | ||||||||
790 | // conversion rank is less than or equal to the rank of int | ||||||||
791 | // and unsigned int. | ||||||||
792 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||||||
793 | // | ||||||||
794 | // If an int can represent all values of the original type, the | ||||||||
795 | // value is converted to an int; otherwise, it is converted to an | ||||||||
796 | // unsigned int. These are called the integer promotions. All | ||||||||
797 | // other types are unchanged by the integer promotions. | ||||||||
798 | |||||||||
799 | QualType PTy = Context.isPromotableBitField(E); | ||||||||
800 | if (!PTy.isNull()) { | ||||||||
801 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||||||
802 | return E; | ||||||||
803 | } | ||||||||
804 | if (Ty->isPromotableIntegerType()) { | ||||||||
805 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||||||
806 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||||||
807 | return E; | ||||||||
808 | } | ||||||||
809 | } | ||||||||
810 | return E; | ||||||||
811 | } | ||||||||
812 | |||||||||
813 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||||||
814 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||||||
815 | /// are promoted to double. All other argument types are converted by | ||||||||
816 | /// UsualUnaryConversions(). | ||||||||
817 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||||||
818 | QualType Ty = E->getType(); | ||||||||
819 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 819, __PRETTY_FUNCTION__)); | ||||||||
820 | |||||||||
821 | ExprResult Res = UsualUnaryConversions(E); | ||||||||
822 | if (Res.isInvalid()) | ||||||||
823 | return ExprError(); | ||||||||
824 | E = Res.get(); | ||||||||
825 | |||||||||
826 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||||||
827 | // promote to double. | ||||||||
828 | // Note that default argument promotion applies only to float (and | ||||||||
829 | // half/fp16); it does not apply to _Float16. | ||||||||
830 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||||||
831 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||||||
832 | BTy->getKind() == BuiltinType::Float)) { | ||||||||
833 | if (getLangOpts().OpenCL && | ||||||||
834 | !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { | ||||||||
835 | if (BTy->getKind() == BuiltinType::Half) { | ||||||||
836 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
837 | } | ||||||||
838 | } else { | ||||||||
839 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||||||
840 | } | ||||||||
841 | } | ||||||||
842 | |||||||||
843 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||||||
844 | // promotion, even on class types, but note: | ||||||||
845 | // C++11 [conv.lval]p2: | ||||||||
846 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||||||
847 | // operand or a subexpression thereof the value contained in the | ||||||||
848 | // referenced object is not accessed. Otherwise, if the glvalue | ||||||||
849 | // has a class type, the conversion copy-initializes a temporary | ||||||||
850 | // of type T from the glvalue and the result of the conversion | ||||||||
851 | // is a prvalue for the temporary. | ||||||||
852 | // FIXME: add some way to gate this entire thing for correctness in | ||||||||
853 | // potentially potentially evaluated contexts. | ||||||||
854 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||||||
855 | ExprResult Temp = PerformCopyInitialization( | ||||||||
856 | InitializedEntity::InitializeTemporary(E->getType()), | ||||||||
857 | E->getExprLoc(), E); | ||||||||
858 | if (Temp.isInvalid()) | ||||||||
859 | return ExprError(); | ||||||||
860 | E = Temp.get(); | ||||||||
861 | } | ||||||||
862 | |||||||||
863 | return E; | ||||||||
864 | } | ||||||||
865 | |||||||||
866 | /// Determine the degree of POD-ness for an expression. | ||||||||
867 | /// Incomplete types are considered POD, since this check can be performed | ||||||||
868 | /// when we're in an unevaluated context. | ||||||||
869 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||||||
870 | if (Ty->isIncompleteType()) { | ||||||||
871 | // C++11 [expr.call]p7: | ||||||||
872 | // After these conversions, if the argument does not have arithmetic, | ||||||||
873 | // enumeration, pointer, pointer to member, or class type, the program | ||||||||
874 | // is ill-formed. | ||||||||
875 | // | ||||||||
876 | // Since we've already performed array-to-pointer and function-to-pointer | ||||||||
877 | // decay, the only such type in C++ is cv void. This also handles | ||||||||
878 | // initializer lists as variadic arguments. | ||||||||
879 | if (Ty->isVoidType()) | ||||||||
880 | return VAK_Invalid; | ||||||||
881 | |||||||||
882 | if (Ty->isObjCObjectType()) | ||||||||
883 | return VAK_Invalid; | ||||||||
884 | return VAK_Valid; | ||||||||
885 | } | ||||||||
886 | |||||||||
887 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
888 | return VAK_Invalid; | ||||||||
889 | |||||||||
890 | if (Ty.isCXX98PODType(Context)) | ||||||||
891 | return VAK_Valid; | ||||||||
892 | |||||||||
893 | // C++11 [expr.call]p7: | ||||||||
894 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||||||
895 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||||||
896 | // or a non-trivial destructor, with no corresponding parameter, | ||||||||
897 | // is conditionally-supported with implementation-defined semantics. | ||||||||
898 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||||||
899 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||||||
900 | if (!Record->hasNonTrivialCopyConstructor() && | ||||||||
901 | !Record->hasNonTrivialMoveConstructor() && | ||||||||
902 | !Record->hasNonTrivialDestructor()) | ||||||||
903 | return VAK_ValidInCXX11; | ||||||||
904 | |||||||||
905 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||||||
906 | return VAK_Valid; | ||||||||
907 | |||||||||
908 | if (Ty->isObjCObjectType()) | ||||||||
909 | return VAK_Invalid; | ||||||||
910 | |||||||||
911 | if (getLangOpts().MSVCCompat) | ||||||||
912 | return VAK_MSVCUndefined; | ||||||||
913 | |||||||||
914 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||||||
915 | // permitted to reject them. We should consider doing so. | ||||||||
916 | return VAK_Undefined; | ||||||||
917 | } | ||||||||
918 | |||||||||
919 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||||||
920 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||||||
921 | const QualType &Ty = E->getType(); | ||||||||
922 | VarArgKind VAK = isValidVarArgType(Ty); | ||||||||
923 | |||||||||
924 | // Complain about passing non-POD types through varargs. | ||||||||
925 | switch (VAK) { | ||||||||
926 | case VAK_ValidInCXX11: | ||||||||
927 | DiagRuntimeBehavior( | ||||||||
928 | E->getBeginLoc(), nullptr, | ||||||||
929 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||||||
930 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
931 | case VAK_Valid: | ||||||||
932 | if (Ty->isRecordType()) { | ||||||||
933 | // This is unlikely to be what the user intended. If the class has a | ||||||||
934 | // 'c_str' member function, the user probably meant to call that. | ||||||||
935 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
936 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||||||
937 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||||||
938 | } | ||||||||
939 | break; | ||||||||
940 | |||||||||
941 | case VAK_Undefined: | ||||||||
942 | case VAK_MSVCUndefined: | ||||||||
943 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
944 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||||||
945 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||||||
946 | break; | ||||||||
947 | |||||||||
948 | case VAK_Invalid: | ||||||||
949 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
950 | Diag(E->getBeginLoc(), | ||||||||
951 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||||||
952 | << Ty << CT; | ||||||||
953 | else if (Ty->isObjCObjectType()) | ||||||||
954 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
955 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||||||
956 | << Ty << CT); | ||||||||
957 | else | ||||||||
958 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||||||
959 | << isa<InitListExpr>(E) << Ty << CT; | ||||||||
960 | break; | ||||||||
961 | } | ||||||||
962 | } | ||||||||
963 | |||||||||
964 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||||||
965 | /// will create a trap if the resulting type is not a POD type. | ||||||||
966 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||||||
967 | FunctionDecl *FDecl) { | ||||||||
968 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||||||
969 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||||||
970 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||||||
971 | (CT == VariadicMethod || | ||||||||
972 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||||||
973 | E = stripARCUnbridgedCast(E); | ||||||||
974 | |||||||||
975 | // Otherwise, do normal placeholder checking. | ||||||||
976 | } else { | ||||||||
977 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||||||
978 | if (ExprRes.isInvalid()) | ||||||||
979 | return ExprError(); | ||||||||
980 | E = ExprRes.get(); | ||||||||
981 | } | ||||||||
982 | } | ||||||||
983 | |||||||||
984 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||||||
985 | if (ExprRes.isInvalid()) | ||||||||
986 | return ExprError(); | ||||||||
987 | |||||||||
988 | // Copy blocks to the heap. | ||||||||
989 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||||||
990 | maybeExtendBlockObject(ExprRes); | ||||||||
991 | |||||||||
992 | E = ExprRes.get(); | ||||||||
993 | |||||||||
994 | // Diagnostics regarding non-POD argument types are | ||||||||
995 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||||||
996 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||||||
997 | // Turn this into a trap. | ||||||||
998 | CXXScopeSpec SS; | ||||||||
999 | SourceLocation TemplateKWLoc; | ||||||||
1000 | UnqualifiedId Name; | ||||||||
1001 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||||||
1002 | E->getBeginLoc()); | ||||||||
1003 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||||||
1004 | /*HasTrailingLParen=*/true, | ||||||||
1005 | /*IsAddressOfOperand=*/false); | ||||||||
1006 | if (TrapFn.isInvalid()) | ||||||||
1007 | return ExprError(); | ||||||||
1008 | |||||||||
1009 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||||||
1010 | None, E->getEndLoc()); | ||||||||
1011 | if (Call.isInvalid()) | ||||||||
1012 | return ExprError(); | ||||||||
1013 | |||||||||
1014 | ExprResult Comma = | ||||||||
1015 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||||||
1016 | if (Comma.isInvalid()) | ||||||||
1017 | return ExprError(); | ||||||||
1018 | return Comma.get(); | ||||||||
1019 | } | ||||||||
1020 | |||||||||
1021 | if (!getLangOpts().CPlusPlus && | ||||||||
1022 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||||||
1023 | diag::err_call_incomplete_argument)) | ||||||||
1024 | return ExprError(); | ||||||||
1025 | |||||||||
1026 | return E; | ||||||||
1027 | } | ||||||||
1028 | |||||||||
1029 | /// Converts an integer to complex float type. Helper function of | ||||||||
1030 | /// UsualArithmeticConversions() | ||||||||
1031 | /// | ||||||||
1032 | /// \return false if the integer expression is an integer type and is | ||||||||
1033 | /// successfully converted to the complex type. | ||||||||
1034 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||||||
1035 | ExprResult &ComplexExpr, | ||||||||
1036 | QualType IntTy, | ||||||||
1037 | QualType ComplexTy, | ||||||||
1038 | bool SkipCast) { | ||||||||
1039 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||||||
1040 | if (SkipCast) return false; | ||||||||
1041 | if (IntTy->isIntegerType()) { | ||||||||
1042 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | ||||||||
1043 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||||||
1044 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||||||
1045 | CK_FloatingRealToComplex); | ||||||||
1046 | } else { | ||||||||
1047 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1047, __PRETTY_FUNCTION__)); | ||||||||
1048 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||||||
1049 | CK_IntegralComplexToFloatingComplex); | ||||||||
1050 | } | ||||||||
1051 | return false; | ||||||||
1052 | } | ||||||||
1053 | |||||||||
1054 | /// Handle arithmetic conversion with complex types. Helper function of | ||||||||
1055 | /// UsualArithmeticConversions() | ||||||||
1056 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | ||||||||
1057 | ExprResult &RHS, QualType LHSType, | ||||||||
1058 | QualType RHSType, | ||||||||
1059 | bool IsCompAssign) { | ||||||||
1060 | // if we have an integer operand, the result is the complex type. | ||||||||
1061 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||||||
1062 | /*skipCast*/false)) | ||||||||
1063 | return LHSType; | ||||||||
1064 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
1065 | /*skipCast*/IsCompAssign)) | ||||||||
1066 | return RHSType; | ||||||||
1067 | |||||||||
1068 | // This handles complex/complex, complex/float, or float/complex. | ||||||||
1069 | // When both operands are complex, the shorter operand is converted to the | ||||||||
1070 | // type of the longer, and that is the type of the result. This corresponds | ||||||||
1071 | // to what is done when combining two real floating-point operands. | ||||||||
1072 | // The fun begins when size promotion occur across type domains. | ||||||||
1073 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||||||
1074 | // floating-point type, the less precise type is converted, within it's | ||||||||
1075 | // real or complex domain, to the precision of the other type. For example, | ||||||||
1076 | // when combining a "long double" with a "double _Complex", the | ||||||||
1077 | // "double _Complex" is promoted to "long double _Complex". | ||||||||
1078 | |||||||||
1079 | // Compute the rank of the two types, regardless of whether they are complex. | ||||||||
1080 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||||||
1081 | |||||||||
1082 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | ||||||||
1083 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | ||||||||
1084 | QualType LHSElementType = | ||||||||
1085 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | ||||||||
1086 | QualType RHSElementType = | ||||||||
1087 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | ||||||||
1088 | |||||||||
1089 | QualType ResultType = S.Context.getComplexType(LHSElementType); | ||||||||
1090 | if (Order < 0) { | ||||||||
1091 | // Promote the precision of the LHS if not an assignment. | ||||||||
1092 | ResultType = S.Context.getComplexType(RHSElementType); | ||||||||
1093 | if (!IsCompAssign) { | ||||||||
1094 | if (LHSComplexType) | ||||||||
1095 | LHS = | ||||||||
1096 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | ||||||||
1097 | else | ||||||||
1098 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | ||||||||
1099 | } | ||||||||
1100 | } else if (Order > 0) { | ||||||||
1101 | // Promote the precision of the RHS. | ||||||||
1102 | if (RHSComplexType) | ||||||||
1103 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | ||||||||
1104 | else | ||||||||
1105 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | ||||||||
1106 | } | ||||||||
1107 | return ResultType; | ||||||||
1108 | } | ||||||||
1109 | |||||||||
1110 | /// Handle arithmetic conversion from integer to float. Helper function | ||||||||
1111 | /// of UsualArithmeticConversions() | ||||||||
1112 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||||||
1113 | ExprResult &IntExpr, | ||||||||
1114 | QualType FloatTy, QualType IntTy, | ||||||||
1115 | bool ConvertFloat, bool ConvertInt) { | ||||||||
1116 | if (IntTy->isIntegerType()) { | ||||||||
1117 | if (ConvertInt) | ||||||||
1118 | // Convert intExpr to the lhs floating point type. | ||||||||
1119 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||||||
1120 | CK_IntegralToFloating); | ||||||||
1121 | return FloatTy; | ||||||||
1122 | } | ||||||||
1123 | |||||||||
1124 | // Convert both sides to the appropriate complex float. | ||||||||
1125 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1125, __PRETTY_FUNCTION__)); | ||||||||
1126 | QualType result = S.Context.getComplexType(FloatTy); | ||||||||
1127 | |||||||||
1128 | // _Complex int -> _Complex float | ||||||||
1129 | if (ConvertInt) | ||||||||
1130 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||||||
1131 | CK_IntegralComplexToFloatingComplex); | ||||||||
1132 | |||||||||
1133 | // float -> _Complex float | ||||||||
1134 | if (ConvertFloat) | ||||||||
1135 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||||||
1136 | CK_FloatingRealToComplex); | ||||||||
1137 | |||||||||
1138 | return result; | ||||||||
1139 | } | ||||||||
1140 | |||||||||
1141 | /// Handle arithmethic conversion with floating point types. Helper | ||||||||
1142 | /// function of UsualArithmeticConversions() | ||||||||
1143 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||||||
1144 | ExprResult &RHS, QualType LHSType, | ||||||||
1145 | QualType RHSType, bool IsCompAssign) { | ||||||||
1146 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||||||
1147 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||||||
1148 | |||||||||
1149 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||||||
1150 | // operand has a fixed-point type, the fixed-point operand | ||||||||
1151 | // is converted to the floating type [...] | ||||||||
1152 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||||||
1153 | if (LHSFloat) | ||||||||
1154 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||||||
1155 | else if (!IsCompAssign) | ||||||||
1156 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||||||
1157 | return LHSFloat ? LHSType : RHSType; | ||||||||
1158 | } | ||||||||
1159 | |||||||||
1160 | // If we have two real floating types, convert the smaller operand | ||||||||
1161 | // to the bigger result. | ||||||||
1162 | if (LHSFloat && RHSFloat) { | ||||||||
1163 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||||||
1164 | if (order > 0) { | ||||||||
1165 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||||||
1166 | return LHSType; | ||||||||
1167 | } | ||||||||
1168 | |||||||||
1169 | assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast <void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1169, __PRETTY_FUNCTION__)); | ||||||||
1170 | if (!IsCompAssign) | ||||||||
1171 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||||||
1172 | return RHSType; | ||||||||
1173 | } | ||||||||
1174 | |||||||||
1175 | if (LHSFloat) { | ||||||||
1176 | // Half FP has to be promoted to float unless it is natively supported | ||||||||
1177 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||||||
1178 | LHSType = S.Context.FloatTy; | ||||||||
1179 | |||||||||
1180 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
1181 | /*ConvertFloat=*/!IsCompAssign, | ||||||||
1182 | /*ConvertInt=*/ true); | ||||||||
1183 | } | ||||||||
1184 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1184, __PRETTY_FUNCTION__)); | ||||||||
1185 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||||||
1186 | /*ConvertFloat=*/ true, | ||||||||
1187 | /*ConvertInt=*/!IsCompAssign); | ||||||||
1188 | } | ||||||||
1189 | |||||||||
1190 | /// Diagnose attempts to convert between __float128 and long double if | ||||||||
1191 | /// there is no support for such conversion. Helper function of | ||||||||
1192 | /// UsualArithmeticConversions(). | ||||||||
1193 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||||||
1194 | QualType RHSType) { | ||||||||
1195 | /* No issue converting if at least one of the types is not a floating point | ||||||||
1196 | type or the two types have the same rank. | ||||||||
1197 | */ | ||||||||
1198 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | ||||||||
1199 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | ||||||||
1200 | return false; | ||||||||
1201 | |||||||||
1202 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1203, __PRETTY_FUNCTION__)) | ||||||||
1203 | "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1203, __PRETTY_FUNCTION__)); | ||||||||
1204 | |||||||||
1205 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||||||
1206 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||||||
1207 | |||||||||
1208 | QualType LHSElemType = LHSComplex
| ||||||||
1209 | LHSComplex->getElementType() : LHSType; | ||||||||
1210 | QualType RHSElemType = RHSComplex
| ||||||||
1211 | RHSComplex->getElementType() : RHSType; | ||||||||
1212 | |||||||||
1213 | // No issue if the two types have the same representation | ||||||||
1214 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | ||||||||
1215 | &S.Context.getFloatTypeSemantics(RHSElemType)) | ||||||||
1216 | return false; | ||||||||
1217 | |||||||||
1218 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | ||||||||
1219 | RHSElemType == S.Context.LongDoubleTy); | ||||||||
1220 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | ||||||||
1221 | RHSElemType == S.Context.Float128Ty); | ||||||||
1222 | |||||||||
1223 | // We've handled the situation where __float128 and long double have the same | ||||||||
1224 | // representation. We allow all conversions for all possible long double types | ||||||||
1225 | // except PPC's double double. | ||||||||
1226 | return Float128AndLongDouble
| ||||||||
1227 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | ||||||||
1228 | &llvm::APFloat::PPCDoubleDouble()); | ||||||||
1229 | } | ||||||||
1230 | |||||||||
1231 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||||||
1232 | |||||||||
1233 | namespace { | ||||||||
1234 | /// These helper callbacks are placed in an anonymous namespace to | ||||||||
1235 | /// permit their use as function template parameters. | ||||||||
1236 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||||||
1237 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||||||
1238 | } | ||||||||
1239 | |||||||||
1240 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||||||
1241 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||||||
1242 | CK_IntegralComplexCast); | ||||||||
1243 | } | ||||||||
1244 | } | ||||||||
1245 | |||||||||
1246 | /// Handle integer arithmetic conversions. Helper function of | ||||||||
1247 | /// UsualArithmeticConversions() | ||||||||
1248 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||||||
1249 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||||||
1250 | ExprResult &RHS, QualType LHSType, | ||||||||
1251 | QualType RHSType, bool IsCompAssign) { | ||||||||
1252 | // The rules for this case are in C99 6.3.1.8 | ||||||||
1253 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||||||
1254 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||||||
1255 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||||||
1256 | if (LHSSigned == RHSSigned) { | ||||||||
1257 | // Same signedness; use the higher-ranked type | ||||||||
1258 | if (order >= 0) { | ||||||||
1259 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1260 | return LHSType; | ||||||||
1261 | } else if (!IsCompAssign) | ||||||||
1262 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1263 | return RHSType; | ||||||||
1264 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||||||
1265 | // The unsigned type has greater than or equal rank to the | ||||||||
1266 | // signed type, so use the unsigned type | ||||||||
1267 | if (RHSSigned) { | ||||||||
1268 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1269 | return LHSType; | ||||||||
1270 | } else if (!IsCompAssign) | ||||||||
1271 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1272 | return RHSType; | ||||||||
1273 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||||||
1274 | // The two types are different widths; if we are here, that | ||||||||
1275 | // means the signed type is larger than the unsigned type, so | ||||||||
1276 | // use the signed type. | ||||||||
1277 | if (LHSSigned) { | ||||||||
1278 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1279 | return LHSType; | ||||||||
1280 | } else if (!IsCompAssign) | ||||||||
1281 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1282 | return RHSType; | ||||||||
1283 | } else { | ||||||||
1284 | // The signed type is higher-ranked than the unsigned type, | ||||||||
1285 | // but isn't actually any bigger (like unsigned int and long | ||||||||
1286 | // on most 32-bit systems). Use the unsigned type corresponding | ||||||||
1287 | // to the signed type. | ||||||||
1288 | QualType result = | ||||||||
1289 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||||||
1290 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||||||
1291 | if (!IsCompAssign) | ||||||||
1292 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||||||
1293 | return result; | ||||||||
1294 | } | ||||||||
1295 | } | ||||||||
1296 | |||||||||
1297 | /// Handle conversions with GCC complex int extension. Helper function | ||||||||
1298 | /// of UsualArithmeticConversions() | ||||||||
1299 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||||||
1300 | ExprResult &RHS, QualType LHSType, | ||||||||
1301 | QualType RHSType, | ||||||||
1302 | bool IsCompAssign) { | ||||||||
1303 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||||||
1304 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||||||
1305 | |||||||||
1306 | if (LHSComplexInt && RHSComplexInt) { | ||||||||
1307 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||||||
1308 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||||||
1309 | QualType ScalarType = | ||||||||
1310 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||||||
1311 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||||||
1312 | |||||||||
1313 | return S.Context.getComplexType(ScalarType); | ||||||||
1314 | } | ||||||||
1315 | |||||||||
1316 | if (LHSComplexInt) { | ||||||||
1317 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||||||
1318 | QualType ScalarType = | ||||||||
1319 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||||||
1320 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||||||
1321 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||||||
1322 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||||||
1323 | CK_IntegralRealToComplex); | ||||||||
1324 | |||||||||
1325 | return ComplexType; | ||||||||
1326 | } | ||||||||
1327 | |||||||||
1328 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1328, __PRETTY_FUNCTION__)); | ||||||||
1329 | |||||||||
1330 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||||||
1331 | QualType ScalarType = | ||||||||
1332 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||||||
1333 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||||||
1334 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||||||
1335 | |||||||||
1336 | if (!IsCompAssign) | ||||||||
1337 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||||||
1338 | CK_IntegralRealToComplex); | ||||||||
1339 | return ComplexType; | ||||||||
1340 | } | ||||||||
1341 | |||||||||
1342 | /// Return the rank of a given fixed point or integer type. The value itself | ||||||||
1343 | /// doesn't matter, but the values must be increasing with proper increasing | ||||||||
1344 | /// rank as described in N1169 4.1.1. | ||||||||
1345 | static unsigned GetFixedPointRank(QualType Ty) { | ||||||||
1346 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||||||
1347 | assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast< void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1347, __PRETTY_FUNCTION__)); | ||||||||
1348 | |||||||||
1349 | switch (BTy->getKind()) { | ||||||||
1350 | case BuiltinType::ShortFract: | ||||||||
1351 | case BuiltinType::UShortFract: | ||||||||
1352 | case BuiltinType::SatShortFract: | ||||||||
1353 | case BuiltinType::SatUShortFract: | ||||||||
1354 | return 1; | ||||||||
1355 | case BuiltinType::Fract: | ||||||||
1356 | case BuiltinType::UFract: | ||||||||
1357 | case BuiltinType::SatFract: | ||||||||
1358 | case BuiltinType::SatUFract: | ||||||||
1359 | return 2; | ||||||||
1360 | case BuiltinType::LongFract: | ||||||||
1361 | case BuiltinType::ULongFract: | ||||||||
1362 | case BuiltinType::SatLongFract: | ||||||||
1363 | case BuiltinType::SatULongFract: | ||||||||
1364 | return 3; | ||||||||
1365 | case BuiltinType::ShortAccum: | ||||||||
1366 | case BuiltinType::UShortAccum: | ||||||||
1367 | case BuiltinType::SatShortAccum: | ||||||||
1368 | case BuiltinType::SatUShortAccum: | ||||||||
1369 | return 4; | ||||||||
1370 | case BuiltinType::Accum: | ||||||||
1371 | case BuiltinType::UAccum: | ||||||||
1372 | case BuiltinType::SatAccum: | ||||||||
1373 | case BuiltinType::SatUAccum: | ||||||||
1374 | return 5; | ||||||||
1375 | case BuiltinType::LongAccum: | ||||||||
1376 | case BuiltinType::ULongAccum: | ||||||||
1377 | case BuiltinType::SatLongAccum: | ||||||||
1378 | case BuiltinType::SatULongAccum: | ||||||||
1379 | return 6; | ||||||||
1380 | default: | ||||||||
1381 | if (BTy->isInteger()) | ||||||||
1382 | return 0; | ||||||||
1383 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1383); | ||||||||
1384 | } | ||||||||
1385 | } | ||||||||
1386 | |||||||||
1387 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||||||
1388 | /// point types and integers or other fixed point types do not fall under | ||||||||
1389 | /// usual arithmetic conversion since these conversions could result in loss | ||||||||
1390 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||||||
1391 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||||||
1392 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||||||
1393 | QualType RHSTy) { | ||||||||
1394 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1395, __PRETTY_FUNCTION__)) | ||||||||
1395 | "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1395, __PRETTY_FUNCTION__)); | ||||||||
1396 | assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)) | ||||||||
1397 | RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)) | ||||||||
1398 | "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)) | ||||||||
1399 | "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)); | ||||||||
1400 | |||||||||
1401 | // If one operand has signed fixed-point type and the other operand has | ||||||||
1402 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||||||
1403 | // converted to its corresponding signed fixed-point type and the resulting | ||||||||
1404 | // type is the type of the converted operand. | ||||||||
1405 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||||||
1406 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||||||
1407 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||||||
1408 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||||||
1409 | |||||||||
1410 | // The result type is the type with the highest rank, whereby a fixed-point | ||||||||
1411 | // conversion rank is always greater than an integer conversion rank; if the | ||||||||
1412 | // type of either of the operands is a saturating fixedpoint type, the result | ||||||||
1413 | // type shall be the saturating fixed-point type corresponding to the type | ||||||||
1414 | // with the highest rank; the resulting value is converted (taking into | ||||||||
1415 | // account rounding and overflow) to the precision of the resulting type. | ||||||||
1416 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||||||
1417 | // types are either signed or both unsigned at this point. | ||||||||
1418 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||||||
1419 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||||||
1420 | |||||||||
1421 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||||||
1422 | |||||||||
1423 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||||||
1424 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||||||
1425 | |||||||||
1426 | return ResultTy; | ||||||||
1427 | } | ||||||||
1428 | |||||||||
1429 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||||||
1430 | /// expressions that might be of enumeration type. | ||||||||
1431 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||||||
1432 | SourceLocation Loc, | ||||||||
1433 | Sema::ArithConvKind ACK) { | ||||||||
1434 | // C++2a [expr.arith.conv]p1: | ||||||||
1435 | // If one operand is of enumeration type and the other operand is of a | ||||||||
1436 | // different enumeration type or a floating-point type, this behavior is | ||||||||
1437 | // deprecated ([depr.arith.conv.enum]). | ||||||||
1438 | // | ||||||||
1439 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||||||
1440 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||||||
1441 | QualType L = LHS->getType(), R = RHS->getType(); | ||||||||
1442 | bool LEnum = L->isUnscopedEnumerationType(), | ||||||||
1443 | REnum = R->isUnscopedEnumerationType(); | ||||||||
1444 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||||||
1445 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||||||
1446 | (REnum && L->isFloatingType())) { | ||||||||
1447 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||||||
1448 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||||||
1449 | : diag::warn_arith_conv_enum_float) | ||||||||
1450 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
1451 | << (int)ACK << LEnum << L << R; | ||||||||
1452 | } else if (!IsCompAssign && LEnum && REnum && | ||||||||
1453 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||||||
1454 | unsigned DiagID; | ||||||||
1455 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||||||
1456 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||||||
1457 | // If either enumeration type is unnamed, it's less likely that the | ||||||||
1458 | // user cares about this, but this situation is still deprecated in | ||||||||
1459 | // C++2a. Use a different warning group. | ||||||||
1460 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1461 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||||||
1462 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||||||
1463 | } else if (ACK == Sema::ACK_Conditional) { | ||||||||
1464 | // Conditional expressions are separated out because they have | ||||||||
1465 | // historically had a different warning flag. | ||||||||
1466 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1467 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||||||
1468 | : diag::warn_conditional_mixed_enum_types; | ||||||||
1469 | } else if (ACK == Sema::ACK_Comparison) { | ||||||||
1470 | // Comparison expressions are separated out because they have | ||||||||
1471 | // historically had a different warning flag. | ||||||||
1472 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1473 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||||||
1474 | : diag::warn_comparison_mixed_enum_types; | ||||||||
1475 | } else { | ||||||||
1476 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1477 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||||||
1478 | : diag::warn_arith_conv_mixed_enum_types; | ||||||||
1479 | } | ||||||||
1480 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
1481 | << (int)ACK << L << R; | ||||||||
1482 | } | ||||||||
1483 | } | ||||||||
1484 | |||||||||
1485 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||||||
1486 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||||||
1487 | /// routine returns the first non-arithmetic type found. The client is | ||||||||
1488 | /// responsible for emitting appropriate error diagnostics. | ||||||||
1489 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||||||
1490 | SourceLocation Loc, | ||||||||
1491 | ArithConvKind ACK) { | ||||||||
1492 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||||||
1493 | |||||||||
1494 | if (ACK != ACK_CompAssign) { | ||||||||
1495 | LHS = UsualUnaryConversions(LHS.get()); | ||||||||
1496 | if (LHS.isInvalid()) | ||||||||
1497 | return QualType(); | ||||||||
1498 | } | ||||||||
1499 | |||||||||
1500 | RHS = UsualUnaryConversions(RHS.get()); | ||||||||
1501 | if (RHS.isInvalid()) | ||||||||
1502 | return QualType(); | ||||||||
1503 | |||||||||
1504 | // For conversion purposes, we ignore any qualifiers. | ||||||||
1505 | // For example, "const float" and "float" are equivalent. | ||||||||
1506 | QualType LHSType = | ||||||||
1507 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||||||
1508 | QualType RHSType = | ||||||||
1509 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||||||
1510 | |||||||||
1511 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||||||
1512 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||||||
1513 | LHSType = AtomicLHS->getValueType(); | ||||||||
1514 | |||||||||
1515 | // If both types are identical, no conversion is needed. | ||||||||
1516 | if (LHSType == RHSType) | ||||||||
1517 | return LHSType; | ||||||||
1518 | |||||||||
1519 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||||||
1520 | // The caller can deal with this (e.g. pointer + int). | ||||||||
1521 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||||||
1522 | return QualType(); | ||||||||
1523 | |||||||||
1524 | // Apply unary and bitfield promotions to the LHS's type. | ||||||||
1525 | QualType LHSUnpromotedType = LHSType; | ||||||||
1526 | if (LHSType->isPromotableIntegerType()) | ||||||||
1527 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||||||
1528 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||||||
1529 | if (!LHSBitfieldPromoteTy.isNull()) | ||||||||
1530 | LHSType = LHSBitfieldPromoteTy; | ||||||||
1531 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||||||
1532 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||||||
1533 | |||||||||
1534 | // If both types are identical, no conversion is needed. | ||||||||
1535 | if (LHSType == RHSType) | ||||||||
1536 | return LHSType; | ||||||||
1537 | |||||||||
1538 | // ExtInt types aren't subject to conversions between them or normal integers, | ||||||||
1539 | // so this fails. | ||||||||
1540 | if(LHSType->isExtIntType() || RHSType->isExtIntType()) | ||||||||
1541 | return QualType(); | ||||||||
1542 | |||||||||
1543 | // At this point, we have two different arithmetic types. | ||||||||
1544 | |||||||||
1545 | // Diagnose attempts to convert between __float128 and long double where | ||||||||
1546 | // such conversions currently can't be handled. | ||||||||
1547 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||||||
1548 | return QualType(); | ||||||||
1549 | |||||||||
1550 | // Handle complex types first (C99 6.3.1.8p1). | ||||||||
1551 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||||||
1552 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1553 | ACK == ACK_CompAssign); | ||||||||
1554 | |||||||||
1555 | // Now handle "real" floating types (i.e. float, double, long double). | ||||||||
1556 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||||||
1557 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1558 | ACK == ACK_CompAssign); | ||||||||
1559 | |||||||||
1560 | // Handle GCC complex int extension. | ||||||||
1561 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||||||
1562 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1563 | ACK == ACK_CompAssign); | ||||||||
1564 | |||||||||
1565 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||||||
1566 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||||||
1567 | |||||||||
1568 | // Finally, we have two differing integer types. | ||||||||
1569 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||||||
1570 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||||||
1571 | } | ||||||||
1572 | |||||||||
1573 | //===----------------------------------------------------------------------===// | ||||||||
1574 | // Semantic Analysis for various Expression Types | ||||||||
1575 | //===----------------------------------------------------------------------===// | ||||||||
1576 | |||||||||
1577 | |||||||||
1578 | ExprResult | ||||||||
1579 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||||||
1580 | SourceLocation DefaultLoc, | ||||||||
1581 | SourceLocation RParenLoc, | ||||||||
1582 | Expr *ControllingExpr, | ||||||||
1583 | ArrayRef<ParsedType> ArgTypes, | ||||||||
1584 | ArrayRef<Expr *> ArgExprs) { | ||||||||
1585 | unsigned NumAssocs = ArgTypes.size(); | ||||||||
1586 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1586, __PRETTY_FUNCTION__)); | ||||||||
1587 | |||||||||
1588 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||||||
1589 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1590 | if (ArgTypes[i]) | ||||||||
1591 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||||||
1592 | else | ||||||||
1593 | Types[i] = nullptr; | ||||||||
1594 | } | ||||||||
1595 | |||||||||
1596 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||||||
1597 | ControllingExpr, | ||||||||
1598 | llvm::makeArrayRef(Types, NumAssocs), | ||||||||
1599 | ArgExprs); | ||||||||
1600 | delete [] Types; | ||||||||
1601 | return ER; | ||||||||
1602 | } | ||||||||
1603 | |||||||||
1604 | ExprResult | ||||||||
1605 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||||||
1606 | SourceLocation DefaultLoc, | ||||||||
1607 | SourceLocation RParenLoc, | ||||||||
1608 | Expr *ControllingExpr, | ||||||||
1609 | ArrayRef<TypeSourceInfo *> Types, | ||||||||
1610 | ArrayRef<Expr *> Exprs) { | ||||||||
1611 | unsigned NumAssocs = Types.size(); | ||||||||
1612 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1612, __PRETTY_FUNCTION__)); | ||||||||
1613 | |||||||||
1614 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||||||
1615 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||||||
1616 | { | ||||||||
1617 | EnterExpressionEvaluationContext Unevaluated( | ||||||||
1618 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||||||
1619 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||||||
1620 | if (R.isInvalid()) | ||||||||
1621 | return ExprError(); | ||||||||
1622 | ControllingExpr = R.get(); | ||||||||
1623 | } | ||||||||
1624 | |||||||||
1625 | // The controlling expression is an unevaluated operand, so side effects are | ||||||||
1626 | // likely unintended. | ||||||||
1627 | if (!inTemplateInstantiation() && | ||||||||
1628 | ControllingExpr->HasSideEffects(Context, false)) | ||||||||
1629 | Diag(ControllingExpr->getExprLoc(), | ||||||||
1630 | diag::warn_side_effects_unevaluated_context); | ||||||||
1631 | |||||||||
1632 | bool TypeErrorFound = false, | ||||||||
1633 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||||||
1634 | ContainsUnexpandedParameterPack | ||||||||
1635 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||||||
1636 | |||||||||
1637 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1638 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||||||
1639 | ContainsUnexpandedParameterPack = true; | ||||||||
1640 | |||||||||
1641 | if (Types[i]) { | ||||||||
1642 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||||||
1643 | ContainsUnexpandedParameterPack = true; | ||||||||
1644 | |||||||||
1645 | if (Types[i]->getType()->isDependentType()) { | ||||||||
1646 | IsResultDependent = true; | ||||||||
1647 | } else { | ||||||||
1648 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||||||
1649 | // complete object type other than a variably modified type." | ||||||||
1650 | unsigned D = 0; | ||||||||
1651 | if (Types[i]->getType()->isIncompleteType()) | ||||||||
1652 | D = diag::err_assoc_type_incomplete; | ||||||||
1653 | else if (!Types[i]->getType()->isObjectType()) | ||||||||
1654 | D = diag::err_assoc_type_nonobject; | ||||||||
1655 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||||||
1656 | D = diag::err_assoc_type_variably_modified; | ||||||||
1657 | |||||||||
1658 | if (D != 0) { | ||||||||
1659 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||||||
1660 | << Types[i]->getTypeLoc().getSourceRange() | ||||||||
1661 | << Types[i]->getType(); | ||||||||
1662 | TypeErrorFound = true; | ||||||||
1663 | } | ||||||||
1664 | |||||||||
1665 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||||||
1666 | // selection shall specify compatible types." | ||||||||
1667 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||||||
1668 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||||||
1669 | Context.typesAreCompatible(Types[i]->getType(), | ||||||||
1670 | Types[j]->getType())) { | ||||||||
1671 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||||||
1672 | diag::err_assoc_compatible_types) | ||||||||
1673 | << Types[j]->getTypeLoc().getSourceRange() | ||||||||
1674 | << Types[j]->getType() | ||||||||
1675 | << Types[i]->getType(); | ||||||||
1676 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||||||
1677 | diag::note_compat_assoc) | ||||||||
1678 | << Types[i]->getTypeLoc().getSourceRange() | ||||||||
1679 | << Types[i]->getType(); | ||||||||
1680 | TypeErrorFound = true; | ||||||||
1681 | } | ||||||||
1682 | } | ||||||||
1683 | } | ||||||||
1684 | } | ||||||||
1685 | if (TypeErrorFound) | ||||||||
1686 | return ExprError(); | ||||||||
1687 | |||||||||
1688 | // If we determined that the generic selection is result-dependent, don't | ||||||||
1689 | // try to compute the result expression. | ||||||||
1690 | if (IsResultDependent) | ||||||||
1691 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||||||
1692 | Exprs, DefaultLoc, RParenLoc, | ||||||||
1693 | ContainsUnexpandedParameterPack); | ||||||||
1694 | |||||||||
1695 | SmallVector<unsigned, 1> CompatIndices; | ||||||||
1696 | unsigned DefaultIndex = -1U; | ||||||||
1697 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1698 | if (!Types[i]) | ||||||||
1699 | DefaultIndex = i; | ||||||||
1700 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | ||||||||
1701 | Types[i]->getType())) | ||||||||
1702 | CompatIndices.push_back(i); | ||||||||
1703 | } | ||||||||
1704 | |||||||||
1705 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||||||
1706 | // type compatible with at most one of the types named in its generic | ||||||||
1707 | // association list." | ||||||||
1708 | if (CompatIndices.size() > 1) { | ||||||||
1709 | // We strip parens here because the controlling expression is typically | ||||||||
1710 | // parenthesized in macro definitions. | ||||||||
1711 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||||||
1712 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||||||
1713 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||||||
1714 | << (unsigned)CompatIndices.size(); | ||||||||
1715 | for (unsigned I : CompatIndices) { | ||||||||
1716 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||||||
1717 | diag::note_compat_assoc) | ||||||||
1718 | << Types[I]->getTypeLoc().getSourceRange() | ||||||||
1719 | << Types[I]->getType(); | ||||||||
1720 | } | ||||||||
1721 | return ExprError(); | ||||||||
1722 | } | ||||||||
1723 | |||||||||
1724 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||||||
1725 | // its controlling expression shall have type compatible with exactly one of | ||||||||
1726 | // the types named in its generic association list." | ||||||||
1727 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||||||
1728 | // We strip parens here because the controlling expression is typically | ||||||||
1729 | // parenthesized in macro definitions. | ||||||||
1730 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||||||
1731 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||||||
1732 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||||||
1733 | return ExprError(); | ||||||||
1734 | } | ||||||||
1735 | |||||||||
1736 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||||||
1737 | // type name that is compatible with the type of the controlling expression, | ||||||||
1738 | // then the result expression of the generic selection is the expression | ||||||||
1739 | // in that generic association. Otherwise, the result expression of the | ||||||||
1740 | // generic selection is the expression in the default generic association." | ||||||||
1741 | unsigned ResultIndex = | ||||||||
1742 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||||||
1743 | |||||||||
1744 | return GenericSelectionExpr::Create( | ||||||||
1745 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||||||
1746 | ContainsUnexpandedParameterPack, ResultIndex); | ||||||||
1747 | } | ||||||||
1748 | |||||||||
1749 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||||||
1750 | /// location of the token and the offset of the ud-suffix within it. | ||||||||
1751 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||||||
1752 | unsigned Offset) { | ||||||||
1753 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||||||
1754 | S.getLangOpts()); | ||||||||
1755 | } | ||||||||
1756 | |||||||||
1757 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||||||
1758 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||||||
1759 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||||||
1760 | IdentifierInfo *UDSuffix, | ||||||||
1761 | SourceLocation UDSuffixLoc, | ||||||||
1762 | ArrayRef<Expr*> Args, | ||||||||
1763 | SourceLocation LitEndLoc) { | ||||||||
1764 | assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator" ) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1764, __PRETTY_FUNCTION__)); | ||||||||
1765 | |||||||||
1766 | QualType ArgTy[2]; | ||||||||
1767 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||||||
1768 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||||||
1769 | if (ArgTy[ArgIdx]->isArrayType()) | ||||||||
1770 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||||||
1771 | } | ||||||||
1772 | |||||||||
1773 | DeclarationName OpName = | ||||||||
1774 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
1775 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
1776 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
1777 | |||||||||
1778 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||||||
1779 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||||||
1780 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||||||
1781 | /*AllowStringTemplatePack*/ false, | ||||||||
1782 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||||||
1783 | return ExprError(); | ||||||||
1784 | |||||||||
1785 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||||||
1786 | } | ||||||||
1787 | |||||||||
1788 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||||||
1789 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||||||
1790 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||||||
1791 | /// multiple tokens. However, the common case is that StringToks points to one | ||||||||
1792 | /// string. | ||||||||
1793 | /// | ||||||||
1794 | ExprResult | ||||||||
1795 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||||||
1796 | assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!" ) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1796, __PRETTY_FUNCTION__)); | ||||||||
1797 | |||||||||
1798 | StringLiteralParser Literal(StringToks, PP); | ||||||||
1799 | if (Literal.hadError) | ||||||||
1800 | return ExprError(); | ||||||||
1801 | |||||||||
1802 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||||||
1803 | for (const Token &Tok : StringToks) | ||||||||
1804 | StringTokLocs.push_back(Tok.getLocation()); | ||||||||
1805 | |||||||||
1806 | QualType CharTy = Context.CharTy; | ||||||||
1807 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | ||||||||
1808 | if (Literal.isWide()) { | ||||||||
1809 | CharTy = Context.getWideCharType(); | ||||||||
1810 | Kind = StringLiteral::Wide; | ||||||||
1811 | } else if (Literal.isUTF8()) { | ||||||||
1812 | if (getLangOpts().Char8) | ||||||||
1813 | CharTy = Context.Char8Ty; | ||||||||
1814 | Kind = StringLiteral::UTF8; | ||||||||
1815 | } else if (Literal.isUTF16()) { | ||||||||
1816 | CharTy = Context.Char16Ty; | ||||||||
1817 | Kind = StringLiteral::UTF16; | ||||||||
1818 | } else if (Literal.isUTF32()) { | ||||||||
1819 | CharTy = Context.Char32Ty; | ||||||||
1820 | Kind = StringLiteral::UTF32; | ||||||||
1821 | } else if (Literal.isPascal()) { | ||||||||
1822 | CharTy = Context.UnsignedCharTy; | ||||||||
1823 | } | ||||||||
1824 | |||||||||
1825 | // Warn on initializing an array of char from a u8 string literal; this | ||||||||
1826 | // becomes ill-formed in C++2a. | ||||||||
1827 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||||||
1828 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||||||
1829 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||||||
1830 | |||||||||
1831 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||||||
1832 | // ensures C++2a compatibility (but may change the program behavior when | ||||||||
1833 | // built by non-Clang compilers for which the execution character set is | ||||||||
1834 | // not always UTF-8). | ||||||||
1835 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||||||
1836 | SourceLocation RemovalDiagLoc; | ||||||||
1837 | for (const Token &Tok : StringToks) { | ||||||||
1838 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||||||
1839 | if (RemovalDiagLoc.isInvalid()) | ||||||||
1840 | RemovalDiagLoc = Tok.getLocation(); | ||||||||
1841 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||||||
1842 | Tok.getLocation(), | ||||||||
1843 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||||||
1844 | getSourceManager(), getLangOpts()))); | ||||||||
1845 | } | ||||||||
1846 | } | ||||||||
1847 | Diag(RemovalDiagLoc, RemovalDiag); | ||||||||
1848 | } | ||||||||
1849 | |||||||||
1850 | QualType StrTy = | ||||||||
1851 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||||||
1852 | |||||||||
1853 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||||||
1854 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||||||
1855 | Kind, Literal.Pascal, StrTy, | ||||||||
1856 | &StringTokLocs[0], | ||||||||
1857 | StringTokLocs.size()); | ||||||||
1858 | if (Literal.getUDSuffix().empty()) | ||||||||
1859 | return Lit; | ||||||||
1860 | |||||||||
1861 | // We're building a user-defined literal. | ||||||||
1862 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
1863 | SourceLocation UDSuffixLoc = | ||||||||
1864 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||||||
1865 | Literal.getUDSuffixOffset()); | ||||||||
1866 | |||||||||
1867 | // Make sure we're allowed user-defined literals here. | ||||||||
1868 | if (!UDLScope) | ||||||||
1869 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||||||
1870 | |||||||||
1871 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||||||
1872 | // operator "" X (str, len) | ||||||||
1873 | QualType SizeType = Context.getSizeType(); | ||||||||
1874 | |||||||||
1875 | DeclarationName OpName = | ||||||||
1876 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
1877 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
1878 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
1879 | |||||||||
1880 | QualType ArgTy[] = { | ||||||||
1881 | Context.getArrayDecayedType(StrTy), SizeType | ||||||||
1882 | }; | ||||||||
1883 | |||||||||
1884 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||||||
1885 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||||||
1886 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||||||
1887 | /*AllowStringTemplatePack*/ true, | ||||||||
1888 | /*DiagnoseMissing*/ true, Lit)) { | ||||||||
1889 | |||||||||
1890 | case LOLR_Cooked: { | ||||||||
1891 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||||||
1892 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||||||
1893 | StringTokLocs[0]); | ||||||||
1894 | Expr *Args[] = { Lit, LenArg }; | ||||||||
1895 | |||||||||
1896 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||||||
1897 | } | ||||||||
1898 | |||||||||
1899 | case LOLR_Template: { | ||||||||
1900 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
1901 | TemplateArgument Arg(Lit); | ||||||||
1902 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||||||
1903 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
1904 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||||||
1905 | &ExplicitArgs); | ||||||||
1906 | } | ||||||||
1907 | |||||||||
1908 | case LOLR_StringTemplatePack: { | ||||||||
1909 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
1910 | |||||||||
1911 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||||||
1912 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||||||
1913 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||||||
1914 | |||||||||
1915 | TemplateArgument TypeArg(CharTy); | ||||||||
1916 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||||||
1917 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||||||
1918 | |||||||||
1919 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||||||
1920 | Value = Lit->getCodeUnit(I); | ||||||||
1921 | TemplateArgument Arg(Context, Value, CharTy); | ||||||||
1922 | TemplateArgumentLocInfo ArgInfo; | ||||||||
1923 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
1924 | } | ||||||||
1925 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||||||
1926 | &ExplicitArgs); | ||||||||
1927 | } | ||||||||
1928 | case LOLR_Raw: | ||||||||
1929 | case LOLR_ErrorNoDiagnostic: | ||||||||
1930 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1930); | ||||||||
1931 | case LOLR_Error: | ||||||||
1932 | return ExprError(); | ||||||||
1933 | } | ||||||||
1934 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1934); | ||||||||
1935 | } | ||||||||
1936 | |||||||||
1937 | DeclRefExpr * | ||||||||
1938 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1939 | SourceLocation Loc, | ||||||||
1940 | const CXXScopeSpec *SS) { | ||||||||
1941 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||||||
1942 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||||||
1943 | } | ||||||||
1944 | |||||||||
1945 | DeclRefExpr * | ||||||||
1946 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1947 | const DeclarationNameInfo &NameInfo, | ||||||||
1948 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||||||
1949 | SourceLocation TemplateKWLoc, | ||||||||
1950 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
1951 | NestedNameSpecifierLoc NNS = | ||||||||
1952 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||||||
1953 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||||||
1954 | TemplateArgs); | ||||||||
1955 | } | ||||||||
1956 | |||||||||
1957 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||||||
1958 | // host variable in a device or host device lambda. | ||||||||
1959 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||||||
1960 | VarDecl *VD) { | ||||||||
1961 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||||||
1962 | return false; | ||||||||
1963 | assert(VD->getType()->isReferenceType())((VD->getType()->isReferenceType()) ? static_cast<void > (0) : __assert_fail ("VD->getType()->isReferenceType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 1963, __PRETTY_FUNCTION__)); | ||||||||
1964 | |||||||||
1965 | // Check whether the reference variable is referencing a host variable. | ||||||||
1966 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||||||
1967 | if (!DRE) | ||||||||
1968 | return false; | ||||||||
1969 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||||||
1970 | if (!Referee || !Referee->hasGlobalStorage() || | ||||||||
1971 | Referee->hasAttr<CUDADeviceAttr>()) | ||||||||
1972 | return false; | ||||||||
1973 | |||||||||
1974 | // Check whether the current function is a device or host device lambda. | ||||||||
1975 | // Check whether the reference variable is a capture by getDeclContext() | ||||||||
1976 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||||||
1977 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||||||
1978 | if (MD && MD->getParent()->isLambda() && | ||||||||
1979 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||||||
1980 | VD->getDeclContext() != MD) | ||||||||
1981 | return true; | ||||||||
1982 | |||||||||
1983 | return false; | ||||||||
1984 | } | ||||||||
1985 | |||||||||
1986 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||||||
1987 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||||||
1988 | if (isUnevaluatedContext()) | ||||||||
1989 | return NOUR_Unevaluated; | ||||||||
1990 | |||||||||
1991 | // C++2a [basic.def.odr]p4: | ||||||||
1992 | // A variable x whose name appears as a potentially-evaluated expression e | ||||||||
1993 | // is odr-used by e unless [...] x is a reference that is usable in | ||||||||
1994 | // constant expressions. | ||||||||
1995 | // CUDA/HIP: | ||||||||
1996 | // If a reference variable referencing a host variable is captured in a | ||||||||
1997 | // device or host device lambda, the value of the referee must be copied | ||||||||
1998 | // to the capture and the reference variable must be treated as odr-use | ||||||||
1999 | // since the value of the referee is not known at compile time and must | ||||||||
2000 | // be loaded from the captured. | ||||||||
2001 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||||
2002 | if (VD->getType()->isReferenceType() && | ||||||||
2003 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||||||
2004 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||||||
2005 | VD->isUsableInConstantExpressions(Context)) | ||||||||
2006 | return NOUR_Constant; | ||||||||
2007 | } | ||||||||
2008 | |||||||||
2009 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||||||
2010 | // need to wait and see how the expression is used. | ||||||||
2011 | return NOUR_None; | ||||||||
2012 | } | ||||||||
2013 | |||||||||
2014 | /// BuildDeclRefExpr - Build an expression that references a | ||||||||
2015 | /// declaration that does not require a closure capture. | ||||||||
2016 | DeclRefExpr * | ||||||||
2017 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
2018 | const DeclarationNameInfo &NameInfo, | ||||||||
2019 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||||||
2020 | SourceLocation TemplateKWLoc, | ||||||||
2021 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
2022 | bool RefersToCapturedVariable = | ||||||||
2023 | isa<VarDecl>(D) && | ||||||||
2024 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | ||||||||
2025 | |||||||||
2026 | DeclRefExpr *E = DeclRefExpr::Create( | ||||||||
2027 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||||||
2028 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||||||
2029 | MarkDeclRefReferenced(E); | ||||||||
2030 | |||||||||
2031 | // C++ [except.spec]p17: | ||||||||
2032 | // An exception-specification is considered to be needed when: | ||||||||
2033 | // - in an expression, the function is the unique lookup result or | ||||||||
2034 | // the selected member of a set of overloaded functions. | ||||||||
2035 | // | ||||||||
2036 | // We delay doing this until after we've built the function reference and | ||||||||
2037 | // marked it as used so that: | ||||||||
2038 | // a) if the function is defaulted, we get errors from defining it before / | ||||||||
2039 | // instead of errors from computing its exception specification, and | ||||||||
2040 | // b) if the function is a defaulted comparison, we can use the body we | ||||||||
2041 | // build when defining it as input to the exception specification | ||||||||
2042 | // computation rather than computing a new body. | ||||||||
2043 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||||||
2044 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||||||
2045 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||||||
2046 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||||||
2047 | } | ||||||||
2048 | } | ||||||||
2049 | |||||||||
2050 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||||||
2051 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||||||
2052 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||||||
2053 | getCurFunction()->recordUseOfWeak(E); | ||||||||
2054 | |||||||||
2055 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||||||
2056 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||||||
2057 | FD = IFD->getAnonField(); | ||||||||
2058 | if (FD) { | ||||||||
2059 | UnusedPrivateFields.remove(FD); | ||||||||
2060 | // Just in case we're building an illegal pointer-to-member. | ||||||||
2061 | if (FD->isBitField()) | ||||||||
2062 | E->setObjectKind(OK_BitField); | ||||||||
2063 | } | ||||||||
2064 | |||||||||
2065 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||||||
2066 | // designates a bit-field. | ||||||||
2067 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||||||
2068 | if (auto *BE = BD->getBinding()) | ||||||||
2069 | E->setObjectKind(BE->getObjectKind()); | ||||||||
2070 | |||||||||
2071 | return E; | ||||||||
2072 | } | ||||||||
2073 | |||||||||
2074 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||||||
2075 | /// possibly a list of template arguments. | ||||||||
2076 | /// | ||||||||
2077 | /// If this produces template arguments, it is permitted to call | ||||||||
2078 | /// DecomposeTemplateName. | ||||||||
2079 | /// | ||||||||
2080 | /// This actually loses a lot of source location information for | ||||||||
2081 | /// non-standard name kinds; we should consider preserving that in | ||||||||
2082 | /// some way. | ||||||||
2083 | void | ||||||||
2084 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||||||
2085 | TemplateArgumentListInfo &Buffer, | ||||||||
2086 | DeclarationNameInfo &NameInfo, | ||||||||
2087 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||||||
2088 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||||
2089 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||||||
2090 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||||||
2091 | |||||||||
2092 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||||||
2093 | Id.TemplateId->NumArgs); | ||||||||
2094 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||||||
2095 | |||||||||
2096 | TemplateName TName = Id.TemplateId->Template.get(); | ||||||||
2097 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||||||
2098 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||||||
2099 | TemplateArgs = &Buffer; | ||||||||
2100 | } else { | ||||||||
2101 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||||||
2102 | TemplateArgs = nullptr; | ||||||||
2103 | } | ||||||||
2104 | } | ||||||||
2105 | |||||||||
2106 | static void emitEmptyLookupTypoDiagnostic( | ||||||||
2107 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||||||
2108 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||||||
2109 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||||||
2110 | DeclContext *Ctx = | ||||||||
2111 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||||||
2112 | if (!TC) { | ||||||||
2113 | // Emit a special diagnostic for failed member lookups. | ||||||||
2114 | // FIXME: computing the declaration context might fail here (?) | ||||||||
2115 | if (Ctx) | ||||||||
2116 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||||||
2117 | << SS.getRange(); | ||||||||
2118 | else | ||||||||
2119 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||||||
2120 | return; | ||||||||
2121 | } | ||||||||
2122 | |||||||||
2123 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||||||
2124 | bool DroppedSpecifier = | ||||||||
2125 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||||||
2126 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||||||
2127 | ? diag::note_implicit_param_decl | ||||||||
2128 | : diag::note_previous_decl; | ||||||||
2129 | if (!Ctx) | ||||||||
2130 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||||||
2131 | SemaRef.PDiag(NoteID)); | ||||||||
2132 | else | ||||||||
2133 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||||||
2134 | << Typo << Ctx << DroppedSpecifier | ||||||||
2135 | << SS.getRange(), | ||||||||
2136 | SemaRef.PDiag(NoteID)); | ||||||||
2137 | } | ||||||||
2138 | |||||||||
2139 | /// Diagnose a lookup that found results in an enclosing class during error | ||||||||
2140 | /// recovery. This usually indicates that the results were found in a dependent | ||||||||
2141 | /// base class that could not be searched as part of a template definition. | ||||||||
2142 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||||||
2143 | /// compatibility mode). | ||||||||
2144 | /// | ||||||||
2145 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||||||
2146 | /// should attempt to recover using these lookup results. | ||||||||
2147 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||||||
2148 | // During a default argument instantiation the CurContext points | ||||||||
2149 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||||||
2150 | // function parameter list, hence add an explicit check. | ||||||||
2151 | bool isDefaultArgument = | ||||||||
2152 | !CodeSynthesisContexts.empty() && | ||||||||
2153 | CodeSynthesisContexts.back().Kind == | ||||||||
2154 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||||||
2155 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||||||
2156 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||||||
2157 | R.getNamingClass() == CurMethod->getParent() && | ||||||||
2158 | !isDefaultArgument; | ||||||||
2159 | |||||||||
2160 | // There are two ways we can find a class-scope declaration during template | ||||||||
2161 | // instantiation that we did not find in the template definition: if it is a | ||||||||
2162 | // member of a dependent base class, or if it is declared after the point of | ||||||||
2163 | // use in the same class. Distinguish these by comparing the class in which | ||||||||
2164 | // the member was found to the naming class of the lookup. | ||||||||
2165 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||||||
2166 | unsigned NoteID = diag::note_member_declared_at; | ||||||||
2167 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||||||
2168 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||||||
2169 | : diag::err_found_later_in_class; | ||||||||
2170 | } else if (getLangOpts().MSVCCompat) { | ||||||||
2171 | DiagID = diag::ext_found_in_dependent_base; | ||||||||
2172 | NoteID = diag::note_dependent_member_use; | ||||||||
2173 | } | ||||||||
2174 | |||||||||
2175 | if (isInstance) { | ||||||||
2176 | // Give a code modification hint to insert 'this->'. | ||||||||
2177 | Diag(R.getNameLoc(), DiagID) | ||||||||
2178 | << R.getLookupName() | ||||||||
2179 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||||||
2180 | CheckCXXThisCapture(R.getNameLoc()); | ||||||||
2181 | } else { | ||||||||
2182 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||||||
2183 | // they're not shadowed). | ||||||||
2184 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||||||
2185 | } | ||||||||
2186 | |||||||||
2187 | for (NamedDecl *D : R) | ||||||||
2188 | Diag(D->getLocation(), NoteID); | ||||||||
2189 | |||||||||
2190 | // Return true if we are inside a default argument instantiation | ||||||||
2191 | // and the found name refers to an instance member function, otherwise | ||||||||
2192 | // the caller will try to create an implicit member call and this is wrong | ||||||||
2193 | // for default arguments. | ||||||||
2194 | // | ||||||||
2195 | // FIXME: Is this special case necessary? We could allow the caller to | ||||||||
2196 | // diagnose this. | ||||||||
2197 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||||||
2198 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||||||
2199 | return true; | ||||||||
2200 | } | ||||||||
2201 | |||||||||
2202 | // Tell the callee to try to recover. | ||||||||
2203 | return false; | ||||||||
2204 | } | ||||||||
2205 | |||||||||
2206 | /// Diagnose an empty lookup. | ||||||||
2207 | /// | ||||||||
2208 | /// \return false if new lookup candidates were found | ||||||||
2209 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||||||
2210 | CorrectionCandidateCallback &CCC, | ||||||||
2211 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||||||
2212 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||||||
2213 | DeclarationName Name = R.getLookupName(); | ||||||||
2214 | |||||||||
2215 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||||||
2216 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||||||
2217 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||||||
2218 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||||||
2219 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||||||
2220 | diagnostic = diag::err_undeclared_use; | ||||||||
2221 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||||||
2222 | } | ||||||||
2223 | |||||||||
2224 | // If the original lookup was an unqualified lookup, fake an | ||||||||
2225 | // unqualified lookup. This is useful when (for example) the | ||||||||
2226 | // original lookup would not have found something because it was a | ||||||||
2227 | // dependent name. | ||||||||
2228 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||||||
2229 | while (DC) { | ||||||||
2230 | if (isa<CXXRecordDecl>(DC)) { | ||||||||
2231 | LookupQualifiedName(R, DC); | ||||||||
2232 | |||||||||
2233 | if (!R.empty()) { | ||||||||
2234 | // Don't give errors about ambiguities in this lookup. | ||||||||
2235 | R.suppressDiagnostics(); | ||||||||
2236 | |||||||||
2237 | // If there's a best viable function among the results, only mention | ||||||||
2238 | // that one in the notes. | ||||||||
2239 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||||||
2240 | OverloadCandidateSet::CSK_Normal); | ||||||||
2241 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||||||
2242 | OverloadCandidateSet::iterator Best; | ||||||||
2243 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||||||
2244 | OR_Success) { | ||||||||
2245 | R.clear(); | ||||||||
2246 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||||||
2247 | R.resolveKind(); | ||||||||
2248 | } | ||||||||
2249 | |||||||||
2250 | return DiagnoseDependentMemberLookup(R); | ||||||||
2251 | } | ||||||||
2252 | |||||||||
2253 | R.clear(); | ||||||||
2254 | } | ||||||||
2255 | |||||||||
2256 | DC = DC->getLookupParent(); | ||||||||
2257 | } | ||||||||
2258 | |||||||||
2259 | // We didn't find anything, so try to correct for a typo. | ||||||||
2260 | TypoCorrection Corrected; | ||||||||
2261 | if (S && Out) { | ||||||||
2262 | SourceLocation TypoLoc = R.getNameLoc(); | ||||||||
2263 | assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2264, __PRETTY_FUNCTION__)) | ||||||||
2264 | "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2264, __PRETTY_FUNCTION__)); | ||||||||
2265 | *Out = CorrectTypoDelayed( | ||||||||
2266 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||||||
2267 | [=](const TypoCorrection &TC) { | ||||||||
2268 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||||||
2269 | diagnostic, diagnostic_suggest); | ||||||||
2270 | }, | ||||||||
2271 | nullptr, CTK_ErrorRecovery); | ||||||||
2272 | if (*Out) | ||||||||
2273 | return true; | ||||||||
2274 | } else if (S && | ||||||||
2275 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||||||
2276 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||||||
2277 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||||
2278 | bool DroppedSpecifier = | ||||||||
2279 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||||||
2280 | R.setLookupName(Corrected.getCorrection()); | ||||||||
2281 | |||||||||
2282 | bool AcceptableWithRecovery = false; | ||||||||
2283 | bool AcceptableWithoutRecovery = false; | ||||||||
2284 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||||||
2285 | if (ND) { | ||||||||
2286 | if (Corrected.isOverloaded()) { | ||||||||
2287 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||||||
2288 | OverloadCandidateSet::CSK_Normal); | ||||||||
2289 | OverloadCandidateSet::iterator Best; | ||||||||
2290 | for (NamedDecl *CD : Corrected) { | ||||||||
2291 | if (FunctionTemplateDecl *FTD = | ||||||||
2292 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||||||
2293 | AddTemplateOverloadCandidate( | ||||||||
2294 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||||||
2295 | Args, OCS); | ||||||||
2296 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||||||
2297 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||||||
2298 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||||||
2299 | Args, OCS); | ||||||||
2300 | } | ||||||||
2301 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||||||
2302 | case OR_Success: | ||||||||
2303 | ND = Best->FoundDecl; | ||||||||
2304 | Corrected.setCorrectionDecl(ND); | ||||||||
2305 | break; | ||||||||
2306 | default: | ||||||||
2307 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||||||
2308 | Corrected.setCorrectionDecl(ND); | ||||||||
2309 | break; | ||||||||
2310 | } | ||||||||
2311 | } | ||||||||
2312 | R.addDecl(ND); | ||||||||
2313 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||||||
2314 | CXXRecordDecl *Record = nullptr; | ||||||||
2315 | if (Corrected.getCorrectionSpecifier()) { | ||||||||
2316 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||||||
2317 | Record = Ty->getAsCXXRecordDecl(); | ||||||||
2318 | } | ||||||||
2319 | if (!Record) | ||||||||
2320 | Record = cast<CXXRecordDecl>( | ||||||||
2321 | ND->getDeclContext()->getRedeclContext()); | ||||||||
2322 | R.setNamingClass(Record); | ||||||||
2323 | } | ||||||||
2324 | |||||||||
2325 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||||||
2326 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||||||
2327 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||||||
2328 | // FIXME: If we ended up with a typo for a type name or | ||||||||
2329 | // Objective-C class name, we're in trouble because the parser | ||||||||
2330 | // is in the wrong place to recover. Suggest the typo | ||||||||
2331 | // correction, but don't make it a fix-it since we're not going | ||||||||
2332 | // to recover well anyway. | ||||||||
2333 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||||||
2334 | getAsTypeTemplateDecl(UnderlyingND) || | ||||||||
2335 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||||||
2336 | } else { | ||||||||
2337 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||||||
2338 | // because we aren't able to recover. | ||||||||
2339 | AcceptableWithoutRecovery = true; | ||||||||
2340 | } | ||||||||
2341 | |||||||||
2342 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||||||
2343 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||||||
2344 | ? diag::note_implicit_param_decl | ||||||||
2345 | : diag::note_previous_decl; | ||||||||
2346 | if (SS.isEmpty()) | ||||||||
2347 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||||||
2348 | PDiag(NoteID), AcceptableWithRecovery); | ||||||||
2349 | else | ||||||||
2350 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||||||
2351 | << Name << computeDeclContext(SS, false) | ||||||||
2352 | << DroppedSpecifier << SS.getRange(), | ||||||||
2353 | PDiag(NoteID), AcceptableWithRecovery); | ||||||||
2354 | |||||||||
2355 | // Tell the callee whether to try to recover. | ||||||||
2356 | return !AcceptableWithRecovery; | ||||||||
2357 | } | ||||||||
2358 | } | ||||||||
2359 | R.clear(); | ||||||||
2360 | |||||||||
2361 | // Emit a special diagnostic for failed member lookups. | ||||||||
2362 | // FIXME: computing the declaration context might fail here (?) | ||||||||
2363 | if (!SS.isEmpty()) { | ||||||||
2364 | Diag(R.getNameLoc(), diag::err_no_member) | ||||||||
2365 | << Name << computeDeclContext(SS, false) | ||||||||
2366 | << SS.getRange(); | ||||||||
2367 | return true; | ||||||||
2368 | } | ||||||||
2369 | |||||||||
2370 | // Give up, we can't recover. | ||||||||
2371 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||||||
2372 | return true; | ||||||||
2373 | } | ||||||||
2374 | |||||||||
2375 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||||||
2376 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||||||
2377 | /// assume the identifier is a member of a dependent base class. We can only | ||||||||
2378 | /// recover successfully in static methods, instance methods, and other contexts | ||||||||
2379 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||||||
2380 | /// instantiation model, but it's close enough. | ||||||||
2381 | static Expr * | ||||||||
2382 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||||||
2383 | DeclarationNameInfo &NameInfo, | ||||||||
2384 | SourceLocation TemplateKWLoc, | ||||||||
2385 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
2386 | // Only try to recover from lookup into dependent bases in static methods or | ||||||||
2387 | // contexts where 'this' is available. | ||||||||
2388 | QualType ThisType = S.getCurrentThisType(); | ||||||||
2389 | const CXXRecordDecl *RD = nullptr; | ||||||||
2390 | if (!ThisType.isNull()) | ||||||||
2391 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||||||
2392 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||||||
2393 | RD = MD->getParent(); | ||||||||
2394 | if (!RD || !RD->hasAnyDependentBases()) | ||||||||
2395 | return nullptr; | ||||||||
2396 | |||||||||
2397 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||||||
2398 | // is available, suggest inserting 'this->' as a fixit. | ||||||||
2399 | SourceLocation Loc = NameInfo.getLoc(); | ||||||||
2400 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||||||
2401 | DB << NameInfo.getName() << RD; | ||||||||
2402 | |||||||||
2403 | if (!ThisType.isNull()) { | ||||||||
2404 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||||||
2405 | return CXXDependentScopeMemberExpr::Create( | ||||||||
2406 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||||||
2407 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||||||
2408 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||||||
2409 | } | ||||||||
2410 | |||||||||
2411 | // Synthesize a fake NNS that points to the derived class. This will | ||||||||
2412 | // perform name lookup during template instantiation. | ||||||||
2413 | CXXScopeSpec SS; | ||||||||
2414 | auto *NNS = | ||||||||
2415 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||||||
2416 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||||||
2417 | return DependentScopeDeclRefExpr::Create( | ||||||||
2418 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||||||
2419 | TemplateArgs); | ||||||||
2420 | } | ||||||||
2421 | |||||||||
2422 | ExprResult | ||||||||
2423 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||||||
2424 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||||||
2425 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||||||
2426 | CorrectionCandidateCallback *CCC, | ||||||||
2427 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||||||
2428 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2429, __PRETTY_FUNCTION__)) | ||||||||
2429 | "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2429, __PRETTY_FUNCTION__)); | ||||||||
2430 | if (SS.isInvalid()) | ||||||||
2431 | return ExprError(); | ||||||||
2432 | |||||||||
2433 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||||||
2434 | |||||||||
2435 | // Decompose the UnqualifiedId into the following data. | ||||||||
2436 | DeclarationNameInfo NameInfo; | ||||||||
2437 | const TemplateArgumentListInfo *TemplateArgs; | ||||||||
2438 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||||||
2439 | |||||||||
2440 | DeclarationName Name = NameInfo.getName(); | ||||||||
2441 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||||
2442 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||||||
2443 | |||||||||
2444 | if (II && II->isEditorPlaceholder()) { | ||||||||
2445 | // FIXME: When typed placeholders are supported we can create a typed | ||||||||
2446 | // placeholder expression node. | ||||||||
2447 | return ExprError(); | ||||||||
2448 | } | ||||||||
2449 | |||||||||
2450 | // C++ [temp.dep.expr]p3: | ||||||||
2451 | // An id-expression is type-dependent if it contains: | ||||||||
2452 | // -- an identifier that was declared with a dependent type, | ||||||||
2453 | // (note: handled after lookup) | ||||||||
2454 | // -- a template-id that is dependent, | ||||||||
2455 | // (note: handled in BuildTemplateIdExpr) | ||||||||
2456 | // -- a conversion-function-id that specifies a dependent type, | ||||||||
2457 | // -- a nested-name-specifier that contains a class-name that | ||||||||
2458 | // names a dependent type. | ||||||||
2459 | // Determine whether this is a member of an unknown specialization; | ||||||||
2460 | // we need to handle these differently. | ||||||||
2461 | bool DependentID = false; | ||||||||
2462 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||||||
2463 | Name.getCXXNameType()->isDependentType()) { | ||||||||
2464 | DependentID = true; | ||||||||
2465 | } else if (SS.isSet()) { | ||||||||
2466 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||||||
2467 | if (RequireCompleteDeclContext(SS, DC)) | ||||||||
2468 | return ExprError(); | ||||||||
2469 | } else { | ||||||||
2470 | DependentID = true; | ||||||||
2471 | } | ||||||||
2472 | } | ||||||||
2473 | |||||||||
2474 | if (DependentID) | ||||||||
2475 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2476 | IsAddressOfOperand, TemplateArgs); | ||||||||
2477 | |||||||||
2478 | // Perform the required lookup. | ||||||||
2479 | LookupResult R(*this, NameInfo, | ||||||||
2480 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||||||
2481 | ? LookupObjCImplicitSelfParam | ||||||||
2482 | : LookupOrdinaryName); | ||||||||
2483 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||||||
2484 | // Lookup the template name again to correctly establish the context in | ||||||||
2485 | // which it was found. This is really unfortunate as we already did the | ||||||||
2486 | // lookup to determine that it was a template name in the first place. If | ||||||||
2487 | // this becomes a performance hit, we can work harder to preserve those | ||||||||
2488 | // results until we get here but it's likely not worth it. | ||||||||
2489 | bool MemberOfUnknownSpecialization; | ||||||||
2490 | AssumedTemplateKind AssumedTemplate; | ||||||||
2491 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||||||
2492 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||||||
2493 | &AssumedTemplate)) | ||||||||
2494 | return ExprError(); | ||||||||
2495 | |||||||||
2496 | if (MemberOfUnknownSpecialization || | ||||||||
2497 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||||||
2498 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2499 | IsAddressOfOperand, TemplateArgs); | ||||||||
2500 | } else { | ||||||||
2501 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||||||
2502 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||||||
2503 | |||||||||
2504 | // If the result might be in a dependent base class, this is a dependent | ||||||||
2505 | // id-expression. | ||||||||
2506 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||||||
2507 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2508 | IsAddressOfOperand, TemplateArgs); | ||||||||
2509 | |||||||||
2510 | // If this reference is in an Objective-C method, then we need to do | ||||||||
2511 | // some special Objective-C lookup, too. | ||||||||
2512 | if (IvarLookupFollowUp) { | ||||||||
2513 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||||||
2514 | if (E.isInvalid()) | ||||||||
2515 | return ExprError(); | ||||||||
2516 | |||||||||
2517 | if (Expr *Ex = E.getAs<Expr>()) | ||||||||
2518 | return Ex; | ||||||||
2519 | } | ||||||||
2520 | } | ||||||||
2521 | |||||||||
2522 | if (R.isAmbiguous()) | ||||||||
2523 | return ExprError(); | ||||||||
2524 | |||||||||
2525 | // This could be an implicitly declared function reference (legal in C90, | ||||||||
2526 | // extension in C99, forbidden in C++). | ||||||||
2527 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | ||||||||
2528 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||||||
2529 | if (D) R.addDecl(D); | ||||||||
2530 | } | ||||||||
2531 | |||||||||
2532 | // Determine whether this name might be a candidate for | ||||||||
2533 | // argument-dependent lookup. | ||||||||
2534 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||||||
2535 | |||||||||
2536 | if (R.empty() && !ADL) { | ||||||||
2537 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||||||
2538 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||||||
2539 | TemplateKWLoc, TemplateArgs)) | ||||||||
2540 | return E; | ||||||||
2541 | } | ||||||||
2542 | |||||||||
2543 | // Don't diagnose an empty lookup for inline assembly. | ||||||||
2544 | if (IsInlineAsmIdentifier) | ||||||||
2545 | return ExprError(); | ||||||||
2546 | |||||||||
2547 | // If this name wasn't predeclared and if this is not a function | ||||||||
2548 | // call, diagnose the problem. | ||||||||
2549 | TypoExpr *TE = nullptr; | ||||||||
2550 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||||||
2551 | : nullptr); | ||||||||
2552 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||||||
2553 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2554, __PRETTY_FUNCTION__)) | ||||||||
2554 | "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2554, __PRETTY_FUNCTION__)); | ||||||||
2555 | if (CCC) { | ||||||||
2556 | // Make sure the callback knows what the typo being diagnosed is. | ||||||||
2557 | CCC->setTypoName(II); | ||||||||
2558 | if (SS.isValid()) | ||||||||
2559 | CCC->setTypoNNS(SS.getScopeRep()); | ||||||||
2560 | } | ||||||||
2561 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||||||
2562 | // a template name, but we happen to have always already looked up the name | ||||||||
2563 | // before we get here if it must be a template name. | ||||||||
2564 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||||||
2565 | None, &TE)) { | ||||||||
2566 | if (TE && KeywordReplacement) { | ||||||||
2567 | auto &State = getTypoExprState(TE); | ||||||||
2568 | auto BestTC = State.Consumer->getNextCorrection(); | ||||||||
2569 | if (BestTC.isKeyword()) { | ||||||||
2570 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||||||
2571 | if (State.DiagHandler) | ||||||||
2572 | State.DiagHandler(BestTC); | ||||||||
2573 | KeywordReplacement->startToken(); | ||||||||
2574 | KeywordReplacement->setKind(II->getTokenID()); | ||||||||
2575 | KeywordReplacement->setIdentifierInfo(II); | ||||||||
2576 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||||||
2577 | // Clean up the state associated with the TypoExpr, since it has | ||||||||
2578 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||||||
2579 | clearDelayedTypo(TE); | ||||||||
2580 | // Signal that a correction to a keyword was performed by returning a | ||||||||
2581 | // valid-but-null ExprResult. | ||||||||
2582 | return (Expr*)nullptr; | ||||||||
2583 | } | ||||||||
2584 | State.Consumer->resetCorrectionStream(); | ||||||||
2585 | } | ||||||||
2586 | return TE ? TE : ExprError(); | ||||||||
2587 | } | ||||||||
2588 | |||||||||
2589 | assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2590, __PRETTY_FUNCTION__)) | ||||||||
2590 | "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2590, __PRETTY_FUNCTION__)); | ||||||||
2591 | |||||||||
2592 | // If we found an Objective-C instance variable, let | ||||||||
2593 | // LookupInObjCMethod build the appropriate expression to | ||||||||
2594 | // reference the ivar. | ||||||||
2595 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||||||
2596 | R.clear(); | ||||||||
2597 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||||||
2598 | // In a hopelessly buggy code, Objective-C instance variable | ||||||||
2599 | // lookup fails and no expression will be built to reference it. | ||||||||
2600 | if (!E.isInvalid() && !E.get()) | ||||||||
2601 | return ExprError(); | ||||||||
2602 | return E; | ||||||||
2603 | } | ||||||||
2604 | } | ||||||||
2605 | |||||||||
2606 | // This is guaranteed from this point on. | ||||||||
2607 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2607, __PRETTY_FUNCTION__)); | ||||||||
2608 | |||||||||
2609 | // Check whether this might be a C++ implicit instance member access. | ||||||||
2610 | // C++ [class.mfct.non-static]p3: | ||||||||
2611 | // When an id-expression that is not part of a class member access | ||||||||
2612 | // syntax and not used to form a pointer to member is used in the | ||||||||
2613 | // body of a non-static member function of class X, if name lookup | ||||||||
2614 | // resolves the name in the id-expression to a non-static non-type | ||||||||
2615 | // member of some class C, the id-expression is transformed into a | ||||||||
2616 | // class member access expression using (*this) as the | ||||||||
2617 | // postfix-expression to the left of the . operator. | ||||||||
2618 | // | ||||||||
2619 | // But we don't actually need to do this for '&' operands if R | ||||||||
2620 | // resolved to a function or overloaded function set, because the | ||||||||
2621 | // expression is ill-formed if it actually works out to be a | ||||||||
2622 | // non-static member function: | ||||||||
2623 | // | ||||||||
2624 | // C++ [expr.ref]p4: | ||||||||
2625 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||||||
2626 | // [t]he expression can be used only as the left-hand operand of a | ||||||||
2627 | // member function call. | ||||||||
2628 | // | ||||||||
2629 | // There are other safeguards against such uses, but it's important | ||||||||
2630 | // to get this right here so that we don't end up making a | ||||||||
2631 | // spuriously dependent expression if we're inside a dependent | ||||||||
2632 | // instance method. | ||||||||
2633 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||||||
2634 | bool MightBeImplicitMember; | ||||||||
2635 | if (!IsAddressOfOperand) | ||||||||
2636 | MightBeImplicitMember = true; | ||||||||
2637 | else if (!SS.isEmpty()) | ||||||||
2638 | MightBeImplicitMember = false; | ||||||||
2639 | else if (R.isOverloadedResult()) | ||||||||
2640 | MightBeImplicitMember = false; | ||||||||
2641 | else if (R.isUnresolvableResult()) | ||||||||
2642 | MightBeImplicitMember = true; | ||||||||
2643 | else | ||||||||
2644 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||||||
2645 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||||||
2646 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||||||
2647 | |||||||||
2648 | if (MightBeImplicitMember) | ||||||||
2649 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||||||
2650 | R, TemplateArgs, S); | ||||||||
2651 | } | ||||||||
2652 | |||||||||
2653 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||||||
2654 | |||||||||
2655 | // In C++1y, if this is a variable template id, then check it | ||||||||
2656 | // in BuildTemplateIdExpr(). | ||||||||
2657 | // The single lookup result must be a variable template declaration. | ||||||||
2658 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||||||
2659 | Id.TemplateId->Kind == TNK_Var_template) { | ||||||||
2660 | assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2661, __PRETTY_FUNCTION__)) | ||||||||
2661 | "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2661, __PRETTY_FUNCTION__)); | ||||||||
2662 | } | ||||||||
2663 | |||||||||
2664 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||||||
2665 | } | ||||||||
2666 | |||||||||
2667 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||||||
2668 | } | ||||||||
2669 | |||||||||
2670 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||||||
2671 | /// declaration name, generally during template instantiation. | ||||||||
2672 | /// There's a large number of things which don't need to be done along | ||||||||
2673 | /// this path. | ||||||||
2674 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||||||
2675 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||||||
2676 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||||||
2677 | DeclContext *DC = computeDeclContext(SS, false); | ||||||||
2678 | if (!DC) | ||||||||
2679 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2680 | NameInfo, /*TemplateArgs=*/nullptr); | ||||||||
2681 | |||||||||
2682 | if (RequireCompleteDeclContext(SS, DC)) | ||||||||
2683 | return ExprError(); | ||||||||
2684 | |||||||||
2685 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||||||
2686 | LookupQualifiedName(R, DC); | ||||||||
2687 | |||||||||
2688 | if (R.isAmbiguous()) | ||||||||
2689 | return ExprError(); | ||||||||
2690 | |||||||||
2691 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||||||
2692 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2693 | NameInfo, /*TemplateArgs=*/nullptr); | ||||||||
2694 | |||||||||
2695 | if (R.empty()) { | ||||||||
2696 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||||||
2697 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||||||
2698 | // is invalid because it's derived from an invalid base class, then missing | ||||||||
2699 | // members were likely supposed to be inherited. | ||||||||
2700 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||||||
2701 | if (CD->isInvalidDecl()) | ||||||||
2702 | return ExprError(); | ||||||||
2703 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||||||
2704 | << NameInfo.getName() << DC << SS.getRange(); | ||||||||
2705 | return ExprError(); | ||||||||
2706 | } | ||||||||
2707 | |||||||||
2708 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||||||
2709 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||||||
2710 | // a dependent context. If we can recover with a type, downgrade this to | ||||||||
2711 | // a warning in Microsoft compatibility mode. | ||||||||
2712 | unsigned DiagID = diag::err_typename_missing; | ||||||||
2713 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||||||
2714 | DiagID = diag::ext_typename_missing; | ||||||||
2715 | SourceLocation Loc = SS.getBeginLoc(); | ||||||||
2716 | auto D = Diag(Loc, DiagID); | ||||||||
2717 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||||||
2718 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||||||
2719 | |||||||||
2720 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||||||
2721 | // context. | ||||||||
2722 | if (!RecoveryTSI) | ||||||||
2723 | return ExprError(); | ||||||||
2724 | |||||||||
2725 | // Only issue the fixit if we're prepared to recover. | ||||||||
2726 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||||||
2727 | |||||||||
2728 | // Recover by pretending this was an elaborated type. | ||||||||
2729 | QualType Ty = Context.getTypeDeclType(TD); | ||||||||
2730 | TypeLocBuilder TLB; | ||||||||
2731 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||||||
2732 | |||||||||
2733 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||||||
2734 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||||||
2735 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||||
2736 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||||
2737 | |||||||||
2738 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||||||
2739 | |||||||||
2740 | return ExprEmpty(); | ||||||||
2741 | } | ||||||||
2742 | |||||||||
2743 | // Defend against this resolving to an implicit member access. We usually | ||||||||
2744 | // won't get here if this might be a legitimate a class member (we end up in | ||||||||
2745 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||||||
2746 | // a pointer-to-member or in an unevaluated context in C++11. | ||||||||
2747 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||||||
2748 | return BuildPossibleImplicitMemberExpr(SS, | ||||||||
2749 | /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2750 | R, /*TemplateArgs=*/nullptr, S); | ||||||||
2751 | |||||||||
2752 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||||||
2753 | } | ||||||||
2754 | |||||||||
2755 | /// The parser has read a name in, and Sema has detected that we're currently | ||||||||
2756 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||||||
2757 | /// should form a reference to an ivar. | ||||||||
2758 | /// | ||||||||
2759 | /// Ideally, most of this would be done by lookup, but there's | ||||||||
2760 | /// actually quite a lot of extra work involved. | ||||||||
2761 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||||||
2762 | IdentifierInfo *II) { | ||||||||
2763 | SourceLocation Loc = Lookup.getNameLoc(); | ||||||||
2764 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||||
2765 | |||||||||
2766 | // Check for error condition which is already reported. | ||||||||
2767 | if (!CurMethod) | ||||||||
2768 | return DeclResult(true); | ||||||||
2769 | |||||||||
2770 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||||||
2771 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||||||
2772 | // found a decl, but that decl is outside the current instance method (i.e. | ||||||||
2773 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||||||
2774 | // this name, if the lookup sucedes, we replace it our current decl. | ||||||||
2775 | |||||||||
2776 | // If we're in a class method, we don't normally want to look for | ||||||||
2777 | // ivars. But if we don't find anything else, and there's an | ||||||||
2778 | // ivar, that's an error. | ||||||||
2779 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||||||
2780 | |||||||||
2781 | bool LookForIvars; | ||||||||
2782 | if (Lookup.empty()) | ||||||||
2783 | LookForIvars = true; | ||||||||
2784 | else if (IsClassMethod) | ||||||||
2785 | LookForIvars = false; | ||||||||
2786 | else | ||||||||
2787 | LookForIvars = (Lookup.isSingleResult() && | ||||||||
2788 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||||||
2789 | ObjCInterfaceDecl *IFace = nullptr; | ||||||||
2790 | if (LookForIvars) { | ||||||||
2791 | IFace = CurMethod->getClassInterface(); | ||||||||
2792 | ObjCInterfaceDecl *ClassDeclared; | ||||||||
2793 | ObjCIvarDecl *IV = nullptr; | ||||||||
2794 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||||||
2795 | // Diagnose using an ivar in a class method. | ||||||||
2796 | if (IsClassMethod) { | ||||||||
2797 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||||||
2798 | return DeclResult(true); | ||||||||
2799 | } | ||||||||
2800 | |||||||||
2801 | // Diagnose the use of an ivar outside of the declaring class. | ||||||||
2802 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||||||
2803 | !declaresSameEntity(ClassDeclared, IFace) && | ||||||||
2804 | !getLangOpts().DebuggerSupport) | ||||||||
2805 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||||||
2806 | |||||||||
2807 | // Success. | ||||||||
2808 | return IV; | ||||||||
2809 | } | ||||||||
2810 | } else if (CurMethod->isInstanceMethod()) { | ||||||||
2811 | // We should warn if a local variable hides an ivar. | ||||||||
2812 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||||||
2813 | ObjCInterfaceDecl *ClassDeclared; | ||||||||
2814 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||||||
2815 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||||||
2816 | declaresSameEntity(IFace, ClassDeclared)) | ||||||||
2817 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||||||
2818 | } | ||||||||
2819 | } | ||||||||
2820 | } else if (Lookup.isSingleResult() && | ||||||||
2821 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||||||
2822 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||||||
2823 | if (const ObjCIvarDecl *IV = | ||||||||
2824 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||||||
2825 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||||||
2826 | return DeclResult(true); | ||||||||
2827 | } | ||||||||
2828 | } | ||||||||
2829 | |||||||||
2830 | // Didn't encounter an error, didn't find an ivar. | ||||||||
2831 | return DeclResult(false); | ||||||||
2832 | } | ||||||||
2833 | |||||||||
2834 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||||||
2835 | ObjCIvarDecl *IV) { | ||||||||
2836 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||||
2837 | assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2838, __PRETTY_FUNCTION__)) | ||||||||
2838 | "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2838, __PRETTY_FUNCTION__)); | ||||||||
2839 | |||||||||
2840 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||||||
2841 | assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context" ) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 2841, __PRETTY_FUNCTION__)); | ||||||||
2842 | |||||||||
2843 | // If we're referencing an invalid decl, just return this as a silent | ||||||||
2844 | // error node. The error diagnostic was already emitted on the decl. | ||||||||
2845 | if (IV->isInvalidDecl()) | ||||||||
2846 | return ExprError(); | ||||||||
2847 | |||||||||
2848 | // Check if referencing a field with __attribute__((deprecated)). | ||||||||
2849 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||||||
2850 | return ExprError(); | ||||||||
2851 | |||||||||
2852 | // FIXME: This should use a new expr for a direct reference, don't | ||||||||
2853 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||||||
2854 | IdentifierInfo &II = Context.Idents.get("self"); | ||||||||
2855 | UnqualifiedId SelfName; | ||||||||
2856 | SelfName.setImplicitSelfParam(&II); | ||||||||
2857 | CXXScopeSpec SelfScopeSpec; | ||||||||
2858 | SourceLocation TemplateKWLoc; | ||||||||
2859 | ExprResult SelfExpr = | ||||||||
2860 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||||||
2861 | /*HasTrailingLParen=*/false, | ||||||||
2862 | /*IsAddressOfOperand=*/false); | ||||||||
2863 | if (SelfExpr.isInvalid()) | ||||||||
2864 | return ExprError(); | ||||||||
2865 | |||||||||
2866 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||||||
2867 | if (SelfExpr.isInvalid()) | ||||||||
2868 | return ExprError(); | ||||||||
2869 | |||||||||
2870 | MarkAnyDeclReferenced(Loc, IV, true); | ||||||||
2871 | |||||||||
2872 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||||||
2873 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||||||
2874 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||||||
2875 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||||||
2876 | |||||||||
2877 | ObjCIvarRefExpr *Result = new (Context) | ||||||||
2878 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||||||
2879 | IV->getLocation(), SelfExpr.get(), true, true); | ||||||||
2880 | |||||||||
2881 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||||||
2882 | if (!isUnevaluatedContext() && | ||||||||
2883 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||||||
2884 | getCurFunction()->recordUseOfWeak(Result); | ||||||||
2885 | } | ||||||||
2886 | if (getLangOpts().ObjCAutoRefCount) | ||||||||
2887 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||||||
2888 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||||||
2889 | |||||||||
2890 | return Result; | ||||||||
2891 | } | ||||||||
2892 | |||||||||
2893 | /// The parser has read a name in, and Sema has detected that we're currently | ||||||||
2894 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||||||
2895 | /// should form a reference to an ivar. If so, build an expression referencing | ||||||||
2896 | /// that ivar. | ||||||||
2897 | ExprResult | ||||||||
2898 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||||||
2899 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||||||
2900 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||||||
2901 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||||||
2902 | if (Ivar.isInvalid()) | ||||||||
2903 | return ExprError(); | ||||||||
2904 | if (Ivar.isUsable()) | ||||||||
2905 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||||||
2906 | cast<ObjCIvarDecl>(Ivar.get())); | ||||||||
2907 | |||||||||
2908 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||||||
2909 | LookupBuiltin(Lookup); | ||||||||
2910 | |||||||||
2911 | // Sentinel value saying that we didn't do anything special. | ||||||||
2912 | return ExprResult(false); | ||||||||
2913 | } | ||||||||
2914 | |||||||||
2915 | /// Cast a base object to a member's actual type. | ||||||||
2916 | /// | ||||||||
2917 | /// There are two relevant checks: | ||||||||
2918 | /// | ||||||||
2919 | /// C++ [class.access.base]p7: | ||||||||
2920 | /// | ||||||||
2921 | /// If a class member access operator [...] is used to access a non-static | ||||||||
2922 | /// data member or non-static member function, the reference is ill-formed if | ||||||||
2923 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||||||
2924 | /// naming class of the right operand. | ||||||||
2925 | /// | ||||||||
2926 | /// C++ [expr.ref]p7: | ||||||||
2927 | /// | ||||||||
2928 | /// If E2 is a non-static data member or a non-static member function, the | ||||||||
2929 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||||||
2930 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||||||
2931 | /// | ||||||||
2932 | /// Note that the latter check does not consider access; the access of the | ||||||||
2933 | /// "real" base class is checked as appropriate when checking the access of the | ||||||||
2934 | /// member name. | ||||||||
2935 | ExprResult | ||||||||
2936 | Sema::PerformObjectMemberConversion(Expr *From, | ||||||||
2937 | NestedNameSpecifier *Qualifier, | ||||||||
2938 | NamedDecl *FoundDecl, | ||||||||
2939 | NamedDecl *Member) { | ||||||||
2940 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||||||
2941 | if (!RD) | ||||||||
2942 | return From; | ||||||||
2943 | |||||||||
2944 | QualType DestRecordType; | ||||||||
2945 | QualType DestType; | ||||||||
2946 | QualType FromRecordType; | ||||||||
2947 | QualType FromType = From->getType(); | ||||||||
2948 | bool PointerConversions = false; | ||||||||
2949 | if (isa<FieldDecl>(Member)) { | ||||||||
2950 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||||||
2951 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||||||
2952 | DestRecordType = Context.getAddrSpaceQualType( | ||||||||
2953 | DestRecordType, FromPtrType | ||||||||
2954 | ? FromType->getPointeeType().getAddressSpace() | ||||||||
2955 | : FromType.getAddressSpace()); | ||||||||
2956 | |||||||||
2957 | if (FromPtrType) { | ||||||||
2958 | DestType = Context.getPointerType(DestRecordType); | ||||||||
2959 | FromRecordType = FromPtrType->getPointeeType(); | ||||||||
2960 | PointerConversions = true; | ||||||||
2961 | } else { | ||||||||
2962 | DestType = DestRecordType; | ||||||||
2963 | FromRecordType = FromType; | ||||||||
2964 | } | ||||||||
2965 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||||||
2966 | if (Method->isStatic()) | ||||||||
2967 | return From; | ||||||||
2968 | |||||||||
2969 | DestType = Method->getThisType(); | ||||||||
2970 | DestRecordType = DestType->getPointeeType(); | ||||||||
2971 | |||||||||
2972 | if (FromType->getAs<PointerType>()) { | ||||||||
2973 | FromRecordType = FromType->getPointeeType(); | ||||||||
2974 | PointerConversions = true; | ||||||||
2975 | } else { | ||||||||
2976 | FromRecordType = FromType; | ||||||||
2977 | DestType = DestRecordType; | ||||||||
2978 | } | ||||||||
2979 | |||||||||
2980 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||||||
2981 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||||||
2982 | if (FromAS != DestAS) { | ||||||||
2983 | QualType FromRecordTypeWithoutAS = | ||||||||
2984 | Context.removeAddrSpaceQualType(FromRecordType); | ||||||||
2985 | QualType FromTypeWithDestAS = | ||||||||
2986 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||||||
2987 | if (PointerConversions) | ||||||||
2988 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||||||
2989 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||||||
2990 | CK_AddressSpaceConversion, From->getValueKind()) | ||||||||
2991 | .get(); | ||||||||
2992 | } | ||||||||
2993 | } else { | ||||||||
2994 | // No conversion necessary. | ||||||||
2995 | return From; | ||||||||
2996 | } | ||||||||
2997 | |||||||||
2998 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||||||
2999 | return From; | ||||||||
3000 | |||||||||
3001 | // If the unqualified types are the same, no conversion is necessary. | ||||||||
3002 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||||||
3003 | return From; | ||||||||
3004 | |||||||||
3005 | SourceRange FromRange = From->getSourceRange(); | ||||||||
3006 | SourceLocation FromLoc = FromRange.getBegin(); | ||||||||
3007 | |||||||||
3008 | ExprValueKind VK = From->getValueKind(); | ||||||||
3009 | |||||||||
3010 | // C++ [class.member.lookup]p8: | ||||||||
3011 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||||||
3012 | // class name. | ||||||||
3013 | // | ||||||||
3014 | // If the member was a qualified name and the qualified referred to a | ||||||||
3015 | // specific base subobject type, we'll cast to that intermediate type | ||||||||
3016 | // first and then to the object in which the member is declared. That allows | ||||||||
3017 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||||||
3018 | // | ||||||||
3019 | // class Base { public: int x; }; | ||||||||
3020 | // class Derived1 : public Base { }; | ||||||||
3021 | // class Derived2 : public Base { }; | ||||||||
3022 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||||||
3023 | // | ||||||||
3024 | // void VeryDerived::f() { | ||||||||
3025 | // x = 17; // error: ambiguous base subobjects | ||||||||
3026 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||||||
3027 | // } | ||||||||
3028 | if (Qualifier && Qualifier->getAsType()) { | ||||||||
3029 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||||||
3030 | assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type" ) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3030, __PRETTY_FUNCTION__)); | ||||||||
3031 | |||||||||
3032 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | ||||||||
3033 | |||||||||
3034 | // In C++98, the qualifier type doesn't actually have to be a base | ||||||||
3035 | // type of the object type, in which case we just ignore it. | ||||||||
3036 | // Otherwise build the appropriate casts. | ||||||||
3037 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||||||
3038 | CXXCastPath BasePath; | ||||||||
3039 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||||||
3040 | FromLoc, FromRange, &BasePath)) | ||||||||
3041 | return ExprError(); | ||||||||
3042 | |||||||||
3043 | if (PointerConversions) | ||||||||
3044 | QType = Context.getPointerType(QType); | ||||||||
3045 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||||||
3046 | VK, &BasePath).get(); | ||||||||
3047 | |||||||||
3048 | FromType = QType; | ||||||||
3049 | FromRecordType = QRecordType; | ||||||||
3050 | |||||||||
3051 | // If the qualifier type was the same as the destination type, | ||||||||
3052 | // we're done. | ||||||||
3053 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||||||
3054 | return From; | ||||||||
3055 | } | ||||||||
3056 | } | ||||||||
3057 | |||||||||
3058 | CXXCastPath BasePath; | ||||||||
3059 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||||||
3060 | FromLoc, FromRange, &BasePath, | ||||||||
3061 | /*IgnoreAccess=*/true)) | ||||||||
3062 | return ExprError(); | ||||||||
3063 | |||||||||
3064 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||||||
3065 | VK, &BasePath); | ||||||||
3066 | } | ||||||||
3067 | |||||||||
3068 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||||||
3069 | const LookupResult &R, | ||||||||
3070 | bool HasTrailingLParen) { | ||||||||
3071 | // Only when used directly as the postfix-expression of a call. | ||||||||
3072 | if (!HasTrailingLParen) | ||||||||
3073 | return false; | ||||||||
3074 | |||||||||
3075 | // Never if a scope specifier was provided. | ||||||||
3076 | if (SS.isSet()) | ||||||||
3077 | return false; | ||||||||
3078 | |||||||||
3079 | // Only in C++ or ObjC++. | ||||||||
3080 | if (!getLangOpts().CPlusPlus) | ||||||||
3081 | return false; | ||||||||
3082 | |||||||||
3083 | // Turn off ADL when we find certain kinds of declarations during | ||||||||
3084 | // normal lookup: | ||||||||
3085 | for (NamedDecl *D : R) { | ||||||||
3086 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3087 | // -- a declaration of a class member | ||||||||
3088 | // Since using decls preserve this property, we check this on the | ||||||||
3089 | // original decl. | ||||||||
3090 | if (D->isCXXClassMember()) | ||||||||
3091 | return false; | ||||||||
3092 | |||||||||
3093 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3094 | // -- a block-scope function declaration that is not a | ||||||||
3095 | // using-declaration | ||||||||
3096 | // NOTE: we also trigger this for function templates (in fact, we | ||||||||
3097 | // don't check the decl type at all, since all other decl types | ||||||||
3098 | // turn off ADL anyway). | ||||||||
3099 | if (isa<UsingShadowDecl>(D)) | ||||||||
3100 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||||||
3101 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||||
3102 | return false; | ||||||||
3103 | |||||||||
3104 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3105 | // -- a declaration that is neither a function or a function | ||||||||
3106 | // template | ||||||||
3107 | // And also for builtin functions. | ||||||||
3108 | if (isa<FunctionDecl>(D)) { | ||||||||
3109 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||||||
3110 | |||||||||
3111 | // But also builtin functions. | ||||||||
3112 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||||||
3113 | return false; | ||||||||
3114 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||||||
3115 | return false; | ||||||||
3116 | } | ||||||||
3117 | |||||||||
3118 | return true; | ||||||||
3119 | } | ||||||||
3120 | |||||||||
3121 | |||||||||
3122 | /// Diagnoses obvious problems with the use of the given declaration | ||||||||
3123 | /// as an expression. This is only actually called for lookups that | ||||||||
3124 | /// were not overloaded, and it doesn't promise that the declaration | ||||||||
3125 | /// will in fact be used. | ||||||||
3126 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | ||||||||
3127 | if (D->isInvalidDecl()) | ||||||||
3128 | return true; | ||||||||
3129 | |||||||||
3130 | if (isa<TypedefNameDecl>(D)) { | ||||||||
3131 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||||||
3132 | return true; | ||||||||
3133 | } | ||||||||
3134 | |||||||||
3135 | if (isa<ObjCInterfaceDecl>(D)) { | ||||||||
3136 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||||||
3137 | return true; | ||||||||
3138 | } | ||||||||
3139 | |||||||||
3140 | if (isa<NamespaceDecl>(D)) { | ||||||||
3141 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||||||
3142 | return true; | ||||||||
3143 | } | ||||||||
3144 | |||||||||
3145 | return false; | ||||||||
3146 | } | ||||||||
3147 | |||||||||
3148 | // Certain multiversion types should be treated as overloaded even when there is | ||||||||
3149 | // only one result. | ||||||||
3150 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||||||
3151 | assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result" ) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3151, __PRETTY_FUNCTION__)); | ||||||||
3152 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||||||
3153 | return FD && | ||||||||
3154 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||||||
3155 | } | ||||||||
3156 | |||||||||
3157 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||||||
3158 | LookupResult &R, bool NeedsADL, | ||||||||
3159 | bool AcceptInvalidDecl) { | ||||||||
3160 | // If this is a single, fully-resolved result and we don't need ADL, | ||||||||
3161 | // just build an ordinary singleton decl ref. | ||||||||
3162 | if (!NeedsADL && R.isSingleResult() && | ||||||||
3163 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||||||
3164 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||||||
3165 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||||||
3166 | R.getRepresentativeDecl(), nullptr, | ||||||||
3167 | AcceptInvalidDecl); | ||||||||
3168 | |||||||||
3169 | // We only need to check the declaration if there's exactly one | ||||||||
3170 | // result, because in the overloaded case the results can only be | ||||||||
3171 | // functions and function templates. | ||||||||
3172 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||||||
3173 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | ||||||||
3174 | return ExprError(); | ||||||||
3175 | |||||||||
3176 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||||||
3177 | // any lookup-related diagnostics; we'll hash these out later, when | ||||||||
3178 | // we've picked a target. | ||||||||
3179 | R.suppressDiagnostics(); | ||||||||
3180 | |||||||||
3181 | UnresolvedLookupExpr *ULE | ||||||||
3182 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||||||
3183 | SS.getWithLocInContext(Context), | ||||||||
3184 | R.getLookupNameInfo(), | ||||||||
3185 | NeedsADL, R.isOverloadedResult(), | ||||||||
3186 | R.begin(), R.end()); | ||||||||
3187 | |||||||||
3188 | return ULE; | ||||||||
3189 | } | ||||||||
3190 | |||||||||
3191 | static void | ||||||||
3192 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||||||
3193 | ValueDecl *var, DeclContext *DC); | ||||||||
3194 | |||||||||
3195 | /// Complete semantic analysis for a reference to the given declaration. | ||||||||
3196 | ExprResult Sema::BuildDeclarationNameExpr( | ||||||||
3197 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||||||
3198 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||||||
3199 | bool AcceptInvalidDecl) { | ||||||||
3200 | assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast <void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3200, __PRETTY_FUNCTION__)); | ||||||||
3201 | assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3202, __PRETTY_FUNCTION__)) | ||||||||
3202 | "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3202, __PRETTY_FUNCTION__)); | ||||||||
3203 | |||||||||
3204 | SourceLocation Loc = NameInfo.getLoc(); | ||||||||
3205 | if (CheckDeclInExpr(*this, Loc, D)) | ||||||||
3206 | return ExprError(); | ||||||||
3207 | |||||||||
3208 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||||||
3209 | // Specifically diagnose references to class templates that are missing | ||||||||
3210 | // a template argument list. | ||||||||
3211 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||||||
3212 | return ExprError(); | ||||||||
3213 | } | ||||||||
3214 | |||||||||
3215 | // Make sure that we're referring to a value. | ||||||||
3216 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | ||||||||
3217 | if (!VD) { | ||||||||
3218 | Diag(Loc, diag::err_ref_non_value) | ||||||||
3219 | << D << SS.getRange(); | ||||||||
3220 | Diag(D->getLocation(), diag::note_declared_at); | ||||||||
3221 | return ExprError(); | ||||||||
3222 | } | ||||||||
3223 | |||||||||
3224 | // Check whether this declaration can be used. Note that we suppress | ||||||||
3225 | // this check when we're going to perform argument-dependent lookup | ||||||||
3226 | // on this function name, because this might not be the function | ||||||||
3227 | // that overload resolution actually selects. | ||||||||
3228 | if (DiagnoseUseOfDecl(VD, Loc)) | ||||||||
3229 | return ExprError(); | ||||||||
3230 | |||||||||
3231 | // Only create DeclRefExpr's for valid Decl's. | ||||||||
3232 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||||||
3233 | return ExprError(); | ||||||||
3234 | |||||||||
3235 | // Handle members of anonymous structs and unions. If we got here, | ||||||||
3236 | // and the reference is to a class member indirect field, then this | ||||||||
3237 | // must be the subject of a pointer-to-member expression. | ||||||||
3238 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||||||
3239 | if (!indirectField->isCXXClassMember()) | ||||||||
3240 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||||||
3241 | indirectField); | ||||||||
3242 | |||||||||
3243 | { | ||||||||
3244 | QualType type = VD->getType(); | ||||||||
3245 | if (type.isNull()) | ||||||||
3246 | return ExprError(); | ||||||||
3247 | ExprValueKind valueKind = VK_RValue; | ||||||||
3248 | |||||||||
3249 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||||||
3250 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||||||
3251 | // is expanded by some outer '...' in the context of the use. | ||||||||
3252 | type = type.getNonPackExpansionType(); | ||||||||
3253 | |||||||||
3254 | switch (D->getKind()) { | ||||||||
3255 | // Ignore all the non-ValueDecl kinds. | ||||||||
3256 | #define ABSTRACT_DECL(kind) | ||||||||
3257 | #define VALUE(type, base) | ||||||||
3258 | #define DECL(type, base) \ | ||||||||
3259 | case Decl::type: | ||||||||
3260 | #include "clang/AST/DeclNodes.inc" | ||||||||
3261 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3261); | ||||||||
3262 | |||||||||
3263 | // These shouldn't make it here. | ||||||||
3264 | case Decl::ObjCAtDefsField: | ||||||||
3265 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3265); | ||||||||
3266 | |||||||||
3267 | // Enum constants are always r-values and never references. | ||||||||
3268 | // Unresolved using declarations are dependent. | ||||||||
3269 | case Decl::EnumConstant: | ||||||||
3270 | case Decl::UnresolvedUsingValue: | ||||||||
3271 | case Decl::OMPDeclareReduction: | ||||||||
3272 | case Decl::OMPDeclareMapper: | ||||||||
3273 | valueKind = VK_RValue; | ||||||||
3274 | break; | ||||||||
3275 | |||||||||
3276 | // Fields and indirect fields that got here must be for | ||||||||
3277 | // pointer-to-member expressions; we just call them l-values for | ||||||||
3278 | // internal consistency, because this subexpression doesn't really | ||||||||
3279 | // exist in the high-level semantics. | ||||||||
3280 | case Decl::Field: | ||||||||
3281 | case Decl::IndirectField: | ||||||||
3282 | case Decl::ObjCIvar: | ||||||||
3283 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3284, __PRETTY_FUNCTION__)) | ||||||||
3284 | "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3284, __PRETTY_FUNCTION__)); | ||||||||
3285 | |||||||||
3286 | // These can't have reference type in well-formed programs, but | ||||||||
3287 | // for internal consistency we do this anyway. | ||||||||
3288 | type = type.getNonReferenceType(); | ||||||||
3289 | valueKind = VK_LValue; | ||||||||
3290 | break; | ||||||||
3291 | |||||||||
3292 | // Non-type template parameters are either l-values or r-values | ||||||||
3293 | // depending on the type. | ||||||||
3294 | case Decl::NonTypeTemplateParm: { | ||||||||
3295 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||||||
3296 | type = reftype->getPointeeType(); | ||||||||
3297 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||||||
3298 | break; | ||||||||
3299 | } | ||||||||
3300 | |||||||||
3301 | // [expr.prim.id.unqual]p2: | ||||||||
3302 | // If the entity is a template parameter object for a template | ||||||||
3303 | // parameter of type T, the type of the expression is const T. | ||||||||
3304 | // [...] The expression is an lvalue if the entity is a [...] template | ||||||||
3305 | // parameter object. | ||||||||
3306 | if (type->isRecordType()) { | ||||||||
3307 | type = type.getUnqualifiedType().withConst(); | ||||||||
3308 | valueKind = VK_LValue; | ||||||||
3309 | break; | ||||||||
3310 | } | ||||||||
3311 | |||||||||
3312 | // For non-references, we need to strip qualifiers just in case | ||||||||
3313 | // the template parameter was declared as 'const int' or whatever. | ||||||||
3314 | valueKind = VK_RValue; | ||||||||
3315 | type = type.getUnqualifiedType(); | ||||||||
3316 | break; | ||||||||
3317 | } | ||||||||
3318 | |||||||||
3319 | case Decl::Var: | ||||||||
3320 | case Decl::VarTemplateSpecialization: | ||||||||
3321 | case Decl::VarTemplatePartialSpecialization: | ||||||||
3322 | case Decl::Decomposition: | ||||||||
3323 | case Decl::OMPCapturedExpr: | ||||||||
3324 | // In C, "extern void blah;" is valid and is an r-value. | ||||||||
3325 | if (!getLangOpts().CPlusPlus && | ||||||||
3326 | !type.hasQualifiers() && | ||||||||
3327 | type->isVoidType()) { | ||||||||
3328 | valueKind = VK_RValue; | ||||||||
3329 | break; | ||||||||
3330 | } | ||||||||
3331 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
3332 | |||||||||
3333 | case Decl::ImplicitParam: | ||||||||
3334 | case Decl::ParmVar: { | ||||||||
3335 | // These are always l-values. | ||||||||
3336 | valueKind = VK_LValue; | ||||||||
3337 | type = type.getNonReferenceType(); | ||||||||
3338 | |||||||||
3339 | // FIXME: Does the addition of const really only apply in | ||||||||
3340 | // potentially-evaluated contexts? Since the variable isn't actually | ||||||||
3341 | // captured in an unevaluated context, it seems that the answer is no. | ||||||||
3342 | if (!isUnevaluatedContext()) { | ||||||||
3343 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||||||
3344 | if (!CapturedType.isNull()) | ||||||||
3345 | type = CapturedType; | ||||||||
3346 | } | ||||||||
3347 | |||||||||
3348 | break; | ||||||||
3349 | } | ||||||||
3350 | |||||||||
3351 | case Decl::Binding: { | ||||||||
3352 | // These are always lvalues. | ||||||||
3353 | valueKind = VK_LValue; | ||||||||
3354 | type = type.getNonReferenceType(); | ||||||||
3355 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | ||||||||
3356 | // decides how that's supposed to work. | ||||||||
3357 | auto *BD = cast<BindingDecl>(VD); | ||||||||
3358 | if (BD->getDeclContext() != CurContext) { | ||||||||
3359 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | ||||||||
3360 | if (DD && DD->hasLocalStorage()) | ||||||||
3361 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | ||||||||
3362 | } | ||||||||
3363 | break; | ||||||||
3364 | } | ||||||||
3365 | |||||||||
3366 | case Decl::Function: { | ||||||||
3367 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||||||
3368 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | ||||||||
3369 | type = Context.BuiltinFnTy; | ||||||||
3370 | valueKind = VK_RValue; | ||||||||
3371 | break; | ||||||||
3372 | } | ||||||||
3373 | } | ||||||||
3374 | |||||||||
3375 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||||||
3376 | |||||||||
3377 | // If we're referring to a function with an __unknown_anytype | ||||||||
3378 | // result type, make the entire expression __unknown_anytype. | ||||||||
3379 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||||||
3380 | type = Context.UnknownAnyTy; | ||||||||
3381 | valueKind = VK_RValue; | ||||||||
3382 | break; | ||||||||
3383 | } | ||||||||
3384 | |||||||||
3385 | // Functions are l-values in C++. | ||||||||
3386 | if (getLangOpts().CPlusPlus) { | ||||||||
3387 | valueKind = VK_LValue; | ||||||||
3388 | break; | ||||||||
3389 | } | ||||||||
3390 | |||||||||
3391 | // C99 DR 316 says that, if a function type comes from a | ||||||||
3392 | // function definition (without a prototype), that type is only | ||||||||
3393 | // used for checking compatibility. Therefore, when referencing | ||||||||
3394 | // the function, we pretend that we don't have the full function | ||||||||
3395 | // type. | ||||||||
3396 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | ||||||||
3397 | isa<FunctionProtoType>(fty)) | ||||||||
3398 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||||||
3399 | fty->getExtInfo()); | ||||||||
3400 | |||||||||
3401 | // Functions are r-values in C. | ||||||||
3402 | valueKind = VK_RValue; | ||||||||
3403 | break; | ||||||||
3404 | } | ||||||||
3405 | |||||||||
3406 | case Decl::CXXDeductionGuide: | ||||||||
3407 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3407); | ||||||||
3408 | |||||||||
3409 | case Decl::MSProperty: | ||||||||
3410 | case Decl::MSGuid: | ||||||||
3411 | case Decl::TemplateParamObject: | ||||||||
3412 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||||||
3413 | // capture in OpenMP, or duplicated between host and device? | ||||||||
3414 | valueKind = VK_LValue; | ||||||||
3415 | break; | ||||||||
3416 | |||||||||
3417 | case Decl::CXXMethod: | ||||||||
3418 | // If we're referring to a method with an __unknown_anytype | ||||||||
3419 | // result type, make the entire expression __unknown_anytype. | ||||||||
3420 | // This should only be possible with a type written directly. | ||||||||
3421 | if (const FunctionProtoType *proto | ||||||||
3422 | = dyn_cast<FunctionProtoType>(VD->getType())) | ||||||||
3423 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||||||
3424 | type = Context.UnknownAnyTy; | ||||||||
3425 | valueKind = VK_RValue; | ||||||||
3426 | break; | ||||||||
3427 | } | ||||||||
3428 | |||||||||
3429 | // C++ methods are l-values if static, r-values if non-static. | ||||||||
3430 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||||||
3431 | valueKind = VK_LValue; | ||||||||
3432 | break; | ||||||||
3433 | } | ||||||||
3434 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
3435 | |||||||||
3436 | case Decl::CXXConversion: | ||||||||
3437 | case Decl::CXXDestructor: | ||||||||
3438 | case Decl::CXXConstructor: | ||||||||
3439 | valueKind = VK_RValue; | ||||||||
3440 | break; | ||||||||
3441 | } | ||||||||
3442 | |||||||||
3443 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||||||
3444 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | ||||||||
3445 | TemplateArgs); | ||||||||
3446 | } | ||||||||
3447 | } | ||||||||
3448 | |||||||||
3449 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||||||
3450 | SmallString<32> &Target) { | ||||||||
3451 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||||||
3452 | char *ResultPtr = &Target[0]; | ||||||||
3453 | const llvm::UTF8 *ErrorPtr; | ||||||||
3454 | bool success = | ||||||||
3455 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||||||
3456 | (void)success; | ||||||||
3457 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3457, __PRETTY_FUNCTION__)); | ||||||||
3458 | Target.resize(ResultPtr - &Target[0]); | ||||||||
3459 | } | ||||||||
3460 | |||||||||
3461 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||||||
3462 | PredefinedExpr::IdentKind IK) { | ||||||||
3463 | // Pick the current block, lambda, captured statement or function. | ||||||||
3464 | Decl *currentDecl = nullptr; | ||||||||
3465 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||||||
3466 | currentDecl = BSI->TheDecl; | ||||||||
3467 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||||||
3468 | currentDecl = LSI->CallOperator; | ||||||||
3469 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||||||
3470 | currentDecl = CSI->TheCapturedDecl; | ||||||||
3471 | else | ||||||||
3472 | currentDecl = getCurFunctionOrMethodDecl(); | ||||||||
3473 | |||||||||
3474 | if (!currentDecl) { | ||||||||
3475 | Diag(Loc, diag::ext_predef_outside_function); | ||||||||
3476 | currentDecl = Context.getTranslationUnitDecl(); | ||||||||
3477 | } | ||||||||
3478 | |||||||||
3479 | QualType ResTy; | ||||||||
3480 | StringLiteral *SL = nullptr; | ||||||||
3481 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||||||
3482 | ResTy = Context.DependentTy; | ||||||||
3483 | else { | ||||||||
3484 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||||||
3485 | // the string. | ||||||||
3486 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||||||
3487 | unsigned Length = Str.length(); | ||||||||
3488 | |||||||||
3489 | llvm::APInt LengthI(32, Length + 1); | ||||||||
3490 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||||||
3491 | ResTy = | ||||||||
3492 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||||||
3493 | SmallString<32> RawChars; | ||||||||
3494 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||||||
3495 | Str, RawChars); | ||||||||
3496 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||||||
3497 | ArrayType::Normal, | ||||||||
3498 | /*IndexTypeQuals*/ 0); | ||||||||
3499 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||||||
3500 | /*Pascal*/ false, ResTy, Loc); | ||||||||
3501 | } else { | ||||||||
3502 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||||||
3503 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||||||
3504 | ArrayType::Normal, | ||||||||
3505 | /*IndexTypeQuals*/ 0); | ||||||||
3506 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | ||||||||
3507 | /*Pascal*/ false, ResTy, Loc); | ||||||||
3508 | } | ||||||||
3509 | } | ||||||||
3510 | |||||||||
3511 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||||||
3512 | } | ||||||||
3513 | |||||||||
3514 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||||||
3515 | PredefinedExpr::IdentKind IK; | ||||||||
3516 | |||||||||
3517 | switch (Kind) { | ||||||||
3518 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3518); | ||||||||
3519 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||||||
3520 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||||||
3521 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||||||
3522 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||||||
3523 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||||||
3524 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||||||
3525 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||||||
3526 | } | ||||||||
3527 | |||||||||
3528 | return BuildPredefinedExpr(Loc, IK); | ||||||||
3529 | } | ||||||||
3530 | |||||||||
3531 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||||||
3532 | SmallString<16> CharBuffer; | ||||||||
3533 | bool Invalid = false; | ||||||||
3534 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||||||
3535 | if (Invalid) | ||||||||
3536 | return ExprError(); | ||||||||
3537 | |||||||||
3538 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||||||
3539 | PP, Tok.getKind()); | ||||||||
3540 | if (Literal.hadError()) | ||||||||
3541 | return ExprError(); | ||||||||
3542 | |||||||||
3543 | QualType Ty; | ||||||||
3544 | if (Literal.isWide()) | ||||||||
3545 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||||||
3546 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||||||
3547 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||||||
3548 | else if (Literal.isUTF16()) | ||||||||
3549 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||||||
3550 | else if (Literal.isUTF32()) | ||||||||
3551 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||||||
3552 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||||||
3553 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||||||
3554 | else | ||||||||
3555 | Ty = Context.CharTy; // 'x' -> char in C++ | ||||||||
3556 | |||||||||
3557 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||||||
3558 | if (Literal.isWide()) | ||||||||
3559 | Kind = CharacterLiteral::Wide; | ||||||||
3560 | else if (Literal.isUTF16()) | ||||||||
3561 | Kind = CharacterLiteral::UTF16; | ||||||||
3562 | else if (Literal.isUTF32()) | ||||||||
3563 | Kind = CharacterLiteral::UTF32; | ||||||||
3564 | else if (Literal.isUTF8()) | ||||||||
3565 | Kind = CharacterLiteral::UTF8; | ||||||||
3566 | |||||||||
3567 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||||||
3568 | Tok.getLocation()); | ||||||||
3569 | |||||||||
3570 | if (Literal.getUDSuffix().empty()) | ||||||||
3571 | return Lit; | ||||||||
3572 | |||||||||
3573 | // We're building a user-defined literal. | ||||||||
3574 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
3575 | SourceLocation UDSuffixLoc = | ||||||||
3576 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||||||
3577 | |||||||||
3578 | // Make sure we're allowed user-defined literals here. | ||||||||
3579 | if (!UDLScope) | ||||||||
3580 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||||||
3581 | |||||||||
3582 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||||||
3583 | // operator "" X (ch) | ||||||||
3584 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||||||
3585 | Lit, Tok.getLocation()); | ||||||||
3586 | } | ||||||||
3587 | |||||||||
3588 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||||||
3589 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||||||
3590 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||||||
3591 | Context.IntTy, Loc); | ||||||||
3592 | } | ||||||||
3593 | |||||||||
3594 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||||||
3595 | QualType Ty, SourceLocation Loc) { | ||||||||
3596 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||||||
3597 | |||||||||
3598 | using llvm::APFloat; | ||||||||
3599 | APFloat Val(Format); | ||||||||
3600 | |||||||||
3601 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||||||
3602 | |||||||||
3603 | // Overflow is always an error, but underflow is only an error if | ||||||||
3604 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||||||
3605 | if ((result & APFloat::opOverflow) || | ||||||||
3606 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||||||
3607 | unsigned diagnostic; | ||||||||
3608 | SmallString<20> buffer; | ||||||||
3609 | if (result & APFloat::opOverflow) { | ||||||||
3610 | diagnostic = diag::warn_float_overflow; | ||||||||
3611 | APFloat::getLargest(Format).toString(buffer); | ||||||||
3612 | } else { | ||||||||
3613 | diagnostic = diag::warn_float_underflow; | ||||||||
3614 | APFloat::getSmallest(Format).toString(buffer); | ||||||||
3615 | } | ||||||||
3616 | |||||||||
3617 | S.Diag(Loc, diagnostic) | ||||||||
3618 | << Ty | ||||||||
3619 | << StringRef(buffer.data(), buffer.size()); | ||||||||
3620 | } | ||||||||
3621 | |||||||||
3622 | bool isExact = (result == APFloat::opOK); | ||||||||
3623 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||||||
3624 | } | ||||||||
3625 | |||||||||
3626 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||||||
3627 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3627, __PRETTY_FUNCTION__)); | ||||||||
3628 | |||||||||
3629 | if (E->isValueDependent()) | ||||||||
3630 | return false; | ||||||||
3631 | |||||||||
3632 | QualType QT = E->getType(); | ||||||||
3633 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||||||
3634 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||||||
3635 | return true; | ||||||||
3636 | } | ||||||||
3637 | |||||||||
3638 | llvm::APSInt ValueAPS; | ||||||||
3639 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||||||
3640 | |||||||||
3641 | if (R.isInvalid()) | ||||||||
3642 | return true; | ||||||||
3643 | |||||||||
3644 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||||||
3645 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||||||
3646 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||||||
3647 | << ValueAPS.toString(10) << ValueIsPositive; | ||||||||
3648 | return true; | ||||||||
3649 | } | ||||||||
3650 | |||||||||
3651 | return false; | ||||||||
3652 | } | ||||||||
3653 | |||||||||
3654 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||||||
3655 | // Fast path for a single digit (which is quite common). A single digit | ||||||||
3656 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||||||
3657 | if (Tok.getLength() == 1) { | ||||||||
3658 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||||||
3659 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||||||
3660 | } | ||||||||
3661 | |||||||||
3662 | SmallString<128> SpellingBuffer; | ||||||||
3663 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||||||
3664 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||||||
3665 | // returns a StringRef to the memory buffer, it should have a null char at | ||||||||
3666 | // the EOF, so it is also safe. | ||||||||
3667 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||||||
3668 | |||||||||
3669 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||||||
3670 | bool Invalid = false; | ||||||||
3671 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||||||
3672 | if (Invalid) | ||||||||
3673 | return ExprError(); | ||||||||
3674 | |||||||||
3675 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||||||
3676 | PP.getSourceManager(), PP.getLangOpts(), | ||||||||
3677 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||||||
3678 | if (Literal.hadError) | ||||||||
3679 | return ExprError(); | ||||||||
3680 | |||||||||
3681 | if (Literal.hasUDSuffix()) { | ||||||||
3682 | // We're building a user-defined literal. | ||||||||
3683 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
3684 | SourceLocation UDSuffixLoc = | ||||||||
3685 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||||||
3686 | |||||||||
3687 | // Make sure we're allowed user-defined literals here. | ||||||||
3688 | if (!UDLScope) | ||||||||
3689 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||||||
3690 | |||||||||
3691 | QualType CookedTy; | ||||||||
3692 | if (Literal.isFloatingLiteral()) { | ||||||||
3693 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||||||
3694 | // long double, the literal is treated as a call of the form | ||||||||
3695 | // operator "" X (f L) | ||||||||
3696 | CookedTy = Context.LongDoubleTy; | ||||||||
3697 | } else { | ||||||||
3698 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||||||
3699 | // unsigned long long, the literal is treated as a call of the form | ||||||||
3700 | // operator "" X (n ULL) | ||||||||
3701 | CookedTy = Context.UnsignedLongLongTy; | ||||||||
3702 | } | ||||||||
3703 | |||||||||
3704 | DeclarationName OpName = | ||||||||
3705 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
3706 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
3707 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
3708 | |||||||||
3709 | SourceLocation TokLoc = Tok.getLocation(); | ||||||||
3710 | |||||||||
3711 | // Perform literal operator lookup to determine if we're building a raw | ||||||||
3712 | // literal or a cooked one. | ||||||||
3713 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||||||
3714 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||||||
3715 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||||||
3716 | /*AllowStringTemplatePack*/ false, | ||||||||
3717 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||||||
3718 | case LOLR_ErrorNoDiagnostic: | ||||||||
3719 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||||||
3720 | // GNU extension producing _Complex types. | ||||||||
3721 | break; | ||||||||
3722 | case LOLR_Error: | ||||||||
3723 | return ExprError(); | ||||||||
3724 | case LOLR_Cooked: { | ||||||||
3725 | Expr *Lit; | ||||||||
3726 | if (Literal.isFloatingLiteral()) { | ||||||||
3727 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||||||
3728 | } else { | ||||||||
3729 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||||||
3730 | if (Literal.GetIntegerValue(ResultVal)) | ||||||||
3731 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||||||
3732 | << /* Unsigned */ 1; | ||||||||
3733 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||||||
3734 | Tok.getLocation()); | ||||||||
3735 | } | ||||||||
3736 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||||||
3737 | } | ||||||||
3738 | |||||||||
3739 | case LOLR_Raw: { | ||||||||
3740 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||||||
3741 | // literal is treated as a call of the form | ||||||||
3742 | // operator "" X ("n") | ||||||||
3743 | unsigned Length = Literal.getUDSuffixOffset(); | ||||||||
3744 | QualType StrTy = Context.getConstantArrayType( | ||||||||
3745 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||||||
3746 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||||||
3747 | Expr *Lit = StringLiteral::Create( | ||||||||
3748 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | ||||||||
3749 | /*Pascal*/false, StrTy, &TokLoc, 1); | ||||||||
3750 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||||||
3751 | } | ||||||||
3752 | |||||||||
3753 | case LOLR_Template: { | ||||||||
3754 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||||||
3755 | // template), L is treated as a call fo the form | ||||||||
3756 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||||||
3757 | // where n is the source character sequence c1 c2 ... ck. | ||||||||
3758 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
3759 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||||||
3760 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||||||
3761 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||||||
3762 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||||||
3763 | Value = TokSpelling[I]; | ||||||||
3764 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||||||
3765 | TemplateArgumentLocInfo ArgInfo; | ||||||||
3766 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
3767 | } | ||||||||
3768 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||||||
3769 | &ExplicitArgs); | ||||||||
3770 | } | ||||||||
3771 | case LOLR_StringTemplatePack: | ||||||||
3772 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3772); | ||||||||
3773 | } | ||||||||
3774 | } | ||||||||
3775 | |||||||||
3776 | Expr *Res; | ||||||||
3777 | |||||||||
3778 | if (Literal.isFixedPointLiteral()) { | ||||||||
3779 | QualType Ty; | ||||||||
3780 | |||||||||
3781 | if (Literal.isAccum) { | ||||||||
3782 | if (Literal.isHalf) { | ||||||||
3783 | Ty = Context.ShortAccumTy; | ||||||||
3784 | } else if (Literal.isLong) { | ||||||||
3785 | Ty = Context.LongAccumTy; | ||||||||
3786 | } else { | ||||||||
3787 | Ty = Context.AccumTy; | ||||||||
3788 | } | ||||||||
3789 | } else if (Literal.isFract) { | ||||||||
3790 | if (Literal.isHalf) { | ||||||||
3791 | Ty = Context.ShortFractTy; | ||||||||
3792 | } else if (Literal.isLong) { | ||||||||
3793 | Ty = Context.LongFractTy; | ||||||||
3794 | } else { | ||||||||
3795 | Ty = Context.FractTy; | ||||||||
3796 | } | ||||||||
3797 | } | ||||||||
3798 | |||||||||
3799 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||||||
3800 | |||||||||
3801 | bool isSigned = !Literal.isUnsigned; | ||||||||
3802 | unsigned scale = Context.getFixedPointScale(Ty); | ||||||||
3803 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||||||
3804 | |||||||||
3805 | llvm::APInt Val(bit_width, 0, isSigned); | ||||||||
3806 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||||||
3807 | bool ValIsZero = Val.isNullValue() && !Overflowed; | ||||||||
3808 | |||||||||
3809 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||||||
3810 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||||||
3811 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||||||
3812 | // representable values for its type, with exception for constants of a | ||||||||
3813 | // fract type with a value of exactly 1; such a constant shall denote | ||||||||
3814 | // the maximal value for the type. | ||||||||
3815 | --Val; | ||||||||
3816 | else if (Val.ugt(MaxVal) || Overflowed) | ||||||||
3817 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||||||
3818 | |||||||||
3819 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||||||
3820 | Tok.getLocation(), scale); | ||||||||
3821 | } else if (Literal.isFloatingLiteral()) { | ||||||||
3822 | QualType Ty; | ||||||||
3823 | if (Literal.isHalf){ | ||||||||
3824 | if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) | ||||||||
3825 | Ty = Context.HalfTy; | ||||||||
3826 | else { | ||||||||
3827 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||||||
3828 | return ExprError(); | ||||||||
3829 | } | ||||||||
3830 | } else if (Literal.isFloat) | ||||||||
3831 | Ty = Context.FloatTy; | ||||||||
3832 | else if (Literal.isLong) | ||||||||
3833 | Ty = Context.LongDoubleTy; | ||||||||
3834 | else if (Literal.isFloat16) | ||||||||
3835 | Ty = Context.Float16Ty; | ||||||||
3836 | else if (Literal.isFloat128) | ||||||||
3837 | Ty = Context.Float128Ty; | ||||||||
3838 | else | ||||||||
3839 | Ty = Context.DoubleTy; | ||||||||
3840 | |||||||||
3841 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||||||
3842 | |||||||||
3843 | if (Ty == Context.DoubleTy) { | ||||||||
3844 | if (getLangOpts().SinglePrecisionConstants) { | ||||||||
3845 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||||||
3846 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
3847 | } | ||||||||
3848 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( | ||||||||
3849 | "cl_khr_fp64", getLangOpts())) { | ||||||||
3850 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||||||
3851 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | ||||||||
3852 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
3853 | } | ||||||||
3854 | } | ||||||||
3855 | } else if (!Literal.isIntegerLiteral()) { | ||||||||
3856 | return ExprError(); | ||||||||
3857 | } else { | ||||||||
3858 | QualType Ty; | ||||||||
3859 | |||||||||
3860 | // 'long long' is a C99 or C++11 feature. | ||||||||
3861 | if (!getLangOpts().C99 && Literal.isLongLong) { | ||||||||
3862 | if (getLangOpts().CPlusPlus) | ||||||||
3863 | Diag(Tok.getLocation(), | ||||||||
3864 | getLangOpts().CPlusPlus11 ? | ||||||||
3865 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||||||
3866 | else | ||||||||
3867 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||||||
3868 | } | ||||||||
3869 | |||||||||
3870 | // 'z/uz' literals are a C++2b feature. | ||||||||
3871 | if (Literal.isSizeT) | ||||||||
3872 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus | ||||||||
3873 | ? getLangOpts().CPlusPlus2b | ||||||||
3874 | ? diag::warn_cxx20_compat_size_t_suffix | ||||||||
3875 | : diag::ext_cxx2b_size_t_suffix | ||||||||
3876 | : diag::err_cxx2b_size_t_suffix); | ||||||||
3877 | |||||||||
3878 | // Get the value in the widest-possible width. | ||||||||
3879 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | ||||||||
3880 | llvm::APInt ResultVal(MaxWidth, 0); | ||||||||
3881 | |||||||||
3882 | if (Literal.GetIntegerValue(ResultVal)) { | ||||||||
3883 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||||||
3884 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||||||
3885 | << /* Unsigned */ 1; | ||||||||
3886 | Ty = Context.UnsignedLongLongTy; | ||||||||
3887 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3888, __PRETTY_FUNCTION__)) | ||||||||
3888 | "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3888, __PRETTY_FUNCTION__)); | ||||||||
3889 | } else { | ||||||||
3890 | // If this value fits into a ULL, try to figure out what else it fits into | ||||||||
3891 | // according to the rules of C99 6.4.4.1p5. | ||||||||
3892 | |||||||||
3893 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||||||
3894 | // be an unsigned int. | ||||||||
3895 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||||||
3896 | |||||||||
3897 | // Check from smallest to largest, picking the smallest type we can. | ||||||||
3898 | unsigned Width = 0; | ||||||||
3899 | |||||||||
3900 | // Microsoft specific integer suffixes are explicitly sized. | ||||||||
3901 | if (Literal.MicrosoftInteger) { | ||||||||
3902 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||||||
3903 | Width = 8; | ||||||||
3904 | Ty = Context.CharTy; | ||||||||
3905 | } else { | ||||||||
3906 | Width = Literal.MicrosoftInteger; | ||||||||
3907 | Ty = Context.getIntTypeForBitwidth(Width, | ||||||||
3908 | /*Signed=*/!Literal.isUnsigned); | ||||||||
3909 | } | ||||||||
3910 | } | ||||||||
3911 | |||||||||
3912 | // Check C++2b size_t literals. | ||||||||
3913 | if (Literal.isSizeT) { | ||||||||
3914 | assert(!Literal.MicrosoftInteger &&((!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals" ) ? static_cast<void> (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3915, __PRETTY_FUNCTION__)) | ||||||||
3915 | "size_t literals can't be Microsoft literals")((!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals" ) ? static_cast<void> (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 3915, __PRETTY_FUNCTION__)); | ||||||||
3916 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( | ||||||||
3917 | Context.getTargetInfo().getSizeType()); | ||||||||
3918 | |||||||||
3919 | // Does it fit in size_t? | ||||||||
3920 | if (ResultVal.isIntN(SizeTSize)) { | ||||||||
3921 | // Does it fit in ssize_t? | ||||||||
3922 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) | ||||||||
3923 | Ty = Context.getSignedSizeType(); | ||||||||
3924 | else if (AllowUnsigned) | ||||||||
3925 | Ty = Context.getSizeType(); | ||||||||
3926 | Width = SizeTSize; | ||||||||
3927 | } | ||||||||
3928 | } | ||||||||
3929 | |||||||||
3930 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && | ||||||||
3931 | !Literal.isSizeT) { | ||||||||
3932 | // Are int/unsigned possibilities? | ||||||||
3933 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||||||
3934 | |||||||||
3935 | // Does it fit in a unsigned int? | ||||||||
3936 | if (ResultVal.isIntN(IntSize)) { | ||||||||
3937 | // Does it fit in a signed int? | ||||||||
3938 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||||||
3939 | Ty = Context.IntTy; | ||||||||
3940 | else if (AllowUnsigned) | ||||||||
3941 | Ty = Context.UnsignedIntTy; | ||||||||
3942 | Width = IntSize; | ||||||||
3943 | } | ||||||||
3944 | } | ||||||||
3945 | |||||||||
3946 | // Are long/unsigned long possibilities? | ||||||||
3947 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { | ||||||||
3948 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||||||
3949 | |||||||||
3950 | // Does it fit in a unsigned long? | ||||||||
3951 | if (ResultVal.isIntN(LongSize)) { | ||||||||
3952 | // Does it fit in a signed long? | ||||||||
3953 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||||||
3954 | Ty = Context.LongTy; | ||||||||
3955 | else if (AllowUnsigned) | ||||||||
3956 | Ty = Context.UnsignedLongTy; | ||||||||
3957 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||||||
3958 | // is compatible. | ||||||||
3959 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||||||
3960 | const unsigned LongLongSize = | ||||||||
3961 | Context.getTargetInfo().getLongLongWidth(); | ||||||||
3962 | Diag(Tok.getLocation(), | ||||||||
3963 | getLangOpts().CPlusPlus | ||||||||
3964 | ? Literal.isLong | ||||||||
3965 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||||||
3966 | : /*C++98 UB*/ diag:: | ||||||||
3967 | ext_old_implicitly_unsigned_long_cxx | ||||||||
3968 | : diag::warn_old_implicitly_unsigned_long) | ||||||||
3969 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||||||
3970 | : /*will be ill-formed*/ 1); | ||||||||
3971 | Ty = Context.UnsignedLongTy; | ||||||||
3972 | } | ||||||||
3973 | Width = LongSize; | ||||||||
3974 | } | ||||||||
3975 | } | ||||||||
3976 | |||||||||
3977 | // Check long long if needed. | ||||||||
3978 | if (Ty.isNull() && !Literal.isSizeT) { | ||||||||
3979 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||||||
3980 | |||||||||
3981 | // Does it fit in a unsigned long long? | ||||||||
3982 | if (ResultVal.isIntN(LongLongSize)) { | ||||||||
3983 | // Does it fit in a signed long long? | ||||||||
3984 | // To be compatible with MSVC, hex integer literals ending with the | ||||||||
3985 | // LL or i64 suffix are always signed in Microsoft mode. | ||||||||
3986 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||||||
3987 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||||||
3988 | Ty = Context.LongLongTy; | ||||||||
3989 | else if (AllowUnsigned) | ||||||||
3990 | Ty = Context.UnsignedLongLongTy; | ||||||||
3991 | Width = LongLongSize; | ||||||||
3992 | } | ||||||||
3993 | } | ||||||||
3994 | |||||||||
3995 | // If we still couldn't decide a type, we either have 'size_t' literal | ||||||||
3996 | // that is out of range, or a decimal literal that does not fit in a | ||||||||
3997 | // signed long long and has no U suffix. | ||||||||
3998 | if (Ty.isNull()) { | ||||||||
3999 | if (Literal.isSizeT) | ||||||||
4000 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) | ||||||||
4001 | << Literal.isUnsigned; | ||||||||
4002 | else | ||||||||
4003 | Diag(Tok.getLocation(), | ||||||||
4004 | diag::ext_integer_literal_too_large_for_signed); | ||||||||
4005 | Ty = Context.UnsignedLongLongTy; | ||||||||
4006 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||||||
4007 | } | ||||||||
4008 | |||||||||
4009 | if (ResultVal.getBitWidth() != Width) | ||||||||
4010 | ResultVal = ResultVal.trunc(Width); | ||||||||
4011 | } | ||||||||
4012 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||||||
4013 | } | ||||||||
4014 | |||||||||
4015 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||||||
4016 | if (Literal.isImaginary) { | ||||||||
4017 | Res = new (Context) ImaginaryLiteral(Res, | ||||||||
4018 | Context.getComplexType(Res->getType())); | ||||||||
4019 | |||||||||
4020 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||||||
4021 | } | ||||||||
4022 | return Res; | ||||||||
4023 | } | ||||||||
4024 | |||||||||
4025 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||||||
4026 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4026, __PRETTY_FUNCTION__)); | ||||||||
4027 | return new (Context) ParenExpr(L, R, E); | ||||||||
4028 | } | ||||||||
4029 | |||||||||
4030 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||||||
4031 | SourceLocation Loc, | ||||||||
4032 | SourceRange ArgRange) { | ||||||||
4033 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||||||
4034 | // scalar or vector data type argument..." | ||||||||
4035 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||||||
4036 | // type (C99 6.2.5p18) or void. | ||||||||
4037 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||||||
4038 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||||||
4039 | << T << ArgRange; | ||||||||
4040 | return true; | ||||||||
4041 | } | ||||||||
4042 | |||||||||
4043 | assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4044, __PRETTY_FUNCTION__)) | ||||||||
4044 | "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4044, __PRETTY_FUNCTION__)); | ||||||||
4045 | return false; | ||||||||
4046 | } | ||||||||
4047 | |||||||||
4048 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||||||
4049 | SourceLocation Loc, | ||||||||
4050 | SourceRange ArgRange, | ||||||||
4051 | UnaryExprOrTypeTrait TraitKind) { | ||||||||
4052 | // Invalid types must be hard errors for SFINAE in C++. | ||||||||
4053 | if (S.LangOpts.CPlusPlus) | ||||||||
4054 | return true; | ||||||||
4055 | |||||||||
4056 | // C99 6.5.3.4p1: | ||||||||
4057 | if (T->isFunctionType() && | ||||||||
4058 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||||||
4059 | TraitKind == UETT_PreferredAlignOf)) { | ||||||||
4060 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||||||
4061 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||||||
4062 | << getTraitSpelling(TraitKind) << ArgRange; | ||||||||
4063 | return false; | ||||||||
4064 | } | ||||||||
4065 | |||||||||
4066 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||||||
4067 | // this is an error (OpenCL v1.1 s6.3.k) | ||||||||
4068 | if (T->isVoidType()) { | ||||||||
4069 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||||||
4070 | : diag::ext_sizeof_alignof_void_type; | ||||||||
4071 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||||||
4072 | return false; | ||||||||
4073 | } | ||||||||
4074 | |||||||||
4075 | return true; | ||||||||
4076 | } | ||||||||
4077 | |||||||||
4078 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||||||
4079 | SourceLocation Loc, | ||||||||
4080 | SourceRange ArgRange, | ||||||||
4081 | UnaryExprOrTypeTrait TraitKind) { | ||||||||
4082 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||||||
4083 | // runtime doesn't allow it. | ||||||||
4084 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||||||
4085 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||||||
4086 | << T << (TraitKind == UETT_SizeOf) | ||||||||
4087 | << ArgRange; | ||||||||
4088 | return true; | ||||||||
4089 | } | ||||||||
4090 | |||||||||
4091 | return false; | ||||||||
4092 | } | ||||||||
4093 | |||||||||
4094 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||||||
4095 | /// pointer type is equal to T) and emit a warning if it is. | ||||||||
4096 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||||||
4097 | Expr *E) { | ||||||||
4098 | // Don't warn if the operation changed the type. | ||||||||
4099 | if (T != E->getType()) | ||||||||
4100 | return; | ||||||||
4101 | |||||||||
4102 | // Now look for array decays. | ||||||||
4103 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||||||
4104 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||||||
4105 | return; | ||||||||
4106 | |||||||||
4107 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||||||
4108 | << ICE->getType() | ||||||||
4109 | << ICE->getSubExpr()->getType(); | ||||||||
4110 | } | ||||||||
4111 | |||||||||
4112 | /// Check the constraints on expression operands to unary type expression | ||||||||
4113 | /// and type traits. | ||||||||
4114 | /// | ||||||||
4115 | /// Completes any types necessary and validates the constraints on the operand | ||||||||
4116 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||||||
4117 | /// the expression as it completes the type for that expression through template | ||||||||
4118 | /// instantiation, etc. | ||||||||
4119 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||||||
4120 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4121 | QualType ExprTy = E->getType(); | ||||||||
4122 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4122, __PRETTY_FUNCTION__)); | ||||||||
4123 | |||||||||
4124 | bool IsUnevaluatedOperand = | ||||||||
4125 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||||||
4126 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||||||
4127 | if (IsUnevaluatedOperand) { | ||||||||
4128 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||||||
4129 | if (Result.isInvalid()) | ||||||||
4130 | return true; | ||||||||
4131 | E = Result.get(); | ||||||||
4132 | } | ||||||||
4133 | |||||||||
4134 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||||||
4135 | // so side effects could result in unintended consequences. | ||||||||
4136 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||||||
4137 | // used to build SFINAE gadgets. | ||||||||
4138 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||||||
4139 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||||||
4140 | !E->isInstantiationDependent() && | ||||||||
4141 | E->HasSideEffects(Context, false)) | ||||||||
4142 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||||||
4143 | |||||||||
4144 | if (ExprKind == UETT_VecStep) | ||||||||
4145 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||||||
4146 | E->getSourceRange()); | ||||||||
4147 | |||||||||
4148 | // Explicitly list some types as extensions. | ||||||||
4149 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||||||
4150 | E->getSourceRange(), ExprKind)) | ||||||||
4151 | return false; | ||||||||
4152 | |||||||||
4153 | // 'alignof' applied to an expression only requires the base element type of | ||||||||
4154 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||||||
4155 | // be complete (and will attempt to complete it if it's an array of unknown | ||||||||
4156 | // bound). | ||||||||
4157 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||||||
4158 | if (RequireCompleteSizedType( | ||||||||
4159 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||||||
4160 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4161 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||||||
4162 | return true; | ||||||||
4163 | } else { | ||||||||
4164 | if (RequireCompleteSizedExprType( | ||||||||
4165 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4166 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||||||
4167 | return true; | ||||||||
4168 | } | ||||||||
4169 | |||||||||
4170 | // Completing the expression's type may have changed it. | ||||||||
4171 | ExprTy = E->getType(); | ||||||||
4172 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4172, __PRETTY_FUNCTION__)); | ||||||||
4173 | |||||||||
4174 | if (ExprTy->isFunctionType()) { | ||||||||
4175 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||||||
4176 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||||||
4177 | return true; | ||||||||
4178 | } | ||||||||
4179 | |||||||||
4180 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||||||
4181 | E->getSourceRange(), ExprKind)) | ||||||||
4182 | return true; | ||||||||
4183 | |||||||||
4184 | if (ExprKind == UETT_SizeOf) { | ||||||||
4185 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||||||
4186 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||||||
4187 | QualType OType = PVD->getOriginalType(); | ||||||||
4188 | QualType Type = PVD->getType(); | ||||||||
4189 | if (Type->isPointerType() && OType->isArrayType()) { | ||||||||
4190 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||||||
4191 | << Type << OType; | ||||||||
4192 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||||||
4193 | } | ||||||||
4194 | } | ||||||||
4195 | } | ||||||||
4196 | |||||||||
4197 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||||||
4198 | // decays into a pointer and returns an unintended result. This is most | ||||||||
4199 | // likely a typo for "sizeof(array) op x". | ||||||||
4200 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||||||
4201 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||||||
4202 | BO->getLHS()); | ||||||||
4203 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||||||
4204 | BO->getRHS()); | ||||||||
4205 | } | ||||||||
4206 | } | ||||||||
4207 | |||||||||
4208 | return false; | ||||||||
4209 | } | ||||||||
4210 | |||||||||
4211 | /// Check the constraints on operands to unary expression and type | ||||||||
4212 | /// traits. | ||||||||
4213 | /// | ||||||||
4214 | /// This will complete any types necessary, and validate the various constraints | ||||||||
4215 | /// on those operands. | ||||||||
4216 | /// | ||||||||
4217 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||||||
4218 | /// C99 6.3.2.1p[2-4] all state: | ||||||||
4219 | /// Except when it is the operand of the sizeof operator ... | ||||||||
4220 | /// | ||||||||
4221 | /// C++ [expr.sizeof]p4 | ||||||||
4222 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||||||
4223 | /// standard conversions are not applied to the operand of sizeof. | ||||||||
4224 | /// | ||||||||
4225 | /// This policy is followed for all of the unary trait expressions. | ||||||||
4226 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||||||
4227 | SourceLocation OpLoc, | ||||||||
4228 | SourceRange ExprRange, | ||||||||
4229 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4230 | if (ExprType->isDependentType()) | ||||||||
4231 | return false; | ||||||||
4232 | |||||||||
4233 | // C++ [expr.sizeof]p2: | ||||||||
4234 | // When applied to a reference or a reference type, the result | ||||||||
4235 | // is the size of the referenced type. | ||||||||
4236 | // C++11 [expr.alignof]p3: | ||||||||
4237 | // When alignof is applied to a reference type, the result | ||||||||
4238 | // shall be the alignment of the referenced type. | ||||||||
4239 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||||||
4240 | ExprType = Ref->getPointeeType(); | ||||||||
4241 | |||||||||
4242 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||||||
4243 | // When alignof or _Alignof is applied to an array type, the result | ||||||||
4244 | // is the alignment of the element type. | ||||||||
4245 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||||||
4246 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||||||
4247 | ExprType = Context.getBaseElementType(ExprType); | ||||||||
4248 | |||||||||
4249 | if (ExprKind == UETT_VecStep) | ||||||||
4250 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||||||
4251 | |||||||||
4252 | // Explicitly list some types as extensions. | ||||||||
4253 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||||||
4254 | ExprKind)) | ||||||||
4255 | return false; | ||||||||
4256 | |||||||||
4257 | if (RequireCompleteSizedType( | ||||||||
4258 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4259 | getTraitSpelling(ExprKind), ExprRange)) | ||||||||
4260 | return true; | ||||||||
4261 | |||||||||
4262 | if (ExprType->isFunctionType()) { | ||||||||
4263 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||||||
4264 | << getTraitSpelling(ExprKind) << ExprRange; | ||||||||
4265 | return true; | ||||||||
4266 | } | ||||||||
4267 | |||||||||
4268 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||||||
4269 | ExprKind)) | ||||||||
4270 | return true; | ||||||||
4271 | |||||||||
4272 | return false; | ||||||||
4273 | } | ||||||||
4274 | |||||||||
4275 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||||||
4276 | // Cannot know anything else if the expression is dependent. | ||||||||
4277 | if (E->isTypeDependent()) | ||||||||
4278 | return false; | ||||||||
4279 | |||||||||
4280 | if (E->getObjectKind() == OK_BitField) { | ||||||||
4281 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||||||
4282 | << 1 << E->getSourceRange(); | ||||||||
4283 | return true; | ||||||||
4284 | } | ||||||||
4285 | |||||||||
4286 | ValueDecl *D = nullptr; | ||||||||
4287 | Expr *Inner = E->IgnoreParens(); | ||||||||
4288 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||||||
4289 | D = DRE->getDecl(); | ||||||||
4290 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||||||
4291 | D = ME->getMemberDecl(); | ||||||||
4292 | } | ||||||||
4293 | |||||||||
4294 | // If it's a field, require the containing struct to have a | ||||||||
4295 | // complete definition so that we can compute the layout. | ||||||||
4296 | // | ||||||||
4297 | // This can happen in C++11 onwards, either by naming the member | ||||||||
4298 | // in a way that is not transformed into a member access expression | ||||||||
4299 | // (in an unevaluated operand, for instance), or by naming the member | ||||||||
4300 | // in a trailing-return-type. | ||||||||
4301 | // | ||||||||
4302 | // For the record, since __alignof__ on expressions is a GCC | ||||||||
4303 | // extension, GCC seems to permit this but always gives the | ||||||||
4304 | // nonsensical answer 0. | ||||||||
4305 | // | ||||||||
4306 | // We don't really need the layout here --- we could instead just | ||||||||
4307 | // directly check for all the appropriate alignment-lowing | ||||||||
4308 | // attributes --- but that would require duplicating a lot of | ||||||||
4309 | // logic that just isn't worth duplicating for such a marginal | ||||||||
4310 | // use-case. | ||||||||
4311 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||||||
4312 | // Fast path this check, since we at least know the record has a | ||||||||
4313 | // definition if we can find a member of it. | ||||||||
4314 | if (!FD->getParent()->isCompleteDefinition()) { | ||||||||
4315 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||||||
4316 | << E->getSourceRange(); | ||||||||
4317 | return true; | ||||||||
4318 | } | ||||||||
4319 | |||||||||
4320 | // Otherwise, if it's a field, and the field doesn't have | ||||||||
4321 | // reference type, then it must have a complete type (or be a | ||||||||
4322 | // flexible array member, which we explicitly want to | ||||||||
4323 | // white-list anyway), which makes the following checks trivial. | ||||||||
4324 | if (!FD->getType()->isReferenceType()) | ||||||||
4325 | return false; | ||||||||
4326 | } | ||||||||
4327 | |||||||||
4328 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||||||
4329 | } | ||||||||
4330 | |||||||||
4331 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||||||
4332 | E = E->IgnoreParens(); | ||||||||
4333 | |||||||||
4334 | // Cannot know anything else if the expression is dependent. | ||||||||
4335 | if (E->isTypeDependent()) | ||||||||
4336 | return false; | ||||||||
4337 | |||||||||
4338 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||||||
4339 | } | ||||||||
4340 | |||||||||
4341 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||||||
4342 | CapturingScopeInfo *CSI) { | ||||||||
4343 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4343, __PRETTY_FUNCTION__)); | ||||||||
4344 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4344, __PRETTY_FUNCTION__)); | ||||||||
4345 | |||||||||
4346 | // We're going to walk down into the type and look for VLA expressions. | ||||||||
4347 | do { | ||||||||
4348 | const Type *Ty = T.getTypePtr(); | ||||||||
4349 | switch (Ty->getTypeClass()) { | ||||||||
4350 | #define TYPE(Class, Base) | ||||||||
4351 | #define ABSTRACT_TYPE(Class, Base) | ||||||||
4352 | #define NON_CANONICAL_TYPE(Class, Base) | ||||||||
4353 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||||||
4354 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||||||
4355 | #include "clang/AST/TypeNodes.inc" | ||||||||
4356 | T = QualType(); | ||||||||
4357 | break; | ||||||||
4358 | // These types are never variably-modified. | ||||||||
4359 | case Type::Builtin: | ||||||||
4360 | case Type::Complex: | ||||||||
4361 | case Type::Vector: | ||||||||
4362 | case Type::ExtVector: | ||||||||
4363 | case Type::ConstantMatrix: | ||||||||
4364 | case Type::Record: | ||||||||
4365 | case Type::Enum: | ||||||||
4366 | case Type::Elaborated: | ||||||||
4367 | case Type::TemplateSpecialization: | ||||||||
4368 | case Type::ObjCObject: | ||||||||
4369 | case Type::ObjCInterface: | ||||||||
4370 | case Type::ObjCObjectPointer: | ||||||||
4371 | case Type::ObjCTypeParam: | ||||||||
4372 | case Type::Pipe: | ||||||||
4373 | case Type::ExtInt: | ||||||||
4374 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4374); | ||||||||
4375 | case Type::Adjusted: | ||||||||
4376 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||||||
4377 | break; | ||||||||
4378 | case Type::Decayed: | ||||||||
4379 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||||||
4380 | break; | ||||||||
4381 | case Type::Pointer: | ||||||||
4382 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||||||
4383 | break; | ||||||||
4384 | case Type::BlockPointer: | ||||||||
4385 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||||||
4386 | break; | ||||||||
4387 | case Type::LValueReference: | ||||||||
4388 | case Type::RValueReference: | ||||||||
4389 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||||||
4390 | break; | ||||||||
4391 | case Type::MemberPointer: | ||||||||
4392 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||||||
4393 | break; | ||||||||
4394 | case Type::ConstantArray: | ||||||||
4395 | case Type::IncompleteArray: | ||||||||
4396 | // Losing element qualification here is fine. | ||||||||
4397 | T = cast<ArrayType>(Ty)->getElementType(); | ||||||||
4398 | break; | ||||||||
4399 | case Type::VariableArray: { | ||||||||
4400 | // Losing element qualification here is fine. | ||||||||
4401 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||||||
4402 | |||||||||
4403 | // Unknown size indication requires no size computation. | ||||||||
4404 | // Otherwise, evaluate and record it. | ||||||||
4405 | auto Size = VAT->getSizeExpr(); | ||||||||
4406 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||||||
4407 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||||||
4408 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||||||
4409 | |||||||||
4410 | T = VAT->getElementType(); | ||||||||
4411 | break; | ||||||||
4412 | } | ||||||||
4413 | case Type::FunctionProto: | ||||||||
4414 | case Type::FunctionNoProto: | ||||||||
4415 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||||||
4416 | break; | ||||||||
4417 | case Type::Paren: | ||||||||
4418 | case Type::TypeOf: | ||||||||
4419 | case Type::UnaryTransform: | ||||||||
4420 | case Type::Attributed: | ||||||||
4421 | case Type::SubstTemplateTypeParm: | ||||||||
4422 | case Type::MacroQualified: | ||||||||
4423 | // Keep walking after single level desugaring. | ||||||||
4424 | T = T.getSingleStepDesugaredType(Context); | ||||||||
4425 | break; | ||||||||
4426 | case Type::Typedef: | ||||||||
4427 | T = cast<TypedefType>(Ty)->desugar(); | ||||||||
4428 | break; | ||||||||
4429 | case Type::Decltype: | ||||||||
4430 | T = cast<DecltypeType>(Ty)->desugar(); | ||||||||
4431 | break; | ||||||||
4432 | case Type::Auto: | ||||||||
4433 | case Type::DeducedTemplateSpecialization: | ||||||||
4434 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||||||
4435 | break; | ||||||||
4436 | case Type::TypeOfExpr: | ||||||||
4437 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||||||
4438 | break; | ||||||||
4439 | case Type::Atomic: | ||||||||
4440 | T = cast<AtomicType>(Ty)->getValueType(); | ||||||||
4441 | break; | ||||||||
4442 | } | ||||||||
4443 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||||||
4444 | } | ||||||||
4445 | |||||||||
4446 | /// Build a sizeof or alignof expression given a type operand. | ||||||||
4447 | ExprResult | ||||||||
4448 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||||||
4449 | SourceLocation OpLoc, | ||||||||
4450 | UnaryExprOrTypeTrait ExprKind, | ||||||||
4451 | SourceRange R) { | ||||||||
4452 | if (!TInfo) | ||||||||
4453 | return ExprError(); | ||||||||
4454 | |||||||||
4455 | QualType T = TInfo->getType(); | ||||||||
4456 | |||||||||
4457 | if (!T->isDependentType() && | ||||||||
4458 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||||||
4459 | return ExprError(); | ||||||||
4460 | |||||||||
4461 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||||||
4462 | if (auto *TT = T->getAs<TypedefType>()) { | ||||||||
4463 | for (auto I = FunctionScopes.rbegin(), | ||||||||
4464 | E = std::prev(FunctionScopes.rend()); | ||||||||
4465 | I != E; ++I) { | ||||||||
4466 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||||||
4467 | if (CSI == nullptr) | ||||||||
4468 | break; | ||||||||
4469 | DeclContext *DC = nullptr; | ||||||||
4470 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||||||
4471 | DC = LSI->CallOperator; | ||||||||
4472 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||||||
4473 | DC = CRSI->TheCapturedDecl; | ||||||||
4474 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||||||
4475 | DC = BSI->TheDecl; | ||||||||
4476 | if (DC) { | ||||||||
4477 | if (DC->containsDecl(TT->getDecl())) | ||||||||
4478 | break; | ||||||||
4479 | captureVariablyModifiedType(Context, T, CSI); | ||||||||
4480 | } | ||||||||
4481 | } | ||||||||
4482 | } | ||||||||
4483 | } | ||||||||
4484 | |||||||||
4485 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||||||
4486 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||||||
4487 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||||||
4488 | } | ||||||||
4489 | |||||||||
4490 | /// Build a sizeof or alignof expression given an expression | ||||||||
4491 | /// operand. | ||||||||
4492 | ExprResult | ||||||||
4493 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||||||
4494 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4495 | ExprResult PE = CheckPlaceholderExpr(E); | ||||||||
4496 | if (PE.isInvalid()) | ||||||||
4497 | return ExprError(); | ||||||||
4498 | |||||||||
4499 | E = PE.get(); | ||||||||
4500 | |||||||||
4501 | // Verify that the operand is valid. | ||||||||
4502 | bool isInvalid = false; | ||||||||
4503 | if (E->isTypeDependent()) { | ||||||||
4504 | // Delay type-checking for type-dependent expressions. | ||||||||
4505 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||||||
4506 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||||||
4507 | } else if (ExprKind == UETT_VecStep) { | ||||||||
4508 | isInvalid = CheckVecStepExpr(E); | ||||||||
4509 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||||||
4510 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||||||
4511 | isInvalid = true; | ||||||||
4512 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||||||
4513 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||||||
4514 | isInvalid = true; | ||||||||
4515 | } else { | ||||||||
4516 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||||||
4517 | } | ||||||||
4518 | |||||||||
4519 | if (isInvalid) | ||||||||
4520 | return ExprError(); | ||||||||
4521 | |||||||||
4522 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||||||
4523 | PE = TransformToPotentiallyEvaluated(E); | ||||||||
4524 | if (PE.isInvalid()) return ExprError(); | ||||||||
4525 | E = PE.get(); | ||||||||
4526 | } | ||||||||
4527 | |||||||||
4528 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||||||
4529 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||||||
4530 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||||||
4531 | } | ||||||||
4532 | |||||||||
4533 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||||||
4534 | /// expr and the same for @c alignof and @c __alignof | ||||||||
4535 | /// Note that the ArgRange is invalid if isType is false. | ||||||||
4536 | ExprResult | ||||||||
4537 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||||||
4538 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||||||
4539 | void *TyOrEx, SourceRange ArgRange) { | ||||||||
4540 | // If error parsing type, ignore. | ||||||||
4541 | if (!TyOrEx) return ExprError(); | ||||||||
4542 | |||||||||
4543 | if (IsType) { | ||||||||
4544 | TypeSourceInfo *TInfo; | ||||||||
4545 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||||||
4546 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||||||
4547 | } | ||||||||
4548 | |||||||||
4549 | Expr *ArgEx = (Expr *)TyOrEx; | ||||||||
4550 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||||||
4551 | return Result; | ||||||||
4552 | } | ||||||||
4553 | |||||||||
4554 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||||||
4555 | bool IsReal) { | ||||||||
4556 | if (V.get()->isTypeDependent()) | ||||||||
4557 | return S.Context.DependentTy; | ||||||||
4558 | |||||||||
4559 | // _Real and _Imag are only l-values for normal l-values. | ||||||||
4560 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||||||
4561 | V = S.DefaultLvalueConversion(V.get()); | ||||||||
4562 | if (V.isInvalid()) | ||||||||
4563 | return QualType(); | ||||||||
4564 | } | ||||||||
4565 | |||||||||
4566 | // These operators return the element type of a complex type. | ||||||||
4567 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||||||
4568 | return CT->getElementType(); | ||||||||
4569 | |||||||||
4570 | // Otherwise they pass through real integer and floating point types here. | ||||||||
4571 | if (V.get()->getType()->isArithmeticType()) | ||||||||
4572 | return V.get()->getType(); | ||||||||
4573 | |||||||||
4574 | // Test for placeholders. | ||||||||
4575 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||||||
4576 | if (PR.isInvalid()) return QualType(); | ||||||||
4577 | if (PR.get() != V.get()) { | ||||||||
4578 | V = PR; | ||||||||
4579 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||||||
4580 | } | ||||||||
4581 | |||||||||
4582 | // Reject anything else. | ||||||||
4583 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||||||
4584 | << (IsReal ? "__real" : "__imag"); | ||||||||
4585 | return QualType(); | ||||||||
4586 | } | ||||||||
4587 | |||||||||
4588 | |||||||||
4589 | |||||||||
4590 | ExprResult | ||||||||
4591 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||||||
4592 | tok::TokenKind Kind, Expr *Input) { | ||||||||
4593 | UnaryOperatorKind Opc; | ||||||||
4594 | switch (Kind) { | ||||||||
4595 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4595); | ||||||||
4596 | case tok::plusplus: Opc = UO_PostInc; break; | ||||||||
4597 | case tok::minusminus: Opc = UO_PostDec; break; | ||||||||
4598 | } | ||||||||
4599 | |||||||||
4600 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||||||
4601 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||||||
4602 | if (Result.isInvalid()) return ExprError(); | ||||||||
4603 | Input = Result.get(); | ||||||||
4604 | |||||||||
4605 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||||||
4606 | } | ||||||||
4607 | |||||||||
4608 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||||||
4609 | /// | ||||||||
4610 | /// \return true on error | ||||||||
4611 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||||||
4612 | SourceLocation opLoc, | ||||||||
4613 | Expr *op) { | ||||||||
4614 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4614, __PRETTY_FUNCTION__)); | ||||||||
4615 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||||||
4616 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||||||
4617 | return false; | ||||||||
4618 | |||||||||
4619 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||||||
4620 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||||||
4621 | << op->getSourceRange(); | ||||||||
4622 | return true; | ||||||||
4623 | } | ||||||||
4624 | |||||||||
4625 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||||||
4626 | auto *BaseNoParens = Base->IgnoreParens(); | ||||||||
4627 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||||||
4628 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||||||
4629 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||||||
4630 | } | ||||||||
4631 | |||||||||
4632 | ExprResult | ||||||||
4633 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | ||||||||
4634 | Expr *idx, SourceLocation rbLoc) { | ||||||||
4635 | if (base && !base->getType().isNull() && | ||||||||
4636 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | ||||||||
4637 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | ||||||||
4638 | SourceLocation(), /*Length*/ nullptr, | ||||||||
4639 | /*Stride=*/nullptr, rbLoc); | ||||||||
4640 | |||||||||
4641 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||||||
4642 | if (isa<ParenListExpr>(base)) { | ||||||||
4643 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||||||
4644 | if (result.isInvalid()) return ExprError(); | ||||||||
4645 | base = result.get(); | ||||||||
4646 | } | ||||||||
4647 | |||||||||
4648 | // Check if base and idx form a MatrixSubscriptExpr. | ||||||||
4649 | // | ||||||||
4650 | // Helper to check for comma expressions, which are not allowed as indices for | ||||||||
4651 | // matrix subscript expressions. | ||||||||
4652 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||||||
4653 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||||||
4654 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||||||
4655 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4656 | return true; | ||||||||
4657 | } | ||||||||
4658 | return false; | ||||||||
4659 | }; | ||||||||
4660 | // The matrix subscript operator ([][])is considered a single operator. | ||||||||
4661 | // Separating the index expressions by parenthesis is not allowed. | ||||||||
4662 | if (base->getType()->isSpecificPlaceholderType( | ||||||||
4663 | BuiltinType::IncompleteMatrixIdx) && | ||||||||
4664 | !isa<MatrixSubscriptExpr>(base)) { | ||||||||
4665 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||||||
4666 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4667 | return ExprError(); | ||||||||
4668 | } | ||||||||
4669 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||||||
4670 | // MatrixSubscriptExpr. | ||||||||
4671 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||||||
4672 | if (matSubscriptE) { | ||||||||
4673 | if (CheckAndReportCommaError(idx)) | ||||||||
4674 | return ExprError(); | ||||||||
4675 | |||||||||
4676 | assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4677, __PRETTY_FUNCTION__)) | ||||||||
4677 | "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4677, __PRETTY_FUNCTION__)); | ||||||||
4678 | return CreateBuiltinMatrixSubscriptExpr( | ||||||||
4679 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | ||||||||
4680 | } | ||||||||
4681 | |||||||||
4682 | // Handle any non-overload placeholder types in the base and index | ||||||||
4683 | // expressions. We can't handle overloads here because the other | ||||||||
4684 | // operand might be an overloadable type, in which case the overload | ||||||||
4685 | // resolution for the operator overload should get the first crack | ||||||||
4686 | // at the overload. | ||||||||
4687 | bool IsMSPropertySubscript = false; | ||||||||
4688 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4689 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||||||
4690 | if (!IsMSPropertySubscript) { | ||||||||
4691 | ExprResult result = CheckPlaceholderExpr(base); | ||||||||
4692 | if (result.isInvalid()) | ||||||||
4693 | return ExprError(); | ||||||||
4694 | base = result.get(); | ||||||||
4695 | } | ||||||||
4696 | } | ||||||||
4697 | |||||||||
4698 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||||||
4699 | if (base->getType()->isMatrixType()) { | ||||||||
4700 | if (CheckAndReportCommaError(idx)) | ||||||||
4701 | return ExprError(); | ||||||||
4702 | |||||||||
4703 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | ||||||||
4704 | } | ||||||||
4705 | |||||||||
4706 | // A comma-expression as the index is deprecated in C++2a onwards. | ||||||||
4707 | if (getLangOpts().CPlusPlus20 && | ||||||||
4708 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||||||
4709 | (isa<CXXOperatorCallExpr>(idx) && | ||||||||
4710 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | ||||||||
4711 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||||||
4712 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4713 | } | ||||||||
4714 | |||||||||
4715 | if (idx->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4716 | ExprResult result = CheckPlaceholderExpr(idx); | ||||||||
4717 | if (result.isInvalid()) return ExprError(); | ||||||||
4718 | idx = result.get(); | ||||||||
4719 | } | ||||||||
4720 | |||||||||
4721 | // Build an unanalyzed expression if either operand is type-dependent. | ||||||||
4722 | if (getLangOpts().CPlusPlus && | ||||||||
4723 | (base->isTypeDependent() || idx->isTypeDependent())) { | ||||||||
4724 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | ||||||||
4725 | VK_LValue, OK_Ordinary, rbLoc); | ||||||||
4726 | } | ||||||||
4727 | |||||||||
4728 | // MSDN, property (C++) | ||||||||
4729 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||||||
4730 | // This attribute can also be used in the declaration of an empty array in a | ||||||||
4731 | // class or structure definition. For example: | ||||||||
4732 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||||||
4733 | // The above statement indicates that x[] can be used with one or more array | ||||||||
4734 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||||||
4735 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||||||
4736 | if (IsMSPropertySubscript) { | ||||||||
4737 | // Build MS property subscript expression if base is MS property reference | ||||||||
4738 | // or MS property subscript. | ||||||||
4739 | return new (Context) MSPropertySubscriptExpr( | ||||||||
4740 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | ||||||||
4741 | } | ||||||||
4742 | |||||||||
4743 | // Use C++ overloaded-operator rules if either operand has record | ||||||||
4744 | // type. The spec says to do this if either type is *overloadable*, | ||||||||
4745 | // but enum types can't declare subscript operators or conversion | ||||||||
4746 | // operators, so there's nothing interesting for overload resolution | ||||||||
4747 | // to do if there aren't any record types involved. | ||||||||
4748 | // | ||||||||
4749 | // ObjC pointers have their own subscripting logic that is not tied | ||||||||
4750 | // to overload resolution and so should not take this path. | ||||||||
4751 | if (getLangOpts().CPlusPlus && | ||||||||
4752 | (base->getType()->isRecordType() || | ||||||||
4753 | (!base->getType()->isObjCObjectPointerType() && | ||||||||
4754 | idx->getType()->isRecordType()))) { | ||||||||
4755 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | ||||||||
4756 | } | ||||||||
4757 | |||||||||
4758 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | ||||||||
4759 | |||||||||
4760 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||||||
4761 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||||||
4762 | |||||||||
4763 | return Res; | ||||||||
4764 | } | ||||||||
4765 | |||||||||
4766 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||||||
4767 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||||||
4768 | InitializationKind Kind = | ||||||||
4769 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||||||
4770 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||||||
4771 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||||||
4772 | } | ||||||||
4773 | |||||||||
4774 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||||||
4775 | Expr *ColumnIdx, | ||||||||
4776 | SourceLocation RBLoc) { | ||||||||
4777 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||||||
4778 | if (BaseR.isInvalid()) | ||||||||
4779 | return BaseR; | ||||||||
4780 | Base = BaseR.get(); | ||||||||
4781 | |||||||||
4782 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||||||
4783 | if (RowR.isInvalid()) | ||||||||
4784 | return RowR; | ||||||||
4785 | RowIdx = RowR.get(); | ||||||||
4786 | |||||||||
4787 | if (!ColumnIdx) | ||||||||
4788 | return new (Context) MatrixSubscriptExpr( | ||||||||
4789 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||||||
4790 | |||||||||
4791 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||||||
4792 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||||||
4793 | ColumnIdx->isTypeDependent()) | ||||||||
4794 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||||||
4795 | Context.DependentTy, RBLoc); | ||||||||
4796 | |||||||||
4797 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||||||
4798 | if (ColumnR.isInvalid()) | ||||||||
4799 | return ColumnR; | ||||||||
4800 | ColumnIdx = ColumnR.get(); | ||||||||
4801 | |||||||||
4802 | // Check that IndexExpr is an integer expression. If it is a constant | ||||||||
4803 | // expression, check that it is less than Dim (= the number of elements in the | ||||||||
4804 | // corresponding dimension). | ||||||||
4805 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||||||
4806 | bool IsColumnIdx) -> Expr * { | ||||||||
4807 | if (!IndexExpr->getType()->isIntegerType() && | ||||||||
4808 | !IndexExpr->isTypeDependent()) { | ||||||||
4809 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||||||
4810 | << IsColumnIdx; | ||||||||
4811 | return nullptr; | ||||||||
4812 | } | ||||||||
4813 | |||||||||
4814 | if (Optional<llvm::APSInt> Idx = | ||||||||
4815 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||||||
4816 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||||||
4817 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||||||
4818 | << IsColumnIdx << Dim; | ||||||||
4819 | return nullptr; | ||||||||
4820 | } | ||||||||
4821 | } | ||||||||
4822 | |||||||||
4823 | ExprResult ConvExpr = | ||||||||
4824 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||||||
4825 | assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4826, __PRETTY_FUNCTION__)) | ||||||||
4826 | "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 4826, __PRETTY_FUNCTION__)); | ||||||||
4827 | return ConvExpr.get(); | ||||||||
4828 | }; | ||||||||
4829 | |||||||||
4830 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||||||
4831 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||||||
4832 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||||||
4833 | if (!RowIdx || !ColumnIdx) | ||||||||
4834 | return ExprError(); | ||||||||
4835 | |||||||||
4836 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||||||
4837 | MTy->getElementType(), RBLoc); | ||||||||
4838 | } | ||||||||
4839 | |||||||||
4840 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||||||
4841 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||||||
4842 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||||||
4843 | |||||||||
4844 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||||||
4845 | // checked. | ||||||||
4846 | const MemberExpr *Member = nullptr; | ||||||||
4847 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||||||
4848 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||||||
4849 | |||||||||
4850 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||||||
4851 | } | ||||||||
4852 | |||||||||
4853 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||||||
4854 | if (isUnevaluatedContext()) | ||||||||
4855 | return; | ||||||||
4856 | |||||||||
4857 | QualType ResultTy = E->getType(); | ||||||||
4858 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||||||
4859 | |||||||||
4860 | // Bail if the element is an array since it is not memory access. | ||||||||
4861 | if (isa<ArrayType>(ResultTy)) | ||||||||
4862 | return; | ||||||||
4863 | |||||||||
4864 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||||||
4865 | LastRecord.PossibleDerefs.insert(E); | ||||||||
4866 | return; | ||||||||
4867 | } | ||||||||
4868 | |||||||||
4869 | // Check if the base type is a pointer to a member access of a struct | ||||||||
4870 | // marked with noderef. | ||||||||
4871 | const Expr *Base = E->getBase(); | ||||||||
4872 | QualType BaseTy = Base->getType(); | ||||||||
4873 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||||||
4874 | // Not a pointer access | ||||||||
4875 | return; | ||||||||
4876 | |||||||||
4877 | const MemberExpr *Member = nullptr; | ||||||||
4878 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||||||
4879 | Member->isArrow()) | ||||||||
4880 | Base = Member->getBase(); | ||||||||
4881 | |||||||||
4882 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||||||
4883 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||||||
4884 | LastRecord.PossibleDerefs.insert(E); | ||||||||
4885 | } | ||||||||
4886 | } | ||||||||
4887 | |||||||||
4888 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||||||
4889 | Expr *LowerBound, | ||||||||
4890 | SourceLocation ColonLocFirst, | ||||||||
4891 | SourceLocation ColonLocSecond, | ||||||||
4892 | Expr *Length, Expr *Stride, | ||||||||
4893 | SourceLocation RBLoc) { | ||||||||
4894 | if (Base->getType()->isPlaceholderType() && | ||||||||
4895 | !Base->getType()->isSpecificPlaceholderType( | ||||||||
4896 | BuiltinType::OMPArraySection)) { | ||||||||
4897 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||||||
4898 | if (Result.isInvalid()) | ||||||||
4899 | return ExprError(); | ||||||||
4900 | Base = Result.get(); | ||||||||
4901 | } | ||||||||
4902 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4903 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||||||
4904 | if (Result.isInvalid()) | ||||||||
4905 | return ExprError(); | ||||||||
4906 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4907 | if (Result.isInvalid()) | ||||||||
4908 | return ExprError(); | ||||||||
4909 | LowerBound = Result.get(); | ||||||||
4910 | } | ||||||||
4911 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4912 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||||||
4913 | if (Result.isInvalid()) | ||||||||
4914 | return ExprError(); | ||||||||
4915 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4916 | if (Result.isInvalid()) | ||||||||
4917 | return ExprError(); | ||||||||
4918 | Length = Result.get(); | ||||||||
4919 | } | ||||||||
4920 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4921 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||||||
4922 | if (Result.isInvalid()) | ||||||||
4923 | return ExprError(); | ||||||||
4924 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4925 | if (Result.isInvalid()) | ||||||||
4926 | return ExprError(); | ||||||||
4927 | Stride = Result.get(); | ||||||||
4928 | } | ||||||||
4929 | |||||||||
4930 | // Build an unanalyzed expression if either operand is type-dependent. | ||||||||
4931 | if (Base->isTypeDependent() || | ||||||||
4932 | (LowerBound && | ||||||||
4933 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||||||
4934 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||||||
4935 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||||||
4936 | return new (Context) OMPArraySectionExpr( | ||||||||
4937 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||||||
4938 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||||||
4939 | } | ||||||||
4940 | |||||||||
4941 | // Perform default conversions. | ||||||||
4942 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||||||
4943 | QualType ResultTy; | ||||||||
4944 | if (OriginalTy->isAnyPointerType()) { | ||||||||
4945 | ResultTy = OriginalTy->getPointeeType(); | ||||||||
4946 | } else if (OriginalTy->isArrayType()) { | ||||||||
4947 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||||||
4948 | } else { | ||||||||
4949 | return ExprError( | ||||||||
4950 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||||||
4951 | << Base->getSourceRange()); | ||||||||
4952 | } | ||||||||
4953 | // C99 6.5.2.1p1 | ||||||||
4954 | if (LowerBound) { | ||||||||
4955 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||||||
4956 | LowerBound); | ||||||||
4957 | if (Res.isInvalid()) | ||||||||
4958 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||||||
4959 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4960 | << 0 << LowerBound->getSourceRange()); | ||||||||
4961 | LowerBound = Res.get(); | ||||||||
4962 | |||||||||
4963 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4964 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4965 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4966 | << 0 << LowerBound->getSourceRange(); | ||||||||
4967 | } | ||||||||
4968 | if (Length) { | ||||||||
4969 | auto Res = | ||||||||
4970 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||||||
4971 | if (Res.isInvalid()) | ||||||||
4972 | return ExprError(Diag(Length->getExprLoc(), | ||||||||
4973 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4974 | << 1 << Length->getSourceRange()); | ||||||||
4975 | Length = Res.get(); | ||||||||
4976 | |||||||||
4977 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4978 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4979 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4980 | << 1 << Length->getSourceRange(); | ||||||||
4981 | } | ||||||||
4982 | if (Stride) { | ||||||||
4983 | ExprResult Res = | ||||||||
4984 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||||||
4985 | if (Res.isInvalid()) | ||||||||
4986 | return ExprError(Diag(Stride->getExprLoc(), | ||||||||
4987 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4988 | << 1 << Stride->getSourceRange()); | ||||||||
4989 | Stride = Res.get(); | ||||||||
4990 | |||||||||
4991 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4992 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4993 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4994 | << 1 << Stride->getSourceRange(); | ||||||||
4995 | } | ||||||||
4996 | |||||||||
4997 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||||||
4998 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||||||
4999 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||||||
5000 | // incomplete types are not object types. | ||||||||
5001 | if (ResultTy->isFunctionType()) { | ||||||||
5002 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||||||
5003 | << ResultTy << Base->getSourceRange(); | ||||||||
5004 | return ExprError(); | ||||||||
5005 | } | ||||||||
5006 | |||||||||
5007 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||||||
5008 | diag::err_omp_section_incomplete_type, Base)) | ||||||||
5009 | return ExprError(); | ||||||||
5010 | |||||||||
5011 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||||||
5012 | Expr::EvalResult Result; | ||||||||
5013 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||||||
5014 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
5015 | // The array section must be a subset of the original array. | ||||||||
5016 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||||||
5017 | if (LowerBoundValue.isNegative()) { | ||||||||
5018 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||||||
5019 | << LowerBound->getSourceRange(); | ||||||||
5020 | return ExprError(); | ||||||||
5021 | } | ||||||||
5022 | } | ||||||||
5023 | } | ||||||||
5024 | |||||||||
5025 | if (Length) { | ||||||||
5026 | Expr::EvalResult Result; | ||||||||
5027 | if (Length->EvaluateAsInt(Result, Context)) { | ||||||||
5028 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
5029 | // The length must evaluate to non-negative integers. | ||||||||
5030 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||||||
5031 | if (LengthValue.isNegative()) { | ||||||||
5032 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||||||
5033 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5034 | << Length->getSourceRange(); | ||||||||
5035 | return ExprError(); | ||||||||
5036 | } | ||||||||
5037 | } | ||||||||
5038 | } else if (ColonLocFirst.isValid() && | ||||||||
5039 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||||||
5040 | !OriginalTy->isVariableArrayType()))) { | ||||||||
5041 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
5042 | // When the size of the array dimension is not known, the length must be | ||||||||
5043 | // specified explicitly. | ||||||||
5044 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||||||
5045 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||||||
5046 | return ExprError(); | ||||||||
5047 | } | ||||||||
5048 | |||||||||
5049 | if (Stride) { | ||||||||
5050 | Expr::EvalResult Result; | ||||||||
5051 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||||||
5052 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
5053 | // The stride must evaluate to a positive integer. | ||||||||
5054 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||||||
5055 | if (!StrideValue.isStrictlyPositive()) { | ||||||||
5056 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||||||
5057 | << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5058 | << Stride->getSourceRange(); | ||||||||
5059 | return ExprError(); | ||||||||
5060 | } | ||||||||
5061 | } | ||||||||
5062 | } | ||||||||
5063 | |||||||||
5064 | if (!Base->getType()->isSpecificPlaceholderType( | ||||||||
5065 | BuiltinType::OMPArraySection)) { | ||||||||
5066 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||||||
5067 | if (Result.isInvalid()) | ||||||||
5068 | return ExprError(); | ||||||||
5069 | Base = Result.get(); | ||||||||
5070 | } | ||||||||
5071 | return new (Context) OMPArraySectionExpr( | ||||||||
5072 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||||||
5073 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||||||
5074 | } | ||||||||
5075 | |||||||||
5076 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||||||
5077 | SourceLocation RParenLoc, | ||||||||
5078 | ArrayRef<Expr *> Dims, | ||||||||
5079 | ArrayRef<SourceRange> Brackets) { | ||||||||
5080 | if (Base->getType()->isPlaceholderType()) { | ||||||||
5081 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||||||
5082 | if (Result.isInvalid()) | ||||||||
5083 | return ExprError(); | ||||||||
5084 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
5085 | if (Result.isInvalid()) | ||||||||
5086 | return ExprError(); | ||||||||
5087 | Base = Result.get(); | ||||||||
5088 | } | ||||||||
5089 | QualType BaseTy = Base->getType(); | ||||||||
5090 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||||||
5091 | // required. | ||||||||
5092 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||||||
5093 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||||||
5094 | LParenLoc, RParenLoc, Dims, Brackets); | ||||||||
5095 | if (!BaseTy->isPointerType() || | ||||||||
5096 | (!Base->isTypeDependent() && | ||||||||
5097 | BaseTy->getPointeeType()->isIncompleteType())) | ||||||||
5098 | return ExprError(Diag(Base->getExprLoc(), | ||||||||
5099 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||||||
5100 | << Base->getSourceRange()); | ||||||||
5101 | |||||||||
5102 | SmallVector<Expr *, 4> NewDims; | ||||||||
5103 | bool ErrorFound = false; | ||||||||
5104 | for (Expr *Dim : Dims) { | ||||||||
5105 | if (Dim->getType()->isPlaceholderType()) { | ||||||||
5106 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||||||
5107 | if (Result.isInvalid()) { | ||||||||
5108 | ErrorFound = true; | ||||||||
5109 | continue; | ||||||||
5110 | } | ||||||||
5111 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
5112 | if (Result.isInvalid()) { | ||||||||
5113 | ErrorFound = true; | ||||||||
5114 | continue; | ||||||||
5115 | } | ||||||||
5116 | Dim = Result.get(); | ||||||||
5117 | } | ||||||||
5118 | if (!Dim->isTypeDependent()) { | ||||||||
5119 | ExprResult Result = | ||||||||
5120 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||||||
5121 | if (Result.isInvalid()) { | ||||||||
5122 | ErrorFound = true; | ||||||||
5123 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||||||
5124 | << Dim->getSourceRange(); | ||||||||
5125 | continue; | ||||||||
5126 | } | ||||||||
5127 | Dim = Result.get(); | ||||||||
5128 | Expr::EvalResult EvResult; | ||||||||
5129 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||||||
5130 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||||||
5131 | // Each si is an integral type expression that must evaluate to a | ||||||||
5132 | // positive integer. | ||||||||
5133 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||||||
5134 | if (!Value.isStrictlyPositive()) { | ||||||||
5135 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||||||
5136 | << Value.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5137 | << Dim->getSourceRange(); | ||||||||
5138 | ErrorFound = true; | ||||||||
5139 | continue; | ||||||||
5140 | } | ||||||||
5141 | } | ||||||||
5142 | } | ||||||||
5143 | NewDims.push_back(Dim); | ||||||||
5144 | } | ||||||||
5145 | if (ErrorFound) | ||||||||
5146 | return ExprError(); | ||||||||
5147 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||||||
5148 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||||||
5149 | } | ||||||||
5150 | |||||||||
5151 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||||||
5152 | SourceLocation LLoc, SourceLocation RLoc, | ||||||||
5153 | ArrayRef<OMPIteratorData> Data) { | ||||||||
5154 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||||||
5155 | bool IsCorrect = true; | ||||||||
5156 | for (const OMPIteratorData &D : Data) { | ||||||||
5157 | TypeSourceInfo *TInfo = nullptr; | ||||||||
5158 | SourceLocation StartLoc; | ||||||||
5159 | QualType DeclTy; | ||||||||
5160 | if (!D.Type.getAsOpaquePtr()) { | ||||||||
5161 | // OpenMP 5.0, 2.1.6 Iterators | ||||||||
5162 | // In an iterator-specifier, if the iterator-type is not specified then | ||||||||
5163 | // the type of that iterator is of int type. | ||||||||
5164 | DeclTy = Context.IntTy; | ||||||||
5165 | StartLoc = D.DeclIdentLoc; | ||||||||
5166 | } else { | ||||||||
5167 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||||||
5168 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||||||
5169 | } | ||||||||
5170 | |||||||||
5171 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||||||
5172 | DeclTy->containsUnexpandedParameterPack() || | ||||||||
5173 | DeclTy->isInstantiationDependentType(); | ||||||||
5174 | if (!IsDeclTyDependent) { | ||||||||
5175 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||||||
5176 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||||||
5177 | // The iterator-type must be an integral or pointer type. | ||||||||
5178 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||||||
5179 | << DeclTy; | ||||||||
5180 | IsCorrect = false; | ||||||||
5181 | continue; | ||||||||
5182 | } | ||||||||
5183 | if (DeclTy.isConstant(Context)) { | ||||||||
5184 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||||||
5185 | // The iterator-type must not be const qualified. | ||||||||
5186 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||||||
5187 | << DeclTy; | ||||||||
5188 | IsCorrect = false; | ||||||||
5189 | continue; | ||||||||
5190 | } | ||||||||
5191 | } | ||||||||
5192 | |||||||||
5193 | // Iterator declaration. | ||||||||
5194 | assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast <void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5194, __PRETTY_FUNCTION__)); | ||||||||
5195 | // Always try to create iterator declarator to avoid extra error messages | ||||||||
5196 | // about unknown declarations use. | ||||||||
5197 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||||||
5198 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||||||
5199 | VD->setImplicit(); | ||||||||
5200 | if (S) { | ||||||||
5201 | // Check for conflicting previous declaration. | ||||||||
5202 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||||||
5203 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||||||
5204 | ForVisibleRedeclaration); | ||||||||
5205 | Previous.suppressDiagnostics(); | ||||||||
5206 | LookupName(Previous, S); | ||||||||
5207 | |||||||||
5208 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||||||
5209 | /*AllowInlineNamespace=*/false); | ||||||||
5210 | if (!Previous.empty()) { | ||||||||
5211 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||||||
5212 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||||||
5213 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||||||
5214 | } else { | ||||||||
5215 | PushOnScopeChains(VD, S); | ||||||||
5216 | } | ||||||||
5217 | } else { | ||||||||
5218 | CurContext->addDecl(VD); | ||||||||
5219 | } | ||||||||
5220 | Expr *Begin = D.Range.Begin; | ||||||||
5221 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||||||
5222 | ExprResult BeginRes = | ||||||||
5223 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||||||
5224 | Begin = BeginRes.get(); | ||||||||
5225 | } | ||||||||
5226 | Expr *End = D.Range.End; | ||||||||
5227 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||||||
5228 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||||||
5229 | End = EndRes.get(); | ||||||||
5230 | } | ||||||||
5231 | Expr *Step = D.Range.Step; | ||||||||
5232 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||||||
5233 | if (!Step->getType()->isIntegralType(Context)) { | ||||||||
5234 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||||||
5235 | << Step << Step->getSourceRange(); | ||||||||
5236 | IsCorrect = false; | ||||||||
5237 | continue; | ||||||||
5238 | } | ||||||||
5239 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||||||
5240 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||||||
5241 | // If the step expression of a range-specification equals zero, the | ||||||||
5242 | // behavior is unspecified. | ||||||||
5243 | if (Result && Result->isNullValue()) { | ||||||||
5244 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||||||
5245 | << Step << Step->getSourceRange(); | ||||||||
5246 | IsCorrect = false; | ||||||||
5247 | continue; | ||||||||
5248 | } | ||||||||
5249 | } | ||||||||
5250 | if (!Begin || !End || !IsCorrect) { | ||||||||
5251 | IsCorrect = false; | ||||||||
5252 | continue; | ||||||||
5253 | } | ||||||||
5254 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||||||
5255 | IDElem.IteratorDecl = VD; | ||||||||
5256 | IDElem.AssignmentLoc = D.AssignLoc; | ||||||||
5257 | IDElem.Range.Begin = Begin; | ||||||||
5258 | IDElem.Range.End = End; | ||||||||
5259 | IDElem.Range.Step = Step; | ||||||||
5260 | IDElem.ColonLoc = D.ColonLoc; | ||||||||
5261 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||||||
5262 | } | ||||||||
5263 | if (!IsCorrect) { | ||||||||
5264 | // Invalidate all created iterator declarations if error is found. | ||||||||
5265 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5266 | if (Decl *ID = D.IteratorDecl) | ||||||||
5267 | ID->setInvalidDecl(); | ||||||||
5268 | } | ||||||||
5269 | return ExprError(); | ||||||||
5270 | } | ||||||||
5271 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||||||
5272 | if (!CurContext->isDependentContext()) { | ||||||||
5273 | // Build number of ityeration for each iteration range. | ||||||||
5274 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||||||
5275 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||||||
5276 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5277 | // (Endi - Begini) | ||||||||
5278 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||||||
5279 | D.Range.Begin); | ||||||||
5280 | if(!Res.isUsable()) { | ||||||||
5281 | IsCorrect = false; | ||||||||
5282 | continue; | ||||||||
5283 | } | ||||||||
5284 | ExprResult St, St1; | ||||||||
5285 | if (D.Range.Step) { | ||||||||
5286 | St = D.Range.Step; | ||||||||
5287 | // (Endi - Begini) + Stepi | ||||||||
5288 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||||||
5289 | if (!Res.isUsable()) { | ||||||||
5290 | IsCorrect = false; | ||||||||
5291 | continue; | ||||||||
5292 | } | ||||||||
5293 | // (Endi - Begini) + Stepi - 1 | ||||||||
5294 | Res = | ||||||||
5295 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||||||
5296 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||||||
5297 | if (!Res.isUsable()) { | ||||||||
5298 | IsCorrect = false; | ||||||||
5299 | continue; | ||||||||
5300 | } | ||||||||
5301 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||||||
5302 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||||||
5303 | if (!Res.isUsable()) { | ||||||||
5304 | IsCorrect = false; | ||||||||
5305 | continue; | ||||||||
5306 | } | ||||||||
5307 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||||||
5308 | // (Begini - Endi) | ||||||||
5309 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||||||
5310 | D.Range.Begin, D.Range.End); | ||||||||
5311 | if (!Res1.isUsable()) { | ||||||||
5312 | IsCorrect = false; | ||||||||
5313 | continue; | ||||||||
5314 | } | ||||||||
5315 | // (Begini - Endi) - Stepi | ||||||||
5316 | Res1 = | ||||||||
5317 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||||||
5318 | if (!Res1.isUsable()) { | ||||||||
5319 | IsCorrect = false; | ||||||||
5320 | continue; | ||||||||
5321 | } | ||||||||
5322 | // (Begini - Endi) - Stepi - 1 | ||||||||
5323 | Res1 = | ||||||||
5324 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||||||
5325 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||||||
5326 | if (!Res1.isUsable()) { | ||||||||
5327 | IsCorrect = false; | ||||||||
5328 | continue; | ||||||||
5329 | } | ||||||||
5330 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||||||
5331 | Res1 = | ||||||||
5332 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||||||
5333 | if (!Res1.isUsable()) { | ||||||||
5334 | IsCorrect = false; | ||||||||
5335 | continue; | ||||||||
5336 | } | ||||||||
5337 | // Stepi > 0. | ||||||||
5338 | ExprResult CmpRes = | ||||||||
5339 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||||||
5340 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||||||
5341 | if (!CmpRes.isUsable()) { | ||||||||
5342 | IsCorrect = false; | ||||||||
5343 | continue; | ||||||||
5344 | } | ||||||||
5345 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||||||
5346 | Res.get(), Res1.get()); | ||||||||
5347 | if (!Res.isUsable()) { | ||||||||
5348 | IsCorrect = false; | ||||||||
5349 | continue; | ||||||||
5350 | } | ||||||||
5351 | } | ||||||||
5352 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||||||
5353 | if (!Res.isUsable()) { | ||||||||
5354 | IsCorrect = false; | ||||||||
5355 | continue; | ||||||||
5356 | } | ||||||||
5357 | |||||||||
5358 | // Build counter update. | ||||||||
5359 | // Build counter. | ||||||||
5360 | auto *CounterVD = | ||||||||
5361 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||||||
5362 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||||||
5363 | Res.get()->getType(), nullptr, SC_None); | ||||||||
5364 | CounterVD->setImplicit(); | ||||||||
5365 | ExprResult RefRes = | ||||||||
5366 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||||||
5367 | D.IteratorDecl->getBeginLoc()); | ||||||||
5368 | // Build counter update. | ||||||||
5369 | // I = Begini + counter * Stepi; | ||||||||
5370 | ExprResult UpdateRes; | ||||||||
5371 | if (D.Range.Step) { | ||||||||
5372 | UpdateRes = CreateBuiltinBinOp( | ||||||||
5373 | D.AssignmentLoc, BO_Mul, | ||||||||
5374 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||||||
5375 | } else { | ||||||||
5376 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||||||
5377 | } | ||||||||
5378 | if (!UpdateRes.isUsable()) { | ||||||||
5379 | IsCorrect = false; | ||||||||
5380 | continue; | ||||||||
5381 | } | ||||||||
5382 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||||||
5383 | UpdateRes.get()); | ||||||||
5384 | if (!UpdateRes.isUsable()) { | ||||||||
5385 | IsCorrect = false; | ||||||||
5386 | continue; | ||||||||
5387 | } | ||||||||
5388 | ExprResult VDRes = | ||||||||
5389 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||||||
5390 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||||||
5391 | D.IteratorDecl->getBeginLoc()); | ||||||||
5392 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||||||
5393 | UpdateRes.get()); | ||||||||
5394 | if (!UpdateRes.isUsable()) { | ||||||||
5395 | IsCorrect = false; | ||||||||
5396 | continue; | ||||||||
5397 | } | ||||||||
5398 | UpdateRes = | ||||||||
5399 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||||||
5400 | if (!UpdateRes.isUsable()) { | ||||||||
5401 | IsCorrect = false; | ||||||||
5402 | continue; | ||||||||
5403 | } | ||||||||
5404 | ExprResult CounterUpdateRes = | ||||||||
5405 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||||||
5406 | if (!CounterUpdateRes.isUsable()) { | ||||||||
5407 | IsCorrect = false; | ||||||||
5408 | continue; | ||||||||
5409 | } | ||||||||
5410 | CounterUpdateRes = | ||||||||
5411 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||||||
5412 | if (!CounterUpdateRes.isUsable()) { | ||||||||
5413 | IsCorrect = false; | ||||||||
5414 | continue; | ||||||||
5415 | } | ||||||||
5416 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||||||
5417 | HD.CounterVD = CounterVD; | ||||||||
5418 | HD.Upper = Res.get(); | ||||||||
5419 | HD.Update = UpdateRes.get(); | ||||||||
5420 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||||||
5421 | } | ||||||||
5422 | } else { | ||||||||
5423 | Helpers.assign(ID.size(), {}); | ||||||||
5424 | } | ||||||||
5425 | if (!IsCorrect) { | ||||||||
5426 | // Invalidate all created iterator declarations if error is found. | ||||||||
5427 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5428 | if (Decl *ID = D.IteratorDecl) | ||||||||
5429 | ID->setInvalidDecl(); | ||||||||
5430 | } | ||||||||
5431 | return ExprError(); | ||||||||
5432 | } | ||||||||
5433 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||||||
5434 | LLoc, RLoc, ID, Helpers); | ||||||||
5435 | } | ||||||||
5436 | |||||||||
5437 | ExprResult | ||||||||
5438 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||||||
5439 | Expr *Idx, SourceLocation RLoc) { | ||||||||
5440 | Expr *LHSExp = Base; | ||||||||
5441 | Expr *RHSExp = Idx; | ||||||||
5442 | |||||||||
5443 | ExprValueKind VK = VK_LValue; | ||||||||
5444 | ExprObjectKind OK = OK_Ordinary; | ||||||||
5445 | |||||||||
5446 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||||||
5447 | // a non-lvalue array, and an lvalue otherwise. | ||||||||
5448 | if (getLangOpts().CPlusPlus11) { | ||||||||
5449 | for (auto *Op : {LHSExp, RHSExp}) { | ||||||||
5450 | Op = Op->IgnoreImplicit(); | ||||||||
5451 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||||||
5452 | VK = VK_XValue; | ||||||||
5453 | } | ||||||||
5454 | } | ||||||||
5455 | |||||||||
5456 | // Perform default conversions. | ||||||||
5457 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||||||
5458 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||||||
5459 | if (Result.isInvalid()) | ||||||||
5460 | return ExprError(); | ||||||||
5461 | LHSExp = Result.get(); | ||||||||
5462 | } | ||||||||
5463 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||||||
5464 | if (Result.isInvalid()) | ||||||||
5465 | return ExprError(); | ||||||||
5466 | RHSExp = Result.get(); | ||||||||
5467 | |||||||||
5468 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||||||
5469 | |||||||||
5470 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||||||
5471 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||||||
5472 | // in the subscript position. As a result, we need to derive the array base | ||||||||
5473 | // and index from the expression types. | ||||||||
5474 | Expr *BaseExpr, *IndexExpr; | ||||||||
5475 | QualType ResultType; | ||||||||
5476 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||||||
5477 | BaseExpr = LHSExp; | ||||||||
5478 | IndexExpr = RHSExp; | ||||||||
5479 | ResultType = Context.DependentTy; | ||||||||
5480 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||||||
5481 | BaseExpr = LHSExp; | ||||||||
5482 | IndexExpr = RHSExp; | ||||||||
5483 | ResultType = PTy->getPointeeType(); | ||||||||
5484 | } else if (const ObjCObjectPointerType *PTy = | ||||||||
5485 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||||||
5486 | BaseExpr = LHSExp; | ||||||||
5487 | IndexExpr = RHSExp; | ||||||||
5488 | |||||||||
5489 | // Use custom logic if this should be the pseudo-object subscript | ||||||||
5490 | // expression. | ||||||||
5491 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||||||
5492 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||||||
5493 | nullptr); | ||||||||
5494 | |||||||||
5495 | ResultType = PTy->getPointeeType(); | ||||||||
5496 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||||||
5497 | // Handle the uncommon case of "123[Ptr]". | ||||||||
5498 | BaseExpr = RHSExp; | ||||||||
5499 | IndexExpr = LHSExp; | ||||||||
5500 | ResultType = PTy->getPointeeType(); | ||||||||
5501 | } else if (const ObjCObjectPointerType *PTy = | ||||||||
5502 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||||||
5503 | // Handle the uncommon case of "123[Ptr]". | ||||||||
5504 | BaseExpr = RHSExp; | ||||||||
5505 | IndexExpr = LHSExp; | ||||||||
5506 | ResultType = PTy->getPointeeType(); | ||||||||
5507 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||||||
5508 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||||||
5509 | << ResultType << BaseExpr->getSourceRange(); | ||||||||
5510 | return ExprError(); | ||||||||
5511 | } | ||||||||
5512 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||||||
5513 | BaseExpr = LHSExp; // vectors: V[123] | ||||||||
5514 | IndexExpr = RHSExp; | ||||||||
5515 | // We apply C++ DR1213 to vector subscripting too. | ||||||||
5516 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | ||||||||
5517 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||||||
5518 | if (Materialized.isInvalid()) | ||||||||
5519 | return ExprError(); | ||||||||
5520 | LHSExp = Materialized.get(); | ||||||||
5521 | } | ||||||||
5522 | VK = LHSExp->getValueKind(); | ||||||||
5523 | if (VK != VK_RValue) | ||||||||
5524 | OK = OK_VectorComponent; | ||||||||
5525 | |||||||||
5526 | ResultType = VTy->getElementType(); | ||||||||
5527 | QualType BaseType = BaseExpr->getType(); | ||||||||
5528 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||||||
5529 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||||||
5530 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||||||
5531 | if (Combined != MemberQuals) | ||||||||
5532 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||||||
5533 | } else if (LHSTy->isArrayType()) { | ||||||||
5534 | // If we see an array that wasn't promoted by | ||||||||
5535 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||||||
5536 | // wasn't promoted because of the C90 rule that doesn't | ||||||||
5537 | // allow promoting non-lvalue arrays. Warn, then | ||||||||
5538 | // force the promotion here. | ||||||||
5539 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||||||
5540 | << LHSExp->getSourceRange(); | ||||||||
5541 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||||||
5542 | CK_ArrayToPointerDecay).get(); | ||||||||
5543 | LHSTy = LHSExp->getType(); | ||||||||
5544 | |||||||||
5545 | BaseExpr = LHSExp; | ||||||||
5546 | IndexExpr = RHSExp; | ||||||||
5547 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
5548 | } else if (RHSTy->isArrayType()) { | ||||||||
5549 | // Same as previous, except for 123[f().a] case | ||||||||
5550 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||||||
5551 | << RHSExp->getSourceRange(); | ||||||||
5552 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||||||
5553 | CK_ArrayToPointerDecay).get(); | ||||||||
5554 | RHSTy = RHSExp->getType(); | ||||||||
5555 | |||||||||
5556 | BaseExpr = RHSExp; | ||||||||
5557 | IndexExpr = LHSExp; | ||||||||
5558 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
5559 | } else { | ||||||||
5560 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||||||
5561 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||||||
5562 | } | ||||||||
5563 | // C99 6.5.2.1p1 | ||||||||
5564 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||||||
5565 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||||||
5566 | << IndexExpr->getSourceRange()); | ||||||||
5567 | |||||||||
5568 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
5569 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
5570 | && !IndexExpr->isTypeDependent()) | ||||||||
5571 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||||||
5572 | |||||||||
5573 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||||||
5574 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||||||
5575 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||||||
5576 | // incomplete types are not object types. | ||||||||
5577 | if (ResultType->isFunctionType()) { | ||||||||
5578 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||||||
5579 | << ResultType << BaseExpr->getSourceRange(); | ||||||||
5580 | return ExprError(); | ||||||||
5581 | } | ||||||||
5582 | |||||||||
5583 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||||||
5584 | // GNU extension: subscripting on pointer to void | ||||||||
5585 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||||||
5586 | << BaseExpr->getSourceRange(); | ||||||||
5587 | |||||||||
5588 | // C forbids expressions of unqualified void type from being l-values. | ||||||||
5589 | // See IsCForbiddenLValueType. | ||||||||
5590 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | ||||||||
5591 | } else if (!ResultType->isDependentType() && | ||||||||
5592 | RequireCompleteSizedType( | ||||||||
5593 | LLoc, ResultType, | ||||||||
5594 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||||||
5595 | return ExprError(); | ||||||||
5596 | |||||||||
5597 | assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5598, __PRETTY_FUNCTION__)) | ||||||||
5598 | !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5598, __PRETTY_FUNCTION__)); | ||||||||
5599 | |||||||||
5600 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||||||
5601 | FunctionScopes.size() > 1) { | ||||||||
5602 | if (auto *TT = | ||||||||
5603 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||||||
5604 | for (auto I = FunctionScopes.rbegin(), | ||||||||
5605 | E = std::prev(FunctionScopes.rend()); | ||||||||
5606 | I != E; ++I) { | ||||||||
5607 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||||||
5608 | if (CSI == nullptr) | ||||||||
5609 | break; | ||||||||
5610 | DeclContext *DC = nullptr; | ||||||||
5611 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||||||
5612 | DC = LSI->CallOperator; | ||||||||
5613 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||||||
5614 | DC = CRSI->TheCapturedDecl; | ||||||||
5615 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||||||
5616 | DC = BSI->TheDecl; | ||||||||
5617 | if (DC) { | ||||||||
5618 | if (DC->containsDecl(TT->getDecl())) | ||||||||
5619 | break; | ||||||||
5620 | captureVariablyModifiedType( | ||||||||
5621 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||||||
5622 | } | ||||||||
5623 | } | ||||||||
5624 | } | ||||||||
5625 | } | ||||||||
5626 | |||||||||
5627 | return new (Context) | ||||||||
5628 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||||||
5629 | } | ||||||||
5630 | |||||||||
5631 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||||||
5632 | ParmVarDecl *Param) { | ||||||||
5633 | if (Param->hasUnparsedDefaultArg()) { | ||||||||
5634 | // If we've already cleared out the location for the default argument, | ||||||||
5635 | // that means we're parsing it right now. | ||||||||
5636 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||||||
5637 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||||||
5638 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||||||
5639 | Param->setInvalidDecl(); | ||||||||
5640 | return true; | ||||||||
5641 | } | ||||||||
5642 | |||||||||
5643 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||||||
5644 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||||||
5645 | Diag(UnparsedDefaultArgLocs[Param], | ||||||||
5646 | diag::note_default_argument_declared_here); | ||||||||
5647 | return true; | ||||||||
5648 | } | ||||||||
5649 | |||||||||
5650 | if (Param->hasUninstantiatedDefaultArg() && | ||||||||
5651 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||||||
5652 | return true; | ||||||||
5653 | |||||||||
5654 | assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?" ) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5654, __PRETTY_FUNCTION__)); | ||||||||
5655 | |||||||||
5656 | // If the default expression creates temporaries, we need to | ||||||||
5657 | // push them to the current stack of expression temporaries so they'll | ||||||||
5658 | // be properly destroyed. | ||||||||
5659 | // FIXME: We should really be rebuilding the default argument with new | ||||||||
5660 | // bound temporaries; see the comment in PR5810. | ||||||||
5661 | // We don't need to do that with block decls, though, because | ||||||||
5662 | // blocks in default argument expression can never capture anything. | ||||||||
5663 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||||||
5664 | // Set the "needs cleanups" bit regardless of whether there are | ||||||||
5665 | // any explicit objects. | ||||||||
5666 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||||||
5667 | |||||||||
5668 | // Append all the objects to the cleanup list. Right now, this | ||||||||
5669 | // should always be a no-op, because blocks in default argument | ||||||||
5670 | // expressions should never be able to capture anything. | ||||||||
5671 | assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5672, __PRETTY_FUNCTION__)) | ||||||||
5672 | "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5672, __PRETTY_FUNCTION__)); | ||||||||
5673 | } | ||||||||
5674 | |||||||||
5675 | // We already type-checked the argument, so we know it works. | ||||||||
5676 | // Just mark all of the declarations in this potentially-evaluated expression | ||||||||
5677 | // as being "referenced". | ||||||||
5678 | EnterExpressionEvaluationContext EvalContext( | ||||||||
5679 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||||||
5680 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||||||
5681 | /*SkipLocalVariables=*/true); | ||||||||
5682 | return false; | ||||||||
5683 | } | ||||||||
5684 | |||||||||
5685 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||||||
5686 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||||||
5687 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg" ) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5687, __PRETTY_FUNCTION__)); | ||||||||
5688 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||||||
5689 | return ExprError(); | ||||||||
5690 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||||||
5691 | } | ||||||||
5692 | |||||||||
5693 | Sema::VariadicCallType | ||||||||
5694 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||||||
5695 | Expr *Fn) { | ||||||||
5696 | if (Proto && Proto->isVariadic()) { | ||||||||
5697 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | ||||||||
5698 | return VariadicConstructor; | ||||||||
5699 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||||||
5700 | return VariadicBlock; | ||||||||
5701 | else if (FDecl) { | ||||||||
5702 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||||||
5703 | if (Method->isInstance()) | ||||||||
5704 | return VariadicMethod; | ||||||||
5705 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||||||
5706 | return VariadicMethod; | ||||||||
5707 | return VariadicFunction; | ||||||||
5708 | } | ||||||||
5709 | return VariadicDoesNotApply; | ||||||||
5710 | } | ||||||||
5711 | |||||||||
5712 | namespace { | ||||||||
5713 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||||||
5714 | public: | ||||||||
5715 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||||||
5716 | unsigned NumArgs, MemberExpr *ME) | ||||||||
5717 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||||||
5718 | FunctionName(FuncName) {} | ||||||||
5719 | |||||||||
5720 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||||
5721 | if (!candidate.getCorrectionSpecifier() || | ||||||||
5722 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||||||
5723 | return false; | ||||||||
5724 | } | ||||||||
5725 | |||||||||
5726 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||||||
5727 | } | ||||||||
5728 | |||||||||
5729 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||||
5730 | return std::make_unique<FunctionCallCCC>(*this); | ||||||||
5731 | } | ||||||||
5732 | |||||||||
5733 | private: | ||||||||
5734 | const IdentifierInfo *const FunctionName; | ||||||||
5735 | }; | ||||||||
5736 | } | ||||||||
5737 | |||||||||
5738 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||||||
5739 | FunctionDecl *FDecl, | ||||||||
5740 | ArrayRef<Expr *> Args) { | ||||||||
5741 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||||||
5742 | DeclarationName FuncName = FDecl->getDeclName(); | ||||||||
5743 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||||||
5744 | |||||||||
5745 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||||||
5746 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||||||
5747 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||||||
5748 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||||||
5749 | Sema::CTK_ErrorRecovery)) { | ||||||||
5750 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||||||
5751 | if (Corrected.isOverloaded()) { | ||||||||
5752 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||||||
5753 | OverloadCandidateSet::iterator Best; | ||||||||
5754 | for (NamedDecl *CD : Corrected) { | ||||||||
5755 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||||||
5756 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||||||
5757 | OCS); | ||||||||
5758 | } | ||||||||
5759 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||||||
5760 | case OR_Success: | ||||||||
5761 | ND = Best->FoundDecl; | ||||||||
5762 | Corrected.setCorrectionDecl(ND); | ||||||||
5763 | break; | ||||||||
5764 | default: | ||||||||
5765 | break; | ||||||||
5766 | } | ||||||||
5767 | } | ||||||||
5768 | ND = ND->getUnderlyingDecl(); | ||||||||
5769 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||||||
5770 | return Corrected; | ||||||||
5771 | } | ||||||||
5772 | } | ||||||||
5773 | return TypoCorrection(); | ||||||||
5774 | } | ||||||||
5775 | |||||||||
5776 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||||||
5777 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||||||
5778 | /// function prototype Proto. Call is the call expression itself, and | ||||||||
5779 | /// Fn is the function expression. For a C++ member function, this | ||||||||
5780 | /// routine does not attempt to convert the object argument. Returns | ||||||||
5781 | /// true if the call is ill-formed. | ||||||||
5782 | bool | ||||||||
5783 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||||||
5784 | FunctionDecl *FDecl, | ||||||||
5785 | const FunctionProtoType *Proto, | ||||||||
5786 | ArrayRef<Expr *> Args, | ||||||||
5787 | SourceLocation RParenLoc, | ||||||||
5788 | bool IsExecConfig) { | ||||||||
5789 | // Bail out early if calling a builtin with custom typechecking. | ||||||||
5790 | if (FDecl) | ||||||||
5791 | if (unsigned ID = FDecl->getBuiltinID()) | ||||||||
5792 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||||||
5793 | return false; | ||||||||
5794 | |||||||||
5795 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||||||
5796 | // assignment, to the types of the corresponding parameter, ... | ||||||||
5797 | unsigned NumParams = Proto->getNumParams(); | ||||||||
5798 | bool Invalid = false; | ||||||||
5799 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||||||
5800 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||||||
5801 | ? 1 /* block */ | ||||||||
5802 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||||||
5803 | : 0 /* function */); | ||||||||
5804 | |||||||||
5805 | // If too few arguments are available (and we don't have default | ||||||||
5806 | // arguments for the remaining parameters), don't make the call. | ||||||||
5807 | if (Args.size() < NumParams) { | ||||||||
5808 | if (Args.size() < MinArgs) { | ||||||||
5809 | TypoCorrection TC; | ||||||||
5810 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||||||
5811 | unsigned diag_id = | ||||||||
5812 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5813 | ? diag::err_typecheck_call_too_few_args_suggest | ||||||||
5814 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||||||
5815 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||||||
5816 | << static_cast<unsigned>(Args.size()) | ||||||||
5817 | << TC.getCorrectionRange()); | ||||||||
5818 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||||||
5819 | Diag(RParenLoc, | ||||||||
5820 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5821 | ? diag::err_typecheck_call_too_few_args_one | ||||||||
5822 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||||||
5823 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||||||
5824 | else | ||||||||
5825 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5826 | ? diag::err_typecheck_call_too_few_args | ||||||||
5827 | : diag::err_typecheck_call_too_few_args_at_least) | ||||||||
5828 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||||||
5829 | << Fn->getSourceRange(); | ||||||||
5830 | |||||||||
5831 | // Emit the location of the prototype. | ||||||||
5832 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||||||
5833 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||||||
5834 | |||||||||
5835 | return true; | ||||||||
5836 | } | ||||||||
5837 | // We reserve space for the default arguments when we create | ||||||||
5838 | // the call expression, before calling ConvertArgumentsForCall. | ||||||||
5839 | assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5840, __PRETTY_FUNCTION__)) | ||||||||
5840 | "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaExpr.cpp" , 5840, __PRETTY_FUNCTION__)); | ||||||||
5841 | } | ||||||||
5842 | |||||||||
5843 | // If too many are passed and not variadic, error on the extras and drop | ||||||||
5844 | // them. | ||||||||
5845 | if (Args.size() > NumParams) { | ||||||||
5846 | if (!Proto->isVariadic()) { | ||||||||
5847 | TypoCorrection TC; | ||||||||
5848 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||||||
5849 | unsigned diag_id = | ||||||||
5850 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5851 | ? diag::err_typecheck_call_too_many_args_suggest | ||||||||
5852 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||||||
5853 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||||||
5854 | << static_cast<unsigned>(Args.size()) | ||||||||
5855 | << TC.getCorrectionRange()); | ||||||||
5856 | } else if (NumParams == 1 && FDecl && | ||||||||
5857 | FDecl->getParamDecl(0)->getDeclName()) | ||||||||
5858 | Diag(Args[NumParams]->getBeginLoc(), | ||||||||
5859 | MinArgs == NumParams | ||||||||
5860 | ? diag::err_typecheck_call_too_many_args_one | ||||||||
5861 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||||||
5862 | << FnKind << FDecl->getParamDecl(0) | ||||||||
5863 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||||||
5864 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||||||
5865 | Args.back()->getEndLoc()); | ||||||||
5866 | else | ||||||||
5867 | Diag(Args[NumParams]->getBeginLoc(), | ||||||||
5868 | MinArgs == NumParams | ||||||||
5869 | ? diag::err_typecheck_call_too_many_args | ||||||||
5870 | : diag::err_typecheck_call_too_many_args_at_most) | ||||||||
5871 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||||||
5872 | << Fn->getSourceRange() | ||||||||
5873 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||||||
5874 | Args.back()->getEndLoc()); | ||||||||
5875 | |||||||||
5876 | // Emit the location of the prototype. | ||||||||
5877 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||||||
5878 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||||||
5879 | |||||||||
5880 | // This deletes the extra arguments. | ||||||||
5881 | Call->shrinkNumArgs(NumParams); | ||||||||
5882 | return true; | ||||||||
5883 | } | ||||||||
5884 | } | ||||||||
5885 | SmallVector<Expr *, 8> AllArgs; | ||||||||
5886 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||||||
5887 | |||||||||
5888 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||||||
5889 | AllArgs, CallType); | ||||||||
5890 | if (Invalid) | ||||||||
5891 | return true; | ||||||||
5892 | unsigned TotalNumArgs = AllArgs.size(); | ||||||||
5893 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||||||
5894 | Call->setArg(i, AllArgs[i]); | ||||||||
5895 | |||||||||
5896 | return false; | ||||||||
5897 | } | ||||||||
5898 | |||||||||
5899 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||||||
5900 | const FunctionProtoType *Proto, | ||||||||
5901 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||||||
5902 | SmallVectorImpl<Expr *> &AllArgs, | ||||||||
5903 | VariadicCallType CallType, bool AllowExplicit, | ||||||||
5904 | bool IsListInitialization) { | ||||||||
5905 | unsigned NumParams = Proto->getNumParams(); | ||||||||
5906 | bool Invalid = false; | ||||||||
5907 | size_t ArgIx = 0; | ||||||||
5908 | // Continue to check argument types (even if we have too few/many args). | ||||||||
5909 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||||||
5910 | QualType ProtoArgType = Proto->getParamType(i); | ||||||||
5911 | |||||||||
5912 | Expr *Arg; | ||||||||
5913 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||||||
5914 | if (ArgIx < Args.size()) { | ||||||||
5915 | Arg = Args[ArgIx++]; | ||||||||
5916 | |||||||||
5917 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||||||
5918 | diag::err_call_incomplete_argument, Arg)) | ||||||||
5919 | return true; | ||||||||
5920 | |||||||||
5921 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||||||
5922 | bool CFAudited = false; | ||||||||
5923 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||||||
5924 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||||||
5925 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||||||
5926 | Arg = stripARCUnbridgedCast(Arg); | ||||||||
5927 | else if (getLangOpts().ObjCAutoRefCount && | ||||||||
5928 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||||||
5929 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||||||
5930 | CFAudited = true; | ||||||||
5931 | |||||||||
5932 | if (Proto->getExtParameterInfo(i).isNoEscape()) | ||||||||
5933 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||||||
5934 | BE->getBlockDecl()->setDoesNotEscape(); | ||||||||
5935 | |||||||||
5936 | InitializedEntity Entity = | ||||||||
5937 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||||||
5938 | ProtoArgType) | ||||||||
5939 | : InitializedEntity::InitializeParameter( | ||||||||
5940 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||||||
5941 | |||||||||