File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 9195, 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/Support/ConvertUTF.h" | ||||||||
50 | #include "llvm/Support/SaveAndRestore.h" | ||||||||
51 | using namespace clang; | ||||||||
52 | using namespace sema; | ||||||||
53 | using llvm::RoundingMode; | ||||||||
54 | |||||||||
55 | /// Determine whether the use of this declaration is valid, without | ||||||||
56 | /// emitting diagnostics. | ||||||||
57 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||||||
58 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||||||
59 | if (ParsingInitForAutoVars.count(D)) | ||||||||
60 | return false; | ||||||||
61 | |||||||||
62 | // See if this is a deleted function. | ||||||||
63 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
64 | if (FD->isDeleted()) | ||||||||
65 | return false; | ||||||||
66 | |||||||||
67 | // If the function has a deduced return type, and we can't deduce it, | ||||||||
68 | // then we can't use it either. | ||||||||
69 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||||||
70 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||||||
71 | return false; | ||||||||
72 | |||||||||
73 | // See if this is an aligned allocation/deallocation function that is | ||||||||
74 | // unavailable. | ||||||||
75 | if (TreatUnavailableAsInvalid && | ||||||||
76 | isUnavailableAlignedAllocationFunction(*FD)) | ||||||||
77 | return false; | ||||||||
78 | } | ||||||||
79 | |||||||||
80 | // See if this function is unavailable. | ||||||||
81 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||||||
82 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||||||
83 | return false; | ||||||||
84 | |||||||||
85 | return true; | ||||||||
86 | } | ||||||||
87 | |||||||||
88 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||||||
89 | // Warn if this is used but marked unused. | ||||||||
90 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||||||
91 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||||||
92 | // should diagnose them. | ||||||||
93 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||||||
94 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||||||
95 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||||||
96 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||||||
97 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||||||
98 | } | ||||||||
99 | } | ||||||||
100 | } | ||||||||
101 | |||||||||
102 | /// Emit a note explaining that this function is deleted. | ||||||||
103 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||||||
104 | assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void > (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 104, __PRETTY_FUNCTION__)); | ||||||||
105 | |||||||||
106 | if (Decl->isDefaulted()) { | ||||||||
107 | // If the method was explicitly defaulted, point at that declaration. | ||||||||
108 | if (!Decl->isImplicit()) | ||||||||
109 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||||||
110 | |||||||||
111 | // Try to diagnose why this special member function was implicitly | ||||||||
112 | // deleted. This might fail, if that reason no longer applies. | ||||||||
113 | DiagnoseDeletedDefaultedFunction(Decl); | ||||||||
114 | return; | ||||||||
115 | } | ||||||||
116 | |||||||||
117 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||||||
118 | if (Ctor && Ctor->isInheritingConstructor()) | ||||||||
119 | return NoteDeletedInheritingConstructor(Ctor); | ||||||||
120 | |||||||||
121 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||||||
122 | << Decl << 1; | ||||||||
123 | } | ||||||||
124 | |||||||||
125 | /// Determine whether a FunctionDecl was ever declared with an | ||||||||
126 | /// explicit storage class. | ||||||||
127 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||||||
128 | for (auto I : D->redecls()) { | ||||||||
129 | if (I->getStorageClass() != SC_None) | ||||||||
130 | return true; | ||||||||
131 | } | ||||||||
132 | return false; | ||||||||
133 | } | ||||||||
134 | |||||||||
135 | /// Check whether we're in an extern inline function and referring to a | ||||||||
136 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||||||
137 | /// | ||||||||
138 | /// This is only a warning because we used to silently accept this code, but | ||||||||
139 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||||||
140 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||||||
141 | /// and so while there may still be user mistakes, most of the time we can't | ||||||||
142 | /// prove that there are errors. | ||||||||
143 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||||||
144 | const NamedDecl *D, | ||||||||
145 | SourceLocation Loc) { | ||||||||
146 | // This is disabled under C++; there are too many ways for this to fire in | ||||||||
147 | // contexts where the warning is a false positive, or where it is technically | ||||||||
148 | // correct but benign. | ||||||||
149 | if (S.getLangOpts().CPlusPlus) | ||||||||
150 | return; | ||||||||
151 | |||||||||
152 | // Check if this is an inlined function or method. | ||||||||
153 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||||||
154 | if (!Current) | ||||||||
155 | return; | ||||||||
156 | if (!Current->isInlined()) | ||||||||
157 | return; | ||||||||
158 | if (!Current->isExternallyVisible()) | ||||||||
159 | return; | ||||||||
160 | |||||||||
161 | // Check if the decl has internal linkage. | ||||||||
162 | if (D->getFormalLinkage() != InternalLinkage) | ||||||||
163 | return; | ||||||||
164 | |||||||||
165 | // Downgrade from ExtWarn to Extension if | ||||||||
166 | // (1) the supposedly external inline function is in the main file, | ||||||||
167 | // and probably won't be included anywhere else. | ||||||||
168 | // (2) the thing we're referencing is a pure function. | ||||||||
169 | // (3) the thing we're referencing is another inline function. | ||||||||
170 | // This last can give us false negatives, but it's better than warning on | ||||||||
171 | // wrappers for simple C library functions. | ||||||||
172 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||||||
173 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||||||
174 | if (!DowngradeWarning && UsedFn) | ||||||||
175 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||||||
176 | |||||||||
177 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||||||
178 | : diag::ext_internal_in_extern_inline) | ||||||||
179 | << /*IsVar=*/!UsedFn << D; | ||||||||
180 | |||||||||
181 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||||||
182 | |||||||||
183 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||||||
184 | << D; | ||||||||
185 | } | ||||||||
186 | |||||||||
187 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||||||
188 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||||||
189 | |||||||||
190 | // Suggest "static" on the function, if possible. | ||||||||
191 | if (!hasAnyExplicitStorageClass(First)) { | ||||||||
192 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||||||
193 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||||||
194 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||||||
195 | } | ||||||||
196 | } | ||||||||
197 | |||||||||
198 | /// Determine whether the use of this declaration is valid, and | ||||||||
199 | /// emit any corresponding diagnostics. | ||||||||
200 | /// | ||||||||
201 | /// This routine diagnoses various problems with referencing | ||||||||
202 | /// declarations that can occur when using a declaration. For example, | ||||||||
203 | /// it might warn if a deprecated or unavailable declaration is being | ||||||||
204 | /// used, or produce an error (and return true) if a C++0x deleted | ||||||||
205 | /// function is being used. | ||||||||
206 | /// | ||||||||
207 | /// \returns true if there was an error (this declaration cannot be | ||||||||
208 | /// referenced), false otherwise. | ||||||||
209 | /// | ||||||||
210 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||||||
211 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||||||
212 | bool ObjCPropertyAccess, | ||||||||
213 | bool AvoidPartialAvailabilityChecks, | ||||||||
214 | ObjCInterfaceDecl *ClassReceiver) { | ||||||||
215 | SourceLocation Loc = Locs.front(); | ||||||||
216 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||||||
217 | // If there were any diagnostics suppressed by template argument deduction, | ||||||||
218 | // emit them now. | ||||||||
219 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||||||
220 | if (Pos != SuppressedDiagnostics.end()) { | ||||||||
221 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||||||
222 | Diag(Suppressed.first, Suppressed.second); | ||||||||
223 | |||||||||
224 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||||||
225 | // them again for this specialization. However, we don't obsolete this | ||||||||
226 | // entry from the table, because we want to avoid ever emitting these | ||||||||
227 | // diagnostics again. | ||||||||
228 | Pos->second.clear(); | ||||||||
229 | } | ||||||||
230 | |||||||||
231 | // C++ [basic.start.main]p3: | ||||||||
232 | // The function 'main' shall not be used within a program. | ||||||||
233 | if (cast<FunctionDecl>(D)->isMain()) | ||||||||
234 | Diag(Loc, diag::ext_main_used); | ||||||||
235 | |||||||||
236 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||||||
237 | } | ||||||||
238 | |||||||||
239 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||||||
240 | if (ParsingInitForAutoVars.count(D)) { | ||||||||
241 | if (isa<BindingDecl>(D)) { | ||||||||
242 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||||||
243 | << D->getDeclName(); | ||||||||
244 | } else { | ||||||||
245 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||||||
246 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||||||
247 | } | ||||||||
248 | return true; | ||||||||
249 | } | ||||||||
250 | |||||||||
251 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
252 | // See if this is a deleted function. | ||||||||
253 | if (FD->isDeleted()) { | ||||||||
254 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||||||
255 | if (Ctor && Ctor->isInheritingConstructor()) | ||||||||
256 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||||||
257 | << Ctor->getParent() | ||||||||
258 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||||||
259 | else | ||||||||
260 | Diag(Loc, diag::err_deleted_function_use); | ||||||||
261 | NoteDeletedFunction(FD); | ||||||||
262 | return true; | ||||||||
263 | } | ||||||||
264 | |||||||||
265 | // [expr.prim.id]p4 | ||||||||
266 | // A program that refers explicitly or implicitly to a function with a | ||||||||
267 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||||||
268 | // other than to declare it, is ill-formed. [...] | ||||||||
269 | // | ||||||||
270 | // See if this is a function with constraints that need to be satisfied. | ||||||||
271 | // Check this before deducing the return type, as it might instantiate the | ||||||||
272 | // definition. | ||||||||
273 | if (FD->getTrailingRequiresClause()) { | ||||||||
274 | ConstraintSatisfaction Satisfaction; | ||||||||
275 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | ||||||||
276 | // A diagnostic will have already been generated (non-constant | ||||||||
277 | // constraint expression, for example) | ||||||||
278 | return true; | ||||||||
279 | if (!Satisfaction.IsSatisfied) { | ||||||||
280 | Diag(Loc, | ||||||||
281 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||||||
282 | << D; | ||||||||
283 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||||||
284 | return true; | ||||||||
285 | } | ||||||||
286 | } | ||||||||
287 | |||||||||
288 | // If the function has a deduced return type, and we can't deduce it, | ||||||||
289 | // then we can't use it either. | ||||||||
290 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||||||
291 | DeduceReturnType(FD, Loc)) | ||||||||
292 | return true; | ||||||||
293 | |||||||||
294 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||||||
295 | return true; | ||||||||
296 | |||||||||
297 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||||||
298 | return true; | ||||||||
299 | } | ||||||||
300 | |||||||||
301 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||||||
302 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||||||
303 | if (MD->getParent()->isLambda() && | ||||||||
304 | ((isa<CXXConstructorDecl>(MD) && | ||||||||
305 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||||||
306 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||||||
307 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||||||
308 | << !isa<CXXConstructorDecl>(MD); | ||||||||
309 | } | ||||||||
310 | } | ||||||||
311 | |||||||||
312 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||||||
313 | const ObjCPropertyDecl * { | ||||||||
314 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||||||
315 | return MD->findPropertyDecl(); | ||||||||
316 | return nullptr; | ||||||||
317 | }; | ||||||||
318 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||||||
319 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||||||
320 | return true; | ||||||||
321 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||||||
322 | return true; | ||||||||
323 | } | ||||||||
324 | |||||||||
325 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||||||
326 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||||||
327 | // Only the variables omp_priv and omp_orig are allowed in the | ||||||||
328 | // initializer-clause. | ||||||||
329 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||||||
330 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||||||
331 | isa<VarDecl>(D)) { | ||||||||
332 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||||||
333 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||||||
334 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
335 | return true; | ||||||||
336 | } | ||||||||
337 | |||||||||
338 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||||||
339 | // List-items in map clauses on this construct may only refer to the declared | ||||||||
340 | // variable var and entities that could be referenced by a procedure defined | ||||||||
341 | // at the same location | ||||||||
342 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||||||
343 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||||||
344 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||||||
345 | << getOpenMPDeclareMapperVarName(); | ||||||||
346 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
347 | return true; | ||||||||
348 | } | ||||||||
349 | |||||||||
350 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||||||
351 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||||||
352 | |||||||||
353 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||||||
354 | |||||||||
355 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||||||
356 | |||||||||
357 | // CUDA/HIP: Diagnose invalid references of host global variables in device | ||||||||
358 | // functions. Reference of device global variables in host functions is | ||||||||
359 | // allowed through shadow variables therefore it is not diagnosed. | ||||||||
360 | if (LangOpts.CUDAIsDevice) { | ||||||||
361 | auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); | ||||||||
362 | auto Target = IdentifyCUDATarget(FD); | ||||||||
363 | if (FD && Target != CFT_Host) { | ||||||||
364 | const auto *VD = dyn_cast<VarDecl>(D); | ||||||||
365 | if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && | ||||||||
366 | !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && | ||||||||
367 | !VD->getType()->isCUDADeviceBuiltinSurfaceType() && | ||||||||
368 | !VD->getType()->isCUDADeviceBuiltinTextureType() && | ||||||||
369 | !VD->isConstexpr() && !VD->getType().isConstQualified()) | ||||||||
370 | targetDiag(*Locs.begin(), diag::err_ref_bad_target) | ||||||||
371 | << /*host*/ 2 << /*variable*/ 1 << VD << Target; | ||||||||
372 | } | ||||||||
373 | } | ||||||||
374 | |||||||||
375 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||||||
376 | if (const auto *VD = dyn_cast<ValueDecl>(D)) | ||||||||
377 | checkDeviceDecl(VD, Loc); | ||||||||
378 | |||||||||
379 | if (!Context.getTargetInfo().isTLSSupported()) | ||||||||
380 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||||||
381 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||||||
382 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||||||
383 | } | ||||||||
384 | |||||||||
385 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||||||
386 | !isUnevaluatedContext()) { | ||||||||
387 | // C++ [expr.prim.req.nested] p3 | ||||||||
388 | // A local parameter shall only appear as an unevaluated operand | ||||||||
389 | // (Clause 8) within the constraint-expression. | ||||||||
390 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||||||
391 | << D; | ||||||||
392 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
393 | return true; | ||||||||
394 | } | ||||||||
395 | |||||||||
396 | return false; | ||||||||
397 | } | ||||||||
398 | |||||||||
399 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||||||
400 | /// message-send is to a declaration with the sentinel attribute, and | ||||||||
401 | /// if so, it checks that the requirements of the sentinel are | ||||||||
402 | /// satisfied. | ||||||||
403 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||||||
404 | ArrayRef<Expr *> Args) { | ||||||||
405 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||||||
406 | if (!attr) | ||||||||
407 | return; | ||||||||
408 | |||||||||
409 | // The number of formal parameters of the declaration. | ||||||||
410 | unsigned numFormalParams; | ||||||||
411 | |||||||||
412 | // The kind of declaration. This is also an index into a %select in | ||||||||
413 | // the diagnostic. | ||||||||
414 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||||||
415 | |||||||||
416 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||||||
417 | numFormalParams = MD->param_size(); | ||||||||
418 | calleeType = CT_Method; | ||||||||
419 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
420 | numFormalParams = FD->param_size(); | ||||||||
421 | calleeType = CT_Function; | ||||||||
422 | } else if (isa<VarDecl>(D)) { | ||||||||
423 | QualType type = cast<ValueDecl>(D)->getType(); | ||||||||
424 | const FunctionType *fn = nullptr; | ||||||||
425 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||||||
426 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||||||
427 | if (!fn) return; | ||||||||
428 | calleeType = CT_Function; | ||||||||
429 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||||||
430 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||||||
431 | calleeType = CT_Block; | ||||||||
432 | } else { | ||||||||
433 | return; | ||||||||
434 | } | ||||||||
435 | |||||||||
436 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||||||
437 | numFormalParams = proto->getNumParams(); | ||||||||
438 | } else { | ||||||||
439 | numFormalParams = 0; | ||||||||
440 | } | ||||||||
441 | } else { | ||||||||
442 | return; | ||||||||
443 | } | ||||||||
444 | |||||||||
445 | // "nullPos" is the number of formal parameters at the end which | ||||||||
446 | // effectively count as part of the variadic arguments. This is | ||||||||
447 | // useful if you would prefer to not have *any* formal parameters, | ||||||||
448 | // but the language forces you to have at least one. | ||||||||
449 | unsigned nullPos = attr->getNullPos(); | ||||||||
450 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 450, __PRETTY_FUNCTION__)); | ||||||||
451 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||||||
452 | |||||||||
453 | // The number of arguments which should follow the sentinel. | ||||||||
454 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||||||
455 | |||||||||
456 | // If there aren't enough arguments for all the formal parameters, | ||||||||
457 | // the sentinel, and the args after the sentinel, complain. | ||||||||
458 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||||||
459 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||||||
460 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||||||
461 | return; | ||||||||
462 | } | ||||||||
463 | |||||||||
464 | // Otherwise, find the sentinel expression. | ||||||||
465 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||||||
466 | if (!sentinelExpr) return; | ||||||||
467 | if (sentinelExpr->isValueDependent()) return; | ||||||||
468 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||||||
469 | |||||||||
470 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||||||
471 | // or 'NULL' if those are actually defined in the context. Only use | ||||||||
472 | // 'nil' for ObjC methods, where it's much more likely that the | ||||||||
473 | // variadic arguments form a list of object pointers. | ||||||||
474 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||||||
475 | std::string NullValue; | ||||||||
476 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||||||
477 | NullValue = "nil"; | ||||||||
478 | else if (getLangOpts().CPlusPlus11) | ||||||||
479 | NullValue = "nullptr"; | ||||||||
480 | else if (PP.isMacroDefined("NULL")) | ||||||||
481 | NullValue = "NULL"; | ||||||||
482 | else | ||||||||
483 | NullValue = "(void*) 0"; | ||||||||
484 | |||||||||
485 | if (MissingNilLoc.isInvalid()) | ||||||||
486 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||||||
487 | else | ||||||||
488 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||||||
489 | << int(calleeType) | ||||||||
490 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||||||
491 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||||||
492 | } | ||||||||
493 | |||||||||
494 | SourceRange Sema::getExprRange(Expr *E) const { | ||||||||
495 | return E ? E->getSourceRange() : SourceRange(); | ||||||||
496 | } | ||||||||
497 | |||||||||
498 | //===----------------------------------------------------------------------===// | ||||||||
499 | // Standard Promotions and Conversions | ||||||||
500 | //===----------------------------------------------------------------------===// | ||||||||
501 | |||||||||
502 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||||||
503 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||||||
504 | // Handle any placeholder expressions which made it here. | ||||||||
505 | if (E->getType()->isPlaceholderType()) { | ||||||||
506 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
507 | if (result.isInvalid()) return ExprError(); | ||||||||
508 | E = result.get(); | ||||||||
509 | } | ||||||||
510 | |||||||||
511 | QualType Ty = E->getType(); | ||||||||
512 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 512, __PRETTY_FUNCTION__)); | ||||||||
513 | |||||||||
514 | if (Ty->isFunctionType()) { | ||||||||
515 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||||||
516 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||||||
517 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||||||
518 | return ExprError(); | ||||||||
519 | |||||||||
520 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||||||
521 | CK_FunctionToPointerDecay).get(); | ||||||||
522 | } else if (Ty->isArrayType()) { | ||||||||
523 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||||||
524 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||||||
525 | // type 'array of type' is converted to an expression that has type 'pointer | ||||||||
526 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||||||
527 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||||||
528 | // (C90) to "an expression" (C99). | ||||||||
529 | // | ||||||||
530 | // C++ 4.2p1: | ||||||||
531 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||||||
532 | // T" can be converted to an rvalue of type "pointer to T". | ||||||||
533 | // | ||||||||
534 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | ||||||||
535 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||||||
536 | CK_ArrayToPointerDecay).get(); | ||||||||
537 | } | ||||||||
538 | return E; | ||||||||
539 | } | ||||||||
540 | |||||||||
541 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||||||
542 | // Check to see if we are dereferencing a null pointer. If so, | ||||||||
543 | // and if not volatile-qualified, this is undefined behavior that the | ||||||||
544 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||||||
545 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||||||
546 | // only handles the pattern "*null", which is a very syntactic check. | ||||||||
547 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||||||
548 | if (UO && UO->getOpcode() == UO_Deref && | ||||||||
549 | UO->getSubExpr()->getType()->isPointerType()) { | ||||||||
550 | const LangAS AS = | ||||||||
551 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||||||
552 | if ((!isTargetAddressSpace(AS) || | ||||||||
553 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||||||
554 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||||||
555 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||||||
556 | !UO->getType().isVolatileQualified()) { | ||||||||
557 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||
558 | S.PDiag(diag::warn_indirection_through_null) | ||||||||
559 | << UO->getSubExpr()->getSourceRange()); | ||||||||
560 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||
561 | S.PDiag(diag::note_indirection_through_null)); | ||||||||
562 | } | ||||||||
563 | } | ||||||||
564 | } | ||||||||
565 | |||||||||
566 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||||||
567 | SourceLocation AssignLoc, | ||||||||
568 | const Expr* RHS) { | ||||||||
569 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||||||
570 | if (!IV) | ||||||||
571 | return; | ||||||||
572 | |||||||||
573 | DeclarationName MemberName = IV->getDeclName(); | ||||||||
574 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||||||
575 | if (!Member || !Member->isStr("isa")) | ||||||||
576 | return; | ||||||||
577 | |||||||||
578 | const Expr *Base = OIRE->getBase(); | ||||||||
579 | QualType BaseType = Base->getType(); | ||||||||
580 | if (OIRE->isArrow()) | ||||||||
581 | BaseType = BaseType->getPointeeType(); | ||||||||
582 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||||||
583 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||||||
584 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||||||
585 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||||||
586 | if (!ClassDeclared->getSuperClass() | ||||||||
587 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||||||
588 | if (RHS) { | ||||||||
589 | NamedDecl *ObjectSetClass = | ||||||||
590 | S.LookupSingleName(S.TUScope, | ||||||||
591 | &S.Context.Idents.get("object_setClass"), | ||||||||
592 | SourceLocation(), S.LookupOrdinaryName); | ||||||||
593 | if (ObjectSetClass) { | ||||||||
594 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||||||
595 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||||||
596 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||||||
597 | "object_setClass(") | ||||||||
598 | << FixItHint::CreateReplacement( | ||||||||
599 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||||||
600 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||||||
601 | } | ||||||||
602 | else | ||||||||
603 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||||||
604 | } else { | ||||||||
605 | NamedDecl *ObjectGetClass = | ||||||||
606 | S.LookupSingleName(S.TUScope, | ||||||||
607 | &S.Context.Idents.get("object_getClass"), | ||||||||
608 | SourceLocation(), S.LookupOrdinaryName); | ||||||||
609 | if (ObjectGetClass) | ||||||||
610 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||||||
611 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||||||
612 | "object_getClass(") | ||||||||
613 | << FixItHint::CreateReplacement( | ||||||||
614 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||||||
615 | else | ||||||||
616 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||||||
617 | } | ||||||||
618 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||||||
619 | } | ||||||||
620 | } | ||||||||
621 | } | ||||||||
622 | |||||||||
623 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||||||
624 | // Handle any placeholder expressions which made it here. | ||||||||
625 | if (E->getType()->isPlaceholderType()) { | ||||||||
626 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
627 | if (result.isInvalid()) return ExprError(); | ||||||||
628 | E = result.get(); | ||||||||
629 | } | ||||||||
630 | |||||||||
631 | // C++ [conv.lval]p1: | ||||||||
632 | // A glvalue of a non-function, non-array type T can be | ||||||||
633 | // converted to a prvalue. | ||||||||
634 | if (!E->isGLValue()) return E; | ||||||||
635 | |||||||||
636 | QualType T = E->getType(); | ||||||||
637 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 637, __PRETTY_FUNCTION__)); | ||||||||
638 | |||||||||
639 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||||||
640 | if (T->isFunctionType() || T->isArrayType()) | ||||||||
641 | return E; | ||||||||
642 | |||||||||
643 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||||||
644 | // expressions of certain types in C++. | ||||||||
645 | if (getLangOpts().CPlusPlus && | ||||||||
646 | (E->getType() == Context.OverloadTy || | ||||||||
647 | T->isDependentType() || | ||||||||
648 | T->isRecordType())) | ||||||||
649 | return E; | ||||||||
650 | |||||||||
651 | // The C standard is actually really unclear on this point, and | ||||||||
652 | // DR106 tells us what the result should be but not why. It's | ||||||||
653 | // generally best to say that void types just doesn't undergo | ||||||||
654 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||||||
655 | // 'void' type are never l-values, but qualified void can be. | ||||||||
656 | if (T->isVoidType()) | ||||||||
657 | return E; | ||||||||
658 | |||||||||
659 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||||||
660 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | ||||||||
661 | T->isHalfType()) { | ||||||||
662 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||||||
663 | << 0 << T; | ||||||||
664 | return ExprError(); | ||||||||
665 | } | ||||||||
666 | |||||||||
667 | CheckForNullPointerDereference(*this, E); | ||||||||
668 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||||||
669 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||||||
670 | &Context.Idents.get("object_getClass"), | ||||||||
671 | SourceLocation(), LookupOrdinaryName); | ||||||||
672 | if (ObjectGetClass) | ||||||||
673 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||||||
674 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||||||
675 | << FixItHint::CreateReplacement( | ||||||||
676 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||||||
677 | else | ||||||||
678 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||||||
679 | } | ||||||||
680 | else if (const ObjCIvarRefExpr *OIRE = | ||||||||
681 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||||||
682 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||||||
683 | |||||||||
684 | // C++ [conv.lval]p1: | ||||||||
685 | // [...] If T is a non-class type, the type of the prvalue is the | ||||||||
686 | // cv-unqualified version of T. Otherwise, the type of the | ||||||||
687 | // rvalue is T. | ||||||||
688 | // | ||||||||
689 | // C99 6.3.2.1p2: | ||||||||
690 | // If the lvalue has qualified type, the value has the unqualified | ||||||||
691 | // version of the type of the lvalue; otherwise, the value has the | ||||||||
692 | // type of the lvalue. | ||||||||
693 | if (T.hasQualifiers()) | ||||||||
694 | T = T.getUnqualifiedType(); | ||||||||
695 | |||||||||
696 | // Under the MS ABI, lock down the inheritance model now. | ||||||||
697 | if (T->isMemberPointerType() && | ||||||||
698 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||||||
699 | (void)isCompleteType(E->getExprLoc(), T); | ||||||||
700 | |||||||||
701 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||||||
702 | if (Res.isInvalid()) | ||||||||
703 | return Res; | ||||||||
704 | E = Res.get(); | ||||||||
705 | |||||||||
706 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||||||
707 | // balance that. | ||||||||
708 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||||
709 | Cleanup.setExprNeedsCleanups(true); | ||||||||
710 | |||||||||
711 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
712 | Cleanup.setExprNeedsCleanups(true); | ||||||||
713 | |||||||||
714 | // C++ [conv.lval]p3: | ||||||||
715 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||||||
716 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||||||
717 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, | ||||||||
718 | CurFPFeatureOverrides()); | ||||||||
719 | |||||||||
720 | // C11 6.3.2.1p2: | ||||||||
721 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||||||
722 | // of the type of the lvalue ... | ||||||||
723 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||||||
724 | T = Atomic->getValueType().getUnqualifiedType(); | ||||||||
725 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||||||
726 | nullptr, VK_RValue, FPOptionsOverride()); | ||||||||
727 | } | ||||||||
728 | |||||||||
729 | return Res; | ||||||||
730 | } | ||||||||
731 | |||||||||
732 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||||||
733 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||||||
734 | if (Res.isInvalid()) | ||||||||
735 | return ExprError(); | ||||||||
736 | Res = DefaultLvalueConversion(Res.get()); | ||||||||
737 | if (Res.isInvalid()) | ||||||||
738 | return ExprError(); | ||||||||
739 | return Res; | ||||||||
740 | } | ||||||||
741 | |||||||||
742 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||||||
743 | /// performed on a function designator of a call expression. | ||||||||
744 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||||||
745 | QualType Ty = E->getType(); | ||||||||
746 | ExprResult Res = E; | ||||||||
747 | // Only do implicit cast for a function type, but not for a pointer | ||||||||
748 | // to function type. | ||||||||
749 | if (Ty->isFunctionType()) { | ||||||||
750 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||||||
751 | CK_FunctionToPointerDecay); | ||||||||
752 | if (Res.isInvalid()) | ||||||||
753 | return ExprError(); | ||||||||
754 | } | ||||||||
755 | Res = DefaultLvalueConversion(Res.get()); | ||||||||
756 | if (Res.isInvalid()) | ||||||||
757 | return ExprError(); | ||||||||
758 | return Res.get(); | ||||||||
759 | } | ||||||||
760 | |||||||||
761 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||||||
762 | /// operators (C99 6.3). The conversions of array and function types are | ||||||||
763 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||||||
764 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||||||
765 | /// In these instances, this routine should *not* be called. | ||||||||
766 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||||||
767 | // First, convert to an r-value. | ||||||||
768 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||||||
769 | if (Res.isInvalid()) | ||||||||
770 | return ExprError(); | ||||||||
771 | E = Res.get(); | ||||||||
772 | |||||||||
773 | QualType Ty = E->getType(); | ||||||||
774 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 774, __PRETTY_FUNCTION__)); | ||||||||
775 | |||||||||
776 | // Half FP have to be promoted to float unless it is natively supported | ||||||||
777 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||||||
778 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||||||
779 | |||||||||
780 | // Try to perform integral promotions if the object has a theoretically | ||||||||
781 | // promotable type. | ||||||||
782 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||||||
783 | // C99 6.3.1.1p2: | ||||||||
784 | // | ||||||||
785 | // The following may be used in an expression wherever an int or | ||||||||
786 | // unsigned int may be used: | ||||||||
787 | // - an object or expression with an integer type whose integer | ||||||||
788 | // conversion rank is less than or equal to the rank of int | ||||||||
789 | // and unsigned int. | ||||||||
790 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||||||
791 | // | ||||||||
792 | // If an int can represent all values of the original type, the | ||||||||
793 | // value is converted to an int; otherwise, it is converted to an | ||||||||
794 | // unsigned int. These are called the integer promotions. All | ||||||||
795 | // other types are unchanged by the integer promotions. | ||||||||
796 | |||||||||
797 | QualType PTy = Context.isPromotableBitField(E); | ||||||||
798 | if (!PTy.isNull()) { | ||||||||
799 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||||||
800 | return E; | ||||||||
801 | } | ||||||||
802 | if (Ty->isPromotableIntegerType()) { | ||||||||
803 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||||||
804 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||||||
805 | return E; | ||||||||
806 | } | ||||||||
807 | } | ||||||||
808 | return E; | ||||||||
809 | } | ||||||||
810 | |||||||||
811 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||||||
812 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||||||
813 | /// are promoted to double. All other argument types are converted by | ||||||||
814 | /// UsualUnaryConversions(). | ||||||||
815 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||||||
816 | QualType Ty = E->getType(); | ||||||||
817 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 817, __PRETTY_FUNCTION__)); | ||||||||
818 | |||||||||
819 | ExprResult Res = UsualUnaryConversions(E); | ||||||||
820 | if (Res.isInvalid()) | ||||||||
821 | return ExprError(); | ||||||||
822 | E = Res.get(); | ||||||||
823 | |||||||||
824 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||||||
825 | // promote to double. | ||||||||
826 | // Note that default argument promotion applies only to float (and | ||||||||
827 | // half/fp16); it does not apply to _Float16. | ||||||||
828 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||||||
829 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||||||
830 | BTy->getKind() == BuiltinType::Float)) { | ||||||||
831 | if (getLangOpts().OpenCL && | ||||||||
832 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | ||||||||
833 | if (BTy->getKind() == BuiltinType::Half) { | ||||||||
834 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
835 | } | ||||||||
836 | } else { | ||||||||
837 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||||||
838 | } | ||||||||
839 | } | ||||||||
840 | |||||||||
841 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||||||
842 | // promotion, even on class types, but note: | ||||||||
843 | // C++11 [conv.lval]p2: | ||||||||
844 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||||||
845 | // operand or a subexpression thereof the value contained in the | ||||||||
846 | // referenced object is not accessed. Otherwise, if the glvalue | ||||||||
847 | // has a class type, the conversion copy-initializes a temporary | ||||||||
848 | // of type T from the glvalue and the result of the conversion | ||||||||
849 | // is a prvalue for the temporary. | ||||||||
850 | // FIXME: add some way to gate this entire thing for correctness in | ||||||||
851 | // potentially potentially evaluated contexts. | ||||||||
852 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||||||
853 | ExprResult Temp = PerformCopyInitialization( | ||||||||
854 | InitializedEntity::InitializeTemporary(E->getType()), | ||||||||
855 | E->getExprLoc(), E); | ||||||||
856 | if (Temp.isInvalid()) | ||||||||
857 | return ExprError(); | ||||||||
858 | E = Temp.get(); | ||||||||
859 | } | ||||||||
860 | |||||||||
861 | return E; | ||||||||
862 | } | ||||||||
863 | |||||||||
864 | /// Determine the degree of POD-ness for an expression. | ||||||||
865 | /// Incomplete types are considered POD, since this check can be performed | ||||||||
866 | /// when we're in an unevaluated context. | ||||||||
867 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||||||
868 | if (Ty->isIncompleteType()) { | ||||||||
869 | // C++11 [expr.call]p7: | ||||||||
870 | // After these conversions, if the argument does not have arithmetic, | ||||||||
871 | // enumeration, pointer, pointer to member, or class type, the program | ||||||||
872 | // is ill-formed. | ||||||||
873 | // | ||||||||
874 | // Since we've already performed array-to-pointer and function-to-pointer | ||||||||
875 | // decay, the only such type in C++ is cv void. This also handles | ||||||||
876 | // initializer lists as variadic arguments. | ||||||||
877 | if (Ty->isVoidType()) | ||||||||
878 | return VAK_Invalid; | ||||||||
879 | |||||||||
880 | if (Ty->isObjCObjectType()) | ||||||||
881 | return VAK_Invalid; | ||||||||
882 | return VAK_Valid; | ||||||||
883 | } | ||||||||
884 | |||||||||
885 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
886 | return VAK_Invalid; | ||||||||
887 | |||||||||
888 | if (Ty.isCXX98PODType(Context)) | ||||||||
889 | return VAK_Valid; | ||||||||
890 | |||||||||
891 | // C++11 [expr.call]p7: | ||||||||
892 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||||||
893 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||||||
894 | // or a non-trivial destructor, with no corresponding parameter, | ||||||||
895 | // is conditionally-supported with implementation-defined semantics. | ||||||||
896 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||||||
897 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||||||
898 | if (!Record->hasNonTrivialCopyConstructor() && | ||||||||
899 | !Record->hasNonTrivialMoveConstructor() && | ||||||||
900 | !Record->hasNonTrivialDestructor()) | ||||||||
901 | return VAK_ValidInCXX11; | ||||||||
902 | |||||||||
903 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||||||
904 | return VAK_Valid; | ||||||||
905 | |||||||||
906 | if (Ty->isObjCObjectType()) | ||||||||
907 | return VAK_Invalid; | ||||||||
908 | |||||||||
909 | if (getLangOpts().MSVCCompat) | ||||||||
910 | return VAK_MSVCUndefined; | ||||||||
911 | |||||||||
912 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||||||
913 | // permitted to reject them. We should consider doing so. | ||||||||
914 | return VAK_Undefined; | ||||||||
915 | } | ||||||||
916 | |||||||||
917 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||||||
918 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||||||
919 | const QualType &Ty = E->getType(); | ||||||||
920 | VarArgKind VAK = isValidVarArgType(Ty); | ||||||||
921 | |||||||||
922 | // Complain about passing non-POD types through varargs. | ||||||||
923 | switch (VAK) { | ||||||||
924 | case VAK_ValidInCXX11: | ||||||||
925 | DiagRuntimeBehavior( | ||||||||
926 | E->getBeginLoc(), nullptr, | ||||||||
927 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||||||
928 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
929 | case VAK_Valid: | ||||||||
930 | if (Ty->isRecordType()) { | ||||||||
931 | // This is unlikely to be what the user intended. If the class has a | ||||||||
932 | // 'c_str' member function, the user probably meant to call that. | ||||||||
933 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
934 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||||||
935 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||||||
936 | } | ||||||||
937 | break; | ||||||||
938 | |||||||||
939 | case VAK_Undefined: | ||||||||
940 | case VAK_MSVCUndefined: | ||||||||
941 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
942 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||||||
943 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||||||
944 | break; | ||||||||
945 | |||||||||
946 | case VAK_Invalid: | ||||||||
947 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
948 | Diag(E->getBeginLoc(), | ||||||||
949 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||||||
950 | << Ty << CT; | ||||||||
951 | else if (Ty->isObjCObjectType()) | ||||||||
952 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
953 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||||||
954 | << Ty << CT); | ||||||||
955 | else | ||||||||
956 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||||||
957 | << isa<InitListExpr>(E) << Ty << CT; | ||||||||
958 | break; | ||||||||
959 | } | ||||||||
960 | } | ||||||||
961 | |||||||||
962 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||||||
963 | /// will create a trap if the resulting type is not a POD type. | ||||||||
964 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||||||
965 | FunctionDecl *FDecl) { | ||||||||
966 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||||||
967 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||||||
968 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||||||
969 | (CT == VariadicMethod || | ||||||||
970 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||||||
971 | E = stripARCUnbridgedCast(E); | ||||||||
972 | |||||||||
973 | // Otherwise, do normal placeholder checking. | ||||||||
974 | } else { | ||||||||
975 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||||||
976 | if (ExprRes.isInvalid()) | ||||||||
977 | return ExprError(); | ||||||||
978 | E = ExprRes.get(); | ||||||||
979 | } | ||||||||
980 | } | ||||||||
981 | |||||||||
982 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||||||
983 | if (ExprRes.isInvalid()) | ||||||||
984 | return ExprError(); | ||||||||
985 | |||||||||
986 | // Copy blocks to the heap. | ||||||||
987 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||||||
988 | maybeExtendBlockObject(ExprRes); | ||||||||
989 | |||||||||
990 | E = ExprRes.get(); | ||||||||
991 | |||||||||
992 | // Diagnostics regarding non-POD argument types are | ||||||||
993 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||||||
994 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||||||
995 | // Turn this into a trap. | ||||||||
996 | CXXScopeSpec SS; | ||||||||
997 | SourceLocation TemplateKWLoc; | ||||||||
998 | UnqualifiedId Name; | ||||||||
999 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||||||
1000 | E->getBeginLoc()); | ||||||||
1001 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||||||
1002 | /*HasTrailingLParen=*/true, | ||||||||
1003 | /*IsAddressOfOperand=*/false); | ||||||||
1004 | if (TrapFn.isInvalid()) | ||||||||
1005 | return ExprError(); | ||||||||
1006 | |||||||||
1007 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||||||
1008 | None, E->getEndLoc()); | ||||||||
1009 | if (Call.isInvalid()) | ||||||||
1010 | return ExprError(); | ||||||||
1011 | |||||||||
1012 | ExprResult Comma = | ||||||||
1013 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||||||
1014 | if (Comma.isInvalid()) | ||||||||
1015 | return ExprError(); | ||||||||
1016 | return Comma.get(); | ||||||||
1017 | } | ||||||||
1018 | |||||||||
1019 | if (!getLangOpts().CPlusPlus && | ||||||||
1020 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||||||
1021 | diag::err_call_incomplete_argument)) | ||||||||
1022 | return ExprError(); | ||||||||
1023 | |||||||||
1024 | return E; | ||||||||
1025 | } | ||||||||
1026 | |||||||||
1027 | /// Converts an integer to complex float type. Helper function of | ||||||||
1028 | /// UsualArithmeticConversions() | ||||||||
1029 | /// | ||||||||
1030 | /// \return false if the integer expression is an integer type and is | ||||||||
1031 | /// successfully converted to the complex type. | ||||||||
1032 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||||||
1033 | ExprResult &ComplexExpr, | ||||||||
1034 | QualType IntTy, | ||||||||
1035 | QualType ComplexTy, | ||||||||
1036 | bool SkipCast) { | ||||||||
1037 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||||||
1038 | if (SkipCast) return false; | ||||||||
1039 | if (IntTy->isIntegerType()) { | ||||||||
1040 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | ||||||||
1041 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||||||
1042 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||||||
1043 | CK_FloatingRealToComplex); | ||||||||
1044 | } else { | ||||||||
1045 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1045, __PRETTY_FUNCTION__)); | ||||||||
1046 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||||||
1047 | CK_IntegralComplexToFloatingComplex); | ||||||||
1048 | } | ||||||||
1049 | return false; | ||||||||
1050 | } | ||||||||
1051 | |||||||||
1052 | /// Handle arithmetic conversion with complex types. Helper function of | ||||||||
1053 | /// UsualArithmeticConversions() | ||||||||
1054 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | ||||||||
1055 | ExprResult &RHS, QualType LHSType, | ||||||||
1056 | QualType RHSType, | ||||||||
1057 | bool IsCompAssign) { | ||||||||
1058 | // if we have an integer operand, the result is the complex type. | ||||||||
1059 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||||||
1060 | /*skipCast*/false)) | ||||||||
1061 | return LHSType; | ||||||||
1062 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
1063 | /*skipCast*/IsCompAssign)) | ||||||||
1064 | return RHSType; | ||||||||
1065 | |||||||||
1066 | // This handles complex/complex, complex/float, or float/complex. | ||||||||
1067 | // When both operands are complex, the shorter operand is converted to the | ||||||||
1068 | // type of the longer, and that is the type of the result. This corresponds | ||||||||
1069 | // to what is done when combining two real floating-point operands. | ||||||||
1070 | // The fun begins when size promotion occur across type domains. | ||||||||
1071 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||||||
1072 | // floating-point type, the less precise type is converted, within it's | ||||||||
1073 | // real or complex domain, to the precision of the other type. For example, | ||||||||
1074 | // when combining a "long double" with a "double _Complex", the | ||||||||
1075 | // "double _Complex" is promoted to "long double _Complex". | ||||||||
1076 | |||||||||
1077 | // Compute the rank of the two types, regardless of whether they are complex. | ||||||||
1078 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||||||
1079 | |||||||||
1080 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | ||||||||
1081 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | ||||||||
1082 | QualType LHSElementType = | ||||||||
1083 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | ||||||||
1084 | QualType RHSElementType = | ||||||||
1085 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | ||||||||
1086 | |||||||||
1087 | QualType ResultType = S.Context.getComplexType(LHSElementType); | ||||||||
1088 | if (Order < 0) { | ||||||||
1089 | // Promote the precision of the LHS if not an assignment. | ||||||||
1090 | ResultType = S.Context.getComplexType(RHSElementType); | ||||||||
1091 | if (!IsCompAssign) { | ||||||||
1092 | if (LHSComplexType) | ||||||||
1093 | LHS = | ||||||||
1094 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | ||||||||
1095 | else | ||||||||
1096 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | ||||||||
1097 | } | ||||||||
1098 | } else if (Order > 0) { | ||||||||
1099 | // Promote the precision of the RHS. | ||||||||
1100 | if (RHSComplexType) | ||||||||
1101 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | ||||||||
1102 | else | ||||||||
1103 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | ||||||||
1104 | } | ||||||||
1105 | return ResultType; | ||||||||
1106 | } | ||||||||
1107 | |||||||||
1108 | /// Handle arithmetic conversion from integer to float. Helper function | ||||||||
1109 | /// of UsualArithmeticConversions() | ||||||||
1110 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||||||
1111 | ExprResult &IntExpr, | ||||||||
1112 | QualType FloatTy, QualType IntTy, | ||||||||
1113 | bool ConvertFloat, bool ConvertInt) { | ||||||||
1114 | if (IntTy->isIntegerType()) { | ||||||||
1115 | if (ConvertInt) | ||||||||
1116 | // Convert intExpr to the lhs floating point type. | ||||||||
1117 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||||||
1118 | CK_IntegralToFloating); | ||||||||
1119 | return FloatTy; | ||||||||
1120 | } | ||||||||
1121 | |||||||||
1122 | // Convert both sides to the appropriate complex float. | ||||||||
1123 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1123, __PRETTY_FUNCTION__)); | ||||||||
1124 | QualType result = S.Context.getComplexType(FloatTy); | ||||||||
1125 | |||||||||
1126 | // _Complex int -> _Complex float | ||||||||
1127 | if (ConvertInt) | ||||||||
1128 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||||||
1129 | CK_IntegralComplexToFloatingComplex); | ||||||||
1130 | |||||||||
1131 | // float -> _Complex float | ||||||||
1132 | if (ConvertFloat) | ||||||||
1133 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||||||
1134 | CK_FloatingRealToComplex); | ||||||||
1135 | |||||||||
1136 | return result; | ||||||||
1137 | } | ||||||||
1138 | |||||||||
1139 | /// Handle arithmethic conversion with floating point types. Helper | ||||||||
1140 | /// function of UsualArithmeticConversions() | ||||||||
1141 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||||||
1142 | ExprResult &RHS, QualType LHSType, | ||||||||
1143 | QualType RHSType, bool IsCompAssign) { | ||||||||
1144 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||||||
1145 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||||||
1146 | |||||||||
1147 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||||||
1148 | // operand has a fixed-point type, the fixed-point operand | ||||||||
1149 | // is converted to the floating type [...] | ||||||||
1150 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||||||
1151 | if (LHSFloat) | ||||||||
1152 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||||||
1153 | else if (!IsCompAssign) | ||||||||
1154 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||||||
1155 | return LHSFloat ? LHSType : RHSType; | ||||||||
1156 | } | ||||||||
1157 | |||||||||
1158 | // If we have two real floating types, convert the smaller operand | ||||||||
1159 | // to the bigger result. | ||||||||
1160 | if (LHSFloat && RHSFloat) { | ||||||||
1161 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||||||
1162 | if (order > 0) { | ||||||||
1163 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||||||
1164 | return LHSType; | ||||||||
1165 | } | ||||||||
1166 | |||||||||
1167 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1167, __PRETTY_FUNCTION__)); | ||||||||
1168 | if (!IsCompAssign) | ||||||||
1169 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||||||
1170 | return RHSType; | ||||||||
1171 | } | ||||||||
1172 | |||||||||
1173 | if (LHSFloat) { | ||||||||
1174 | // Half FP has to be promoted to float unless it is natively supported | ||||||||
1175 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||||||
1176 | LHSType = S.Context.FloatTy; | ||||||||
1177 | |||||||||
1178 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
1179 | /*ConvertFloat=*/!IsCompAssign, | ||||||||
1180 | /*ConvertInt=*/ true); | ||||||||
1181 | } | ||||||||
1182 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1182, __PRETTY_FUNCTION__)); | ||||||||
1183 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||||||
1184 | /*ConvertFloat=*/ true, | ||||||||
1185 | /*ConvertInt=*/!IsCompAssign); | ||||||||
1186 | } | ||||||||
1187 | |||||||||
1188 | /// Diagnose attempts to convert between __float128 and long double if | ||||||||
1189 | /// there is no support for such conversion. Helper function of | ||||||||
1190 | /// UsualArithmeticConversions(). | ||||||||
1191 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||||||
1192 | QualType RHSType) { | ||||||||
1193 | /* No issue converting if at least one of the types is not a floating point | ||||||||
1194 | type or the two types have the same rank. | ||||||||
1195 | */ | ||||||||
1196 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | ||||||||
1197 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | ||||||||
1198 | return false; | ||||||||
1199 | |||||||||
1200 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1201, __PRETTY_FUNCTION__)) | ||||||||
1201 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1201, __PRETTY_FUNCTION__)); | ||||||||
1202 | |||||||||
1203 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||||||
1204 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||||||
1205 | |||||||||
1206 | QualType LHSElemType = LHSComplex
| ||||||||
1207 | LHSComplex->getElementType() : LHSType; | ||||||||
1208 | QualType RHSElemType = RHSComplex
| ||||||||
1209 | RHSComplex->getElementType() : RHSType; | ||||||||
1210 | |||||||||
1211 | // No issue if the two types have the same representation | ||||||||
1212 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | ||||||||
1213 | &S.Context.getFloatTypeSemantics(RHSElemType)) | ||||||||
1214 | return false; | ||||||||
1215 | |||||||||
1216 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | ||||||||
1217 | RHSElemType == S.Context.LongDoubleTy); | ||||||||
1218 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | ||||||||
1219 | RHSElemType == S.Context.Float128Ty); | ||||||||
1220 | |||||||||
1221 | // We've handled the situation where __float128 and long double have the same | ||||||||
1222 | // representation. We allow all conversions for all possible long double types | ||||||||
1223 | // except PPC's double double. | ||||||||
1224 | return Float128AndLongDouble
| ||||||||
1225 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | ||||||||
1226 | &llvm::APFloat::PPCDoubleDouble()); | ||||||||
1227 | } | ||||||||
1228 | |||||||||
1229 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||||||
1230 | |||||||||
1231 | namespace { | ||||||||
1232 | /// These helper callbacks are placed in an anonymous namespace to | ||||||||
1233 | /// permit their use as function template parameters. | ||||||||
1234 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||||||
1235 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||||||
1236 | } | ||||||||
1237 | |||||||||
1238 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||||||
1239 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||||||
1240 | CK_IntegralComplexCast); | ||||||||
1241 | } | ||||||||
1242 | } | ||||||||
1243 | |||||||||
1244 | /// Handle integer arithmetic conversions. Helper function of | ||||||||
1245 | /// UsualArithmeticConversions() | ||||||||
1246 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||||||
1247 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||||||
1248 | ExprResult &RHS, QualType LHSType, | ||||||||
1249 | QualType RHSType, bool IsCompAssign) { | ||||||||
1250 | // The rules for this case are in C99 6.3.1.8 | ||||||||
1251 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||||||
1252 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||||||
1253 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||||||
1254 | if (LHSSigned == RHSSigned) { | ||||||||
1255 | // Same signedness; use the higher-ranked type | ||||||||
1256 | if (order >= 0) { | ||||||||
1257 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1258 | return LHSType; | ||||||||
1259 | } else if (!IsCompAssign) | ||||||||
1260 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1261 | return RHSType; | ||||||||
1262 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||||||
1263 | // The unsigned type has greater than or equal rank to the | ||||||||
1264 | // signed type, so use the unsigned type | ||||||||
1265 | if (RHSSigned) { | ||||||||
1266 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1267 | return LHSType; | ||||||||
1268 | } else if (!IsCompAssign) | ||||||||
1269 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1270 | return RHSType; | ||||||||
1271 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||||||
1272 | // The two types are different widths; if we are here, that | ||||||||
1273 | // means the signed type is larger than the unsigned type, so | ||||||||
1274 | // use the signed type. | ||||||||
1275 | if (LHSSigned) { | ||||||||
1276 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1277 | return LHSType; | ||||||||
1278 | } else if (!IsCompAssign) | ||||||||
1279 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1280 | return RHSType; | ||||||||
1281 | } else { | ||||||||
1282 | // The signed type is higher-ranked than the unsigned type, | ||||||||
1283 | // but isn't actually any bigger (like unsigned int and long | ||||||||
1284 | // on most 32-bit systems). Use the unsigned type corresponding | ||||||||
1285 | // to the signed type. | ||||||||
1286 | QualType result = | ||||||||
1287 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||||||
1288 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||||||
1289 | if (!IsCompAssign) | ||||||||
1290 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||||||
1291 | return result; | ||||||||
1292 | } | ||||||||
1293 | } | ||||||||
1294 | |||||||||
1295 | /// Handle conversions with GCC complex int extension. Helper function | ||||||||
1296 | /// of UsualArithmeticConversions() | ||||||||
1297 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||||||
1298 | ExprResult &RHS, QualType LHSType, | ||||||||
1299 | QualType RHSType, | ||||||||
1300 | bool IsCompAssign) { | ||||||||
1301 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||||||
1302 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||||||
1303 | |||||||||
1304 | if (LHSComplexInt && RHSComplexInt) { | ||||||||
1305 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||||||
1306 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||||||
1307 | QualType ScalarType = | ||||||||
1308 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||||||
1309 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||||||
1310 | |||||||||
1311 | return S.Context.getComplexType(ScalarType); | ||||||||
1312 | } | ||||||||
1313 | |||||||||
1314 | if (LHSComplexInt) { | ||||||||
1315 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||||||
1316 | QualType ScalarType = | ||||||||
1317 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||||||
1318 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||||||
1319 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||||||
1320 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||||||
1321 | CK_IntegralRealToComplex); | ||||||||
1322 | |||||||||
1323 | return ComplexType; | ||||||||
1324 | } | ||||||||
1325 | |||||||||
1326 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1326, __PRETTY_FUNCTION__)); | ||||||||
1327 | |||||||||
1328 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||||||
1329 | QualType ScalarType = | ||||||||
1330 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||||||
1331 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||||||
1332 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||||||
1333 | |||||||||
1334 | if (!IsCompAssign) | ||||||||
1335 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||||||
1336 | CK_IntegralRealToComplex); | ||||||||
1337 | return ComplexType; | ||||||||
1338 | } | ||||||||
1339 | |||||||||
1340 | /// Return the rank of a given fixed point or integer type. The value itself | ||||||||
1341 | /// doesn't matter, but the values must be increasing with proper increasing | ||||||||
1342 | /// rank as described in N1169 4.1.1. | ||||||||
1343 | static unsigned GetFixedPointRank(QualType Ty) { | ||||||||
1344 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||||||
1345 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1345, __PRETTY_FUNCTION__)); | ||||||||
1346 | |||||||||
1347 | switch (BTy->getKind()) { | ||||||||
1348 | case BuiltinType::ShortFract: | ||||||||
1349 | case BuiltinType::UShortFract: | ||||||||
1350 | case BuiltinType::SatShortFract: | ||||||||
1351 | case BuiltinType::SatUShortFract: | ||||||||
1352 | return 1; | ||||||||
1353 | case BuiltinType::Fract: | ||||||||
1354 | case BuiltinType::UFract: | ||||||||
1355 | case BuiltinType::SatFract: | ||||||||
1356 | case BuiltinType::SatUFract: | ||||||||
1357 | return 2; | ||||||||
1358 | case BuiltinType::LongFract: | ||||||||
1359 | case BuiltinType::ULongFract: | ||||||||
1360 | case BuiltinType::SatLongFract: | ||||||||
1361 | case BuiltinType::SatULongFract: | ||||||||
1362 | return 3; | ||||||||
1363 | case BuiltinType::ShortAccum: | ||||||||
1364 | case BuiltinType::UShortAccum: | ||||||||
1365 | case BuiltinType::SatShortAccum: | ||||||||
1366 | case BuiltinType::SatUShortAccum: | ||||||||
1367 | return 4; | ||||||||
1368 | case BuiltinType::Accum: | ||||||||
1369 | case BuiltinType::UAccum: | ||||||||
1370 | case BuiltinType::SatAccum: | ||||||||
1371 | case BuiltinType::SatUAccum: | ||||||||
1372 | return 5; | ||||||||
1373 | case BuiltinType::LongAccum: | ||||||||
1374 | case BuiltinType::ULongAccum: | ||||||||
1375 | case BuiltinType::SatLongAccum: | ||||||||
1376 | case BuiltinType::SatULongAccum: | ||||||||
1377 | return 6; | ||||||||
1378 | default: | ||||||||
1379 | if (BTy->isInteger()) | ||||||||
1380 | return 0; | ||||||||
1381 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1381); | ||||||||
1382 | } | ||||||||
1383 | } | ||||||||
1384 | |||||||||
1385 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||||||
1386 | /// point types and integers or other fixed point types do not fall under | ||||||||
1387 | /// usual arithmetic conversion since these conversions could result in loss | ||||||||
1388 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||||||
1389 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||||||
1390 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||||||
1391 | QualType RHSTy) { | ||||||||
1392 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1393, __PRETTY_FUNCTION__)) | ||||||||
1393 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1393, __PRETTY_FUNCTION__)); | ||||||||
1394 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)) | ||||||||
1395 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)) | ||||||||
1396 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)) | ||||||||
1397 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)); | ||||||||
1398 | |||||||||
1399 | // If one operand has signed fixed-point type and the other operand has | ||||||||
1400 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||||||
1401 | // converted to its corresponding signed fixed-point type and the resulting | ||||||||
1402 | // type is the type of the converted operand. | ||||||||
1403 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||||||
1404 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||||||
1405 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||||||
1406 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||||||
1407 | |||||||||
1408 | // The result type is the type with the highest rank, whereby a fixed-point | ||||||||
1409 | // conversion rank is always greater than an integer conversion rank; if the | ||||||||
1410 | // type of either of the operands is a saturating fixedpoint type, the result | ||||||||
1411 | // type shall be the saturating fixed-point type corresponding to the type | ||||||||
1412 | // with the highest rank; the resulting value is converted (taking into | ||||||||
1413 | // account rounding and overflow) to the precision of the resulting type. | ||||||||
1414 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||||||
1415 | // types are either signed or both unsigned at this point. | ||||||||
1416 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||||||
1417 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||||||
1418 | |||||||||
1419 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||||||
1420 | |||||||||
1421 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||||||
1422 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||||||
1423 | |||||||||
1424 | return ResultTy; | ||||||||
1425 | } | ||||||||
1426 | |||||||||
1427 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||||||
1428 | /// expressions that might be of enumeration type. | ||||||||
1429 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||||||
1430 | SourceLocation Loc, | ||||||||
1431 | Sema::ArithConvKind ACK) { | ||||||||
1432 | // C++2a [expr.arith.conv]p1: | ||||||||
1433 | // If one operand is of enumeration type and the other operand is of a | ||||||||
1434 | // different enumeration type or a floating-point type, this behavior is | ||||||||
1435 | // deprecated ([depr.arith.conv.enum]). | ||||||||
1436 | // | ||||||||
1437 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||||||
1438 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||||||
1439 | QualType L = LHS->getType(), R = RHS->getType(); | ||||||||
1440 | bool LEnum = L->isUnscopedEnumerationType(), | ||||||||
1441 | REnum = R->isUnscopedEnumerationType(); | ||||||||
1442 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||||||
1443 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||||||
1444 | (REnum && L->isFloatingType())) { | ||||||||
1445 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||||||
1446 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||||||
1447 | : diag::warn_arith_conv_enum_float) | ||||||||
1448 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
1449 | << (int)ACK << LEnum << L << R; | ||||||||
1450 | } else if (!IsCompAssign && LEnum && REnum && | ||||||||
1451 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||||||
1452 | unsigned DiagID; | ||||||||
1453 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||||||
1454 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||||||
1455 | // If either enumeration type is unnamed, it's less likely that the | ||||||||
1456 | // user cares about this, but this situation is still deprecated in | ||||||||
1457 | // C++2a. Use a different warning group. | ||||||||
1458 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1459 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||||||
1460 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||||||
1461 | } else if (ACK == Sema::ACK_Conditional) { | ||||||||
1462 | // Conditional expressions are separated out because they have | ||||||||
1463 | // historically had a different warning flag. | ||||||||
1464 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1465 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||||||
1466 | : diag::warn_conditional_mixed_enum_types; | ||||||||
1467 | } else if (ACK == Sema::ACK_Comparison) { | ||||||||
1468 | // Comparison expressions are separated out because they have | ||||||||
1469 | // historically had a different warning flag. | ||||||||
1470 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1471 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||||||
1472 | : diag::warn_comparison_mixed_enum_types; | ||||||||
1473 | } else { | ||||||||
1474 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1475 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||||||
1476 | : diag::warn_arith_conv_mixed_enum_types; | ||||||||
1477 | } | ||||||||
1478 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
1479 | << (int)ACK << L << R; | ||||||||
1480 | } | ||||||||
1481 | } | ||||||||
1482 | |||||||||
1483 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||||||
1484 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||||||
1485 | /// routine returns the first non-arithmetic type found. The client is | ||||||||
1486 | /// responsible for emitting appropriate error diagnostics. | ||||||||
1487 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||||||
1488 | SourceLocation Loc, | ||||||||
1489 | ArithConvKind ACK) { | ||||||||
1490 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||||||
1491 | |||||||||
1492 | if (ACK != ACK_CompAssign) { | ||||||||
1493 | LHS = UsualUnaryConversions(LHS.get()); | ||||||||
1494 | if (LHS.isInvalid()) | ||||||||
1495 | return QualType(); | ||||||||
1496 | } | ||||||||
1497 | |||||||||
1498 | RHS = UsualUnaryConversions(RHS.get()); | ||||||||
1499 | if (RHS.isInvalid()) | ||||||||
1500 | return QualType(); | ||||||||
1501 | |||||||||
1502 | // For conversion purposes, we ignore any qualifiers. | ||||||||
1503 | // For example, "const float" and "float" are equivalent. | ||||||||
1504 | QualType LHSType = | ||||||||
1505 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||||||
1506 | QualType RHSType = | ||||||||
1507 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||||||
1508 | |||||||||
1509 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||||||
1510 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||||||
1511 | LHSType = AtomicLHS->getValueType(); | ||||||||
1512 | |||||||||
1513 | // If both types are identical, no conversion is needed. | ||||||||
1514 | if (LHSType == RHSType) | ||||||||
1515 | return LHSType; | ||||||||
1516 | |||||||||
1517 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||||||
1518 | // The caller can deal with this (e.g. pointer + int). | ||||||||
1519 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||||||
1520 | return QualType(); | ||||||||
1521 | |||||||||
1522 | // Apply unary and bitfield promotions to the LHS's type. | ||||||||
1523 | QualType LHSUnpromotedType = LHSType; | ||||||||
1524 | if (LHSType->isPromotableIntegerType()) | ||||||||
1525 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||||||
1526 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||||||
1527 | if (!LHSBitfieldPromoteTy.isNull()) | ||||||||
1528 | LHSType = LHSBitfieldPromoteTy; | ||||||||
1529 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||||||
1530 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||||||
1531 | |||||||||
1532 | // If both types are identical, no conversion is needed. | ||||||||
1533 | if (LHSType == RHSType) | ||||||||
1534 | return LHSType; | ||||||||
1535 | |||||||||
1536 | // ExtInt types aren't subject to conversions between them or normal integers, | ||||||||
1537 | // so this fails. | ||||||||
1538 | if(LHSType->isExtIntType() || RHSType->isExtIntType()) | ||||||||
1539 | return QualType(); | ||||||||
1540 | |||||||||
1541 | // At this point, we have two different arithmetic types. | ||||||||
1542 | |||||||||
1543 | // Diagnose attempts to convert between __float128 and long double where | ||||||||
1544 | // such conversions currently can't be handled. | ||||||||
1545 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||||||
1546 | return QualType(); | ||||||||
1547 | |||||||||
1548 | // Handle complex types first (C99 6.3.1.8p1). | ||||||||
1549 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||||||
1550 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1551 | ACK == ACK_CompAssign); | ||||||||
1552 | |||||||||
1553 | // Now handle "real" floating types (i.e. float, double, long double). | ||||||||
1554 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||||||
1555 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1556 | ACK == ACK_CompAssign); | ||||||||
1557 | |||||||||
1558 | // Handle GCC complex int extension. | ||||||||
1559 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||||||
1560 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1561 | ACK == ACK_CompAssign); | ||||||||
1562 | |||||||||
1563 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||||||
1564 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||||||
1565 | |||||||||
1566 | // Finally, we have two differing integer types. | ||||||||
1567 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||||||
1568 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||||||
1569 | } | ||||||||
1570 | |||||||||
1571 | //===----------------------------------------------------------------------===// | ||||||||
1572 | // Semantic Analysis for various Expression Types | ||||||||
1573 | //===----------------------------------------------------------------------===// | ||||||||
1574 | |||||||||
1575 | |||||||||
1576 | ExprResult | ||||||||
1577 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||||||
1578 | SourceLocation DefaultLoc, | ||||||||
1579 | SourceLocation RParenLoc, | ||||||||
1580 | Expr *ControllingExpr, | ||||||||
1581 | ArrayRef<ParsedType> ArgTypes, | ||||||||
1582 | ArrayRef<Expr *> ArgExprs) { | ||||||||
1583 | unsigned NumAssocs = ArgTypes.size(); | ||||||||
1584 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1584, __PRETTY_FUNCTION__)); | ||||||||
1585 | |||||||||
1586 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||||||
1587 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1588 | if (ArgTypes[i]) | ||||||||
1589 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||||||
1590 | else | ||||||||
1591 | Types[i] = nullptr; | ||||||||
1592 | } | ||||||||
1593 | |||||||||
1594 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||||||
1595 | ControllingExpr, | ||||||||
1596 | llvm::makeArrayRef(Types, NumAssocs), | ||||||||
1597 | ArgExprs); | ||||||||
1598 | delete [] Types; | ||||||||
1599 | return ER; | ||||||||
1600 | } | ||||||||
1601 | |||||||||
1602 | ExprResult | ||||||||
1603 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||||||
1604 | SourceLocation DefaultLoc, | ||||||||
1605 | SourceLocation RParenLoc, | ||||||||
1606 | Expr *ControllingExpr, | ||||||||
1607 | ArrayRef<TypeSourceInfo *> Types, | ||||||||
1608 | ArrayRef<Expr *> Exprs) { | ||||||||
1609 | unsigned NumAssocs = Types.size(); | ||||||||
1610 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1610, __PRETTY_FUNCTION__)); | ||||||||
1611 | |||||||||
1612 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||||||
1613 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||||||
1614 | { | ||||||||
1615 | EnterExpressionEvaluationContext Unevaluated( | ||||||||
1616 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||||||
1617 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||||||
1618 | if (R.isInvalid()) | ||||||||
1619 | return ExprError(); | ||||||||
1620 | ControllingExpr = R.get(); | ||||||||
1621 | } | ||||||||
1622 | |||||||||
1623 | // The controlling expression is an unevaluated operand, so side effects are | ||||||||
1624 | // likely unintended. | ||||||||
1625 | if (!inTemplateInstantiation() && | ||||||||
1626 | ControllingExpr->HasSideEffects(Context, false)) | ||||||||
1627 | Diag(ControllingExpr->getExprLoc(), | ||||||||
1628 | diag::warn_side_effects_unevaluated_context); | ||||||||
1629 | |||||||||
1630 | bool TypeErrorFound = false, | ||||||||
1631 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||||||
1632 | ContainsUnexpandedParameterPack | ||||||||
1633 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||||||
1634 | |||||||||
1635 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1636 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||||||
1637 | ContainsUnexpandedParameterPack = true; | ||||||||
1638 | |||||||||
1639 | if (Types[i]) { | ||||||||
1640 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||||||
1641 | ContainsUnexpandedParameterPack = true; | ||||||||
1642 | |||||||||
1643 | if (Types[i]->getType()->isDependentType()) { | ||||||||
1644 | IsResultDependent = true; | ||||||||
1645 | } else { | ||||||||
1646 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||||||
1647 | // complete object type other than a variably modified type." | ||||||||
1648 | unsigned D = 0; | ||||||||
1649 | if (Types[i]->getType()->isIncompleteType()) | ||||||||
1650 | D = diag::err_assoc_type_incomplete; | ||||||||
1651 | else if (!Types[i]->getType()->isObjectType()) | ||||||||
1652 | D = diag::err_assoc_type_nonobject; | ||||||||
1653 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||||||
1654 | D = diag::err_assoc_type_variably_modified; | ||||||||
1655 | |||||||||
1656 | if (D != 0) { | ||||||||
1657 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||||||
1658 | << Types[i]->getTypeLoc().getSourceRange() | ||||||||
1659 | << Types[i]->getType(); | ||||||||
1660 | TypeErrorFound = true; | ||||||||
1661 | } | ||||||||
1662 | |||||||||
1663 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||||||
1664 | // selection shall specify compatible types." | ||||||||
1665 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||||||
1666 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||||||
1667 | Context.typesAreCompatible(Types[i]->getType(), | ||||||||
1668 | Types[j]->getType())) { | ||||||||
1669 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||||||
1670 | diag::err_assoc_compatible_types) | ||||||||
1671 | << Types[j]->getTypeLoc().getSourceRange() | ||||||||
1672 | << Types[j]->getType() | ||||||||
1673 | << Types[i]->getType(); | ||||||||
1674 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||||||
1675 | diag::note_compat_assoc) | ||||||||
1676 | << Types[i]->getTypeLoc().getSourceRange() | ||||||||
1677 | << Types[i]->getType(); | ||||||||
1678 | TypeErrorFound = true; | ||||||||
1679 | } | ||||||||
1680 | } | ||||||||
1681 | } | ||||||||
1682 | } | ||||||||
1683 | if (TypeErrorFound) | ||||||||
1684 | return ExprError(); | ||||||||
1685 | |||||||||
1686 | // If we determined that the generic selection is result-dependent, don't | ||||||||
1687 | // try to compute the result expression. | ||||||||
1688 | if (IsResultDependent) | ||||||||
1689 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||||||
1690 | Exprs, DefaultLoc, RParenLoc, | ||||||||
1691 | ContainsUnexpandedParameterPack); | ||||||||
1692 | |||||||||
1693 | SmallVector<unsigned, 1> CompatIndices; | ||||||||
1694 | unsigned DefaultIndex = -1U; | ||||||||
1695 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1696 | if (!Types[i]) | ||||||||
1697 | DefaultIndex = i; | ||||||||
1698 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | ||||||||
1699 | Types[i]->getType())) | ||||||||
1700 | CompatIndices.push_back(i); | ||||||||
1701 | } | ||||||||
1702 | |||||||||
1703 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||||||
1704 | // type compatible with at most one of the types named in its generic | ||||||||
1705 | // association list." | ||||||||
1706 | if (CompatIndices.size() > 1) { | ||||||||
1707 | // We strip parens here because the controlling expression is typically | ||||||||
1708 | // parenthesized in macro definitions. | ||||||||
1709 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||||||
1710 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||||||
1711 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||||||
1712 | << (unsigned)CompatIndices.size(); | ||||||||
1713 | for (unsigned I : CompatIndices) { | ||||||||
1714 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||||||
1715 | diag::note_compat_assoc) | ||||||||
1716 | << Types[I]->getTypeLoc().getSourceRange() | ||||||||
1717 | << Types[I]->getType(); | ||||||||
1718 | } | ||||||||
1719 | return ExprError(); | ||||||||
1720 | } | ||||||||
1721 | |||||||||
1722 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||||||
1723 | // its controlling expression shall have type compatible with exactly one of | ||||||||
1724 | // the types named in its generic association list." | ||||||||
1725 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||||||
1726 | // We strip parens here because the controlling expression is typically | ||||||||
1727 | // parenthesized in macro definitions. | ||||||||
1728 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||||||
1729 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||||||
1730 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||||||
1731 | return ExprError(); | ||||||||
1732 | } | ||||||||
1733 | |||||||||
1734 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||||||
1735 | // type name that is compatible with the type of the controlling expression, | ||||||||
1736 | // then the result expression of the generic selection is the expression | ||||||||
1737 | // in that generic association. Otherwise, the result expression of the | ||||||||
1738 | // generic selection is the expression in the default generic association." | ||||||||
1739 | unsigned ResultIndex = | ||||||||
1740 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||||||
1741 | |||||||||
1742 | return GenericSelectionExpr::Create( | ||||||||
1743 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||||||
1744 | ContainsUnexpandedParameterPack, ResultIndex); | ||||||||
1745 | } | ||||||||
1746 | |||||||||
1747 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||||||
1748 | /// location of the token and the offset of the ud-suffix within it. | ||||||||
1749 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||||||
1750 | unsigned Offset) { | ||||||||
1751 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||||||
1752 | S.getLangOpts()); | ||||||||
1753 | } | ||||||||
1754 | |||||||||
1755 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||||||
1756 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||||||
1757 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||||||
1758 | IdentifierInfo *UDSuffix, | ||||||||
1759 | SourceLocation UDSuffixLoc, | ||||||||
1760 | ArrayRef<Expr*> Args, | ||||||||
1761 | SourceLocation LitEndLoc) { | ||||||||
1762 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1762, __PRETTY_FUNCTION__)); | ||||||||
1763 | |||||||||
1764 | QualType ArgTy[2]; | ||||||||
1765 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||||||
1766 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||||||
1767 | if (ArgTy[ArgIdx]->isArrayType()) | ||||||||
1768 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||||||
1769 | } | ||||||||
1770 | |||||||||
1771 | DeclarationName OpName = | ||||||||
1772 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
1773 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
1774 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
1775 | |||||||||
1776 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||||||
1777 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||||||
1778 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||||||
1779 | /*AllowStringTemplatePack*/ false, | ||||||||
1780 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||||||
1781 | return ExprError(); | ||||||||
1782 | |||||||||
1783 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||||||
1784 | } | ||||||||
1785 | |||||||||
1786 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||||||
1787 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||||||
1788 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||||||
1789 | /// multiple tokens. However, the common case is that StringToks points to one | ||||||||
1790 | /// string. | ||||||||
1791 | /// | ||||||||
1792 | ExprResult | ||||||||
1793 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||||||
1794 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1794, __PRETTY_FUNCTION__)); | ||||||||
1795 | |||||||||
1796 | StringLiteralParser Literal(StringToks, PP); | ||||||||
1797 | if (Literal.hadError) | ||||||||
1798 | return ExprError(); | ||||||||
1799 | |||||||||
1800 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||||||
1801 | for (const Token &Tok : StringToks) | ||||||||
1802 | StringTokLocs.push_back(Tok.getLocation()); | ||||||||
1803 | |||||||||
1804 | QualType CharTy = Context.CharTy; | ||||||||
1805 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | ||||||||
1806 | if (Literal.isWide()) { | ||||||||
1807 | CharTy = Context.getWideCharType(); | ||||||||
1808 | Kind = StringLiteral::Wide; | ||||||||
1809 | } else if (Literal.isUTF8()) { | ||||||||
1810 | if (getLangOpts().Char8) | ||||||||
1811 | CharTy = Context.Char8Ty; | ||||||||
1812 | Kind = StringLiteral::UTF8; | ||||||||
1813 | } else if (Literal.isUTF16()) { | ||||||||
1814 | CharTy = Context.Char16Ty; | ||||||||
1815 | Kind = StringLiteral::UTF16; | ||||||||
1816 | } else if (Literal.isUTF32()) { | ||||||||
1817 | CharTy = Context.Char32Ty; | ||||||||
1818 | Kind = StringLiteral::UTF32; | ||||||||
1819 | } else if (Literal.isPascal()) { | ||||||||
1820 | CharTy = Context.UnsignedCharTy; | ||||||||
1821 | } | ||||||||
1822 | |||||||||
1823 | // Warn on initializing an array of char from a u8 string literal; this | ||||||||
1824 | // becomes ill-formed in C++2a. | ||||||||
1825 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||||||
1826 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||||||
1827 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||||||
1828 | |||||||||
1829 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||||||
1830 | // ensures C++2a compatibility (but may change the program behavior when | ||||||||
1831 | // built by non-Clang compilers for which the execution character set is | ||||||||
1832 | // not always UTF-8). | ||||||||
1833 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||||||
1834 | SourceLocation RemovalDiagLoc; | ||||||||
1835 | for (const Token &Tok : StringToks) { | ||||||||
1836 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||||||
1837 | if (RemovalDiagLoc.isInvalid()) | ||||||||
1838 | RemovalDiagLoc = Tok.getLocation(); | ||||||||
1839 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||||||
1840 | Tok.getLocation(), | ||||||||
1841 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||||||
1842 | getSourceManager(), getLangOpts()))); | ||||||||
1843 | } | ||||||||
1844 | } | ||||||||
1845 | Diag(RemovalDiagLoc, RemovalDiag); | ||||||||
1846 | } | ||||||||
1847 | |||||||||
1848 | QualType StrTy = | ||||||||
1849 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||||||
1850 | |||||||||
1851 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||||||
1852 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||||||
1853 | Kind, Literal.Pascal, StrTy, | ||||||||
1854 | &StringTokLocs[0], | ||||||||
1855 | StringTokLocs.size()); | ||||||||
1856 | if (Literal.getUDSuffix().empty()) | ||||||||
1857 | return Lit; | ||||||||
1858 | |||||||||
1859 | // We're building a user-defined literal. | ||||||||
1860 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
1861 | SourceLocation UDSuffixLoc = | ||||||||
1862 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||||||
1863 | Literal.getUDSuffixOffset()); | ||||||||
1864 | |||||||||
1865 | // Make sure we're allowed user-defined literals here. | ||||||||
1866 | if (!UDLScope) | ||||||||
1867 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||||||
1868 | |||||||||
1869 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||||||
1870 | // operator "" X (str, len) | ||||||||
1871 | QualType SizeType = Context.getSizeType(); | ||||||||
1872 | |||||||||
1873 | DeclarationName OpName = | ||||||||
1874 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
1875 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
1876 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
1877 | |||||||||
1878 | QualType ArgTy[] = { | ||||||||
1879 | Context.getArrayDecayedType(StrTy), SizeType | ||||||||
1880 | }; | ||||||||
1881 | |||||||||
1882 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||||||
1883 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||||||
1884 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||||||
1885 | /*AllowStringTemplatePack*/ true, | ||||||||
1886 | /*DiagnoseMissing*/ true, Lit)) { | ||||||||
1887 | |||||||||
1888 | case LOLR_Cooked: { | ||||||||
1889 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||||||
1890 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||||||
1891 | StringTokLocs[0]); | ||||||||
1892 | Expr *Args[] = { Lit, LenArg }; | ||||||||
1893 | |||||||||
1894 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||||||
1895 | } | ||||||||
1896 | |||||||||
1897 | case LOLR_Template: { | ||||||||
1898 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
1899 | TemplateArgument Arg(Lit); | ||||||||
1900 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||||||
1901 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
1902 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||||||
1903 | &ExplicitArgs); | ||||||||
1904 | } | ||||||||
1905 | |||||||||
1906 | case LOLR_StringTemplatePack: { | ||||||||
1907 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
1908 | |||||||||
1909 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||||||
1910 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||||||
1911 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||||||
1912 | |||||||||
1913 | TemplateArgument TypeArg(CharTy); | ||||||||
1914 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||||||
1915 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||||||
1916 | |||||||||
1917 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||||||
1918 | Value = Lit->getCodeUnit(I); | ||||||||
1919 | TemplateArgument Arg(Context, Value, CharTy); | ||||||||
1920 | TemplateArgumentLocInfo ArgInfo; | ||||||||
1921 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
1922 | } | ||||||||
1923 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||||||
1924 | &ExplicitArgs); | ||||||||
1925 | } | ||||||||
1926 | case LOLR_Raw: | ||||||||
1927 | case LOLR_ErrorNoDiagnostic: | ||||||||
1928 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1928); | ||||||||
1929 | case LOLR_Error: | ||||||||
1930 | return ExprError(); | ||||||||
1931 | } | ||||||||
1932 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1932); | ||||||||
1933 | } | ||||||||
1934 | |||||||||
1935 | DeclRefExpr * | ||||||||
1936 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1937 | SourceLocation Loc, | ||||||||
1938 | const CXXScopeSpec *SS) { | ||||||||
1939 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||||||
1940 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||||||
1941 | } | ||||||||
1942 | |||||||||
1943 | DeclRefExpr * | ||||||||
1944 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1945 | const DeclarationNameInfo &NameInfo, | ||||||||
1946 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||||||
1947 | SourceLocation TemplateKWLoc, | ||||||||
1948 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
1949 | NestedNameSpecifierLoc NNS = | ||||||||
1950 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||||||
1951 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||||||
1952 | TemplateArgs); | ||||||||
1953 | } | ||||||||
1954 | |||||||||
1955 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||||||
1956 | // host variable in a device or host device lambda. | ||||||||
1957 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||||||
1958 | VarDecl *VD) { | ||||||||
1959 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||||||
1960 | return false; | ||||||||
1961 | assert(VD->getType()->isReferenceType())((VD->getType()->isReferenceType()) ? static_cast<void > (0) : __assert_fail ("VD->getType()->isReferenceType()" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 1961, __PRETTY_FUNCTION__)); | ||||||||
1962 | |||||||||
1963 | // Check whether the reference variable is referencing a host variable. | ||||||||
1964 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||||||
1965 | if (!DRE) | ||||||||
1966 | return false; | ||||||||
1967 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||||||
1968 | if (!Referee || !Referee->hasGlobalStorage() || | ||||||||
1969 | Referee->hasAttr<CUDADeviceAttr>()) | ||||||||
1970 | return false; | ||||||||
1971 | |||||||||
1972 | // Check whether the current function is a device or host device lambda. | ||||||||
1973 | // Check whether the reference variable is a capture by getDeclContext() | ||||||||
1974 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||||||
1975 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||||||
1976 | if (MD && MD->getParent()->isLambda() && | ||||||||
1977 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||||||
1978 | VD->getDeclContext() != MD) | ||||||||
1979 | return true; | ||||||||
1980 | |||||||||
1981 | return false; | ||||||||
1982 | } | ||||||||
1983 | |||||||||
1984 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||||||
1985 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||||||
1986 | if (isUnevaluatedContext()) | ||||||||
1987 | return NOUR_Unevaluated; | ||||||||
1988 | |||||||||
1989 | // C++2a [basic.def.odr]p4: | ||||||||
1990 | // A variable x whose name appears as a potentially-evaluated expression e | ||||||||
1991 | // is odr-used by e unless [...] x is a reference that is usable in | ||||||||
1992 | // constant expressions. | ||||||||
1993 | // CUDA/HIP: | ||||||||
1994 | // If a reference variable referencing a host variable is captured in a | ||||||||
1995 | // device or host device lambda, the value of the referee must be copied | ||||||||
1996 | // to the capture and the reference variable must be treated as odr-use | ||||||||
1997 | // since the value of the referee is not known at compile time and must | ||||||||
1998 | // be loaded from the captured. | ||||||||
1999 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||||
2000 | if (VD->getType()->isReferenceType() && | ||||||||
2001 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||||||
2002 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||||||
2003 | VD->isUsableInConstantExpressions(Context)) | ||||||||
2004 | return NOUR_Constant; | ||||||||
2005 | } | ||||||||
2006 | |||||||||
2007 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||||||
2008 | // need to wait and see how the expression is used. | ||||||||
2009 | return NOUR_None; | ||||||||
2010 | } | ||||||||
2011 | |||||||||
2012 | /// BuildDeclRefExpr - Build an expression that references a | ||||||||
2013 | /// declaration that does not require a closure capture. | ||||||||
2014 | DeclRefExpr * | ||||||||
2015 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
2016 | const DeclarationNameInfo &NameInfo, | ||||||||
2017 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||||||
2018 | SourceLocation TemplateKWLoc, | ||||||||
2019 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
2020 | bool RefersToCapturedVariable = | ||||||||
2021 | isa<VarDecl>(D) && | ||||||||
2022 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | ||||||||
2023 | |||||||||
2024 | DeclRefExpr *E = DeclRefExpr::Create( | ||||||||
2025 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||||||
2026 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||||||
2027 | MarkDeclRefReferenced(E); | ||||||||
2028 | |||||||||
2029 | // C++ [except.spec]p17: | ||||||||
2030 | // An exception-specification is considered to be needed when: | ||||||||
2031 | // - in an expression, the function is the unique lookup result or | ||||||||
2032 | // the selected member of a set of overloaded functions. | ||||||||
2033 | // | ||||||||
2034 | // We delay doing this until after we've built the function reference and | ||||||||
2035 | // marked it as used so that: | ||||||||
2036 | // a) if the function is defaulted, we get errors from defining it before / | ||||||||
2037 | // instead of errors from computing its exception specification, and | ||||||||
2038 | // b) if the function is a defaulted comparison, we can use the body we | ||||||||
2039 | // build when defining it as input to the exception specification | ||||||||
2040 | // computation rather than computing a new body. | ||||||||
2041 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||||||
2042 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||||||
2043 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||||||
2044 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||||||
2045 | } | ||||||||
2046 | } | ||||||||
2047 | |||||||||
2048 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||||||
2049 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||||||
2050 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||||||
2051 | getCurFunction()->recordUseOfWeak(E); | ||||||||
2052 | |||||||||
2053 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||||||
2054 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||||||
2055 | FD = IFD->getAnonField(); | ||||||||
2056 | if (FD) { | ||||||||
2057 | UnusedPrivateFields.remove(FD); | ||||||||
2058 | // Just in case we're building an illegal pointer-to-member. | ||||||||
2059 | if (FD->isBitField()) | ||||||||
2060 | E->setObjectKind(OK_BitField); | ||||||||
2061 | } | ||||||||
2062 | |||||||||
2063 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||||||
2064 | // designates a bit-field. | ||||||||
2065 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||||||
2066 | if (auto *BE = BD->getBinding()) | ||||||||
2067 | E->setObjectKind(BE->getObjectKind()); | ||||||||
2068 | |||||||||
2069 | return E; | ||||||||
2070 | } | ||||||||
2071 | |||||||||
2072 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||||||
2073 | /// possibly a list of template arguments. | ||||||||
2074 | /// | ||||||||
2075 | /// If this produces template arguments, it is permitted to call | ||||||||
2076 | /// DecomposeTemplateName. | ||||||||
2077 | /// | ||||||||
2078 | /// This actually loses a lot of source location information for | ||||||||
2079 | /// non-standard name kinds; we should consider preserving that in | ||||||||
2080 | /// some way. | ||||||||
2081 | void | ||||||||
2082 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||||||
2083 | TemplateArgumentListInfo &Buffer, | ||||||||
2084 | DeclarationNameInfo &NameInfo, | ||||||||
2085 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||||||
2086 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||||
2087 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||||||
2088 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||||||
2089 | |||||||||
2090 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||||||
2091 | Id.TemplateId->NumArgs); | ||||||||
2092 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||||||
2093 | |||||||||
2094 | TemplateName TName = Id.TemplateId->Template.get(); | ||||||||
2095 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||||||
2096 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||||||
2097 | TemplateArgs = &Buffer; | ||||||||
2098 | } else { | ||||||||
2099 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||||||
2100 | TemplateArgs = nullptr; | ||||||||
2101 | } | ||||||||
2102 | } | ||||||||
2103 | |||||||||
2104 | static void emitEmptyLookupTypoDiagnostic( | ||||||||
2105 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||||||
2106 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||||||
2107 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||||||
2108 | DeclContext *Ctx = | ||||||||
2109 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||||||
2110 | if (!TC) { | ||||||||
2111 | // Emit a special diagnostic for failed member lookups. | ||||||||
2112 | // FIXME: computing the declaration context might fail here (?) | ||||||||
2113 | if (Ctx) | ||||||||
2114 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||||||
2115 | << SS.getRange(); | ||||||||
2116 | else | ||||||||
2117 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||||||
2118 | return; | ||||||||
2119 | } | ||||||||
2120 | |||||||||
2121 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||||||
2122 | bool DroppedSpecifier = | ||||||||
2123 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||||||
2124 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||||||
2125 | ? diag::note_implicit_param_decl | ||||||||
2126 | : diag::note_previous_decl; | ||||||||
2127 | if (!Ctx) | ||||||||
2128 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||||||
2129 | SemaRef.PDiag(NoteID)); | ||||||||
2130 | else | ||||||||
2131 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||||||
2132 | << Typo << Ctx << DroppedSpecifier | ||||||||
2133 | << SS.getRange(), | ||||||||
2134 | SemaRef.PDiag(NoteID)); | ||||||||
2135 | } | ||||||||
2136 | |||||||||
2137 | /// Diagnose a lookup that found results in an enclosing class during error | ||||||||
2138 | /// recovery. This usually indicates that the results were found in a dependent | ||||||||
2139 | /// base class that could not be searched as part of a template definition. | ||||||||
2140 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||||||
2141 | /// compatibility mode). | ||||||||
2142 | /// | ||||||||
2143 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||||||
2144 | /// should attempt to recover using these lookup results. | ||||||||
2145 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||||||
2146 | // During a default argument instantiation the CurContext points | ||||||||
2147 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||||||
2148 | // function parameter list, hence add an explicit check. | ||||||||
2149 | bool isDefaultArgument = | ||||||||
2150 | !CodeSynthesisContexts.empty() && | ||||||||
2151 | CodeSynthesisContexts.back().Kind == | ||||||||
2152 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||||||
2153 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||||||
2154 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||||||
2155 | R.getNamingClass() == CurMethod->getParent() && | ||||||||
2156 | !isDefaultArgument; | ||||||||
2157 | |||||||||
2158 | // There are two ways we can find a class-scope declaration during template | ||||||||
2159 | // instantiation that we did not find in the template definition: if it is a | ||||||||
2160 | // member of a dependent base class, or if it is declared after the point of | ||||||||
2161 | // use in the same class. Distinguish these by comparing the class in which | ||||||||
2162 | // the member was found to the naming class of the lookup. | ||||||||
2163 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||||||
2164 | unsigned NoteID = diag::note_member_declared_at; | ||||||||
2165 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||||||
2166 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||||||
2167 | : diag::err_found_later_in_class; | ||||||||
2168 | } else if (getLangOpts().MSVCCompat) { | ||||||||
2169 | DiagID = diag::ext_found_in_dependent_base; | ||||||||
2170 | NoteID = diag::note_dependent_member_use; | ||||||||
2171 | } | ||||||||
2172 | |||||||||
2173 | if (isInstance) { | ||||||||
2174 | // Give a code modification hint to insert 'this->'. | ||||||||
2175 | Diag(R.getNameLoc(), DiagID) | ||||||||
2176 | << R.getLookupName() | ||||||||
2177 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||||||
2178 | CheckCXXThisCapture(R.getNameLoc()); | ||||||||
2179 | } else { | ||||||||
2180 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||||||
2181 | // they're not shadowed). | ||||||||
2182 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||||||
2183 | } | ||||||||
2184 | |||||||||
2185 | for (NamedDecl *D : R) | ||||||||
2186 | Diag(D->getLocation(), NoteID); | ||||||||
2187 | |||||||||
2188 | // Return true if we are inside a default argument instantiation | ||||||||
2189 | // and the found name refers to an instance member function, otherwise | ||||||||
2190 | // the caller will try to create an implicit member call and this is wrong | ||||||||
2191 | // for default arguments. | ||||||||
2192 | // | ||||||||
2193 | // FIXME: Is this special case necessary? We could allow the caller to | ||||||||
2194 | // diagnose this. | ||||||||
2195 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||||||
2196 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||||||
2197 | return true; | ||||||||
2198 | } | ||||||||
2199 | |||||||||
2200 | // Tell the callee to try to recover. | ||||||||
2201 | return false; | ||||||||
2202 | } | ||||||||
2203 | |||||||||
2204 | /// Diagnose an empty lookup. | ||||||||
2205 | /// | ||||||||
2206 | /// \return false if new lookup candidates were found | ||||||||
2207 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||||||
2208 | CorrectionCandidateCallback &CCC, | ||||||||
2209 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||||||
2210 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||||||
2211 | DeclarationName Name = R.getLookupName(); | ||||||||
2212 | |||||||||
2213 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||||||
2214 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||||||
2215 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||||||
2216 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||||||
2217 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||||||
2218 | diagnostic = diag::err_undeclared_use; | ||||||||
2219 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||||||
2220 | } | ||||||||
2221 | |||||||||
2222 | // If the original lookup was an unqualified lookup, fake an | ||||||||
2223 | // unqualified lookup. This is useful when (for example) the | ||||||||
2224 | // original lookup would not have found something because it was a | ||||||||
2225 | // dependent name. | ||||||||
2226 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||||||
2227 | while (DC) { | ||||||||
2228 | if (isa<CXXRecordDecl>(DC)) { | ||||||||
2229 | LookupQualifiedName(R, DC); | ||||||||
2230 | |||||||||
2231 | if (!R.empty()) { | ||||||||
2232 | // Don't give errors about ambiguities in this lookup. | ||||||||
2233 | R.suppressDiagnostics(); | ||||||||
2234 | |||||||||
2235 | // If there's a best viable function among the results, only mention | ||||||||
2236 | // that one in the notes. | ||||||||
2237 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||||||
2238 | OverloadCandidateSet::CSK_Normal); | ||||||||
2239 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||||||
2240 | OverloadCandidateSet::iterator Best; | ||||||||
2241 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||||||
2242 | OR_Success) { | ||||||||
2243 | R.clear(); | ||||||||
2244 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||||||
2245 | R.resolveKind(); | ||||||||
2246 | } | ||||||||
2247 | |||||||||
2248 | return DiagnoseDependentMemberLookup(R); | ||||||||
2249 | } | ||||||||
2250 | |||||||||
2251 | R.clear(); | ||||||||
2252 | } | ||||||||
2253 | |||||||||
2254 | DC = DC->getLookupParent(); | ||||||||
2255 | } | ||||||||
2256 | |||||||||
2257 | // We didn't find anything, so try to correct for a typo. | ||||||||
2258 | TypoCorrection Corrected; | ||||||||
2259 | if (S && Out) { | ||||||||
2260 | SourceLocation TypoLoc = R.getNameLoc(); | ||||||||
2261 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2262, __PRETTY_FUNCTION__)) | ||||||||
2262 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2262, __PRETTY_FUNCTION__)); | ||||||||
2263 | *Out = CorrectTypoDelayed( | ||||||||
2264 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||||||
2265 | [=](const TypoCorrection &TC) { | ||||||||
2266 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||||||
2267 | diagnostic, diagnostic_suggest); | ||||||||
2268 | }, | ||||||||
2269 | nullptr, CTK_ErrorRecovery); | ||||||||
2270 | if (*Out) | ||||||||
2271 | return true; | ||||||||
2272 | } else if (S && | ||||||||
2273 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||||||
2274 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||||||
2275 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||||
2276 | bool DroppedSpecifier = | ||||||||
2277 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||||||
2278 | R.setLookupName(Corrected.getCorrection()); | ||||||||
2279 | |||||||||
2280 | bool AcceptableWithRecovery = false; | ||||||||
2281 | bool AcceptableWithoutRecovery = false; | ||||||||
2282 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||||||
2283 | if (ND) { | ||||||||
2284 | if (Corrected.isOverloaded()) { | ||||||||
2285 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||||||
2286 | OverloadCandidateSet::CSK_Normal); | ||||||||
2287 | OverloadCandidateSet::iterator Best; | ||||||||
2288 | for (NamedDecl *CD : Corrected) { | ||||||||
2289 | if (FunctionTemplateDecl *FTD = | ||||||||
2290 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||||||
2291 | AddTemplateOverloadCandidate( | ||||||||
2292 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||||||
2293 | Args, OCS); | ||||||||
2294 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||||||
2295 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||||||
2296 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||||||
2297 | Args, OCS); | ||||||||
2298 | } | ||||||||
2299 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||||||
2300 | case OR_Success: | ||||||||
2301 | ND = Best->FoundDecl; | ||||||||
2302 | Corrected.setCorrectionDecl(ND); | ||||||||
2303 | break; | ||||||||
2304 | default: | ||||||||
2305 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||||||
2306 | Corrected.setCorrectionDecl(ND); | ||||||||
2307 | break; | ||||||||
2308 | } | ||||||||
2309 | } | ||||||||
2310 | R.addDecl(ND); | ||||||||
2311 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||||||
2312 | CXXRecordDecl *Record = nullptr; | ||||||||
2313 | if (Corrected.getCorrectionSpecifier()) { | ||||||||
2314 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||||||
2315 | Record = Ty->getAsCXXRecordDecl(); | ||||||||
2316 | } | ||||||||
2317 | if (!Record) | ||||||||
2318 | Record = cast<CXXRecordDecl>( | ||||||||
2319 | ND->getDeclContext()->getRedeclContext()); | ||||||||
2320 | R.setNamingClass(Record); | ||||||||
2321 | } | ||||||||
2322 | |||||||||
2323 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||||||
2324 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||||||
2325 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||||||
2326 | // FIXME: If we ended up with a typo for a type name or | ||||||||
2327 | // Objective-C class name, we're in trouble because the parser | ||||||||
2328 | // is in the wrong place to recover. Suggest the typo | ||||||||
2329 | // correction, but don't make it a fix-it since we're not going | ||||||||
2330 | // to recover well anyway. | ||||||||
2331 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||||||
2332 | getAsTypeTemplateDecl(UnderlyingND) || | ||||||||
2333 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||||||
2334 | } else { | ||||||||
2335 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||||||
2336 | // because we aren't able to recover. | ||||||||
2337 | AcceptableWithoutRecovery = true; | ||||||||
2338 | } | ||||||||
2339 | |||||||||
2340 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||||||
2341 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||||||
2342 | ? diag::note_implicit_param_decl | ||||||||
2343 | : diag::note_previous_decl; | ||||||||
2344 | if (SS.isEmpty()) | ||||||||
2345 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||||||
2346 | PDiag(NoteID), AcceptableWithRecovery); | ||||||||
2347 | else | ||||||||
2348 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||||||
2349 | << Name << computeDeclContext(SS, false) | ||||||||
2350 | << DroppedSpecifier << SS.getRange(), | ||||||||
2351 | PDiag(NoteID), AcceptableWithRecovery); | ||||||||
2352 | |||||||||
2353 | // Tell the callee whether to try to recover. | ||||||||
2354 | return !AcceptableWithRecovery; | ||||||||
2355 | } | ||||||||
2356 | } | ||||||||
2357 | R.clear(); | ||||||||
2358 | |||||||||
2359 | // Emit a special diagnostic for failed member lookups. | ||||||||
2360 | // FIXME: computing the declaration context might fail here (?) | ||||||||
2361 | if (!SS.isEmpty()) { | ||||||||
2362 | Diag(R.getNameLoc(), diag::err_no_member) | ||||||||
2363 | << Name << computeDeclContext(SS, false) | ||||||||
2364 | << SS.getRange(); | ||||||||
2365 | return true; | ||||||||
2366 | } | ||||||||
2367 | |||||||||
2368 | // Give up, we can't recover. | ||||||||
2369 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||||||
2370 | return true; | ||||||||
2371 | } | ||||||||
2372 | |||||||||
2373 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||||||
2374 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||||||
2375 | /// assume the identifier is a member of a dependent base class. We can only | ||||||||
2376 | /// recover successfully in static methods, instance methods, and other contexts | ||||||||
2377 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||||||
2378 | /// instantiation model, but it's close enough. | ||||||||
2379 | static Expr * | ||||||||
2380 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||||||
2381 | DeclarationNameInfo &NameInfo, | ||||||||
2382 | SourceLocation TemplateKWLoc, | ||||||||
2383 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
2384 | // Only try to recover from lookup into dependent bases in static methods or | ||||||||
2385 | // contexts where 'this' is available. | ||||||||
2386 | QualType ThisType = S.getCurrentThisType(); | ||||||||
2387 | const CXXRecordDecl *RD = nullptr; | ||||||||
2388 | if (!ThisType.isNull()) | ||||||||
2389 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||||||
2390 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||||||
2391 | RD = MD->getParent(); | ||||||||
2392 | if (!RD || !RD->hasAnyDependentBases()) | ||||||||
2393 | return nullptr; | ||||||||
2394 | |||||||||
2395 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||||||
2396 | // is available, suggest inserting 'this->' as a fixit. | ||||||||
2397 | SourceLocation Loc = NameInfo.getLoc(); | ||||||||
2398 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||||||
2399 | DB << NameInfo.getName() << RD; | ||||||||
2400 | |||||||||
2401 | if (!ThisType.isNull()) { | ||||||||
2402 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||||||
2403 | return CXXDependentScopeMemberExpr::Create( | ||||||||
2404 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||||||
2405 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||||||
2406 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||||||
2407 | } | ||||||||
2408 | |||||||||
2409 | // Synthesize a fake NNS that points to the derived class. This will | ||||||||
2410 | // perform name lookup during template instantiation. | ||||||||
2411 | CXXScopeSpec SS; | ||||||||
2412 | auto *NNS = | ||||||||
2413 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||||||
2414 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||||||
2415 | return DependentScopeDeclRefExpr::Create( | ||||||||
2416 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||||||
2417 | TemplateArgs); | ||||||||
2418 | } | ||||||||
2419 | |||||||||
2420 | ExprResult | ||||||||
2421 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||||||
2422 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||||||
2423 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||||||
2424 | CorrectionCandidateCallback *CCC, | ||||||||
2425 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||||||
2426 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2427, __PRETTY_FUNCTION__)) | ||||||||
2427 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2427, __PRETTY_FUNCTION__)); | ||||||||
2428 | if (SS.isInvalid()) | ||||||||
2429 | return ExprError(); | ||||||||
2430 | |||||||||
2431 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||||||
2432 | |||||||||
2433 | // Decompose the UnqualifiedId into the following data. | ||||||||
2434 | DeclarationNameInfo NameInfo; | ||||||||
2435 | const TemplateArgumentListInfo *TemplateArgs; | ||||||||
2436 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||||||
2437 | |||||||||
2438 | DeclarationName Name = NameInfo.getName(); | ||||||||
2439 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||||
2440 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||||||
2441 | |||||||||
2442 | if (II && II->isEditorPlaceholder()) { | ||||||||
2443 | // FIXME: When typed placeholders are supported we can create a typed | ||||||||
2444 | // placeholder expression node. | ||||||||
2445 | return ExprError(); | ||||||||
2446 | } | ||||||||
2447 | |||||||||
2448 | // C++ [temp.dep.expr]p3: | ||||||||
2449 | // An id-expression is type-dependent if it contains: | ||||||||
2450 | // -- an identifier that was declared with a dependent type, | ||||||||
2451 | // (note: handled after lookup) | ||||||||
2452 | // -- a template-id that is dependent, | ||||||||
2453 | // (note: handled in BuildTemplateIdExpr) | ||||||||
2454 | // -- a conversion-function-id that specifies a dependent type, | ||||||||
2455 | // -- a nested-name-specifier that contains a class-name that | ||||||||
2456 | // names a dependent type. | ||||||||
2457 | // Determine whether this is a member of an unknown specialization; | ||||||||
2458 | // we need to handle these differently. | ||||||||
2459 | bool DependentID = false; | ||||||||
2460 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||||||
2461 | Name.getCXXNameType()->isDependentType()) { | ||||||||
2462 | DependentID = true; | ||||||||
2463 | } else if (SS.isSet()) { | ||||||||
2464 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||||||
2465 | if (RequireCompleteDeclContext(SS, DC)) | ||||||||
2466 | return ExprError(); | ||||||||
2467 | } else { | ||||||||
2468 | DependentID = true; | ||||||||
2469 | } | ||||||||
2470 | } | ||||||||
2471 | |||||||||
2472 | if (DependentID) | ||||||||
2473 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2474 | IsAddressOfOperand, TemplateArgs); | ||||||||
2475 | |||||||||
2476 | // Perform the required lookup. | ||||||||
2477 | LookupResult R(*this, NameInfo, | ||||||||
2478 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||||||
2479 | ? LookupObjCImplicitSelfParam | ||||||||
2480 | : LookupOrdinaryName); | ||||||||
2481 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||||||
2482 | // Lookup the template name again to correctly establish the context in | ||||||||
2483 | // which it was found. This is really unfortunate as we already did the | ||||||||
2484 | // lookup to determine that it was a template name in the first place. If | ||||||||
2485 | // this becomes a performance hit, we can work harder to preserve those | ||||||||
2486 | // results until we get here but it's likely not worth it. | ||||||||
2487 | bool MemberOfUnknownSpecialization; | ||||||||
2488 | AssumedTemplateKind AssumedTemplate; | ||||||||
2489 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||||||
2490 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||||||
2491 | &AssumedTemplate)) | ||||||||
2492 | return ExprError(); | ||||||||
2493 | |||||||||
2494 | if (MemberOfUnknownSpecialization || | ||||||||
2495 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||||||
2496 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2497 | IsAddressOfOperand, TemplateArgs); | ||||||||
2498 | } else { | ||||||||
2499 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||||||
2500 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||||||
2501 | |||||||||
2502 | // If the result might be in a dependent base class, this is a dependent | ||||||||
2503 | // id-expression. | ||||||||
2504 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||||||
2505 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2506 | IsAddressOfOperand, TemplateArgs); | ||||||||
2507 | |||||||||
2508 | // If this reference is in an Objective-C method, then we need to do | ||||||||
2509 | // some special Objective-C lookup, too. | ||||||||
2510 | if (IvarLookupFollowUp) { | ||||||||
2511 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||||||
2512 | if (E.isInvalid()) | ||||||||
2513 | return ExprError(); | ||||||||
2514 | |||||||||
2515 | if (Expr *Ex = E.getAs<Expr>()) | ||||||||
2516 | return Ex; | ||||||||
2517 | } | ||||||||
2518 | } | ||||||||
2519 | |||||||||
2520 | if (R.isAmbiguous()) | ||||||||
2521 | return ExprError(); | ||||||||
2522 | |||||||||
2523 | // This could be an implicitly declared function reference (legal in C90, | ||||||||
2524 | // extension in C99, forbidden in C++). | ||||||||
2525 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | ||||||||
2526 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||||||
2527 | if (D) R.addDecl(D); | ||||||||
2528 | } | ||||||||
2529 | |||||||||
2530 | // Determine whether this name might be a candidate for | ||||||||
2531 | // argument-dependent lookup. | ||||||||
2532 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||||||
2533 | |||||||||
2534 | if (R.empty() && !ADL) { | ||||||||
2535 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||||||
2536 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||||||
2537 | TemplateKWLoc, TemplateArgs)) | ||||||||
2538 | return E; | ||||||||
2539 | } | ||||||||
2540 | |||||||||
2541 | // Don't diagnose an empty lookup for inline assembly. | ||||||||
2542 | if (IsInlineAsmIdentifier) | ||||||||
2543 | return ExprError(); | ||||||||
2544 | |||||||||
2545 | // If this name wasn't predeclared and if this is not a function | ||||||||
2546 | // call, diagnose the problem. | ||||||||
2547 | TypoExpr *TE = nullptr; | ||||||||
2548 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||||||
2549 | : nullptr); | ||||||||
2550 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||||||
2551 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2552, __PRETTY_FUNCTION__)) | ||||||||
2552 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2552, __PRETTY_FUNCTION__)); | ||||||||
2553 | if (CCC) { | ||||||||
2554 | // Make sure the callback knows what the typo being diagnosed is. | ||||||||
2555 | CCC->setTypoName(II); | ||||||||
2556 | if (SS.isValid()) | ||||||||
2557 | CCC->setTypoNNS(SS.getScopeRep()); | ||||||||
2558 | } | ||||||||
2559 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||||||
2560 | // a template name, but we happen to have always already looked up the name | ||||||||
2561 | // before we get here if it must be a template name. | ||||||||
2562 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||||||
2563 | None, &TE)) { | ||||||||
2564 | if (TE && KeywordReplacement) { | ||||||||
2565 | auto &State = getTypoExprState(TE); | ||||||||
2566 | auto BestTC = State.Consumer->getNextCorrection(); | ||||||||
2567 | if (BestTC.isKeyword()) { | ||||||||
2568 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||||||
2569 | if (State.DiagHandler) | ||||||||
2570 | State.DiagHandler(BestTC); | ||||||||
2571 | KeywordReplacement->startToken(); | ||||||||
2572 | KeywordReplacement->setKind(II->getTokenID()); | ||||||||
2573 | KeywordReplacement->setIdentifierInfo(II); | ||||||||
2574 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||||||
2575 | // Clean up the state associated with the TypoExpr, since it has | ||||||||
2576 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||||||
2577 | clearDelayedTypo(TE); | ||||||||
2578 | // Signal that a correction to a keyword was performed by returning a | ||||||||
2579 | // valid-but-null ExprResult. | ||||||||
2580 | return (Expr*)nullptr; | ||||||||
2581 | } | ||||||||
2582 | State.Consumer->resetCorrectionStream(); | ||||||||
2583 | } | ||||||||
2584 | return TE ? TE : ExprError(); | ||||||||
2585 | } | ||||||||
2586 | |||||||||
2587 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2588, __PRETTY_FUNCTION__)) | ||||||||
2588 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2588, __PRETTY_FUNCTION__)); | ||||||||
2589 | |||||||||
2590 | // If we found an Objective-C instance variable, let | ||||||||
2591 | // LookupInObjCMethod build the appropriate expression to | ||||||||
2592 | // reference the ivar. | ||||||||
2593 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||||||
2594 | R.clear(); | ||||||||
2595 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||||||
2596 | // In a hopelessly buggy code, Objective-C instance variable | ||||||||
2597 | // lookup fails and no expression will be built to reference it. | ||||||||
2598 | if (!E.isInvalid() && !E.get()) | ||||||||
2599 | return ExprError(); | ||||||||
2600 | return E; | ||||||||
2601 | } | ||||||||
2602 | } | ||||||||
2603 | |||||||||
2604 | // This is guaranteed from this point on. | ||||||||
2605 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2605, __PRETTY_FUNCTION__)); | ||||||||
2606 | |||||||||
2607 | // Check whether this might be a C++ implicit instance member access. | ||||||||
2608 | // C++ [class.mfct.non-static]p3: | ||||||||
2609 | // When an id-expression that is not part of a class member access | ||||||||
2610 | // syntax and not used to form a pointer to member is used in the | ||||||||
2611 | // body of a non-static member function of class X, if name lookup | ||||||||
2612 | // resolves the name in the id-expression to a non-static non-type | ||||||||
2613 | // member of some class C, the id-expression is transformed into a | ||||||||
2614 | // class member access expression using (*this) as the | ||||||||
2615 | // postfix-expression to the left of the . operator. | ||||||||
2616 | // | ||||||||
2617 | // But we don't actually need to do this for '&' operands if R | ||||||||
2618 | // resolved to a function or overloaded function set, because the | ||||||||
2619 | // expression is ill-formed if it actually works out to be a | ||||||||
2620 | // non-static member function: | ||||||||
2621 | // | ||||||||
2622 | // C++ [expr.ref]p4: | ||||||||
2623 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||||||
2624 | // [t]he expression can be used only as the left-hand operand of a | ||||||||
2625 | // member function call. | ||||||||
2626 | // | ||||||||
2627 | // There are other safeguards against such uses, but it's important | ||||||||
2628 | // to get this right here so that we don't end up making a | ||||||||
2629 | // spuriously dependent expression if we're inside a dependent | ||||||||
2630 | // instance method. | ||||||||
2631 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||||||
2632 | bool MightBeImplicitMember; | ||||||||
2633 | if (!IsAddressOfOperand) | ||||||||
2634 | MightBeImplicitMember = true; | ||||||||
2635 | else if (!SS.isEmpty()) | ||||||||
2636 | MightBeImplicitMember = false; | ||||||||
2637 | else if (R.isOverloadedResult()) | ||||||||
2638 | MightBeImplicitMember = false; | ||||||||
2639 | else if (R.isUnresolvableResult()) | ||||||||
2640 | MightBeImplicitMember = true; | ||||||||
2641 | else | ||||||||
2642 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||||||
2643 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||||||
2644 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||||||
2645 | |||||||||
2646 | if (MightBeImplicitMember) | ||||||||
2647 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||||||
2648 | R, TemplateArgs, S); | ||||||||
2649 | } | ||||||||
2650 | |||||||||
2651 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||||||
2652 | |||||||||
2653 | // In C++1y, if this is a variable template id, then check it | ||||||||
2654 | // in BuildTemplateIdExpr(). | ||||||||
2655 | // The single lookup result must be a variable template declaration. | ||||||||
2656 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||||||
2657 | Id.TemplateId->Kind == TNK_Var_template) { | ||||||||
2658 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2659, __PRETTY_FUNCTION__)) | ||||||||
2659 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2659, __PRETTY_FUNCTION__)); | ||||||||
2660 | } | ||||||||
2661 | |||||||||
2662 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||||||
2663 | } | ||||||||
2664 | |||||||||
2665 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||||||
2666 | } | ||||||||
2667 | |||||||||
2668 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||||||
2669 | /// declaration name, generally during template instantiation. | ||||||||
2670 | /// There's a large number of things which don't need to be done along | ||||||||
2671 | /// this path. | ||||||||
2672 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||||||
2673 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||||||
2674 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||||||
2675 | DeclContext *DC = computeDeclContext(SS, false); | ||||||||
2676 | if (!DC) | ||||||||
2677 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2678 | NameInfo, /*TemplateArgs=*/nullptr); | ||||||||
2679 | |||||||||
2680 | if (RequireCompleteDeclContext(SS, DC)) | ||||||||
2681 | return ExprError(); | ||||||||
2682 | |||||||||
2683 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||||||
2684 | LookupQualifiedName(R, DC); | ||||||||
2685 | |||||||||
2686 | if (R.isAmbiguous()) | ||||||||
2687 | return ExprError(); | ||||||||
2688 | |||||||||
2689 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||||||
2690 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2691 | NameInfo, /*TemplateArgs=*/nullptr); | ||||||||
2692 | |||||||||
2693 | if (R.empty()) { | ||||||||
2694 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||||||
2695 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||||||
2696 | // is invalid because it's derived from an invalid base class, then missing | ||||||||
2697 | // members were likely supposed to be inherited. | ||||||||
2698 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||||||
2699 | if (CD->isInvalidDecl()) | ||||||||
2700 | return ExprError(); | ||||||||
2701 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||||||
2702 | << NameInfo.getName() << DC << SS.getRange(); | ||||||||
2703 | return ExprError(); | ||||||||
2704 | } | ||||||||
2705 | |||||||||
2706 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||||||
2707 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||||||
2708 | // a dependent context. If we can recover with a type, downgrade this to | ||||||||
2709 | // a warning in Microsoft compatibility mode. | ||||||||
2710 | unsigned DiagID = diag::err_typename_missing; | ||||||||
2711 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||||||
2712 | DiagID = diag::ext_typename_missing; | ||||||||
2713 | SourceLocation Loc = SS.getBeginLoc(); | ||||||||
2714 | auto D = Diag(Loc, DiagID); | ||||||||
2715 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||||||
2716 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||||||
2717 | |||||||||
2718 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||||||
2719 | // context. | ||||||||
2720 | if (!RecoveryTSI) | ||||||||
2721 | return ExprError(); | ||||||||
2722 | |||||||||
2723 | // Only issue the fixit if we're prepared to recover. | ||||||||
2724 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||||||
2725 | |||||||||
2726 | // Recover by pretending this was an elaborated type. | ||||||||
2727 | QualType Ty = Context.getTypeDeclType(TD); | ||||||||
2728 | TypeLocBuilder TLB; | ||||||||
2729 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||||||
2730 | |||||||||
2731 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||||||
2732 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||||||
2733 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||||
2734 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||||
2735 | |||||||||
2736 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||||||
2737 | |||||||||
2738 | return ExprEmpty(); | ||||||||
2739 | } | ||||||||
2740 | |||||||||
2741 | // Defend against this resolving to an implicit member access. We usually | ||||||||
2742 | // won't get here if this might be a legitimate a class member (we end up in | ||||||||
2743 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||||||
2744 | // a pointer-to-member or in an unevaluated context in C++11. | ||||||||
2745 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||||||
2746 | return BuildPossibleImplicitMemberExpr(SS, | ||||||||
2747 | /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2748 | R, /*TemplateArgs=*/nullptr, S); | ||||||||
2749 | |||||||||
2750 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||||||
2751 | } | ||||||||
2752 | |||||||||
2753 | /// The parser has read a name in, and Sema has detected that we're currently | ||||||||
2754 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||||||
2755 | /// should form a reference to an ivar. | ||||||||
2756 | /// | ||||||||
2757 | /// Ideally, most of this would be done by lookup, but there's | ||||||||
2758 | /// actually quite a lot of extra work involved. | ||||||||
2759 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||||||
2760 | IdentifierInfo *II) { | ||||||||
2761 | SourceLocation Loc = Lookup.getNameLoc(); | ||||||||
2762 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||||
2763 | |||||||||
2764 | // Check for error condition which is already reported. | ||||||||
2765 | if (!CurMethod) | ||||||||
2766 | return DeclResult(true); | ||||||||
2767 | |||||||||
2768 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||||||
2769 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||||||
2770 | // found a decl, but that decl is outside the current instance method (i.e. | ||||||||
2771 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||||||
2772 | // this name, if the lookup sucedes, we replace it our current decl. | ||||||||
2773 | |||||||||
2774 | // If we're in a class method, we don't normally want to look for | ||||||||
2775 | // ivars. But if we don't find anything else, and there's an | ||||||||
2776 | // ivar, that's an error. | ||||||||
2777 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||||||
2778 | |||||||||
2779 | bool LookForIvars; | ||||||||
2780 | if (Lookup.empty()) | ||||||||
2781 | LookForIvars = true; | ||||||||
2782 | else if (IsClassMethod) | ||||||||
2783 | LookForIvars = false; | ||||||||
2784 | else | ||||||||
2785 | LookForIvars = (Lookup.isSingleResult() && | ||||||||
2786 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||||||
2787 | ObjCInterfaceDecl *IFace = nullptr; | ||||||||
2788 | if (LookForIvars) { | ||||||||
2789 | IFace = CurMethod->getClassInterface(); | ||||||||
2790 | ObjCInterfaceDecl *ClassDeclared; | ||||||||
2791 | ObjCIvarDecl *IV = nullptr; | ||||||||
2792 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||||||
2793 | // Diagnose using an ivar in a class method. | ||||||||
2794 | if (IsClassMethod) { | ||||||||
2795 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||||||
2796 | return DeclResult(true); | ||||||||
2797 | } | ||||||||
2798 | |||||||||
2799 | // Diagnose the use of an ivar outside of the declaring class. | ||||||||
2800 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||||||
2801 | !declaresSameEntity(ClassDeclared, IFace) && | ||||||||
2802 | !getLangOpts().DebuggerSupport) | ||||||||
2803 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||||||
2804 | |||||||||
2805 | // Success. | ||||||||
2806 | return IV; | ||||||||
2807 | } | ||||||||
2808 | } else if (CurMethod->isInstanceMethod()) { | ||||||||
2809 | // We should warn if a local variable hides an ivar. | ||||||||
2810 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||||||
2811 | ObjCInterfaceDecl *ClassDeclared; | ||||||||
2812 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||||||
2813 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||||||
2814 | declaresSameEntity(IFace, ClassDeclared)) | ||||||||
2815 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||||||
2816 | } | ||||||||
2817 | } | ||||||||
2818 | } else if (Lookup.isSingleResult() && | ||||||||
2819 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||||||
2820 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||||||
2821 | if (const ObjCIvarDecl *IV = | ||||||||
2822 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||||||
2823 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||||||
2824 | return DeclResult(true); | ||||||||
2825 | } | ||||||||
2826 | } | ||||||||
2827 | |||||||||
2828 | // Didn't encounter an error, didn't find an ivar. | ||||||||
2829 | return DeclResult(false); | ||||||||
2830 | } | ||||||||
2831 | |||||||||
2832 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||||||
2833 | ObjCIvarDecl *IV) { | ||||||||
2834 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||||
2835 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2836, __PRETTY_FUNCTION__)) | ||||||||
2836 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2836, __PRETTY_FUNCTION__)); | ||||||||
2837 | |||||||||
2838 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||||||
2839 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 2839, __PRETTY_FUNCTION__)); | ||||||||
2840 | |||||||||
2841 | // If we're referencing an invalid decl, just return this as a silent | ||||||||
2842 | // error node. The error diagnostic was already emitted on the decl. | ||||||||
2843 | if (IV->isInvalidDecl()) | ||||||||
2844 | return ExprError(); | ||||||||
2845 | |||||||||
2846 | // Check if referencing a field with __attribute__((deprecated)). | ||||||||
2847 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||||||
2848 | return ExprError(); | ||||||||
2849 | |||||||||
2850 | // FIXME: This should use a new expr for a direct reference, don't | ||||||||
2851 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||||||
2852 | IdentifierInfo &II = Context.Idents.get("self"); | ||||||||
2853 | UnqualifiedId SelfName; | ||||||||
2854 | SelfName.setIdentifier(&II, SourceLocation()); | ||||||||
2855 | SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); | ||||||||
2856 | CXXScopeSpec SelfScopeSpec; | ||||||||
2857 | SourceLocation TemplateKWLoc; | ||||||||
2858 | ExprResult SelfExpr = | ||||||||
2859 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||||||
2860 | /*HasTrailingLParen=*/false, | ||||||||
2861 | /*IsAddressOfOperand=*/false); | ||||||||
2862 | if (SelfExpr.isInvalid()) | ||||||||
2863 | return ExprError(); | ||||||||
2864 | |||||||||
2865 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||||||
2866 | if (SelfExpr.isInvalid()) | ||||||||
2867 | return ExprError(); | ||||||||
2868 | |||||||||
2869 | MarkAnyDeclReferenced(Loc, IV, true); | ||||||||
2870 | |||||||||
2871 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||||||
2872 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||||||
2873 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||||||
2874 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||||||
2875 | |||||||||
2876 | ObjCIvarRefExpr *Result = new (Context) | ||||||||
2877 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||||||
2878 | IV->getLocation(), SelfExpr.get(), true, true); | ||||||||
2879 | |||||||||
2880 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||||||
2881 | if (!isUnevaluatedContext() && | ||||||||
2882 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||||||
2883 | getCurFunction()->recordUseOfWeak(Result); | ||||||||
2884 | } | ||||||||
2885 | if (getLangOpts().ObjCAutoRefCount) | ||||||||
2886 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||||||
2887 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||||||
2888 | |||||||||
2889 | return Result; | ||||||||
2890 | } | ||||||||
2891 | |||||||||
2892 | /// The parser has read a name in, and Sema has detected that we're currently | ||||||||
2893 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||||||
2894 | /// should form a reference to an ivar. If so, build an expression referencing | ||||||||
2895 | /// that ivar. | ||||||||
2896 | ExprResult | ||||||||
2897 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||||||
2898 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||||||
2899 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||||||
2900 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||||||
2901 | if (Ivar.isInvalid()) | ||||||||
2902 | return ExprError(); | ||||||||
2903 | if (Ivar.isUsable()) | ||||||||
2904 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||||||
2905 | cast<ObjCIvarDecl>(Ivar.get())); | ||||||||
2906 | |||||||||
2907 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||||||
2908 | LookupBuiltin(Lookup); | ||||||||
2909 | |||||||||
2910 | // Sentinel value saying that we didn't do anything special. | ||||||||
2911 | return ExprResult(false); | ||||||||
2912 | } | ||||||||
2913 | |||||||||
2914 | /// Cast a base object to a member's actual type. | ||||||||
2915 | /// | ||||||||
2916 | /// There are two relevant checks: | ||||||||
2917 | /// | ||||||||
2918 | /// C++ [class.access.base]p7: | ||||||||
2919 | /// | ||||||||
2920 | /// If a class member access operator [...] is used to access a non-static | ||||||||
2921 | /// data member or non-static member function, the reference is ill-formed if | ||||||||
2922 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||||||
2923 | /// naming class of the right operand. | ||||||||
2924 | /// | ||||||||
2925 | /// C++ [expr.ref]p7: | ||||||||
2926 | /// | ||||||||
2927 | /// If E2 is a non-static data member or a non-static member function, the | ||||||||
2928 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||||||
2929 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||||||
2930 | /// | ||||||||
2931 | /// Note that the latter check does not consider access; the access of the | ||||||||
2932 | /// "real" base class is checked as appropriate when checking the access of the | ||||||||
2933 | /// member name. | ||||||||
2934 | ExprResult | ||||||||
2935 | Sema::PerformObjectMemberConversion(Expr *From, | ||||||||
2936 | NestedNameSpecifier *Qualifier, | ||||||||
2937 | NamedDecl *FoundDecl, | ||||||||
2938 | NamedDecl *Member) { | ||||||||
2939 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||||||
2940 | if (!RD) | ||||||||
2941 | return From; | ||||||||
2942 | |||||||||
2943 | QualType DestRecordType; | ||||||||
2944 | QualType DestType; | ||||||||
2945 | QualType FromRecordType; | ||||||||
2946 | QualType FromType = From->getType(); | ||||||||
2947 | bool PointerConversions = false; | ||||||||
2948 | if (isa<FieldDecl>(Member)) { | ||||||||
2949 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||||||
2950 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||||||
2951 | DestRecordType = Context.getAddrSpaceQualType( | ||||||||
2952 | DestRecordType, FromPtrType | ||||||||
2953 | ? FromType->getPointeeType().getAddressSpace() | ||||||||
2954 | : FromType.getAddressSpace()); | ||||||||
2955 | |||||||||
2956 | if (FromPtrType) { | ||||||||
2957 | DestType = Context.getPointerType(DestRecordType); | ||||||||
2958 | FromRecordType = FromPtrType->getPointeeType(); | ||||||||
2959 | PointerConversions = true; | ||||||||
2960 | } else { | ||||||||
2961 | DestType = DestRecordType; | ||||||||
2962 | FromRecordType = FromType; | ||||||||
2963 | } | ||||||||
2964 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||||||
2965 | if (Method->isStatic()) | ||||||||
2966 | return From; | ||||||||
2967 | |||||||||
2968 | DestType = Method->getThisType(); | ||||||||
2969 | DestRecordType = DestType->getPointeeType(); | ||||||||
2970 | |||||||||
2971 | if (FromType->getAs<PointerType>()) { | ||||||||
2972 | FromRecordType = FromType->getPointeeType(); | ||||||||
2973 | PointerConversions = true; | ||||||||
2974 | } else { | ||||||||
2975 | FromRecordType = FromType; | ||||||||
2976 | DestType = DestRecordType; | ||||||||
2977 | } | ||||||||
2978 | |||||||||
2979 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||||||
2980 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||||||
2981 | if (FromAS != DestAS) { | ||||||||
2982 | QualType FromRecordTypeWithoutAS = | ||||||||
2983 | Context.removeAddrSpaceQualType(FromRecordType); | ||||||||
2984 | QualType FromTypeWithDestAS = | ||||||||
2985 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||||||
2986 | if (PointerConversions) | ||||||||
2987 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||||||
2988 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||||||
2989 | CK_AddressSpaceConversion, From->getValueKind()) | ||||||||
2990 | .get(); | ||||||||
2991 | } | ||||||||
2992 | } else { | ||||||||
2993 | // No conversion necessary. | ||||||||
2994 | return From; | ||||||||
2995 | } | ||||||||
2996 | |||||||||
2997 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||||||
2998 | return From; | ||||||||
2999 | |||||||||
3000 | // If the unqualified types are the same, no conversion is necessary. | ||||||||
3001 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||||||
3002 | return From; | ||||||||
3003 | |||||||||
3004 | SourceRange FromRange = From->getSourceRange(); | ||||||||
3005 | SourceLocation FromLoc = FromRange.getBegin(); | ||||||||
3006 | |||||||||
3007 | ExprValueKind VK = From->getValueKind(); | ||||||||
3008 | |||||||||
3009 | // C++ [class.member.lookup]p8: | ||||||||
3010 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||||||
3011 | // class name. | ||||||||
3012 | // | ||||||||
3013 | // If the member was a qualified name and the qualified referred to a | ||||||||
3014 | // specific base subobject type, we'll cast to that intermediate type | ||||||||
3015 | // first and then to the object in which the member is declared. That allows | ||||||||
3016 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||||||
3017 | // | ||||||||
3018 | // class Base { public: int x; }; | ||||||||
3019 | // class Derived1 : public Base { }; | ||||||||
3020 | // class Derived2 : public Base { }; | ||||||||
3021 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||||||
3022 | // | ||||||||
3023 | // void VeryDerived::f() { | ||||||||
3024 | // x = 17; // error: ambiguous base subobjects | ||||||||
3025 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||||||
3026 | // } | ||||||||
3027 | if (Qualifier && Qualifier->getAsType()) { | ||||||||
3028 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||||||
3029 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3029, __PRETTY_FUNCTION__)); | ||||||||
3030 | |||||||||
3031 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | ||||||||
3032 | |||||||||
3033 | // In C++98, the qualifier type doesn't actually have to be a base | ||||||||
3034 | // type of the object type, in which case we just ignore it. | ||||||||
3035 | // Otherwise build the appropriate casts. | ||||||||
3036 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||||||
3037 | CXXCastPath BasePath; | ||||||||
3038 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||||||
3039 | FromLoc, FromRange, &BasePath)) | ||||||||
3040 | return ExprError(); | ||||||||
3041 | |||||||||
3042 | if (PointerConversions) | ||||||||
3043 | QType = Context.getPointerType(QType); | ||||||||
3044 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||||||
3045 | VK, &BasePath).get(); | ||||||||
3046 | |||||||||
3047 | FromType = QType; | ||||||||
3048 | FromRecordType = QRecordType; | ||||||||
3049 | |||||||||
3050 | // If the qualifier type was the same as the destination type, | ||||||||
3051 | // we're done. | ||||||||
3052 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||||||
3053 | return From; | ||||||||
3054 | } | ||||||||
3055 | } | ||||||||
3056 | |||||||||
3057 | CXXCastPath BasePath; | ||||||||
3058 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||||||
3059 | FromLoc, FromRange, &BasePath, | ||||||||
3060 | /*IgnoreAccess=*/true)) | ||||||||
3061 | return ExprError(); | ||||||||
3062 | |||||||||
3063 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||||||
3064 | VK, &BasePath); | ||||||||
3065 | } | ||||||||
3066 | |||||||||
3067 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||||||
3068 | const LookupResult &R, | ||||||||
3069 | bool HasTrailingLParen) { | ||||||||
3070 | // Only when used directly as the postfix-expression of a call. | ||||||||
3071 | if (!HasTrailingLParen) | ||||||||
3072 | return false; | ||||||||
3073 | |||||||||
3074 | // Never if a scope specifier was provided. | ||||||||
3075 | if (SS.isSet()) | ||||||||
3076 | return false; | ||||||||
3077 | |||||||||
3078 | // Only in C++ or ObjC++. | ||||||||
3079 | if (!getLangOpts().CPlusPlus) | ||||||||
3080 | return false; | ||||||||
3081 | |||||||||
3082 | // Turn off ADL when we find certain kinds of declarations during | ||||||||
3083 | // normal lookup: | ||||||||
3084 | for (NamedDecl *D : R) { | ||||||||
3085 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3086 | // -- a declaration of a class member | ||||||||
3087 | // Since using decls preserve this property, we check this on the | ||||||||
3088 | // original decl. | ||||||||
3089 | if (D->isCXXClassMember()) | ||||||||
3090 | return false; | ||||||||
3091 | |||||||||
3092 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3093 | // -- a block-scope function declaration that is not a | ||||||||
3094 | // using-declaration | ||||||||
3095 | // NOTE: we also trigger this for function templates (in fact, we | ||||||||
3096 | // don't check the decl type at all, since all other decl types | ||||||||
3097 | // turn off ADL anyway). | ||||||||
3098 | if (isa<UsingShadowDecl>(D)) | ||||||||
3099 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||||||
3100 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||||
3101 | return false; | ||||||||
3102 | |||||||||
3103 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3104 | // -- a declaration that is neither a function or a function | ||||||||
3105 | // template | ||||||||
3106 | // And also for builtin functions. | ||||||||
3107 | if (isa<FunctionDecl>(D)) { | ||||||||
3108 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||||||
3109 | |||||||||
3110 | // But also builtin functions. | ||||||||
3111 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||||||
3112 | return false; | ||||||||
3113 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||||||
3114 | return false; | ||||||||
3115 | } | ||||||||
3116 | |||||||||
3117 | return true; | ||||||||
3118 | } | ||||||||
3119 | |||||||||
3120 | |||||||||
3121 | /// Diagnoses obvious problems with the use of the given declaration | ||||||||
3122 | /// as an expression. This is only actually called for lookups that | ||||||||
3123 | /// were not overloaded, and it doesn't promise that the declaration | ||||||||
3124 | /// will in fact be used. | ||||||||
3125 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | ||||||||
3126 | if (D->isInvalidDecl()) | ||||||||
3127 | return true; | ||||||||
3128 | |||||||||
3129 | if (isa<TypedefNameDecl>(D)) { | ||||||||
3130 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||||||
3131 | return true; | ||||||||
3132 | } | ||||||||
3133 | |||||||||
3134 | if (isa<ObjCInterfaceDecl>(D)) { | ||||||||
3135 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||||||
3136 | return true; | ||||||||
3137 | } | ||||||||
3138 | |||||||||
3139 | if (isa<NamespaceDecl>(D)) { | ||||||||
3140 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||||||
3141 | return true; | ||||||||
3142 | } | ||||||||
3143 | |||||||||
3144 | return false; | ||||||||
3145 | } | ||||||||
3146 | |||||||||
3147 | // Certain multiversion types should be treated as overloaded even when there is | ||||||||
3148 | // only one result. | ||||||||
3149 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||||||
3150 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3150, __PRETTY_FUNCTION__)); | ||||||||
3151 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||||||
3152 | return FD && | ||||||||
3153 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||||||
3154 | } | ||||||||
3155 | |||||||||
3156 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||||||
3157 | LookupResult &R, bool NeedsADL, | ||||||||
3158 | bool AcceptInvalidDecl) { | ||||||||
3159 | // If this is a single, fully-resolved result and we don't need ADL, | ||||||||
3160 | // just build an ordinary singleton decl ref. | ||||||||
3161 | if (!NeedsADL && R.isSingleResult() && | ||||||||
3162 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||||||
3163 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||||||
3164 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||||||
3165 | R.getRepresentativeDecl(), nullptr, | ||||||||
3166 | AcceptInvalidDecl); | ||||||||
3167 | |||||||||
3168 | // We only need to check the declaration if there's exactly one | ||||||||
3169 | // result, because in the overloaded case the results can only be | ||||||||
3170 | // functions and function templates. | ||||||||
3171 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||||||
3172 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | ||||||||
3173 | return ExprError(); | ||||||||
3174 | |||||||||
3175 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||||||
3176 | // any lookup-related diagnostics; we'll hash these out later, when | ||||||||
3177 | // we've picked a target. | ||||||||
3178 | R.suppressDiagnostics(); | ||||||||
3179 | |||||||||
3180 | UnresolvedLookupExpr *ULE | ||||||||
3181 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||||||
3182 | SS.getWithLocInContext(Context), | ||||||||
3183 | R.getLookupNameInfo(), | ||||||||
3184 | NeedsADL, R.isOverloadedResult(), | ||||||||
3185 | R.begin(), R.end()); | ||||||||
3186 | |||||||||
3187 | return ULE; | ||||||||
3188 | } | ||||||||
3189 | |||||||||
3190 | static void | ||||||||
3191 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||||||
3192 | ValueDecl *var, DeclContext *DC); | ||||||||
3193 | |||||||||
3194 | /// Complete semantic analysis for a reference to the given declaration. | ||||||||
3195 | ExprResult Sema::BuildDeclarationNameExpr( | ||||||||
3196 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||||||
3197 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||||||
3198 | bool AcceptInvalidDecl) { | ||||||||
3199 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3199, __PRETTY_FUNCTION__)); | ||||||||
3200 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3201, __PRETTY_FUNCTION__)) | ||||||||
3201 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3201, __PRETTY_FUNCTION__)); | ||||||||
3202 | |||||||||
3203 | SourceLocation Loc = NameInfo.getLoc(); | ||||||||
3204 | if (CheckDeclInExpr(*this, Loc, D)) | ||||||||
3205 | return ExprError(); | ||||||||
3206 | |||||||||
3207 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||||||
3208 | // Specifically diagnose references to class templates that are missing | ||||||||
3209 | // a template argument list. | ||||||||
3210 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||||||
3211 | return ExprError(); | ||||||||
3212 | } | ||||||||
3213 | |||||||||
3214 | // Make sure that we're referring to a value. | ||||||||
3215 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | ||||||||
3216 | if (!VD) { | ||||||||
3217 | Diag(Loc, diag::err_ref_non_value) | ||||||||
3218 | << D << SS.getRange(); | ||||||||
3219 | Diag(D->getLocation(), diag::note_declared_at); | ||||||||
3220 | return ExprError(); | ||||||||
3221 | } | ||||||||
3222 | |||||||||
3223 | // Check whether this declaration can be used. Note that we suppress | ||||||||
3224 | // this check when we're going to perform argument-dependent lookup | ||||||||
3225 | // on this function name, because this might not be the function | ||||||||
3226 | // that overload resolution actually selects. | ||||||||
3227 | if (DiagnoseUseOfDecl(VD, Loc)) | ||||||||
3228 | return ExprError(); | ||||||||
3229 | |||||||||
3230 | // Only create DeclRefExpr's for valid Decl's. | ||||||||
3231 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||||||
3232 | return ExprError(); | ||||||||
3233 | |||||||||
3234 | // Handle members of anonymous structs and unions. If we got here, | ||||||||
3235 | // and the reference is to a class member indirect field, then this | ||||||||
3236 | // must be the subject of a pointer-to-member expression. | ||||||||
3237 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||||||
3238 | if (!indirectField->isCXXClassMember()) | ||||||||
3239 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||||||
3240 | indirectField); | ||||||||
3241 | |||||||||
3242 | { | ||||||||
3243 | QualType type = VD->getType(); | ||||||||
3244 | if (type.isNull()) | ||||||||
3245 | return ExprError(); | ||||||||
3246 | ExprValueKind valueKind = VK_RValue; | ||||||||
3247 | |||||||||
3248 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||||||
3249 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||||||
3250 | // is expanded by some outer '...' in the context of the use. | ||||||||
3251 | type = type.getNonPackExpansionType(); | ||||||||
3252 | |||||||||
3253 | switch (D->getKind()) { | ||||||||
3254 | // Ignore all the non-ValueDecl kinds. | ||||||||
3255 | #define ABSTRACT_DECL(kind) | ||||||||
3256 | #define VALUE(type, base) | ||||||||
3257 | #define DECL(type, base) \ | ||||||||
3258 | case Decl::type: | ||||||||
3259 | #include "clang/AST/DeclNodes.inc" | ||||||||
3260 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3260); | ||||||||
3261 | |||||||||
3262 | // These shouldn't make it here. | ||||||||
3263 | case Decl::ObjCAtDefsField: | ||||||||
3264 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3264); | ||||||||
3265 | |||||||||
3266 | // Enum constants are always r-values and never references. | ||||||||
3267 | // Unresolved using declarations are dependent. | ||||||||
3268 | case Decl::EnumConstant: | ||||||||
3269 | case Decl::UnresolvedUsingValue: | ||||||||
3270 | case Decl::OMPDeclareReduction: | ||||||||
3271 | case Decl::OMPDeclareMapper: | ||||||||
3272 | valueKind = VK_RValue; | ||||||||
3273 | break; | ||||||||
3274 | |||||||||
3275 | // Fields and indirect fields that got here must be for | ||||||||
3276 | // pointer-to-member expressions; we just call them l-values for | ||||||||
3277 | // internal consistency, because this subexpression doesn't really | ||||||||
3278 | // exist in the high-level semantics. | ||||||||
3279 | case Decl::Field: | ||||||||
3280 | case Decl::IndirectField: | ||||||||
3281 | case Decl::ObjCIvar: | ||||||||
3282 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3283, __PRETTY_FUNCTION__)) | ||||||||
3283 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3283, __PRETTY_FUNCTION__)); | ||||||||
3284 | |||||||||
3285 | // These can't have reference type in well-formed programs, but | ||||||||
3286 | // for internal consistency we do this anyway. | ||||||||
3287 | type = type.getNonReferenceType(); | ||||||||
3288 | valueKind = VK_LValue; | ||||||||
3289 | break; | ||||||||
3290 | |||||||||
3291 | // Non-type template parameters are either l-values or r-values | ||||||||
3292 | // depending on the type. | ||||||||
3293 | case Decl::NonTypeTemplateParm: { | ||||||||
3294 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||||||
3295 | type = reftype->getPointeeType(); | ||||||||
3296 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||||||
3297 | break; | ||||||||
3298 | } | ||||||||
3299 | |||||||||
3300 | // [expr.prim.id.unqual]p2: | ||||||||
3301 | // If the entity is a template parameter object for a template | ||||||||
3302 | // parameter of type T, the type of the expression is const T. | ||||||||
3303 | // [...] The expression is an lvalue if the entity is a [...] template | ||||||||
3304 | // parameter object. | ||||||||
3305 | if (type->isRecordType()) { | ||||||||
3306 | type = type.getUnqualifiedType().withConst(); | ||||||||
3307 | valueKind = VK_LValue; | ||||||||
3308 | break; | ||||||||
3309 | } | ||||||||
3310 | |||||||||
3311 | // For non-references, we need to strip qualifiers just in case | ||||||||
3312 | // the template parameter was declared as 'const int' or whatever. | ||||||||
3313 | valueKind = VK_RValue; | ||||||||
3314 | type = type.getUnqualifiedType(); | ||||||||
3315 | break; | ||||||||
3316 | } | ||||||||
3317 | |||||||||
3318 | case Decl::Var: | ||||||||
3319 | case Decl::VarTemplateSpecialization: | ||||||||
3320 | case Decl::VarTemplatePartialSpecialization: | ||||||||
3321 | case Decl::Decomposition: | ||||||||
3322 | case Decl::OMPCapturedExpr: | ||||||||
3323 | // In C, "extern void blah;" is valid and is an r-value. | ||||||||
3324 | if (!getLangOpts().CPlusPlus && | ||||||||
3325 | !type.hasQualifiers() && | ||||||||
3326 | type->isVoidType()) { | ||||||||
3327 | valueKind = VK_RValue; | ||||||||
3328 | break; | ||||||||
3329 | } | ||||||||
3330 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
3331 | |||||||||
3332 | case Decl::ImplicitParam: | ||||||||
3333 | case Decl::ParmVar: { | ||||||||
3334 | // These are always l-values. | ||||||||
3335 | valueKind = VK_LValue; | ||||||||
3336 | type = type.getNonReferenceType(); | ||||||||
3337 | |||||||||
3338 | // FIXME: Does the addition of const really only apply in | ||||||||
3339 | // potentially-evaluated contexts? Since the variable isn't actually | ||||||||
3340 | // captured in an unevaluated context, it seems that the answer is no. | ||||||||
3341 | if (!isUnevaluatedContext()) { | ||||||||
3342 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||||||
3343 | if (!CapturedType.isNull()) | ||||||||
3344 | type = CapturedType; | ||||||||
3345 | } | ||||||||
3346 | |||||||||
3347 | break; | ||||||||
3348 | } | ||||||||
3349 | |||||||||
3350 | case Decl::Binding: { | ||||||||
3351 | // These are always lvalues. | ||||||||
3352 | valueKind = VK_LValue; | ||||||||
3353 | type = type.getNonReferenceType(); | ||||||||
3354 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | ||||||||
3355 | // decides how that's supposed to work. | ||||||||
3356 | auto *BD = cast<BindingDecl>(VD); | ||||||||
3357 | if (BD->getDeclContext() != CurContext) { | ||||||||
3358 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | ||||||||
3359 | if (DD && DD->hasLocalStorage()) | ||||||||
3360 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | ||||||||
3361 | } | ||||||||
3362 | break; | ||||||||
3363 | } | ||||||||
3364 | |||||||||
3365 | case Decl::Function: { | ||||||||
3366 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||||||
3367 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | ||||||||
3368 | type = Context.BuiltinFnTy; | ||||||||
3369 | valueKind = VK_RValue; | ||||||||
3370 | break; | ||||||||
3371 | } | ||||||||
3372 | } | ||||||||
3373 | |||||||||
3374 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||||||
3375 | |||||||||
3376 | // If we're referring to a function with an __unknown_anytype | ||||||||
3377 | // result type, make the entire expression __unknown_anytype. | ||||||||
3378 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||||||
3379 | type = Context.UnknownAnyTy; | ||||||||
3380 | valueKind = VK_RValue; | ||||||||
3381 | break; | ||||||||
3382 | } | ||||||||
3383 | |||||||||
3384 | // Functions are l-values in C++. | ||||||||
3385 | if (getLangOpts().CPlusPlus) { | ||||||||
3386 | valueKind = VK_LValue; | ||||||||
3387 | break; | ||||||||
3388 | } | ||||||||
3389 | |||||||||
3390 | // C99 DR 316 says that, if a function type comes from a | ||||||||
3391 | // function definition (without a prototype), that type is only | ||||||||
3392 | // used for checking compatibility. Therefore, when referencing | ||||||||
3393 | // the function, we pretend that we don't have the full function | ||||||||
3394 | // type. | ||||||||
3395 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | ||||||||
3396 | isa<FunctionProtoType>(fty)) | ||||||||
3397 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||||||
3398 | fty->getExtInfo()); | ||||||||
3399 | |||||||||
3400 | // Functions are r-values in C. | ||||||||
3401 | valueKind = VK_RValue; | ||||||||
3402 | break; | ||||||||
3403 | } | ||||||||
3404 | |||||||||
3405 | case Decl::CXXDeductionGuide: | ||||||||
3406 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3406); | ||||||||
3407 | |||||||||
3408 | case Decl::MSProperty: | ||||||||
3409 | case Decl::MSGuid: | ||||||||
3410 | case Decl::TemplateParamObject: | ||||||||
3411 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||||||
3412 | // capture in OpenMP, or duplicated between host and device? | ||||||||
3413 | valueKind = VK_LValue; | ||||||||
3414 | break; | ||||||||
3415 | |||||||||
3416 | case Decl::CXXMethod: | ||||||||
3417 | // If we're referring to a method with an __unknown_anytype | ||||||||
3418 | // result type, make the entire expression __unknown_anytype. | ||||||||
3419 | // This should only be possible with a type written directly. | ||||||||
3420 | if (const FunctionProtoType *proto | ||||||||
3421 | = dyn_cast<FunctionProtoType>(VD->getType())) | ||||||||
3422 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||||||
3423 | type = Context.UnknownAnyTy; | ||||||||
3424 | valueKind = VK_RValue; | ||||||||
3425 | break; | ||||||||
3426 | } | ||||||||
3427 | |||||||||
3428 | // C++ methods are l-values if static, r-values if non-static. | ||||||||
3429 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||||||
3430 | valueKind = VK_LValue; | ||||||||
3431 | break; | ||||||||
3432 | } | ||||||||
3433 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
3434 | |||||||||
3435 | case Decl::CXXConversion: | ||||||||
3436 | case Decl::CXXDestructor: | ||||||||
3437 | case Decl::CXXConstructor: | ||||||||
3438 | valueKind = VK_RValue; | ||||||||
3439 | break; | ||||||||
3440 | } | ||||||||
3441 | |||||||||
3442 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||||||
3443 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | ||||||||
3444 | TemplateArgs); | ||||||||
3445 | } | ||||||||
3446 | } | ||||||||
3447 | |||||||||
3448 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||||||
3449 | SmallString<32> &Target) { | ||||||||
3450 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||||||
3451 | char *ResultPtr = &Target[0]; | ||||||||
3452 | const llvm::UTF8 *ErrorPtr; | ||||||||
3453 | bool success = | ||||||||
3454 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||||||
3455 | (void)success; | ||||||||
3456 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3456, __PRETTY_FUNCTION__)); | ||||||||
3457 | Target.resize(ResultPtr - &Target[0]); | ||||||||
3458 | } | ||||||||
3459 | |||||||||
3460 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||||||
3461 | PredefinedExpr::IdentKind IK) { | ||||||||
3462 | // Pick the current block, lambda, captured statement or function. | ||||||||
3463 | Decl *currentDecl = nullptr; | ||||||||
3464 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||||||
3465 | currentDecl = BSI->TheDecl; | ||||||||
3466 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||||||
3467 | currentDecl = LSI->CallOperator; | ||||||||
3468 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||||||
3469 | currentDecl = CSI->TheCapturedDecl; | ||||||||
3470 | else | ||||||||
3471 | currentDecl = getCurFunctionOrMethodDecl(); | ||||||||
3472 | |||||||||
3473 | if (!currentDecl) { | ||||||||
3474 | Diag(Loc, diag::ext_predef_outside_function); | ||||||||
3475 | currentDecl = Context.getTranslationUnitDecl(); | ||||||||
3476 | } | ||||||||
3477 | |||||||||
3478 | QualType ResTy; | ||||||||
3479 | StringLiteral *SL = nullptr; | ||||||||
3480 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||||||
3481 | ResTy = Context.DependentTy; | ||||||||
3482 | else { | ||||||||
3483 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||||||
3484 | // the string. | ||||||||
3485 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||||||
3486 | unsigned Length = Str.length(); | ||||||||
3487 | |||||||||
3488 | llvm::APInt LengthI(32, Length + 1); | ||||||||
3489 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||||||
3490 | ResTy = | ||||||||
3491 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||||||
3492 | SmallString<32> RawChars; | ||||||||
3493 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||||||
3494 | Str, RawChars); | ||||||||
3495 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||||||
3496 | ArrayType::Normal, | ||||||||
3497 | /*IndexTypeQuals*/ 0); | ||||||||
3498 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||||||
3499 | /*Pascal*/ false, ResTy, Loc); | ||||||||
3500 | } else { | ||||||||
3501 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||||||
3502 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||||||
3503 | ArrayType::Normal, | ||||||||
3504 | /*IndexTypeQuals*/ 0); | ||||||||
3505 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | ||||||||
3506 | /*Pascal*/ false, ResTy, Loc); | ||||||||
3507 | } | ||||||||
3508 | } | ||||||||
3509 | |||||||||
3510 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||||||
3511 | } | ||||||||
3512 | |||||||||
3513 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||||||
3514 | PredefinedExpr::IdentKind IK; | ||||||||
3515 | |||||||||
3516 | switch (Kind) { | ||||||||
3517 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3517); | ||||||||
3518 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||||||
3519 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||||||
3520 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||||||
3521 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||||||
3522 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||||||
3523 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||||||
3524 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||||||
3525 | } | ||||||||
3526 | |||||||||
3527 | return BuildPredefinedExpr(Loc, IK); | ||||||||
3528 | } | ||||||||
3529 | |||||||||
3530 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||||||
3531 | SmallString<16> CharBuffer; | ||||||||
3532 | bool Invalid = false; | ||||||||
3533 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||||||
3534 | if (Invalid) | ||||||||
3535 | return ExprError(); | ||||||||
3536 | |||||||||
3537 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||||||
3538 | PP, Tok.getKind()); | ||||||||
3539 | if (Literal.hadError()) | ||||||||
3540 | return ExprError(); | ||||||||
3541 | |||||||||
3542 | QualType Ty; | ||||||||
3543 | if (Literal.isWide()) | ||||||||
3544 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||||||
3545 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||||||
3546 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||||||
3547 | else if (Literal.isUTF16()) | ||||||||
3548 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||||||
3549 | else if (Literal.isUTF32()) | ||||||||
3550 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||||||
3551 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||||||
3552 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||||||
3553 | else | ||||||||
3554 | Ty = Context.CharTy; // 'x' -> char in C++ | ||||||||
3555 | |||||||||
3556 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||||||
3557 | if (Literal.isWide()) | ||||||||
3558 | Kind = CharacterLiteral::Wide; | ||||||||
3559 | else if (Literal.isUTF16()) | ||||||||
3560 | Kind = CharacterLiteral::UTF16; | ||||||||
3561 | else if (Literal.isUTF32()) | ||||||||
3562 | Kind = CharacterLiteral::UTF32; | ||||||||
3563 | else if (Literal.isUTF8()) | ||||||||
3564 | Kind = CharacterLiteral::UTF8; | ||||||||
3565 | |||||||||
3566 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||||||
3567 | Tok.getLocation()); | ||||||||
3568 | |||||||||
3569 | if (Literal.getUDSuffix().empty()) | ||||||||
3570 | return Lit; | ||||||||
3571 | |||||||||
3572 | // We're building a user-defined literal. | ||||||||
3573 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
3574 | SourceLocation UDSuffixLoc = | ||||||||
3575 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||||||
3576 | |||||||||
3577 | // Make sure we're allowed user-defined literals here. | ||||||||
3578 | if (!UDLScope) | ||||||||
3579 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||||||
3580 | |||||||||
3581 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||||||
3582 | // operator "" X (ch) | ||||||||
3583 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||||||
3584 | Lit, Tok.getLocation()); | ||||||||
3585 | } | ||||||||
3586 | |||||||||
3587 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||||||
3588 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||||||
3589 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||||||
3590 | Context.IntTy, Loc); | ||||||||
3591 | } | ||||||||
3592 | |||||||||
3593 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||||||
3594 | QualType Ty, SourceLocation Loc) { | ||||||||
3595 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||||||
3596 | |||||||||
3597 | using llvm::APFloat; | ||||||||
3598 | APFloat Val(Format); | ||||||||
3599 | |||||||||
3600 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||||||
3601 | |||||||||
3602 | // Overflow is always an error, but underflow is only an error if | ||||||||
3603 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||||||
3604 | if ((result & APFloat::opOverflow) || | ||||||||
3605 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||||||
3606 | unsigned diagnostic; | ||||||||
3607 | SmallString<20> buffer; | ||||||||
3608 | if (result & APFloat::opOverflow) { | ||||||||
3609 | diagnostic = diag::warn_float_overflow; | ||||||||
3610 | APFloat::getLargest(Format).toString(buffer); | ||||||||
3611 | } else { | ||||||||
3612 | diagnostic = diag::warn_float_underflow; | ||||||||
3613 | APFloat::getSmallest(Format).toString(buffer); | ||||||||
3614 | } | ||||||||
3615 | |||||||||
3616 | S.Diag(Loc, diagnostic) | ||||||||
3617 | << Ty | ||||||||
3618 | << StringRef(buffer.data(), buffer.size()); | ||||||||
3619 | } | ||||||||
3620 | |||||||||
3621 | bool isExact = (result == APFloat::opOK); | ||||||||
3622 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||||||
3623 | } | ||||||||
3624 | |||||||||
3625 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||||||
3626 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3626, __PRETTY_FUNCTION__)); | ||||||||
3627 | |||||||||
3628 | if (E->isValueDependent()) | ||||||||
3629 | return false; | ||||||||
3630 | |||||||||
3631 | QualType QT = E->getType(); | ||||||||
3632 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||||||
3633 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||||||
3634 | return true; | ||||||||
3635 | } | ||||||||
3636 | |||||||||
3637 | llvm::APSInt ValueAPS; | ||||||||
3638 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||||||
3639 | |||||||||
3640 | if (R.isInvalid()) | ||||||||
3641 | return true; | ||||||||
3642 | |||||||||
3643 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||||||
3644 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||||||
3645 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||||||
3646 | << ValueAPS.toString(10) << ValueIsPositive; | ||||||||
3647 | return true; | ||||||||
3648 | } | ||||||||
3649 | |||||||||
3650 | return false; | ||||||||
3651 | } | ||||||||
3652 | |||||||||
3653 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||||||
3654 | // Fast path for a single digit (which is quite common). A single digit | ||||||||
3655 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||||||
3656 | if (Tok.getLength() == 1) { | ||||||||
3657 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||||||
3658 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||||||
3659 | } | ||||||||
3660 | |||||||||
3661 | SmallString<128> SpellingBuffer; | ||||||||
3662 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||||||
3663 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||||||
3664 | // returns a StringRef to the memory buffer, it should have a null char at | ||||||||
3665 | // the EOF, so it is also safe. | ||||||||
3666 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||||||
3667 | |||||||||
3668 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||||||
3669 | bool Invalid = false; | ||||||||
3670 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||||||
3671 | if (Invalid) | ||||||||
3672 | return ExprError(); | ||||||||
3673 | |||||||||
3674 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||||||
3675 | PP.getSourceManager(), PP.getLangOpts(), | ||||||||
3676 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||||||
3677 | if (Literal.hadError) | ||||||||
3678 | return ExprError(); | ||||||||
3679 | |||||||||
3680 | if (Literal.hasUDSuffix()) { | ||||||||
3681 | // We're building a user-defined literal. | ||||||||
3682 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
3683 | SourceLocation UDSuffixLoc = | ||||||||
3684 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||||||
3685 | |||||||||
3686 | // Make sure we're allowed user-defined literals here. | ||||||||
3687 | if (!UDLScope) | ||||||||
3688 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||||||
3689 | |||||||||
3690 | QualType CookedTy; | ||||||||
3691 | if (Literal.isFloatingLiteral()) { | ||||||||
3692 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||||||
3693 | // long double, the literal is treated as a call of the form | ||||||||
3694 | // operator "" X (f L) | ||||||||
3695 | CookedTy = Context.LongDoubleTy; | ||||||||
3696 | } else { | ||||||||
3697 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||||||
3698 | // unsigned long long, the literal is treated as a call of the form | ||||||||
3699 | // operator "" X (n ULL) | ||||||||
3700 | CookedTy = Context.UnsignedLongLongTy; | ||||||||
3701 | } | ||||||||
3702 | |||||||||
3703 | DeclarationName OpName = | ||||||||
3704 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
3705 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
3706 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
3707 | |||||||||
3708 | SourceLocation TokLoc = Tok.getLocation(); | ||||||||
3709 | |||||||||
3710 | // Perform literal operator lookup to determine if we're building a raw | ||||||||
3711 | // literal or a cooked one. | ||||||||
3712 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||||||
3713 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||||||
3714 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||||||
3715 | /*AllowStringTemplatePack*/ false, | ||||||||
3716 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||||||
3717 | case LOLR_ErrorNoDiagnostic: | ||||||||
3718 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||||||
3719 | // GNU extension producing _Complex types. | ||||||||
3720 | break; | ||||||||
3721 | case LOLR_Error: | ||||||||
3722 | return ExprError(); | ||||||||
3723 | case LOLR_Cooked: { | ||||||||
3724 | Expr *Lit; | ||||||||
3725 | if (Literal.isFloatingLiteral()) { | ||||||||
3726 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||||||
3727 | } else { | ||||||||
3728 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||||||
3729 | if (Literal.GetIntegerValue(ResultVal)) | ||||||||
3730 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||||||
3731 | << /* Unsigned */ 1; | ||||||||
3732 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||||||
3733 | Tok.getLocation()); | ||||||||
3734 | } | ||||||||
3735 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||||||
3736 | } | ||||||||
3737 | |||||||||
3738 | case LOLR_Raw: { | ||||||||
3739 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||||||
3740 | // literal is treated as a call of the form | ||||||||
3741 | // operator "" X ("n") | ||||||||
3742 | unsigned Length = Literal.getUDSuffixOffset(); | ||||||||
3743 | QualType StrTy = Context.getConstantArrayType( | ||||||||
3744 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||||||
3745 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||||||
3746 | Expr *Lit = StringLiteral::Create( | ||||||||
3747 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | ||||||||
3748 | /*Pascal*/false, StrTy, &TokLoc, 1); | ||||||||
3749 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||||||
3750 | } | ||||||||
3751 | |||||||||
3752 | case LOLR_Template: { | ||||||||
3753 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||||||
3754 | // template), L is treated as a call fo the form | ||||||||
3755 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||||||
3756 | // where n is the source character sequence c1 c2 ... ck. | ||||||||
3757 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
3758 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||||||
3759 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||||||
3760 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||||||
3761 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||||||
3762 | Value = TokSpelling[I]; | ||||||||
3763 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||||||
3764 | TemplateArgumentLocInfo ArgInfo; | ||||||||
3765 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
3766 | } | ||||||||
3767 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||||||
3768 | &ExplicitArgs); | ||||||||
3769 | } | ||||||||
3770 | case LOLR_StringTemplatePack: | ||||||||
3771 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3771); | ||||||||
3772 | } | ||||||||
3773 | } | ||||||||
3774 | |||||||||
3775 | Expr *Res; | ||||||||
3776 | |||||||||
3777 | if (Literal.isFixedPointLiteral()) { | ||||||||
3778 | QualType Ty; | ||||||||
3779 | |||||||||
3780 | if (Literal.isAccum) { | ||||||||
3781 | if (Literal.isHalf) { | ||||||||
3782 | Ty = Context.ShortAccumTy; | ||||||||
3783 | } else if (Literal.isLong) { | ||||||||
3784 | Ty = Context.LongAccumTy; | ||||||||
3785 | } else { | ||||||||
3786 | Ty = Context.AccumTy; | ||||||||
3787 | } | ||||||||
3788 | } else if (Literal.isFract) { | ||||||||
3789 | if (Literal.isHalf) { | ||||||||
3790 | Ty = Context.ShortFractTy; | ||||||||
3791 | } else if (Literal.isLong) { | ||||||||
3792 | Ty = Context.LongFractTy; | ||||||||
3793 | } else { | ||||||||
3794 | Ty = Context.FractTy; | ||||||||
3795 | } | ||||||||
3796 | } | ||||||||
3797 | |||||||||
3798 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||||||
3799 | |||||||||
3800 | bool isSigned = !Literal.isUnsigned; | ||||||||
3801 | unsigned scale = Context.getFixedPointScale(Ty); | ||||||||
3802 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||||||
3803 | |||||||||
3804 | llvm::APInt Val(bit_width, 0, isSigned); | ||||||||
3805 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||||||
3806 | bool ValIsZero = Val.isNullValue() && !Overflowed; | ||||||||
3807 | |||||||||
3808 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||||||
3809 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||||||
3810 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||||||
3811 | // representable values for its type, with exception for constants of a | ||||||||
3812 | // fract type with a value of exactly 1; such a constant shall denote | ||||||||
3813 | // the maximal value for the type. | ||||||||
3814 | --Val; | ||||||||
3815 | else if (Val.ugt(MaxVal) || Overflowed) | ||||||||
3816 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||||||
3817 | |||||||||
3818 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||||||
3819 | Tok.getLocation(), scale); | ||||||||
3820 | } else if (Literal.isFloatingLiteral()) { | ||||||||
3821 | QualType Ty; | ||||||||
3822 | if (Literal.isHalf){ | ||||||||
3823 | if (getOpenCLOptions().isEnabled("cl_khr_fp16")) | ||||||||
3824 | Ty = Context.HalfTy; | ||||||||
3825 | else { | ||||||||
3826 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||||||
3827 | return ExprError(); | ||||||||
3828 | } | ||||||||
3829 | } else if (Literal.isFloat) | ||||||||
3830 | Ty = Context.FloatTy; | ||||||||
3831 | else if (Literal.isLong) | ||||||||
3832 | Ty = Context.LongDoubleTy; | ||||||||
3833 | else if (Literal.isFloat16) | ||||||||
3834 | Ty = Context.Float16Ty; | ||||||||
3835 | else if (Literal.isFloat128) | ||||||||
3836 | Ty = Context.Float128Ty; | ||||||||
3837 | else | ||||||||
3838 | Ty = Context.DoubleTy; | ||||||||
3839 | |||||||||
3840 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||||||
3841 | |||||||||
3842 | if (Ty == Context.DoubleTy) { | ||||||||
3843 | if (getLangOpts().SinglePrecisionConstants) { | ||||||||
3844 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||||||
3845 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
3846 | } | ||||||||
3847 | } else if (getLangOpts().OpenCL && | ||||||||
3848 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | ||||||||
3849 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||||||
3850 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | ||||||||
3851 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
3852 | } | ||||||||
3853 | } | ||||||||
3854 | } else if (!Literal.isIntegerLiteral()) { | ||||||||
3855 | return ExprError(); | ||||||||
3856 | } else { | ||||||||
3857 | QualType Ty; | ||||||||
3858 | |||||||||
3859 | // 'long long' is a C99 or C++11 feature. | ||||||||
3860 | if (!getLangOpts().C99 && Literal.isLongLong) { | ||||||||
3861 | if (getLangOpts().CPlusPlus) | ||||||||
3862 | Diag(Tok.getLocation(), | ||||||||
3863 | getLangOpts().CPlusPlus11 ? | ||||||||
3864 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||||||
3865 | else | ||||||||
3866 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||||||
3867 | } | ||||||||
3868 | |||||||||
3869 | // Get the value in the widest-possible width. | ||||||||
3870 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | ||||||||
3871 | llvm::APInt ResultVal(MaxWidth, 0); | ||||||||
3872 | |||||||||
3873 | if (Literal.GetIntegerValue(ResultVal)) { | ||||||||
3874 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||||||
3875 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||||||
3876 | << /* Unsigned */ 1; | ||||||||
3877 | Ty = Context.UnsignedLongLongTy; | ||||||||
3878 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3879, __PRETTY_FUNCTION__)) | ||||||||
3879 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3879, __PRETTY_FUNCTION__)); | ||||||||
3880 | } else { | ||||||||
3881 | // If this value fits into a ULL, try to figure out what else it fits into | ||||||||
3882 | // according to the rules of C99 6.4.4.1p5. | ||||||||
3883 | |||||||||
3884 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||||||
3885 | // be an unsigned int. | ||||||||
3886 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||||||
3887 | |||||||||
3888 | // Check from smallest to largest, picking the smallest type we can. | ||||||||
3889 | unsigned Width = 0; | ||||||||
3890 | |||||||||
3891 | // Microsoft specific integer suffixes are explicitly sized. | ||||||||
3892 | if (Literal.MicrosoftInteger) { | ||||||||
3893 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||||||
3894 | Width = 8; | ||||||||
3895 | Ty = Context.CharTy; | ||||||||
3896 | } else { | ||||||||
3897 | Width = Literal.MicrosoftInteger; | ||||||||
3898 | Ty = Context.getIntTypeForBitwidth(Width, | ||||||||
3899 | /*Signed=*/!Literal.isUnsigned); | ||||||||
3900 | } | ||||||||
3901 | } | ||||||||
3902 | |||||||||
3903 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { | ||||||||
3904 | // Are int/unsigned possibilities? | ||||||||
3905 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||||||
3906 | |||||||||
3907 | // Does it fit in a unsigned int? | ||||||||
3908 | if (ResultVal.isIntN(IntSize)) { | ||||||||
3909 | // Does it fit in a signed int? | ||||||||
3910 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||||||
3911 | Ty = Context.IntTy; | ||||||||
3912 | else if (AllowUnsigned) | ||||||||
3913 | Ty = Context.UnsignedIntTy; | ||||||||
3914 | Width = IntSize; | ||||||||
3915 | } | ||||||||
3916 | } | ||||||||
3917 | |||||||||
3918 | // Are long/unsigned long possibilities? | ||||||||
3919 | if (Ty.isNull() && !Literal.isLongLong) { | ||||||||
3920 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||||||
3921 | |||||||||
3922 | // Does it fit in a unsigned long? | ||||||||
3923 | if (ResultVal.isIntN(LongSize)) { | ||||||||
3924 | // Does it fit in a signed long? | ||||||||
3925 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||||||
3926 | Ty = Context.LongTy; | ||||||||
3927 | else if (AllowUnsigned) | ||||||||
3928 | Ty = Context.UnsignedLongTy; | ||||||||
3929 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||||||
3930 | // is compatible. | ||||||||
3931 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||||||
3932 | const unsigned LongLongSize = | ||||||||
3933 | Context.getTargetInfo().getLongLongWidth(); | ||||||||
3934 | Diag(Tok.getLocation(), | ||||||||
3935 | getLangOpts().CPlusPlus | ||||||||
3936 | ? Literal.isLong | ||||||||
3937 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||||||
3938 | : /*C++98 UB*/ diag:: | ||||||||
3939 | ext_old_implicitly_unsigned_long_cxx | ||||||||
3940 | : diag::warn_old_implicitly_unsigned_long) | ||||||||
3941 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||||||
3942 | : /*will be ill-formed*/ 1); | ||||||||
3943 | Ty = Context.UnsignedLongTy; | ||||||||
3944 | } | ||||||||
3945 | Width = LongSize; | ||||||||
3946 | } | ||||||||
3947 | } | ||||||||
3948 | |||||||||
3949 | // Check long long if needed. | ||||||||
3950 | if (Ty.isNull()) { | ||||||||
3951 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||||||
3952 | |||||||||
3953 | // Does it fit in a unsigned long long? | ||||||||
3954 | if (ResultVal.isIntN(LongLongSize)) { | ||||||||
3955 | // Does it fit in a signed long long? | ||||||||
3956 | // To be compatible with MSVC, hex integer literals ending with the | ||||||||
3957 | // LL or i64 suffix are always signed in Microsoft mode. | ||||||||
3958 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||||||
3959 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||||||
3960 | Ty = Context.LongLongTy; | ||||||||
3961 | else if (AllowUnsigned) | ||||||||
3962 | Ty = Context.UnsignedLongLongTy; | ||||||||
3963 | Width = LongLongSize; | ||||||||
3964 | } | ||||||||
3965 | } | ||||||||
3966 | |||||||||
3967 | // If we still couldn't decide a type, we probably have something that | ||||||||
3968 | // does not fit in a signed long long, but has no U suffix. | ||||||||
3969 | if (Ty.isNull()) { | ||||||||
3970 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); | ||||||||
3971 | Ty = Context.UnsignedLongLongTy; | ||||||||
3972 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||||||
3973 | } | ||||||||
3974 | |||||||||
3975 | if (ResultVal.getBitWidth() != Width) | ||||||||
3976 | ResultVal = ResultVal.trunc(Width); | ||||||||
3977 | } | ||||||||
3978 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||||||
3979 | } | ||||||||
3980 | |||||||||
3981 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||||||
3982 | if (Literal.isImaginary) { | ||||||||
3983 | Res = new (Context) ImaginaryLiteral(Res, | ||||||||
3984 | Context.getComplexType(Res->getType())); | ||||||||
3985 | |||||||||
3986 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||||||
3987 | } | ||||||||
3988 | return Res; | ||||||||
3989 | } | ||||||||
3990 | |||||||||
3991 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||||||
3992 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 3992, __PRETTY_FUNCTION__)); | ||||||||
3993 | return new (Context) ParenExpr(L, R, E); | ||||||||
3994 | } | ||||||||
3995 | |||||||||
3996 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||||||
3997 | SourceLocation Loc, | ||||||||
3998 | SourceRange ArgRange) { | ||||||||
3999 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||||||
4000 | // scalar or vector data type argument..." | ||||||||
4001 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||||||
4002 | // type (C99 6.2.5p18) or void. | ||||||||
4003 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||||||
4004 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||||||
4005 | << T << ArgRange; | ||||||||
4006 | return true; | ||||||||
4007 | } | ||||||||
4008 | |||||||||
4009 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4010, __PRETTY_FUNCTION__)) | ||||||||
4010 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4010, __PRETTY_FUNCTION__)); | ||||||||
4011 | return false; | ||||||||
4012 | } | ||||||||
4013 | |||||||||
4014 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||||||
4015 | SourceLocation Loc, | ||||||||
4016 | SourceRange ArgRange, | ||||||||
4017 | UnaryExprOrTypeTrait TraitKind) { | ||||||||
4018 | // Invalid types must be hard errors for SFINAE in C++. | ||||||||
4019 | if (S.LangOpts.CPlusPlus) | ||||||||
4020 | return true; | ||||||||
4021 | |||||||||
4022 | // C99 6.5.3.4p1: | ||||||||
4023 | if (T->isFunctionType() && | ||||||||
4024 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||||||
4025 | TraitKind == UETT_PreferredAlignOf)) { | ||||||||
4026 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||||||
4027 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||||||
4028 | << getTraitSpelling(TraitKind) << ArgRange; | ||||||||
4029 | return false; | ||||||||
4030 | } | ||||||||
4031 | |||||||||
4032 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||||||
4033 | // this is an error (OpenCL v1.1 s6.3.k) | ||||||||
4034 | if (T->isVoidType()) { | ||||||||
4035 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||||||
4036 | : diag::ext_sizeof_alignof_void_type; | ||||||||
4037 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||||||
4038 | return false; | ||||||||
4039 | } | ||||||||
4040 | |||||||||
4041 | return true; | ||||||||
4042 | } | ||||||||
4043 | |||||||||
4044 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||||||
4045 | SourceLocation Loc, | ||||||||
4046 | SourceRange ArgRange, | ||||||||
4047 | UnaryExprOrTypeTrait TraitKind) { | ||||||||
4048 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||||||
4049 | // runtime doesn't allow it. | ||||||||
4050 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||||||
4051 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||||||
4052 | << T << (TraitKind == UETT_SizeOf) | ||||||||
4053 | << ArgRange; | ||||||||
4054 | return true; | ||||||||
4055 | } | ||||||||
4056 | |||||||||
4057 | return false; | ||||||||
4058 | } | ||||||||
4059 | |||||||||
4060 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||||||
4061 | /// pointer type is equal to T) and emit a warning if it is. | ||||||||
4062 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||||||
4063 | Expr *E) { | ||||||||
4064 | // Don't warn if the operation changed the type. | ||||||||
4065 | if (T != E->getType()) | ||||||||
4066 | return; | ||||||||
4067 | |||||||||
4068 | // Now look for array decays. | ||||||||
4069 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||||||
4070 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||||||
4071 | return; | ||||||||
4072 | |||||||||
4073 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||||||
4074 | << ICE->getType() | ||||||||
4075 | << ICE->getSubExpr()->getType(); | ||||||||
4076 | } | ||||||||
4077 | |||||||||
4078 | /// Check the constraints on expression operands to unary type expression | ||||||||
4079 | /// and type traits. | ||||||||
4080 | /// | ||||||||
4081 | /// Completes any types necessary and validates the constraints on the operand | ||||||||
4082 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||||||
4083 | /// the expression as it completes the type for that expression through template | ||||||||
4084 | /// instantiation, etc. | ||||||||
4085 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||||||
4086 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4087 | QualType ExprTy = E->getType(); | ||||||||
4088 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4088, __PRETTY_FUNCTION__)); | ||||||||
4089 | |||||||||
4090 | bool IsUnevaluatedOperand = | ||||||||
4091 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||||||
4092 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||||||
4093 | if (IsUnevaluatedOperand) { | ||||||||
4094 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||||||
4095 | if (Result.isInvalid()) | ||||||||
4096 | return true; | ||||||||
4097 | E = Result.get(); | ||||||||
4098 | } | ||||||||
4099 | |||||||||
4100 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||||||
4101 | // so side effects could result in unintended consequences. | ||||||||
4102 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||||||
4103 | // used to build SFINAE gadgets. | ||||||||
4104 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||||||
4105 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||||||
4106 | !E->isInstantiationDependent() && | ||||||||
4107 | E->HasSideEffects(Context, false)) | ||||||||
4108 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||||||
4109 | |||||||||
4110 | if (ExprKind == UETT_VecStep) | ||||||||
4111 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||||||
4112 | E->getSourceRange()); | ||||||||
4113 | |||||||||
4114 | // Explicitly list some types as extensions. | ||||||||
4115 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||||||
4116 | E->getSourceRange(), ExprKind)) | ||||||||
4117 | return false; | ||||||||
4118 | |||||||||
4119 | // 'alignof' applied to an expression only requires the base element type of | ||||||||
4120 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||||||
4121 | // be complete (and will attempt to complete it if it's an array of unknown | ||||||||
4122 | // bound). | ||||||||
4123 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||||||
4124 | if (RequireCompleteSizedType( | ||||||||
4125 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||||||
4126 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4127 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||||||
4128 | return true; | ||||||||
4129 | } else { | ||||||||
4130 | if (RequireCompleteSizedExprType( | ||||||||
4131 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4132 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||||||
4133 | return true; | ||||||||
4134 | } | ||||||||
4135 | |||||||||
4136 | // Completing the expression's type may have changed it. | ||||||||
4137 | ExprTy = E->getType(); | ||||||||
4138 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4138, __PRETTY_FUNCTION__)); | ||||||||
4139 | |||||||||
4140 | if (ExprTy->isFunctionType()) { | ||||||||
4141 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||||||
4142 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||||||
4143 | return true; | ||||||||
4144 | } | ||||||||
4145 | |||||||||
4146 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||||||
4147 | E->getSourceRange(), ExprKind)) | ||||||||
4148 | return true; | ||||||||
4149 | |||||||||
4150 | if (ExprKind == UETT_SizeOf) { | ||||||||
4151 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||||||
4152 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||||||
4153 | QualType OType = PVD->getOriginalType(); | ||||||||
4154 | QualType Type = PVD->getType(); | ||||||||
4155 | if (Type->isPointerType() && OType->isArrayType()) { | ||||||||
4156 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||||||
4157 | << Type << OType; | ||||||||
4158 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||||||
4159 | } | ||||||||
4160 | } | ||||||||
4161 | } | ||||||||
4162 | |||||||||
4163 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||||||
4164 | // decays into a pointer and returns an unintended result. This is most | ||||||||
4165 | // likely a typo for "sizeof(array) op x". | ||||||||
4166 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||||||
4167 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||||||
4168 | BO->getLHS()); | ||||||||
4169 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||||||
4170 | BO->getRHS()); | ||||||||
4171 | } | ||||||||
4172 | } | ||||||||
4173 | |||||||||
4174 | return false; | ||||||||
4175 | } | ||||||||
4176 | |||||||||
4177 | /// Check the constraints on operands to unary expression and type | ||||||||
4178 | /// traits. | ||||||||
4179 | /// | ||||||||
4180 | /// This will complete any types necessary, and validate the various constraints | ||||||||
4181 | /// on those operands. | ||||||||
4182 | /// | ||||||||
4183 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||||||
4184 | /// C99 6.3.2.1p[2-4] all state: | ||||||||
4185 | /// Except when it is the operand of the sizeof operator ... | ||||||||
4186 | /// | ||||||||
4187 | /// C++ [expr.sizeof]p4 | ||||||||
4188 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||||||
4189 | /// standard conversions are not applied to the operand of sizeof. | ||||||||
4190 | /// | ||||||||
4191 | /// This policy is followed for all of the unary trait expressions. | ||||||||
4192 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||||||
4193 | SourceLocation OpLoc, | ||||||||
4194 | SourceRange ExprRange, | ||||||||
4195 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4196 | if (ExprType->isDependentType()) | ||||||||
4197 | return false; | ||||||||
4198 | |||||||||
4199 | // C++ [expr.sizeof]p2: | ||||||||
4200 | // When applied to a reference or a reference type, the result | ||||||||
4201 | // is the size of the referenced type. | ||||||||
4202 | // C++11 [expr.alignof]p3: | ||||||||
4203 | // When alignof is applied to a reference type, the result | ||||||||
4204 | // shall be the alignment of the referenced type. | ||||||||
4205 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||||||
4206 | ExprType = Ref->getPointeeType(); | ||||||||
4207 | |||||||||
4208 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||||||
4209 | // When alignof or _Alignof is applied to an array type, the result | ||||||||
4210 | // is the alignment of the element type. | ||||||||
4211 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||||||
4212 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||||||
4213 | ExprType = Context.getBaseElementType(ExprType); | ||||||||
4214 | |||||||||
4215 | if (ExprKind == UETT_VecStep) | ||||||||
4216 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||||||
4217 | |||||||||
4218 | // Explicitly list some types as extensions. | ||||||||
4219 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||||||
4220 | ExprKind)) | ||||||||
4221 | return false; | ||||||||
4222 | |||||||||
4223 | if (RequireCompleteSizedType( | ||||||||
4224 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4225 | getTraitSpelling(ExprKind), ExprRange)) | ||||||||
4226 | return true; | ||||||||
4227 | |||||||||
4228 | if (ExprType->isFunctionType()) { | ||||||||
4229 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||||||
4230 | << getTraitSpelling(ExprKind) << ExprRange; | ||||||||
4231 | return true; | ||||||||
4232 | } | ||||||||
4233 | |||||||||
4234 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||||||
4235 | ExprKind)) | ||||||||
4236 | return true; | ||||||||
4237 | |||||||||
4238 | return false; | ||||||||
4239 | } | ||||||||
4240 | |||||||||
4241 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||||||
4242 | // Cannot know anything else if the expression is dependent. | ||||||||
4243 | if (E->isTypeDependent()) | ||||||||
4244 | return false; | ||||||||
4245 | |||||||||
4246 | if (E->getObjectKind() == OK_BitField) { | ||||||||
4247 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||||||
4248 | << 1 << E->getSourceRange(); | ||||||||
4249 | return true; | ||||||||
4250 | } | ||||||||
4251 | |||||||||
4252 | ValueDecl *D = nullptr; | ||||||||
4253 | Expr *Inner = E->IgnoreParens(); | ||||||||
4254 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||||||
4255 | D = DRE->getDecl(); | ||||||||
4256 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||||||
4257 | D = ME->getMemberDecl(); | ||||||||
4258 | } | ||||||||
4259 | |||||||||
4260 | // If it's a field, require the containing struct to have a | ||||||||
4261 | // complete definition so that we can compute the layout. | ||||||||
4262 | // | ||||||||
4263 | // This can happen in C++11 onwards, either by naming the member | ||||||||
4264 | // in a way that is not transformed into a member access expression | ||||||||
4265 | // (in an unevaluated operand, for instance), or by naming the member | ||||||||
4266 | // in a trailing-return-type. | ||||||||
4267 | // | ||||||||
4268 | // For the record, since __alignof__ on expressions is a GCC | ||||||||
4269 | // extension, GCC seems to permit this but always gives the | ||||||||
4270 | // nonsensical answer 0. | ||||||||
4271 | // | ||||||||
4272 | // We don't really need the layout here --- we could instead just | ||||||||
4273 | // directly check for all the appropriate alignment-lowing | ||||||||
4274 | // attributes --- but that would require duplicating a lot of | ||||||||
4275 | // logic that just isn't worth duplicating for such a marginal | ||||||||
4276 | // use-case. | ||||||||
4277 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||||||
4278 | // Fast path this check, since we at least know the record has a | ||||||||
4279 | // definition if we can find a member of it. | ||||||||
4280 | if (!FD->getParent()->isCompleteDefinition()) { | ||||||||
4281 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||||||
4282 | << E->getSourceRange(); | ||||||||
4283 | return true; | ||||||||
4284 | } | ||||||||
4285 | |||||||||
4286 | // Otherwise, if it's a field, and the field doesn't have | ||||||||
4287 | // reference type, then it must have a complete type (or be a | ||||||||
4288 | // flexible array member, which we explicitly want to | ||||||||
4289 | // white-list anyway), which makes the following checks trivial. | ||||||||
4290 | if (!FD->getType()->isReferenceType()) | ||||||||
4291 | return false; | ||||||||
4292 | } | ||||||||
4293 | |||||||||
4294 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||||||
4295 | } | ||||||||
4296 | |||||||||
4297 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||||||
4298 | E = E->IgnoreParens(); | ||||||||
4299 | |||||||||
4300 | // Cannot know anything else if the expression is dependent. | ||||||||
4301 | if (E->isTypeDependent()) | ||||||||
4302 | return false; | ||||||||
4303 | |||||||||
4304 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||||||
4305 | } | ||||||||
4306 | |||||||||
4307 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||||||
4308 | CapturingScopeInfo *CSI) { | ||||||||
4309 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4309, __PRETTY_FUNCTION__)); | ||||||||
4310 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4310, __PRETTY_FUNCTION__)); | ||||||||
4311 | |||||||||
4312 | // We're going to walk down into the type and look for VLA expressions. | ||||||||
4313 | do { | ||||||||
4314 | const Type *Ty = T.getTypePtr(); | ||||||||
4315 | switch (Ty->getTypeClass()) { | ||||||||
4316 | #define TYPE(Class, Base) | ||||||||
4317 | #define ABSTRACT_TYPE(Class, Base) | ||||||||
4318 | #define NON_CANONICAL_TYPE(Class, Base) | ||||||||
4319 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||||||
4320 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||||||
4321 | #include "clang/AST/TypeNodes.inc" | ||||||||
4322 | T = QualType(); | ||||||||
4323 | break; | ||||||||
4324 | // These types are never variably-modified. | ||||||||
4325 | case Type::Builtin: | ||||||||
4326 | case Type::Complex: | ||||||||
4327 | case Type::Vector: | ||||||||
4328 | case Type::ExtVector: | ||||||||
4329 | case Type::ConstantMatrix: | ||||||||
4330 | case Type::Record: | ||||||||
4331 | case Type::Enum: | ||||||||
4332 | case Type::Elaborated: | ||||||||
4333 | case Type::TemplateSpecialization: | ||||||||
4334 | case Type::ObjCObject: | ||||||||
4335 | case Type::ObjCInterface: | ||||||||
4336 | case Type::ObjCObjectPointer: | ||||||||
4337 | case Type::ObjCTypeParam: | ||||||||
4338 | case Type::Pipe: | ||||||||
4339 | case Type::ExtInt: | ||||||||
4340 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4340); | ||||||||
4341 | case Type::Adjusted: | ||||||||
4342 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||||||
4343 | break; | ||||||||
4344 | case Type::Decayed: | ||||||||
4345 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||||||
4346 | break; | ||||||||
4347 | case Type::Pointer: | ||||||||
4348 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||||||
4349 | break; | ||||||||
4350 | case Type::BlockPointer: | ||||||||
4351 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||||||
4352 | break; | ||||||||
4353 | case Type::LValueReference: | ||||||||
4354 | case Type::RValueReference: | ||||||||
4355 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||||||
4356 | break; | ||||||||
4357 | case Type::MemberPointer: | ||||||||
4358 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||||||
4359 | break; | ||||||||
4360 | case Type::ConstantArray: | ||||||||
4361 | case Type::IncompleteArray: | ||||||||
4362 | // Losing element qualification here is fine. | ||||||||
4363 | T = cast<ArrayType>(Ty)->getElementType(); | ||||||||
4364 | break; | ||||||||
4365 | case Type::VariableArray: { | ||||||||
4366 | // Losing element qualification here is fine. | ||||||||
4367 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||||||
4368 | |||||||||
4369 | // Unknown size indication requires no size computation. | ||||||||
4370 | // Otherwise, evaluate and record it. | ||||||||
4371 | auto Size = VAT->getSizeExpr(); | ||||||||
4372 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||||||
4373 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||||||
4374 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||||||
4375 | |||||||||
4376 | T = VAT->getElementType(); | ||||||||
4377 | break; | ||||||||
4378 | } | ||||||||
4379 | case Type::FunctionProto: | ||||||||
4380 | case Type::FunctionNoProto: | ||||||||
4381 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||||||
4382 | break; | ||||||||
4383 | case Type::Paren: | ||||||||
4384 | case Type::TypeOf: | ||||||||
4385 | case Type::UnaryTransform: | ||||||||
4386 | case Type::Attributed: | ||||||||
4387 | case Type::SubstTemplateTypeParm: | ||||||||
4388 | case Type::MacroQualified: | ||||||||
4389 | // Keep walking after single level desugaring. | ||||||||
4390 | T = T.getSingleStepDesugaredType(Context); | ||||||||
4391 | break; | ||||||||
4392 | case Type::Typedef: | ||||||||
4393 | T = cast<TypedefType>(Ty)->desugar(); | ||||||||
4394 | break; | ||||||||
4395 | case Type::Decltype: | ||||||||
4396 | T = cast<DecltypeType>(Ty)->desugar(); | ||||||||
4397 | break; | ||||||||
4398 | case Type::Auto: | ||||||||
4399 | case Type::DeducedTemplateSpecialization: | ||||||||
4400 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||||||
4401 | break; | ||||||||
4402 | case Type::TypeOfExpr: | ||||||||
4403 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||||||
4404 | break; | ||||||||
4405 | case Type::Atomic: | ||||||||
4406 | T = cast<AtomicType>(Ty)->getValueType(); | ||||||||
4407 | break; | ||||||||
4408 | } | ||||||||
4409 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||||||
4410 | } | ||||||||
4411 | |||||||||
4412 | /// Build a sizeof or alignof expression given a type operand. | ||||||||
4413 | ExprResult | ||||||||
4414 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||||||
4415 | SourceLocation OpLoc, | ||||||||
4416 | UnaryExprOrTypeTrait ExprKind, | ||||||||
4417 | SourceRange R) { | ||||||||
4418 | if (!TInfo) | ||||||||
4419 | return ExprError(); | ||||||||
4420 | |||||||||
4421 | QualType T = TInfo->getType(); | ||||||||
4422 | |||||||||
4423 | if (!T->isDependentType() && | ||||||||
4424 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||||||
4425 | return ExprError(); | ||||||||
4426 | |||||||||
4427 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||||||
4428 | if (auto *TT = T->getAs<TypedefType>()) { | ||||||||
4429 | for (auto I = FunctionScopes.rbegin(), | ||||||||
4430 | E = std::prev(FunctionScopes.rend()); | ||||||||
4431 | I != E; ++I) { | ||||||||
4432 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||||||
4433 | if (CSI == nullptr) | ||||||||
4434 | break; | ||||||||
4435 | DeclContext *DC = nullptr; | ||||||||
4436 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||||||
4437 | DC = LSI->CallOperator; | ||||||||
4438 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||||||
4439 | DC = CRSI->TheCapturedDecl; | ||||||||
4440 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||||||
4441 | DC = BSI->TheDecl; | ||||||||
4442 | if (DC) { | ||||||||
4443 | if (DC->containsDecl(TT->getDecl())) | ||||||||
4444 | break; | ||||||||
4445 | captureVariablyModifiedType(Context, T, CSI); | ||||||||
4446 | } | ||||||||
4447 | } | ||||||||
4448 | } | ||||||||
4449 | } | ||||||||
4450 | |||||||||
4451 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||||||
4452 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||||||
4453 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||||||
4454 | } | ||||||||
4455 | |||||||||
4456 | /// Build a sizeof or alignof expression given an expression | ||||||||
4457 | /// operand. | ||||||||
4458 | ExprResult | ||||||||
4459 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||||||
4460 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4461 | ExprResult PE = CheckPlaceholderExpr(E); | ||||||||
4462 | if (PE.isInvalid()) | ||||||||
4463 | return ExprError(); | ||||||||
4464 | |||||||||
4465 | E = PE.get(); | ||||||||
4466 | |||||||||
4467 | // Verify that the operand is valid. | ||||||||
4468 | bool isInvalid = false; | ||||||||
4469 | if (E->isTypeDependent()) { | ||||||||
4470 | // Delay type-checking for type-dependent expressions. | ||||||||
4471 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||||||
4472 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||||||
4473 | } else if (ExprKind == UETT_VecStep) { | ||||||||
4474 | isInvalid = CheckVecStepExpr(E); | ||||||||
4475 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||||||
4476 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||||||
4477 | isInvalid = true; | ||||||||
4478 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||||||
4479 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||||||
4480 | isInvalid = true; | ||||||||
4481 | } else { | ||||||||
4482 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||||||
4483 | } | ||||||||
4484 | |||||||||
4485 | if (isInvalid) | ||||||||
4486 | return ExprError(); | ||||||||
4487 | |||||||||
4488 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||||||
4489 | PE = TransformToPotentiallyEvaluated(E); | ||||||||
4490 | if (PE.isInvalid()) return ExprError(); | ||||||||
4491 | E = PE.get(); | ||||||||
4492 | } | ||||||||
4493 | |||||||||
4494 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||||||
4495 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||||||
4496 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||||||
4497 | } | ||||||||
4498 | |||||||||
4499 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||||||
4500 | /// expr and the same for @c alignof and @c __alignof | ||||||||
4501 | /// Note that the ArgRange is invalid if isType is false. | ||||||||
4502 | ExprResult | ||||||||
4503 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||||||
4504 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||||||
4505 | void *TyOrEx, SourceRange ArgRange) { | ||||||||
4506 | // If error parsing type, ignore. | ||||||||
4507 | if (!TyOrEx) return ExprError(); | ||||||||
4508 | |||||||||
4509 | if (IsType) { | ||||||||
4510 | TypeSourceInfo *TInfo; | ||||||||
4511 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||||||
4512 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||||||
4513 | } | ||||||||
4514 | |||||||||
4515 | Expr *ArgEx = (Expr *)TyOrEx; | ||||||||
4516 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||||||
4517 | return Result; | ||||||||
4518 | } | ||||||||
4519 | |||||||||
4520 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||||||
4521 | bool IsReal) { | ||||||||
4522 | if (V.get()->isTypeDependent()) | ||||||||
4523 | return S.Context.DependentTy; | ||||||||
4524 | |||||||||
4525 | // _Real and _Imag are only l-values for normal l-values. | ||||||||
4526 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||||||
4527 | V = S.DefaultLvalueConversion(V.get()); | ||||||||
4528 | if (V.isInvalid()) | ||||||||
4529 | return QualType(); | ||||||||
4530 | } | ||||||||
4531 | |||||||||
4532 | // These operators return the element type of a complex type. | ||||||||
4533 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||||||
4534 | return CT->getElementType(); | ||||||||
4535 | |||||||||
4536 | // Otherwise they pass through real integer and floating point types here. | ||||||||
4537 | if (V.get()->getType()->isArithmeticType()) | ||||||||
4538 | return V.get()->getType(); | ||||||||
4539 | |||||||||
4540 | // Test for placeholders. | ||||||||
4541 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||||||
4542 | if (PR.isInvalid()) return QualType(); | ||||||||
4543 | if (PR.get() != V.get()) { | ||||||||
4544 | V = PR; | ||||||||
4545 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||||||
4546 | } | ||||||||
4547 | |||||||||
4548 | // Reject anything else. | ||||||||
4549 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||||||
4550 | << (IsReal ? "__real" : "__imag"); | ||||||||
4551 | return QualType(); | ||||||||
4552 | } | ||||||||
4553 | |||||||||
4554 | |||||||||
4555 | |||||||||
4556 | ExprResult | ||||||||
4557 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||||||
4558 | tok::TokenKind Kind, Expr *Input) { | ||||||||
4559 | UnaryOperatorKind Opc; | ||||||||
4560 | switch (Kind) { | ||||||||
4561 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4561); | ||||||||
4562 | case tok::plusplus: Opc = UO_PostInc; break; | ||||||||
4563 | case tok::minusminus: Opc = UO_PostDec; break; | ||||||||
4564 | } | ||||||||
4565 | |||||||||
4566 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||||||
4567 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||||||
4568 | if (Result.isInvalid()) return ExprError(); | ||||||||
4569 | Input = Result.get(); | ||||||||
4570 | |||||||||
4571 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||||||
4572 | } | ||||||||
4573 | |||||||||
4574 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||||||
4575 | /// | ||||||||
4576 | /// \return true on error | ||||||||
4577 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||||||
4578 | SourceLocation opLoc, | ||||||||
4579 | Expr *op) { | ||||||||
4580 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4580, __PRETTY_FUNCTION__)); | ||||||||
4581 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||||||
4582 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||||||
4583 | return false; | ||||||||
4584 | |||||||||
4585 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||||||
4586 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||||||
4587 | << op->getSourceRange(); | ||||||||
4588 | return true; | ||||||||
4589 | } | ||||||||
4590 | |||||||||
4591 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||||||
4592 | auto *BaseNoParens = Base->IgnoreParens(); | ||||||||
4593 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||||||
4594 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||||||
4595 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||||||
4596 | } | ||||||||
4597 | |||||||||
4598 | ExprResult | ||||||||
4599 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | ||||||||
4600 | Expr *idx, SourceLocation rbLoc) { | ||||||||
4601 | if (base && !base->getType().isNull() && | ||||||||
4602 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | ||||||||
4603 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | ||||||||
4604 | SourceLocation(), /*Length*/ nullptr, | ||||||||
4605 | /*Stride=*/nullptr, rbLoc); | ||||||||
4606 | |||||||||
4607 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||||||
4608 | if (isa<ParenListExpr>(base)) { | ||||||||
4609 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||||||
4610 | if (result.isInvalid()) return ExprError(); | ||||||||
4611 | base = result.get(); | ||||||||
4612 | } | ||||||||
4613 | |||||||||
4614 | // Check if base and idx form a MatrixSubscriptExpr. | ||||||||
4615 | // | ||||||||
4616 | // Helper to check for comma expressions, which are not allowed as indices for | ||||||||
4617 | // matrix subscript expressions. | ||||||||
4618 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||||||
4619 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||||||
4620 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||||||
4621 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4622 | return true; | ||||||||
4623 | } | ||||||||
4624 | return false; | ||||||||
4625 | }; | ||||||||
4626 | // The matrix subscript operator ([][])is considered a single operator. | ||||||||
4627 | // Separating the index expressions by parenthesis is not allowed. | ||||||||
4628 | if (base->getType()->isSpecificPlaceholderType( | ||||||||
4629 | BuiltinType::IncompleteMatrixIdx) && | ||||||||
4630 | !isa<MatrixSubscriptExpr>(base)) { | ||||||||
4631 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||||||
4632 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4633 | return ExprError(); | ||||||||
4634 | } | ||||||||
4635 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||||||
4636 | // MatrixSubscriptExpr. | ||||||||
4637 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||||||
4638 | if (matSubscriptE) { | ||||||||
4639 | if (CheckAndReportCommaError(idx)) | ||||||||
4640 | return ExprError(); | ||||||||
4641 | |||||||||
4642 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4643, __PRETTY_FUNCTION__)) | ||||||||
4643 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4643, __PRETTY_FUNCTION__)); | ||||||||
4644 | return CreateBuiltinMatrixSubscriptExpr( | ||||||||
4645 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | ||||||||
4646 | } | ||||||||
4647 | |||||||||
4648 | // Handle any non-overload placeholder types in the base and index | ||||||||
4649 | // expressions. We can't handle overloads here because the other | ||||||||
4650 | // operand might be an overloadable type, in which case the overload | ||||||||
4651 | // resolution for the operator overload should get the first crack | ||||||||
4652 | // at the overload. | ||||||||
4653 | bool IsMSPropertySubscript = false; | ||||||||
4654 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4655 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||||||
4656 | if (!IsMSPropertySubscript) { | ||||||||
4657 | ExprResult result = CheckPlaceholderExpr(base); | ||||||||
4658 | if (result.isInvalid()) | ||||||||
4659 | return ExprError(); | ||||||||
4660 | base = result.get(); | ||||||||
4661 | } | ||||||||
4662 | } | ||||||||
4663 | |||||||||
4664 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||||||
4665 | if (base->getType()->isMatrixType()) { | ||||||||
4666 | if (CheckAndReportCommaError(idx)) | ||||||||
4667 | return ExprError(); | ||||||||
4668 | |||||||||
4669 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | ||||||||
4670 | } | ||||||||
4671 | |||||||||
4672 | // A comma-expression as the index is deprecated in C++2a onwards. | ||||||||
4673 | if (getLangOpts().CPlusPlus20 && | ||||||||
4674 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||||||
4675 | (isa<CXXOperatorCallExpr>(idx) && | ||||||||
4676 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | ||||||||
4677 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||||||
4678 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4679 | } | ||||||||
4680 | |||||||||
4681 | if (idx->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4682 | ExprResult result = CheckPlaceholderExpr(idx); | ||||||||
4683 | if (result.isInvalid()) return ExprError(); | ||||||||
4684 | idx = result.get(); | ||||||||
4685 | } | ||||||||
4686 | |||||||||
4687 | // Build an unanalyzed expression if either operand is type-dependent. | ||||||||
4688 | if (getLangOpts().CPlusPlus && | ||||||||
4689 | (base->isTypeDependent() || idx->isTypeDependent())) { | ||||||||
4690 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | ||||||||
4691 | VK_LValue, OK_Ordinary, rbLoc); | ||||||||
4692 | } | ||||||||
4693 | |||||||||
4694 | // MSDN, property (C++) | ||||||||
4695 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||||||
4696 | // This attribute can also be used in the declaration of an empty array in a | ||||||||
4697 | // class or structure definition. For example: | ||||||||
4698 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||||||
4699 | // The above statement indicates that x[] can be used with one or more array | ||||||||
4700 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||||||
4701 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||||||
4702 | if (IsMSPropertySubscript) { | ||||||||
4703 | // Build MS property subscript expression if base is MS property reference | ||||||||
4704 | // or MS property subscript. | ||||||||
4705 | return new (Context) MSPropertySubscriptExpr( | ||||||||
4706 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | ||||||||
4707 | } | ||||||||
4708 | |||||||||
4709 | // Use C++ overloaded-operator rules if either operand has record | ||||||||
4710 | // type. The spec says to do this if either type is *overloadable*, | ||||||||
4711 | // but enum types can't declare subscript operators or conversion | ||||||||
4712 | // operators, so there's nothing interesting for overload resolution | ||||||||
4713 | // to do if there aren't any record types involved. | ||||||||
4714 | // | ||||||||
4715 | // ObjC pointers have their own subscripting logic that is not tied | ||||||||
4716 | // to overload resolution and so should not take this path. | ||||||||
4717 | if (getLangOpts().CPlusPlus && | ||||||||
4718 | (base->getType()->isRecordType() || | ||||||||
4719 | (!base->getType()->isObjCObjectPointerType() && | ||||||||
4720 | idx->getType()->isRecordType()))) { | ||||||||
4721 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | ||||||||
4722 | } | ||||||||
4723 | |||||||||
4724 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | ||||||||
4725 | |||||||||
4726 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||||||
4727 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||||||
4728 | |||||||||
4729 | return Res; | ||||||||
4730 | } | ||||||||
4731 | |||||||||
4732 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||||||
4733 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||||||
4734 | InitializationKind Kind = | ||||||||
4735 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||||||
4736 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||||||
4737 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||||||
4738 | } | ||||||||
4739 | |||||||||
4740 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||||||
4741 | Expr *ColumnIdx, | ||||||||
4742 | SourceLocation RBLoc) { | ||||||||
4743 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||||||
4744 | if (BaseR.isInvalid()) | ||||||||
4745 | return BaseR; | ||||||||
4746 | Base = BaseR.get(); | ||||||||
4747 | |||||||||
4748 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||||||
4749 | if (RowR.isInvalid()) | ||||||||
4750 | return RowR; | ||||||||
4751 | RowIdx = RowR.get(); | ||||||||
4752 | |||||||||
4753 | if (!ColumnIdx) | ||||||||
4754 | return new (Context) MatrixSubscriptExpr( | ||||||||
4755 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||||||
4756 | |||||||||
4757 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||||||
4758 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||||||
4759 | ColumnIdx->isTypeDependent()) | ||||||||
4760 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||||||
4761 | Context.DependentTy, RBLoc); | ||||||||
4762 | |||||||||
4763 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||||||
4764 | if (ColumnR.isInvalid()) | ||||||||
4765 | return ColumnR; | ||||||||
4766 | ColumnIdx = ColumnR.get(); | ||||||||
4767 | |||||||||
4768 | // Check that IndexExpr is an integer expression. If it is a constant | ||||||||
4769 | // expression, check that it is less than Dim (= the number of elements in the | ||||||||
4770 | // corresponding dimension). | ||||||||
4771 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||||||
4772 | bool IsColumnIdx) -> Expr * { | ||||||||
4773 | if (!IndexExpr->getType()->isIntegerType() && | ||||||||
4774 | !IndexExpr->isTypeDependent()) { | ||||||||
4775 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||||||
4776 | << IsColumnIdx; | ||||||||
4777 | return nullptr; | ||||||||
4778 | } | ||||||||
4779 | |||||||||
4780 | if (Optional<llvm::APSInt> Idx = | ||||||||
4781 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||||||
4782 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||||||
4783 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||||||
4784 | << IsColumnIdx << Dim; | ||||||||
4785 | return nullptr; | ||||||||
4786 | } | ||||||||
4787 | } | ||||||||
4788 | |||||||||
4789 | ExprResult ConvExpr = | ||||||||
4790 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||||||
4791 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4792, __PRETTY_FUNCTION__)) | ||||||||
4792 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 4792, __PRETTY_FUNCTION__)); | ||||||||
4793 | return ConvExpr.get(); | ||||||||
4794 | }; | ||||||||
4795 | |||||||||
4796 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||||||
4797 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||||||
4798 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||||||
4799 | if (!RowIdx || !ColumnIdx) | ||||||||
4800 | return ExprError(); | ||||||||
4801 | |||||||||
4802 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||||||
4803 | MTy->getElementType(), RBLoc); | ||||||||
4804 | } | ||||||||
4805 | |||||||||
4806 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||||||
4807 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||||||
4808 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||||||
4809 | |||||||||
4810 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||||||
4811 | // checked. | ||||||||
4812 | const MemberExpr *Member = nullptr; | ||||||||
4813 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||||||
4814 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||||||
4815 | |||||||||
4816 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||||||
4817 | } | ||||||||
4818 | |||||||||
4819 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||||||
4820 | if (isUnevaluatedContext()) | ||||||||
4821 | return; | ||||||||
4822 | |||||||||
4823 | QualType ResultTy = E->getType(); | ||||||||
4824 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||||||
4825 | |||||||||
4826 | // Bail if the element is an array since it is not memory access. | ||||||||
4827 | if (isa<ArrayType>(ResultTy)) | ||||||||
4828 | return; | ||||||||
4829 | |||||||||
4830 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||||||
4831 | LastRecord.PossibleDerefs.insert(E); | ||||||||
4832 | return; | ||||||||
4833 | } | ||||||||
4834 | |||||||||
4835 | // Check if the base type is a pointer to a member access of a struct | ||||||||
4836 | // marked with noderef. | ||||||||
4837 | const Expr *Base = E->getBase(); | ||||||||
4838 | QualType BaseTy = Base->getType(); | ||||||||
4839 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||||||
4840 | // Not a pointer access | ||||||||
4841 | return; | ||||||||
4842 | |||||||||
4843 | const MemberExpr *Member = nullptr; | ||||||||
4844 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||||||
4845 | Member->isArrow()) | ||||||||
4846 | Base = Member->getBase(); | ||||||||
4847 | |||||||||
4848 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||||||
4849 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||||||
4850 | LastRecord.PossibleDerefs.insert(E); | ||||||||
4851 | } | ||||||||
4852 | } | ||||||||
4853 | |||||||||
4854 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||||||
4855 | Expr *LowerBound, | ||||||||
4856 | SourceLocation ColonLocFirst, | ||||||||
4857 | SourceLocation ColonLocSecond, | ||||||||
4858 | Expr *Length, Expr *Stride, | ||||||||
4859 | SourceLocation RBLoc) { | ||||||||
4860 | if (Base->getType()->isPlaceholderType() && | ||||||||
4861 | !Base->getType()->isSpecificPlaceholderType( | ||||||||
4862 | BuiltinType::OMPArraySection)) { | ||||||||
4863 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||||||
4864 | if (Result.isInvalid()) | ||||||||
4865 | return ExprError(); | ||||||||
4866 | Base = Result.get(); | ||||||||
4867 | } | ||||||||
4868 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4869 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||||||
4870 | if (Result.isInvalid()) | ||||||||
4871 | return ExprError(); | ||||||||
4872 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4873 | if (Result.isInvalid()) | ||||||||
4874 | return ExprError(); | ||||||||
4875 | LowerBound = Result.get(); | ||||||||
4876 | } | ||||||||
4877 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4878 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||||||
4879 | if (Result.isInvalid()) | ||||||||
4880 | return ExprError(); | ||||||||
4881 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4882 | if (Result.isInvalid()) | ||||||||
4883 | return ExprError(); | ||||||||
4884 | Length = Result.get(); | ||||||||
4885 | } | ||||||||
4886 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4887 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||||||
4888 | if (Result.isInvalid()) | ||||||||
4889 | return ExprError(); | ||||||||
4890 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4891 | if (Result.isInvalid()) | ||||||||
4892 | return ExprError(); | ||||||||
4893 | Stride = Result.get(); | ||||||||
4894 | } | ||||||||
4895 | |||||||||
4896 | // Build an unanalyzed expression if either operand is type-dependent. | ||||||||
4897 | if (Base->isTypeDependent() || | ||||||||
4898 | (LowerBound && | ||||||||
4899 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||||||
4900 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||||||
4901 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||||||
4902 | return new (Context) OMPArraySectionExpr( | ||||||||
4903 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||||||
4904 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||||||
4905 | } | ||||||||
4906 | |||||||||
4907 | // Perform default conversions. | ||||||||
4908 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||||||
4909 | QualType ResultTy; | ||||||||
4910 | if (OriginalTy->isAnyPointerType()) { | ||||||||
4911 | ResultTy = OriginalTy->getPointeeType(); | ||||||||
4912 | } else if (OriginalTy->isArrayType()) { | ||||||||
4913 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||||||
4914 | } else { | ||||||||
4915 | return ExprError( | ||||||||
4916 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||||||
4917 | << Base->getSourceRange()); | ||||||||
4918 | } | ||||||||
4919 | // C99 6.5.2.1p1 | ||||||||
4920 | if (LowerBound) { | ||||||||
4921 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||||||
4922 | LowerBound); | ||||||||
4923 | if (Res.isInvalid()) | ||||||||
4924 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||||||
4925 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4926 | << 0 << LowerBound->getSourceRange()); | ||||||||
4927 | LowerBound = Res.get(); | ||||||||
4928 | |||||||||
4929 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4930 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4931 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4932 | << 0 << LowerBound->getSourceRange(); | ||||||||
4933 | } | ||||||||
4934 | if (Length) { | ||||||||
4935 | auto Res = | ||||||||
4936 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||||||
4937 | if (Res.isInvalid()) | ||||||||
4938 | return ExprError(Diag(Length->getExprLoc(), | ||||||||
4939 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4940 | << 1 << Length->getSourceRange()); | ||||||||
4941 | Length = Res.get(); | ||||||||
4942 | |||||||||
4943 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4944 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4945 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4946 | << 1 << Length->getSourceRange(); | ||||||||
4947 | } | ||||||||
4948 | if (Stride) { | ||||||||
4949 | ExprResult Res = | ||||||||
4950 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||||||
4951 | if (Res.isInvalid()) | ||||||||
4952 | return ExprError(Diag(Stride->getExprLoc(), | ||||||||
4953 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4954 | << 1 << Stride->getSourceRange()); | ||||||||
4955 | Stride = Res.get(); | ||||||||
4956 | |||||||||
4957 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4958 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4959 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4960 | << 1 << Stride->getSourceRange(); | ||||||||
4961 | } | ||||||||
4962 | |||||||||
4963 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||||||
4964 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||||||
4965 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||||||
4966 | // incomplete types are not object types. | ||||||||
4967 | if (ResultTy->isFunctionType()) { | ||||||||
4968 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||||||
4969 | << ResultTy << Base->getSourceRange(); | ||||||||
4970 | return ExprError(); | ||||||||
4971 | } | ||||||||
4972 | |||||||||
4973 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||||||
4974 | diag::err_omp_section_incomplete_type, Base)) | ||||||||
4975 | return ExprError(); | ||||||||
4976 | |||||||||
4977 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||||||
4978 | Expr::EvalResult Result; | ||||||||
4979 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||||||
4980 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
4981 | // The array section must be a subset of the original array. | ||||||||
4982 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||||||
4983 | if (LowerBoundValue.isNegative()) { | ||||||||
4984 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||||||
4985 | << LowerBound->getSourceRange(); | ||||||||
4986 | return ExprError(); | ||||||||
4987 | } | ||||||||
4988 | } | ||||||||
4989 | } | ||||||||
4990 | |||||||||
4991 | if (Length) { | ||||||||
4992 | Expr::EvalResult Result; | ||||||||
4993 | if (Length->EvaluateAsInt(Result, Context)) { | ||||||||
4994 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
4995 | // The length must evaluate to non-negative integers. | ||||||||
4996 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||||||
4997 | if (LengthValue.isNegative()) { | ||||||||
4998 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||||||
4999 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5000 | << Length->getSourceRange(); | ||||||||
5001 | return ExprError(); | ||||||||
5002 | } | ||||||||
5003 | } | ||||||||
5004 | } else if (ColonLocFirst.isValid() && | ||||||||
5005 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||||||
5006 | !OriginalTy->isVariableArrayType()))) { | ||||||||
5007 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
5008 | // When the size of the array dimension is not known, the length must be | ||||||||
5009 | // specified explicitly. | ||||||||
5010 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||||||
5011 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||||||
5012 | return ExprError(); | ||||||||
5013 | } | ||||||||
5014 | |||||||||
5015 | if (Stride) { | ||||||||
5016 | Expr::EvalResult Result; | ||||||||
5017 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||||||
5018 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
5019 | // The stride must evaluate to a positive integer. | ||||||||
5020 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||||||
5021 | if (!StrideValue.isStrictlyPositive()) { | ||||||||
5022 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||||||
5023 | << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5024 | << Stride->getSourceRange(); | ||||||||
5025 | return ExprError(); | ||||||||
5026 | } | ||||||||
5027 | } | ||||||||
5028 | } | ||||||||
5029 | |||||||||
5030 | if (!Base->getType()->isSpecificPlaceholderType( | ||||||||
5031 | BuiltinType::OMPArraySection)) { | ||||||||
5032 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||||||
5033 | if (Result.isInvalid()) | ||||||||
5034 | return ExprError(); | ||||||||
5035 | Base = Result.get(); | ||||||||
5036 | } | ||||||||
5037 | return new (Context) OMPArraySectionExpr( | ||||||||
5038 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||||||
5039 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||||||
5040 | } | ||||||||
5041 | |||||||||
5042 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||||||
5043 | SourceLocation RParenLoc, | ||||||||
5044 | ArrayRef<Expr *> Dims, | ||||||||
5045 | ArrayRef<SourceRange> Brackets) { | ||||||||
5046 | if (Base->getType()->isPlaceholderType()) { | ||||||||
5047 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||||||
5048 | if (Result.isInvalid()) | ||||||||
5049 | return ExprError(); | ||||||||
5050 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
5051 | if (Result.isInvalid()) | ||||||||
5052 | return ExprError(); | ||||||||
5053 | Base = Result.get(); | ||||||||
5054 | } | ||||||||
5055 | QualType BaseTy = Base->getType(); | ||||||||
5056 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||||||
5057 | // required. | ||||||||
5058 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||||||
5059 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||||||
5060 | LParenLoc, RParenLoc, Dims, Brackets); | ||||||||
5061 | if (!BaseTy->isPointerType() || | ||||||||
5062 | (!Base->isTypeDependent() && | ||||||||
5063 | BaseTy->getPointeeType()->isIncompleteType())) | ||||||||
5064 | return ExprError(Diag(Base->getExprLoc(), | ||||||||
5065 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||||||
5066 | << Base->getSourceRange()); | ||||||||
5067 | |||||||||
5068 | SmallVector<Expr *, 4> NewDims; | ||||||||
5069 | bool ErrorFound = false; | ||||||||
5070 | for (Expr *Dim : Dims) { | ||||||||
5071 | if (Dim->getType()->isPlaceholderType()) { | ||||||||
5072 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||||||
5073 | if (Result.isInvalid()) { | ||||||||
5074 | ErrorFound = true; | ||||||||
5075 | continue; | ||||||||
5076 | } | ||||||||
5077 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
5078 | if (Result.isInvalid()) { | ||||||||
5079 | ErrorFound = true; | ||||||||
5080 | continue; | ||||||||
5081 | } | ||||||||
5082 | Dim = Result.get(); | ||||||||
5083 | } | ||||||||
5084 | if (!Dim->isTypeDependent()) { | ||||||||
5085 | ExprResult Result = | ||||||||
5086 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||||||
5087 | if (Result.isInvalid()) { | ||||||||
5088 | ErrorFound = true; | ||||||||
5089 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||||||
5090 | << Dim->getSourceRange(); | ||||||||
5091 | continue; | ||||||||
5092 | } | ||||||||
5093 | Dim = Result.get(); | ||||||||
5094 | Expr::EvalResult EvResult; | ||||||||
5095 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||||||
5096 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||||||
5097 | // Each si is an integral type expression that must evaluate to a | ||||||||
5098 | // positive integer. | ||||||||
5099 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||||||
5100 | if (!Value.isStrictlyPositive()) { | ||||||||
5101 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||||||
5102 | << Value.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5103 | << Dim->getSourceRange(); | ||||||||
5104 | ErrorFound = true; | ||||||||
5105 | continue; | ||||||||
5106 | } | ||||||||
5107 | } | ||||||||
5108 | } | ||||||||
5109 | NewDims.push_back(Dim); | ||||||||
5110 | } | ||||||||
5111 | if (ErrorFound) | ||||||||
5112 | return ExprError(); | ||||||||
5113 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||||||
5114 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||||||
5115 | } | ||||||||
5116 | |||||||||
5117 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||||||
5118 | SourceLocation LLoc, SourceLocation RLoc, | ||||||||
5119 | ArrayRef<OMPIteratorData> Data) { | ||||||||
5120 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||||||
5121 | bool IsCorrect = true; | ||||||||
5122 | for (const OMPIteratorData &D : Data) { | ||||||||
5123 | TypeSourceInfo *TInfo = nullptr; | ||||||||
5124 | SourceLocation StartLoc; | ||||||||
5125 | QualType DeclTy; | ||||||||
5126 | if (!D.Type.getAsOpaquePtr()) { | ||||||||
5127 | // OpenMP 5.0, 2.1.6 Iterators | ||||||||
5128 | // In an iterator-specifier, if the iterator-type is not specified then | ||||||||
5129 | // the type of that iterator is of int type. | ||||||||
5130 | DeclTy = Context.IntTy; | ||||||||
5131 | StartLoc = D.DeclIdentLoc; | ||||||||
5132 | } else { | ||||||||
5133 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||||||
5134 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||||||
5135 | } | ||||||||
5136 | |||||||||
5137 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||||||
5138 | DeclTy->containsUnexpandedParameterPack() || | ||||||||
5139 | DeclTy->isInstantiationDependentType(); | ||||||||
5140 | if (!IsDeclTyDependent) { | ||||||||
5141 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||||||
5142 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||||||
5143 | // The iterator-type must be an integral or pointer type. | ||||||||
5144 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||||||
5145 | << DeclTy; | ||||||||
5146 | IsCorrect = false; | ||||||||
5147 | continue; | ||||||||
5148 | } | ||||||||
5149 | if (DeclTy.isConstant(Context)) { | ||||||||
5150 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||||||
5151 | // The iterator-type must not be const qualified. | ||||||||
5152 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||||||
5153 | << DeclTy; | ||||||||
5154 | IsCorrect = false; | ||||||||
5155 | continue; | ||||||||
5156 | } | ||||||||
5157 | } | ||||||||
5158 | |||||||||
5159 | // Iterator declaration. | ||||||||
5160 | assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast <void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5160, __PRETTY_FUNCTION__)); | ||||||||
5161 | // Always try to create iterator declarator to avoid extra error messages | ||||||||
5162 | // about unknown declarations use. | ||||||||
5163 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||||||
5164 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||||||
5165 | VD->setImplicit(); | ||||||||
5166 | if (S) { | ||||||||
5167 | // Check for conflicting previous declaration. | ||||||||
5168 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||||||
5169 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||||||
5170 | ForVisibleRedeclaration); | ||||||||
5171 | Previous.suppressDiagnostics(); | ||||||||
5172 | LookupName(Previous, S); | ||||||||
5173 | |||||||||
5174 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||||||
5175 | /*AllowInlineNamespace=*/false); | ||||||||
5176 | if (!Previous.empty()) { | ||||||||
5177 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||||||
5178 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||||||
5179 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||||||
5180 | } else { | ||||||||
5181 | PushOnScopeChains(VD, S); | ||||||||
5182 | } | ||||||||
5183 | } else { | ||||||||
5184 | CurContext->addDecl(VD); | ||||||||
5185 | } | ||||||||
5186 | Expr *Begin = D.Range.Begin; | ||||||||
5187 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||||||
5188 | ExprResult BeginRes = | ||||||||
5189 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||||||
5190 | Begin = BeginRes.get(); | ||||||||
5191 | } | ||||||||
5192 | Expr *End = D.Range.End; | ||||||||
5193 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||||||
5194 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||||||
5195 | End = EndRes.get(); | ||||||||
5196 | } | ||||||||
5197 | Expr *Step = D.Range.Step; | ||||||||
5198 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||||||
5199 | if (!Step->getType()->isIntegralType(Context)) { | ||||||||
5200 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||||||
5201 | << Step << Step->getSourceRange(); | ||||||||
5202 | IsCorrect = false; | ||||||||
5203 | continue; | ||||||||
5204 | } | ||||||||
5205 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||||||
5206 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||||||
5207 | // If the step expression of a range-specification equals zero, the | ||||||||
5208 | // behavior is unspecified. | ||||||||
5209 | if (Result && Result->isNullValue()) { | ||||||||
5210 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||||||
5211 | << Step << Step->getSourceRange(); | ||||||||
5212 | IsCorrect = false; | ||||||||
5213 | continue; | ||||||||
5214 | } | ||||||||
5215 | } | ||||||||
5216 | if (!Begin || !End || !IsCorrect) { | ||||||||
5217 | IsCorrect = false; | ||||||||
5218 | continue; | ||||||||
5219 | } | ||||||||
5220 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||||||
5221 | IDElem.IteratorDecl = VD; | ||||||||
5222 | IDElem.AssignmentLoc = D.AssignLoc; | ||||||||
5223 | IDElem.Range.Begin = Begin; | ||||||||
5224 | IDElem.Range.End = End; | ||||||||
5225 | IDElem.Range.Step = Step; | ||||||||
5226 | IDElem.ColonLoc = D.ColonLoc; | ||||||||
5227 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||||||
5228 | } | ||||||||
5229 | if (!IsCorrect) { | ||||||||
5230 | // Invalidate all created iterator declarations if error is found. | ||||||||
5231 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5232 | if (Decl *ID = D.IteratorDecl) | ||||||||
5233 | ID->setInvalidDecl(); | ||||||||
5234 | } | ||||||||
5235 | return ExprError(); | ||||||||
5236 | } | ||||||||
5237 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||||||
5238 | if (!CurContext->isDependentContext()) { | ||||||||
5239 | // Build number of ityeration for each iteration range. | ||||||||
5240 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||||||
5241 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||||||
5242 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5243 | // (Endi - Begini) | ||||||||
5244 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||||||
5245 | D.Range.Begin); | ||||||||
5246 | if(!Res.isUsable()) { | ||||||||
5247 | IsCorrect = false; | ||||||||
5248 | continue; | ||||||||
5249 | } | ||||||||
5250 | ExprResult St, St1; | ||||||||
5251 | if (D.Range.Step) { | ||||||||
5252 | St = D.Range.Step; | ||||||||
5253 | // (Endi - Begini) + Stepi | ||||||||
5254 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||||||
5255 | if (!Res.isUsable()) { | ||||||||
5256 | IsCorrect = false; | ||||||||
5257 | continue; | ||||||||
5258 | } | ||||||||
5259 | // (Endi - Begini) + Stepi - 1 | ||||||||
5260 | Res = | ||||||||
5261 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||||||
5262 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||||||
5263 | if (!Res.isUsable()) { | ||||||||
5264 | IsCorrect = false; | ||||||||
5265 | continue; | ||||||||
5266 | } | ||||||||
5267 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||||||
5268 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||||||
5269 | if (!Res.isUsable()) { | ||||||||
5270 | IsCorrect = false; | ||||||||
5271 | continue; | ||||||||
5272 | } | ||||||||
5273 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||||||
5274 | // (Begini - Endi) | ||||||||
5275 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||||||
5276 | D.Range.Begin, D.Range.End); | ||||||||
5277 | if (!Res1.isUsable()) { | ||||||||
5278 | IsCorrect = false; | ||||||||
5279 | continue; | ||||||||
5280 | } | ||||||||
5281 | // (Begini - Endi) - Stepi | ||||||||
5282 | Res1 = | ||||||||
5283 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||||||
5284 | if (!Res1.isUsable()) { | ||||||||
5285 | IsCorrect = false; | ||||||||
5286 | continue; | ||||||||
5287 | } | ||||||||
5288 | // (Begini - Endi) - Stepi - 1 | ||||||||
5289 | Res1 = | ||||||||
5290 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||||||
5291 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||||||
5292 | if (!Res1.isUsable()) { | ||||||||
5293 | IsCorrect = false; | ||||||||
5294 | continue; | ||||||||
5295 | } | ||||||||
5296 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||||||
5297 | Res1 = | ||||||||
5298 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||||||
5299 | if (!Res1.isUsable()) { | ||||||||
5300 | IsCorrect = false; | ||||||||
5301 | continue; | ||||||||
5302 | } | ||||||||
5303 | // Stepi > 0. | ||||||||
5304 | ExprResult CmpRes = | ||||||||
5305 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||||||
5306 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||||||
5307 | if (!CmpRes.isUsable()) { | ||||||||
5308 | IsCorrect = false; | ||||||||
5309 | continue; | ||||||||
5310 | } | ||||||||
5311 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||||||
5312 | Res.get(), Res1.get()); | ||||||||
5313 | if (!Res.isUsable()) { | ||||||||
5314 | IsCorrect = false; | ||||||||
5315 | continue; | ||||||||
5316 | } | ||||||||
5317 | } | ||||||||
5318 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||||||
5319 | if (!Res.isUsable()) { | ||||||||
5320 | IsCorrect = false; | ||||||||
5321 | continue; | ||||||||
5322 | } | ||||||||
5323 | |||||||||
5324 | // Build counter update. | ||||||||
5325 | // Build counter. | ||||||||
5326 | auto *CounterVD = | ||||||||
5327 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||||||
5328 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||||||
5329 | Res.get()->getType(), nullptr, SC_None); | ||||||||
5330 | CounterVD->setImplicit(); | ||||||||
5331 | ExprResult RefRes = | ||||||||
5332 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||||||
5333 | D.IteratorDecl->getBeginLoc()); | ||||||||
5334 | // Build counter update. | ||||||||
5335 | // I = Begini + counter * Stepi; | ||||||||
5336 | ExprResult UpdateRes; | ||||||||
5337 | if (D.Range.Step) { | ||||||||
5338 | UpdateRes = CreateBuiltinBinOp( | ||||||||
5339 | D.AssignmentLoc, BO_Mul, | ||||||||
5340 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||||||
5341 | } else { | ||||||||
5342 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||||||
5343 | } | ||||||||
5344 | if (!UpdateRes.isUsable()) { | ||||||||
5345 | IsCorrect = false; | ||||||||
5346 | continue; | ||||||||
5347 | } | ||||||||
5348 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||||||
5349 | UpdateRes.get()); | ||||||||
5350 | if (!UpdateRes.isUsable()) { | ||||||||
5351 | IsCorrect = false; | ||||||||
5352 | continue; | ||||||||
5353 | } | ||||||||
5354 | ExprResult VDRes = | ||||||||
5355 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||||||
5356 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||||||
5357 | D.IteratorDecl->getBeginLoc()); | ||||||||
5358 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||||||
5359 | UpdateRes.get()); | ||||||||
5360 | if (!UpdateRes.isUsable()) { | ||||||||
5361 | IsCorrect = false; | ||||||||
5362 | continue; | ||||||||
5363 | } | ||||||||
5364 | UpdateRes = | ||||||||
5365 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||||||
5366 | if (!UpdateRes.isUsable()) { | ||||||||
5367 | IsCorrect = false; | ||||||||
5368 | continue; | ||||||||
5369 | } | ||||||||
5370 | ExprResult CounterUpdateRes = | ||||||||
5371 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||||||
5372 | if (!CounterUpdateRes.isUsable()) { | ||||||||
5373 | IsCorrect = false; | ||||||||
5374 | continue; | ||||||||
5375 | } | ||||||||
5376 | CounterUpdateRes = | ||||||||
5377 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||||||
5378 | if (!CounterUpdateRes.isUsable()) { | ||||||||
5379 | IsCorrect = false; | ||||||||
5380 | continue; | ||||||||
5381 | } | ||||||||
5382 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||||||
5383 | HD.CounterVD = CounterVD; | ||||||||
5384 | HD.Upper = Res.get(); | ||||||||
5385 | HD.Update = UpdateRes.get(); | ||||||||
5386 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||||||
5387 | } | ||||||||
5388 | } else { | ||||||||
5389 | Helpers.assign(ID.size(), {}); | ||||||||
5390 | } | ||||||||
5391 | if (!IsCorrect) { | ||||||||
5392 | // Invalidate all created iterator declarations if error is found. | ||||||||
5393 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5394 | if (Decl *ID = D.IteratorDecl) | ||||||||
5395 | ID->setInvalidDecl(); | ||||||||
5396 | } | ||||||||
5397 | return ExprError(); | ||||||||
5398 | } | ||||||||
5399 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||||||
5400 | LLoc, RLoc, ID, Helpers); | ||||||||
5401 | } | ||||||||
5402 | |||||||||
5403 | ExprResult | ||||||||
5404 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||||||
5405 | Expr *Idx, SourceLocation RLoc) { | ||||||||
5406 | Expr *LHSExp = Base; | ||||||||
5407 | Expr *RHSExp = Idx; | ||||||||
5408 | |||||||||
5409 | ExprValueKind VK = VK_LValue; | ||||||||
5410 | ExprObjectKind OK = OK_Ordinary; | ||||||||
5411 | |||||||||
5412 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||||||
5413 | // a non-lvalue array, and an lvalue otherwise. | ||||||||
5414 | if (getLangOpts().CPlusPlus11) { | ||||||||
5415 | for (auto *Op : {LHSExp, RHSExp}) { | ||||||||
5416 | Op = Op->IgnoreImplicit(); | ||||||||
5417 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||||||
5418 | VK = VK_XValue; | ||||||||
5419 | } | ||||||||
5420 | } | ||||||||
5421 | |||||||||
5422 | // Perform default conversions. | ||||||||
5423 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||||||
5424 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||||||
5425 | if (Result.isInvalid()) | ||||||||
5426 | return ExprError(); | ||||||||
5427 | LHSExp = Result.get(); | ||||||||
5428 | } | ||||||||
5429 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||||||
5430 | if (Result.isInvalid()) | ||||||||
5431 | return ExprError(); | ||||||||
5432 | RHSExp = Result.get(); | ||||||||
5433 | |||||||||
5434 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||||||
5435 | |||||||||
5436 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||||||
5437 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||||||
5438 | // in the subscript position. As a result, we need to derive the array base | ||||||||
5439 | // and index from the expression types. | ||||||||
5440 | Expr *BaseExpr, *IndexExpr; | ||||||||
5441 | QualType ResultType; | ||||||||
5442 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||||||
5443 | BaseExpr = LHSExp; | ||||||||
5444 | IndexExpr = RHSExp; | ||||||||
5445 | ResultType = Context.DependentTy; | ||||||||
5446 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||||||
5447 | BaseExpr = LHSExp; | ||||||||
5448 | IndexExpr = RHSExp; | ||||||||
5449 | ResultType = PTy->getPointeeType(); | ||||||||
5450 | } else if (const ObjCObjectPointerType *PTy = | ||||||||
5451 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||||||
5452 | BaseExpr = LHSExp; | ||||||||
5453 | IndexExpr = RHSExp; | ||||||||
5454 | |||||||||
5455 | // Use custom logic if this should be the pseudo-object subscript | ||||||||
5456 | // expression. | ||||||||
5457 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||||||
5458 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||||||
5459 | nullptr); | ||||||||
5460 | |||||||||
5461 | ResultType = PTy->getPointeeType(); | ||||||||
5462 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||||||
5463 | // Handle the uncommon case of "123[Ptr]". | ||||||||
5464 | BaseExpr = RHSExp; | ||||||||
5465 | IndexExpr = LHSExp; | ||||||||
5466 | ResultType = PTy->getPointeeType(); | ||||||||
5467 | } else if (const ObjCObjectPointerType *PTy = | ||||||||
5468 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||||||
5469 | // Handle the uncommon case of "123[Ptr]". | ||||||||
5470 | BaseExpr = RHSExp; | ||||||||
5471 | IndexExpr = LHSExp; | ||||||||
5472 | ResultType = PTy->getPointeeType(); | ||||||||
5473 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||||||
5474 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||||||
5475 | << ResultType << BaseExpr->getSourceRange(); | ||||||||
5476 | return ExprError(); | ||||||||
5477 | } | ||||||||
5478 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||||||
5479 | BaseExpr = LHSExp; // vectors: V[123] | ||||||||
5480 | IndexExpr = RHSExp; | ||||||||
5481 | // We apply C++ DR1213 to vector subscripting too. | ||||||||
5482 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | ||||||||
5483 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||||||
5484 | if (Materialized.isInvalid()) | ||||||||
5485 | return ExprError(); | ||||||||
5486 | LHSExp = Materialized.get(); | ||||||||
5487 | } | ||||||||
5488 | VK = LHSExp->getValueKind(); | ||||||||
5489 | if (VK != VK_RValue) | ||||||||
5490 | OK = OK_VectorComponent; | ||||||||
5491 | |||||||||
5492 | ResultType = VTy->getElementType(); | ||||||||
5493 | QualType BaseType = BaseExpr->getType(); | ||||||||
5494 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||||||
5495 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||||||
5496 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||||||
5497 | if (Combined != MemberQuals) | ||||||||
5498 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||||||
5499 | } else if (LHSTy->isArrayType()) { | ||||||||
5500 | // If we see an array that wasn't promoted by | ||||||||
5501 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||||||
5502 | // wasn't promoted because of the C90 rule that doesn't | ||||||||
5503 | // allow promoting non-lvalue arrays. Warn, then | ||||||||
5504 | // force the promotion here. | ||||||||
5505 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||||||
5506 | << LHSExp->getSourceRange(); | ||||||||
5507 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||||||
5508 | CK_ArrayToPointerDecay).get(); | ||||||||
5509 | LHSTy = LHSExp->getType(); | ||||||||
5510 | |||||||||
5511 | BaseExpr = LHSExp; | ||||||||
5512 | IndexExpr = RHSExp; | ||||||||
5513 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | ||||||||
5514 | } else if (RHSTy->isArrayType()) { | ||||||||
5515 | // Same as previous, except for 123[f().a] case | ||||||||
5516 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||||||
5517 | << RHSExp->getSourceRange(); | ||||||||
5518 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||||||
5519 | CK_ArrayToPointerDecay).get(); | ||||||||
5520 | RHSTy = RHSExp->getType(); | ||||||||
5521 | |||||||||
5522 | BaseExpr = RHSExp; | ||||||||
5523 | IndexExpr = LHSExp; | ||||||||
5524 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | ||||||||
5525 | } else { | ||||||||
5526 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||||||
5527 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||||||
5528 | } | ||||||||
5529 | // C99 6.5.2.1p1 | ||||||||
5530 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||||||
5531 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||||||
5532 | << IndexExpr->getSourceRange()); | ||||||||
5533 | |||||||||
5534 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
5535 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
5536 | && !IndexExpr->isTypeDependent()) | ||||||||
5537 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||||||
5538 | |||||||||
5539 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||||||
5540 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||||||
5541 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||||||
5542 | // incomplete types are not object types. | ||||||||
5543 | if (ResultType->isFunctionType()) { | ||||||||
5544 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||||||
5545 | << ResultType << BaseExpr->getSourceRange(); | ||||||||
5546 | return ExprError(); | ||||||||
5547 | } | ||||||||
5548 | |||||||||
5549 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||||||
5550 | // GNU extension: subscripting on pointer to void | ||||||||
5551 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||||||
5552 | << BaseExpr->getSourceRange(); | ||||||||
5553 | |||||||||
5554 | // C forbids expressions of unqualified void type from being l-values. | ||||||||
5555 | // See IsCForbiddenLValueType. | ||||||||
5556 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | ||||||||
5557 | } else if (!ResultType->isDependentType() && | ||||||||
5558 | RequireCompleteSizedType( | ||||||||
5559 | LLoc, ResultType, | ||||||||
5560 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||||||
5561 | return ExprError(); | ||||||||
5562 | |||||||||
5563 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5564, __PRETTY_FUNCTION__)) | ||||||||
5564 | !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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5564, __PRETTY_FUNCTION__)); | ||||||||
5565 | |||||||||
5566 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||||||
5567 | FunctionScopes.size() > 1) { | ||||||||
5568 | if (auto *TT = | ||||||||
5569 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||||||
5570 | for (auto I = FunctionScopes.rbegin(), | ||||||||
5571 | E = std::prev(FunctionScopes.rend()); | ||||||||
5572 | I != E; ++I) { | ||||||||
5573 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||||||
5574 | if (CSI == nullptr) | ||||||||
5575 | break; | ||||||||
5576 | DeclContext *DC = nullptr; | ||||||||
5577 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||||||
5578 | DC = LSI->CallOperator; | ||||||||
5579 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||||||
5580 | DC = CRSI->TheCapturedDecl; | ||||||||
5581 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||||||
5582 | DC = BSI->TheDecl; | ||||||||
5583 | if (DC) { | ||||||||
5584 | if (DC->containsDecl(TT->getDecl())) | ||||||||
5585 | break; | ||||||||
5586 | captureVariablyModifiedType( | ||||||||
5587 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||||||
5588 | } | ||||||||
5589 | } | ||||||||
5590 | } | ||||||||
5591 | } | ||||||||
5592 | |||||||||
5593 | return new (Context) | ||||||||
5594 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||||||
5595 | } | ||||||||
5596 | |||||||||
5597 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||||||
5598 | ParmVarDecl *Param) { | ||||||||
5599 | if (Param->hasUnparsedDefaultArg()) { | ||||||||
5600 | // If we've already cleared out the location for the default argument, | ||||||||
5601 | // that means we're parsing it right now. | ||||||||
5602 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||||||
5603 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||||||
5604 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||||||
5605 | Param->setInvalidDecl(); | ||||||||
5606 | return true; | ||||||||
5607 | } | ||||||||
5608 | |||||||||
5609 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||||||
5610 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||||||
5611 | Diag(UnparsedDefaultArgLocs[Param], | ||||||||
5612 | diag::note_default_argument_declared_here); | ||||||||
5613 | return true; | ||||||||
5614 | } | ||||||||
5615 | |||||||||
5616 | if (Param->hasUninstantiatedDefaultArg() && | ||||||||
5617 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||||||
5618 | return true; | ||||||||
5619 | |||||||||
5620 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5620, __PRETTY_FUNCTION__)); | ||||||||
5621 | |||||||||
5622 | // If the default expression creates temporaries, we need to | ||||||||
5623 | // push them to the current stack of expression temporaries so they'll | ||||||||
5624 | // be properly destroyed. | ||||||||
5625 | // FIXME: We should really be rebuilding the default argument with new | ||||||||
5626 | // bound temporaries; see the comment in PR5810. | ||||||||
5627 | // We don't need to do that with block decls, though, because | ||||||||
5628 | // blocks in default argument expression can never capture anything. | ||||||||
5629 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||||||
5630 | // Set the "needs cleanups" bit regardless of whether there are | ||||||||
5631 | // any explicit objects. | ||||||||
5632 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||||||
5633 | |||||||||
5634 | // Append all the objects to the cleanup list. Right now, this | ||||||||
5635 | // should always be a no-op, because blocks in default argument | ||||||||
5636 | // expressions should never be able to capture anything. | ||||||||
5637 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5638, __PRETTY_FUNCTION__)) | ||||||||
5638 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5638, __PRETTY_FUNCTION__)); | ||||||||
5639 | } | ||||||||
5640 | |||||||||
5641 | // We already type-checked the argument, so we know it works. | ||||||||
5642 | // Just mark all of the declarations in this potentially-evaluated expression | ||||||||
5643 | // as being "referenced". | ||||||||
5644 | EnterExpressionEvaluationContext EvalContext( | ||||||||
5645 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||||||
5646 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||||||
5647 | /*SkipLocalVariables=*/true); | ||||||||
5648 | return false; | ||||||||
5649 | } | ||||||||
5650 | |||||||||
5651 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||||||
5652 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||||||
5653 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5653, __PRETTY_FUNCTION__)); | ||||||||
5654 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||||||
5655 | return ExprError(); | ||||||||
5656 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||||||
5657 | } | ||||||||
5658 | |||||||||
5659 | Sema::VariadicCallType | ||||||||
5660 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||||||
5661 | Expr *Fn) { | ||||||||
5662 | if (Proto && Proto->isVariadic()) { | ||||||||
5663 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | ||||||||
5664 | return VariadicConstructor; | ||||||||
5665 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||||||
5666 | return VariadicBlock; | ||||||||
5667 | else if (FDecl) { | ||||||||
5668 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||||||
5669 | if (Method->isInstance()) | ||||||||
5670 | return VariadicMethod; | ||||||||
5671 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||||||
5672 | return VariadicMethod; | ||||||||
5673 | return VariadicFunction; | ||||||||
5674 | } | ||||||||
5675 | return VariadicDoesNotApply; | ||||||||
5676 | } | ||||||||
5677 | |||||||||
5678 | namespace { | ||||||||
5679 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||||||
5680 | public: | ||||||||
5681 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||||||
5682 | unsigned NumArgs, MemberExpr *ME) | ||||||||
5683 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||||||
5684 | FunctionName(FuncName) {} | ||||||||
5685 | |||||||||
5686 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||||
5687 | if (!candidate.getCorrectionSpecifier() || | ||||||||
5688 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||||||
5689 | return false; | ||||||||
5690 | } | ||||||||
5691 | |||||||||
5692 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||||||
5693 | } | ||||||||
5694 | |||||||||
5695 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||||
5696 | return std::make_unique<FunctionCallCCC>(*this); | ||||||||
5697 | } | ||||||||
5698 | |||||||||
5699 | private: | ||||||||
5700 | const IdentifierInfo *const FunctionName; | ||||||||
5701 | }; | ||||||||
5702 | } | ||||||||
5703 | |||||||||
5704 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||||||
5705 | FunctionDecl *FDecl, | ||||||||
5706 | ArrayRef<Expr *> Args) { | ||||||||
5707 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||||||
5708 | DeclarationName FuncName = FDecl->getDeclName(); | ||||||||
5709 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||||||
5710 | |||||||||
5711 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||||||
5712 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||||||
5713 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||||||
5714 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||||||
5715 | Sema::CTK_ErrorRecovery)) { | ||||||||
5716 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||||||
5717 | if (Corrected.isOverloaded()) { | ||||||||
5718 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||||||
5719 | OverloadCandidateSet::iterator Best; | ||||||||
5720 | for (NamedDecl *CD : Corrected) { | ||||||||
5721 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||||||
5722 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||||||
5723 | OCS); | ||||||||
5724 | } | ||||||||
5725 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||||||
5726 | case OR_Success: | ||||||||
5727 | ND = Best->FoundDecl; | ||||||||
5728 | Corrected.setCorrectionDecl(ND); | ||||||||
5729 | break; | ||||||||
5730 | default: | ||||||||
5731 | break; | ||||||||
5732 | } | ||||||||
5733 | } | ||||||||
5734 | ND = ND->getUnderlyingDecl(); | ||||||||
5735 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||||||
5736 | return Corrected; | ||||||||
5737 | } | ||||||||
5738 | } | ||||||||
5739 | return TypoCorrection(); | ||||||||
5740 | } | ||||||||
5741 | |||||||||
5742 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||||||
5743 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||||||
5744 | /// function prototype Proto. Call is the call expression itself, and | ||||||||
5745 | /// Fn is the function expression. For a C++ member function, this | ||||||||
5746 | /// routine does not attempt to convert the object argument. Returns | ||||||||
5747 | /// true if the call is ill-formed. | ||||||||
5748 | bool | ||||||||
5749 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||||||
5750 | FunctionDecl *FDecl, | ||||||||
5751 | const FunctionProtoType *Proto, | ||||||||
5752 | ArrayRef<Expr *> Args, | ||||||||
5753 | SourceLocation RParenLoc, | ||||||||
5754 | bool IsExecConfig) { | ||||||||
5755 | // Bail out early if calling a builtin with custom typechecking. | ||||||||
5756 | if (FDecl) | ||||||||
5757 | if (unsigned ID = FDecl->getBuiltinID()) | ||||||||
5758 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||||||
5759 | return false; | ||||||||
5760 | |||||||||
5761 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||||||
5762 | // assignment, to the types of the corresponding parameter, ... | ||||||||
5763 | unsigned NumParams = Proto->getNumParams(); | ||||||||
5764 | bool Invalid = false; | ||||||||
5765 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||||||
5766 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||||||
5767 | ? 1 /* block */ | ||||||||
5768 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||||||
5769 | : 0 /* function */); | ||||||||
5770 | |||||||||
5771 | // If too few arguments are available (and we don't have default | ||||||||
5772 | // arguments for the remaining parameters), don't make the call. | ||||||||
5773 | if (Args.size() < NumParams) { | ||||||||
5774 | if (Args.size() < MinArgs) { | ||||||||
5775 | TypoCorrection TC; | ||||||||
5776 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||||||
5777 | unsigned diag_id = | ||||||||
5778 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5779 | ? diag::err_typecheck_call_too_few_args_suggest | ||||||||
5780 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||||||
5781 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||||||
5782 | << static_cast<unsigned>(Args.size()) | ||||||||
5783 | << TC.getCorrectionRange()); | ||||||||
5784 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||||||
5785 | Diag(RParenLoc, | ||||||||
5786 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5787 | ? diag::err_typecheck_call_too_few_args_one | ||||||||
5788 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||||||
5789 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||||||
5790 | else | ||||||||
5791 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5792 | ? diag::err_typecheck_call_too_few_args | ||||||||
5793 | : diag::err_typecheck_call_too_few_args_at_least) | ||||||||
5794 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||||||
5795 | << Fn->getSourceRange(); | ||||||||
5796 | |||||||||
5797 | // Emit the location of the prototype. | ||||||||
5798 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||||||
5799 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||||||
5800 | |||||||||
5801 | return true; | ||||||||
5802 | } | ||||||||
5803 | // We reserve space for the default arguments when we create | ||||||||
5804 | // the call expression, before calling ConvertArgumentsForCall. | ||||||||
5805 | 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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5806, __PRETTY_FUNCTION__)) | ||||||||
5806 | "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-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5806, __PRETTY_FUNCTION__)); | ||||||||
5807 | } | ||||||||
5808 | |||||||||
5809 | // If too many are passed and not variadic, error on the extras and drop | ||||||||
5810 | // them. | ||||||||
5811 | if (Args.size() > NumParams) { | ||||||||
5812 | if (!Proto->isVariadic()) { | ||||||||
5813 | TypoCorrection TC; | ||||||||
5814 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||||||
5815 | unsigned diag_id = | ||||||||
5816 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5817 | ? diag::err_typecheck_call_too_many_args_suggest | ||||||||
5818 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||||||
5819 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||||||
5820 | << static_cast<unsigned>(Args.size()) | ||||||||
5821 | << TC.getCorrectionRange()); | ||||||||
5822 | } else if (NumParams == 1 && FDecl && | ||||||||
5823 | FDecl->getParamDecl(0)->getDeclName()) | ||||||||
5824 | Diag(Args[NumParams]->getBeginLoc(), | ||||||||
5825 | MinArgs == NumParams | ||||||||
5826 | ? diag::err_typecheck_call_too_many_args_one | ||||||||
5827 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||||||
5828 | << FnKind << FDecl->getParamDecl(0) | ||||||||
5829 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||||||
5830 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||||||
5831 | Args.back()->getEndLoc()); | ||||||||
5832 | else | ||||||||
5833 | Diag(Args[NumParams]->getBeginLoc(), | ||||||||
5834 | MinArgs == NumParams | ||||||||
5835 | ? diag::err_typecheck_call_too_many_args | ||||||||
5836 | : diag::err_typecheck_call_too_many_args_at_most) | ||||||||
5837 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||||||
5838 | << Fn->getSourceRange() | ||||||||
5839 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||||||
5840 | Args.back()->getEndLoc()); | ||||||||
5841 | |||||||||
5842 | // Emit the location of the prototype. | ||||||||
5843 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||||||
5844 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||||||
5845 | |||||||||
5846 | // This deletes the extra arguments. | ||||||||
5847 | Call->shrinkNumArgs(NumParams); | ||||||||
5848 | return true; | ||||||||
5849 | } | ||||||||
5850 | } | ||||||||
5851 | SmallVector<Expr *, 8> AllArgs; | ||||||||
5852 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||||||
5853 | |||||||||
5854 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||||||
5855 | AllArgs, CallType); | ||||||||
5856 | if (Invalid) | ||||||||
5857 | return true; | ||||||||
5858 | unsigned TotalNumArgs = AllArgs.size(); | ||||||||
5859 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||||||
5860 | Call->setArg(i, AllArgs[i]); | ||||||||
5861 | |||||||||
5862 | return false; | ||||||||
5863 | } | ||||||||
5864 | |||||||||
5865 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||||||
5866 | const FunctionProtoType *Proto, | ||||||||
5867 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||||||
5868 | SmallVectorImpl<Expr *> &AllArgs, | ||||||||
5869 | VariadicCallType CallType, bool AllowExplicit, | ||||||||
5870 | bool IsListInitialization) { | ||||||||
5871 | unsigned NumParams = Proto->getNumParams(); | ||||||||
5872 | bool Invalid = false; | ||||||||
5873 | size_t ArgIx = 0; | ||||||||
5874 | // Continue to check argument types (even if we have too few/many args). | ||||||||
5875 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||||||
5876 | QualType ProtoArgType = Proto->getParamType(i); | ||||||||
5877 | |||||||||
5878 | Expr *Arg; | ||||||||
5879 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||||||
5880 | if (ArgIx < Args.size()) { | ||||||||
5881 | Arg = Args[ArgIx++]; | ||||||||
5882 | |||||||||
5883 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||||||
5884 | diag::err_call_incomplete_argument, Arg)) | ||||||||
5885 | return true; | ||||||||
5886 | |||||||||
5887 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||||||
5888 | bool CFAudited = false; | ||||||||
5889 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||||||
5890 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||||||
5891 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||||||
5892 | Arg = stripARCUnbridgedCast(Arg); | ||||||||
5893 | else if (getLangOpts().ObjCAutoRefCount && | ||||||||
5894 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||||||
5895 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||||||
5896 | CFAudited = true; | ||||||||
5897 | |||||||||
5898 | if (Proto->getExtParameterInfo(i).isNoEscape()) | ||||||||
5899 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||||||
5900 | BE->getBlockDecl()->setDoesNotEscape(); | ||||||||
5901 | |||||||||
5902 | InitializedEntity Entity = | ||||||||
5903 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||||||
5904 | ProtoArgType) | ||||||||
5905 | : InitializedEntity::InitializeParameter( | ||||||||
5906 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||||||
5907 | |||||||||
5908 | // Remember that parameter belongs to a CF audited API. | ||||||||
5909 | if (CFAudited) | ||||||||
5910 | Entity.setParameterCFAudited(); | ||||||||
5911 | |||||||||
5912 | ExprResult ArgE = PerformCopyInitialization( | ||||||||
5913 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||||||
5914 | if (ArgE.isInvalid()) | ||||||||
5915 | return true; | ||||||||
5916 | |||||||||
5917 | Arg = ArgE.getAs<Expr>(); | ||||||||
5918 | } else { | ||||||||
5919 | assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee" ) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaExpr.cpp" , 5919, __PRETTY_FUNCTION__)); | ||||||||
5920 | |||||||||
5921 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||||||
5922 | if (ArgExpr.isInvalid()) | ||||||||
5923 | return true; | ||||||||
5924 | |||||||||
5925 | Arg = ArgExpr.getAs<Expr>(); | ||||||||
5926 | } | ||||||||
5927 | |||||||||
5928 | // Check for array bounds violations for each argument to the call. This | ||||||||
5929 | // check only triggers warnings when the argument isn't a more complex Expr | ||||||||
5930 | // with its own checking, such as a BinaryOperator. | ||||||||
5931 | CheckArrayAccess(Arg); | ||||||||
5932 | |||||||||
5933 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||||||
5934 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||||||
5935 | |||||||||
5936 | AllArgs.push_back(Arg); | ||||||||
5937 | } | ||||||||
5938 | |||||||||
5939 | // If this is a variadic call, handle args passed through "...". | ||||||||
5940 | if (CallType != VariadicDoesNotApply) { | ||||||||
5941 | // Assume that extern "C" functions with variadic arguments that | ||||||||
5942 | // return __unknown_anytype aren't *really* variadic. | ||||||||
5943 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||||||
5944 | FDecl->isExternC()) { | ||||||||
5945 | for (Expr *A : Args.slice(ArgIx)) { | ||||||||
5946 | QualType paramType; // ignored | ||||||||
5947 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, pa |