File: | build/source/clang/lib/Sema/SemaExpr.cpp |
Warning: | line 9955, column 29 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/Designator.h" | ||||
23 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||
24 | #include "clang/AST/Expr.h" | ||||
25 | #include "clang/AST/ExprCXX.h" | ||||
26 | #include "clang/AST/ExprObjC.h" | ||||
27 | #include "clang/AST/ExprOpenMP.h" | ||||
28 | #include "clang/AST/OperationKinds.h" | ||||
29 | #include "clang/AST/ParentMapContext.h" | ||||
30 | #include "clang/AST/RecursiveASTVisitor.h" | ||||
31 | #include "clang/AST/Type.h" | ||||
32 | #include "clang/AST/TypeLoc.h" | ||||
33 | #include "clang/Basic/Builtins.h" | ||||
34 | #include "clang/Basic/DiagnosticSema.h" | ||||
35 | #include "clang/Basic/PartialDiagnostic.h" | ||||
36 | #include "clang/Basic/SourceManager.h" | ||||
37 | #include "clang/Basic/Specifiers.h" | ||||
38 | #include "clang/Basic/TargetInfo.h" | ||||
39 | #include "clang/Lex/LiteralSupport.h" | ||||
40 | #include "clang/Lex/Preprocessor.h" | ||||
41 | #include "clang/Sema/AnalysisBasedWarnings.h" | ||||
42 | #include "clang/Sema/DeclSpec.h" | ||||
43 | #include "clang/Sema/DelayedDiagnostic.h" | ||||
44 | #include "clang/Sema/Initialization.h" | ||||
45 | #include "clang/Sema/Lookup.h" | ||||
46 | #include "clang/Sema/Overload.h" | ||||
47 | #include "clang/Sema/ParsedTemplate.h" | ||||
48 | #include "clang/Sema/Scope.h" | ||||
49 | #include "clang/Sema/ScopeInfo.h" | ||||
50 | #include "clang/Sema/SemaFixItUtils.h" | ||||
51 | #include "clang/Sema/SemaInternal.h" | ||||
52 | #include "clang/Sema/Template.h" | ||||
53 | #include "llvm/ADT/STLExtras.h" | ||||
54 | #include "llvm/ADT/StringExtras.h" | ||||
55 | #include "llvm/Support/Casting.h" | ||||
56 | #include "llvm/Support/ConvertUTF.h" | ||||
57 | #include "llvm/Support/SaveAndRestore.h" | ||||
58 | #include "llvm/Support/TypeSize.h" | ||||
59 | #include <optional> | ||||
60 | |||||
61 | using namespace clang; | ||||
62 | using namespace sema; | ||||
63 | |||||
64 | /// Determine whether the use of this declaration is valid, without | ||||
65 | /// emitting diagnostics. | ||||
66 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||
67 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
68 | if (ParsingInitForAutoVars.count(D)) | ||||
69 | return false; | ||||
70 | |||||
71 | // See if this is a deleted function. | ||||
72 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
73 | if (FD->isDeleted()) | ||||
74 | return false; | ||||
75 | |||||
76 | // If the function has a deduced return type, and we can't deduce it, | ||||
77 | // then we can't use it either. | ||||
78 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
79 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||
80 | return false; | ||||
81 | |||||
82 | // See if this is an aligned allocation/deallocation function that is | ||||
83 | // unavailable. | ||||
84 | if (TreatUnavailableAsInvalid && | ||||
85 | isUnavailableAlignedAllocationFunction(*FD)) | ||||
86 | return false; | ||||
87 | } | ||||
88 | |||||
89 | // See if this function is unavailable. | ||||
90 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||
91 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||
92 | return false; | ||||
93 | |||||
94 | if (isa<UnresolvedUsingIfExistsDecl>(D)) | ||||
95 | return false; | ||||
96 | |||||
97 | return true; | ||||
98 | } | ||||
99 | |||||
100 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||
101 | // Warn if this is used but marked unused. | ||||
102 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||
103 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||
104 | // should diagnose them. | ||||
105 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||
106 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||
107 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||
108 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||
109 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||
110 | } | ||||
111 | } | ||||
112 | } | ||||
113 | |||||
114 | /// Emit a note explaining that this function is deleted. | ||||
115 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||
116 | assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted ()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()" , "clang/lib/Sema/SemaExpr.cpp", 116, __extension__ __PRETTY_FUNCTION__ )); | ||||
117 | |||||
118 | if (Decl->isDefaulted()) { | ||||
119 | // If the method was explicitly defaulted, point at that declaration. | ||||
120 | if (!Decl->isImplicit()) | ||||
121 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||
122 | |||||
123 | // Try to diagnose why this special member function was implicitly | ||||
124 | // deleted. This might fail, if that reason no longer applies. | ||||
125 | DiagnoseDeletedDefaultedFunction(Decl); | ||||
126 | return; | ||||
127 | } | ||||
128 | |||||
129 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||
130 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
131 | return NoteDeletedInheritingConstructor(Ctor); | ||||
132 | |||||
133 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||
134 | << Decl << 1; | ||||
135 | } | ||||
136 | |||||
137 | /// Determine whether a FunctionDecl was ever declared with an | ||||
138 | /// explicit storage class. | ||||
139 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||
140 | for (auto *I : D->redecls()) { | ||||
141 | if (I->getStorageClass() != SC_None) | ||||
142 | return true; | ||||
143 | } | ||||
144 | return false; | ||||
145 | } | ||||
146 | |||||
147 | /// Check whether we're in an extern inline function and referring to a | ||||
148 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||
149 | /// | ||||
150 | /// This is only a warning because we used to silently accept this code, but | ||||
151 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||
152 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||
153 | /// and so while there may still be user mistakes, most of the time we can't | ||||
154 | /// prove that there are errors. | ||||
155 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||
156 | const NamedDecl *D, | ||||
157 | SourceLocation Loc) { | ||||
158 | // This is disabled under C++; there are too many ways for this to fire in | ||||
159 | // contexts where the warning is a false positive, or where it is technically | ||||
160 | // correct but benign. | ||||
161 | if (S.getLangOpts().CPlusPlus) | ||||
162 | return; | ||||
163 | |||||
164 | // Check if this is an inlined function or method. | ||||
165 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||
166 | if (!Current) | ||||
167 | return; | ||||
168 | if (!Current->isInlined()) | ||||
169 | return; | ||||
170 | if (!Current->isExternallyVisible()) | ||||
171 | return; | ||||
172 | |||||
173 | // Check if the decl has internal linkage. | ||||
174 | if (D->getFormalLinkage() != InternalLinkage) | ||||
175 | return; | ||||
176 | |||||
177 | // Downgrade from ExtWarn to Extension if | ||||
178 | // (1) the supposedly external inline function is in the main file, | ||||
179 | // and probably won't be included anywhere else. | ||||
180 | // (2) the thing we're referencing is a pure function. | ||||
181 | // (3) the thing we're referencing is another inline function. | ||||
182 | // This last can give us false negatives, but it's better than warning on | ||||
183 | // wrappers for simple C library functions. | ||||
184 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||
185 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||
186 | if (!DowngradeWarning && UsedFn) | ||||
187 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||
188 | |||||
189 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||
190 | : diag::ext_internal_in_extern_inline) | ||||
191 | << /*IsVar=*/!UsedFn << D; | ||||
192 | |||||
193 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||
194 | |||||
195 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||
196 | << D; | ||||
197 | } | ||||
198 | |||||
199 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||
200 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||
201 | |||||
202 | // Suggest "static" on the function, if possible. | ||||
203 | if (!hasAnyExplicitStorageClass(First)) { | ||||
204 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||
205 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||
206 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||
207 | } | ||||
208 | } | ||||
209 | |||||
210 | /// Determine whether the use of this declaration is valid, and | ||||
211 | /// emit any corresponding diagnostics. | ||||
212 | /// | ||||
213 | /// This routine diagnoses various problems with referencing | ||||
214 | /// declarations that can occur when using a declaration. For example, | ||||
215 | /// it might warn if a deprecated or unavailable declaration is being | ||||
216 | /// used, or produce an error (and return true) if a C++0x deleted | ||||
217 | /// function is being used. | ||||
218 | /// | ||||
219 | /// \returns true if there was an error (this declaration cannot be | ||||
220 | /// referenced), false otherwise. | ||||
221 | /// | ||||
222 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||
223 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||
224 | bool ObjCPropertyAccess, | ||||
225 | bool AvoidPartialAvailabilityChecks, | ||||
226 | ObjCInterfaceDecl *ClassReceiver, | ||||
227 | bool SkipTrailingRequiresClause) { | ||||
228 | SourceLocation Loc = Locs.front(); | ||||
229 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||
230 | // If there were any diagnostics suppressed by template argument deduction, | ||||
231 | // emit them now. | ||||
232 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||
233 | if (Pos != SuppressedDiagnostics.end()) { | ||||
234 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||
235 | Diag(Suppressed.first, Suppressed.second); | ||||
236 | |||||
237 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||
238 | // them again for this specialization. However, we don't obsolete this | ||||
239 | // entry from the table, because we want to avoid ever emitting these | ||||
240 | // diagnostics again. | ||||
241 | Pos->second.clear(); | ||||
242 | } | ||||
243 | |||||
244 | // C++ [basic.start.main]p3: | ||||
245 | // The function 'main' shall not be used within a program. | ||||
246 | if (cast<FunctionDecl>(D)->isMain()) | ||||
247 | Diag(Loc, diag::ext_main_used); | ||||
248 | |||||
249 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||
250 | } | ||||
251 | |||||
252 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
253 | if (ParsingInitForAutoVars.count(D)) { | ||||
254 | if (isa<BindingDecl>(D)) { | ||||
255 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||
256 | << D->getDeclName(); | ||||
257 | } else { | ||||
258 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||
259 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||
260 | } | ||||
261 | return true; | ||||
262 | } | ||||
263 | |||||
264 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
265 | // See if this is a deleted function. | ||||
266 | if (FD->isDeleted()) { | ||||
267 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||
268 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
269 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||
270 | << Ctor->getParent() | ||||
271 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||
272 | else | ||||
273 | Diag(Loc, diag::err_deleted_function_use); | ||||
274 | NoteDeletedFunction(FD); | ||||
275 | return true; | ||||
276 | } | ||||
277 | |||||
278 | // [expr.prim.id]p4 | ||||
279 | // A program that refers explicitly or implicitly to a function with a | ||||
280 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||
281 | // other than to declare it, is ill-formed. [...] | ||||
282 | // | ||||
283 | // See if this is a function with constraints that need to be satisfied. | ||||
284 | // Check this before deducing the return type, as it might instantiate the | ||||
285 | // definition. | ||||
286 | if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) { | ||||
287 | ConstraintSatisfaction Satisfaction; | ||||
288 | if (CheckFunctionConstraints(FD, Satisfaction, Loc, | ||||
289 | /*ForOverloadResolution*/ true)) | ||||
290 | // A diagnostic will have already been generated (non-constant | ||||
291 | // constraint expression, for example) | ||||
292 | return true; | ||||
293 | if (!Satisfaction.IsSatisfied) { | ||||
294 | Diag(Loc, | ||||
295 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||
296 | << D; | ||||
297 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||
298 | return true; | ||||
299 | } | ||||
300 | } | ||||
301 | |||||
302 | // If the function has a deduced return type, and we can't deduce it, | ||||
303 | // then we can't use it either. | ||||
304 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
305 | DeduceReturnType(FD, Loc)) | ||||
306 | return true; | ||||
307 | |||||
308 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||
309 | return true; | ||||
310 | |||||
311 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||
312 | return true; | ||||
313 | } | ||||
314 | |||||
315 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
316 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||
317 | if (MD->getParent()->isLambda() && | ||||
318 | ((isa<CXXConstructorDecl>(MD) && | ||||
319 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||
320 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||
321 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||
322 | << !isa<CXXConstructorDecl>(MD); | ||||
323 | } | ||||
324 | } | ||||
325 | |||||
326 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||
327 | const ObjCPropertyDecl * { | ||||
328 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||
329 | return MD->findPropertyDecl(); | ||||
330 | return nullptr; | ||||
331 | }; | ||||
332 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||
333 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||
334 | return true; | ||||
335 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||
336 | return true; | ||||
337 | } | ||||
338 | |||||
339 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||
340 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||
341 | // Only the variables omp_priv and omp_orig are allowed in the | ||||
342 | // initializer-clause. | ||||
343 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||
344 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||
345 | isa<VarDecl>(D)) { | ||||
346 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||
347 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||
348 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
349 | return true; | ||||
350 | } | ||||
351 | |||||
352 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||
353 | // List-items in map clauses on this construct may only refer to the declared | ||||
354 | // variable var and entities that could be referenced by a procedure defined | ||||
355 | // at the same location. | ||||
356 | // [OpenMP 5.2] Also allow iterator declared variables. | ||||
357 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||
358 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||
359 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||
360 | << getOpenMPDeclareMapperVarName(); | ||||
361 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
362 | return true; | ||||
363 | } | ||||
364 | |||||
365 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { | ||||
366 | Diag(Loc, diag::err_use_of_empty_using_if_exists); | ||||
367 | Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); | ||||
368 | return true; | ||||
369 | } | ||||
370 | |||||
371 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||
372 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||
373 | |||||
374 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||
375 | |||||
376 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||
377 | |||||
378 | if (auto *VD = dyn_cast<ValueDecl>(D)) | ||||
379 | checkTypeSupport(VD->getType(), Loc, VD); | ||||
380 | |||||
381 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||
382 | if (!Context.getTargetInfo().isTLSSupported()) | ||||
383 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
384 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||
385 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||
386 | } | ||||
387 | |||||
388 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||
389 | !isUnevaluatedContext()) { | ||||
390 | // C++ [expr.prim.req.nested] p3 | ||||
391 | // A local parameter shall only appear as an unevaluated operand | ||||
392 | // (Clause 8) within the constraint-expression. | ||||
393 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||
394 | << D; | ||||
395 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
396 | return true; | ||||
397 | } | ||||
398 | |||||
399 | return false; | ||||
400 | } | ||||
401 | |||||
402 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||
403 | /// message-send is to a declaration with the sentinel attribute, and | ||||
404 | /// if so, it checks that the requirements of the sentinel are | ||||
405 | /// satisfied. | ||||
406 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||
407 | ArrayRef<Expr *> Args) { | ||||
408 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||
409 | if (!attr) | ||||
410 | return; | ||||
411 | |||||
412 | // The number of formal parameters of the declaration. | ||||
413 | unsigned numFormalParams; | ||||
414 | |||||
415 | // The kind of declaration. This is also an index into a %select in | ||||
416 | // the diagnostic. | ||||
417 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||
418 | |||||
419 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||
420 | numFormalParams = MD->param_size(); | ||||
421 | calleeType = CT_Method; | ||||
422 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
423 | numFormalParams = FD->param_size(); | ||||
424 | calleeType = CT_Function; | ||||
425 | } else if (isa<VarDecl>(D)) { | ||||
426 | QualType type = cast<ValueDecl>(D)->getType(); | ||||
427 | const FunctionType *fn = nullptr; | ||||
428 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||
429 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||
430 | if (!fn) return; | ||||
431 | calleeType = CT_Function; | ||||
432 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||
433 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||
434 | calleeType = CT_Block; | ||||
435 | } else { | ||||
436 | return; | ||||
437 | } | ||||
438 | |||||
439 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||
440 | numFormalParams = proto->getNumParams(); | ||||
441 | } else { | ||||
442 | numFormalParams = 0; | ||||
443 | } | ||||
444 | } else { | ||||
445 | return; | ||||
446 | } | ||||
447 | |||||
448 | // "nullPos" is the number of formal parameters at the end which | ||||
449 | // effectively count as part of the variadic arguments. This is | ||||
450 | // useful if you would prefer to not have *any* formal parameters, | ||||
451 | // but the language forces you to have at least one. | ||||
452 | unsigned nullPos = attr->getNullPos(); | ||||
453 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(static_cast <bool> ((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel") ? void (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "clang/lib/Sema/SemaExpr.cpp", 453, __extension__ __PRETTY_FUNCTION__ )); | ||||
454 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||
455 | |||||
456 | // The number of arguments which should follow the sentinel. | ||||
457 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||
458 | |||||
459 | // If there aren't enough arguments for all the formal parameters, | ||||
460 | // the sentinel, and the args after the sentinel, complain. | ||||
461 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||
462 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||
463 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
464 | return; | ||||
465 | } | ||||
466 | |||||
467 | // Otherwise, find the sentinel expression. | ||||
468 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||
469 | if (!sentinelExpr) return; | ||||
470 | if (sentinelExpr->isValueDependent()) return; | ||||
471 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||
472 | |||||
473 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||
474 | // or 'NULL' if those are actually defined in the context. Only use | ||||
475 | // 'nil' for ObjC methods, where it's much more likely that the | ||||
476 | // variadic arguments form a list of object pointers. | ||||
477 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||
478 | std::string NullValue; | ||||
479 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||
480 | NullValue = "nil"; | ||||
481 | else if (getLangOpts().CPlusPlus11) | ||||
482 | NullValue = "nullptr"; | ||||
483 | else if (PP.isMacroDefined("NULL")) | ||||
484 | NullValue = "NULL"; | ||||
485 | else | ||||
486 | NullValue = "(void*) 0"; | ||||
487 | |||||
488 | if (MissingNilLoc.isInvalid()) | ||||
489 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||
490 | else | ||||
491 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||
492 | << int(calleeType) | ||||
493 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||
494 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
495 | } | ||||
496 | |||||
497 | SourceRange Sema::getExprRange(Expr *E) const { | ||||
498 | return E ? E->getSourceRange() : SourceRange(); | ||||
499 | } | ||||
500 | |||||
501 | //===----------------------------------------------------------------------===// | ||||
502 | // Standard Promotions and Conversions | ||||
503 | //===----------------------------------------------------------------------===// | ||||
504 | |||||
505 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||
506 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||
507 | // Handle any placeholder expressions which made it here. | ||||
508 | if (E->hasPlaceholderType()) { | ||||
509 | ExprResult result = CheckPlaceholderExpr(E); | ||||
510 | if (result.isInvalid()) return ExprError(); | ||||
511 | E = result.get(); | ||||
512 | } | ||||
513 | |||||
514 | QualType Ty = E->getType(); | ||||
515 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 515, __extension__ __PRETTY_FUNCTION__ )); | ||||
516 | |||||
517 | if (Ty->isFunctionType()) { | ||||
518 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||
519 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||
520 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||
521 | return ExprError(); | ||||
522 | |||||
523 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
524 | CK_FunctionToPointerDecay).get(); | ||||
525 | } else if (Ty->isArrayType()) { | ||||
526 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||
527 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||
528 | // type 'array of type' is converted to an expression that has type 'pointer | ||||
529 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||
530 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||
531 | // (C90) to "an expression" (C99). | ||||
532 | // | ||||
533 | // C++ 4.2p1: | ||||
534 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||
535 | // T" can be converted to an rvalue of type "pointer to T". | ||||
536 | // | ||||
537 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { | ||||
538 | ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||
539 | CK_ArrayToPointerDecay); | ||||
540 | if (Res.isInvalid()) | ||||
541 | return ExprError(); | ||||
542 | E = Res.get(); | ||||
543 | } | ||||
544 | } | ||||
545 | return E; | ||||
546 | } | ||||
547 | |||||
548 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||
549 | // Check to see if we are dereferencing a null pointer. If so, | ||||
550 | // and if not volatile-qualified, this is undefined behavior that the | ||||
551 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||
552 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||
553 | // only handles the pattern "*null", which is a very syntactic check. | ||||
554 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||
555 | if (UO && UO->getOpcode() == UO_Deref && | ||||
556 | UO->getSubExpr()->getType()->isPointerType()) { | ||||
557 | const LangAS AS = | ||||
558 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||
559 | if ((!isTargetAddressSpace(AS) || | ||||
560 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||
561 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||
562 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||
563 | !UO->getType().isVolatileQualified()) { | ||||
564 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
565 | S.PDiag(diag::warn_indirection_through_null) | ||||
566 | << UO->getSubExpr()->getSourceRange()); | ||||
567 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
568 | S.PDiag(diag::note_indirection_through_null)); | ||||
569 | } | ||||
570 | } | ||||
571 | } | ||||
572 | |||||
573 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||
574 | SourceLocation AssignLoc, | ||||
575 | const Expr* RHS) { | ||||
576 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||
577 | if (!IV) | ||||
578 | return; | ||||
579 | |||||
580 | DeclarationName MemberName = IV->getDeclName(); | ||||
581 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||
582 | if (!Member || !Member->isStr("isa")) | ||||
583 | return; | ||||
584 | |||||
585 | const Expr *Base = OIRE->getBase(); | ||||
586 | QualType BaseType = Base->getType(); | ||||
587 | if (OIRE->isArrow()) | ||||
588 | BaseType = BaseType->getPointeeType(); | ||||
589 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||
590 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||
591 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||
592 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||
593 | if (!ClassDeclared->getSuperClass() | ||||
594 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||
595 | if (RHS) { | ||||
596 | NamedDecl *ObjectSetClass = | ||||
597 | S.LookupSingleName(S.TUScope, | ||||
598 | &S.Context.Idents.get("object_setClass"), | ||||
599 | SourceLocation(), S.LookupOrdinaryName); | ||||
600 | if (ObjectSetClass) { | ||||
601 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||
602 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||
603 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
604 | "object_setClass(") | ||||
605 | << FixItHint::CreateReplacement( | ||||
606 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||
607 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
608 | } | ||||
609 | else | ||||
610 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||
611 | } else { | ||||
612 | NamedDecl *ObjectGetClass = | ||||
613 | S.LookupSingleName(S.TUScope, | ||||
614 | &S.Context.Idents.get("object_getClass"), | ||||
615 | SourceLocation(), S.LookupOrdinaryName); | ||||
616 | if (ObjectGetClass) | ||||
617 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||
618 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
619 | "object_getClass(") | ||||
620 | << FixItHint::CreateReplacement( | ||||
621 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||
622 | else | ||||
623 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||
624 | } | ||||
625 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||
626 | } | ||||
627 | } | ||||
628 | } | ||||
629 | |||||
630 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||
631 | // Handle any placeholder expressions which made it here. | ||||
632 | if (E->hasPlaceholderType()) { | ||||
633 | ExprResult result = CheckPlaceholderExpr(E); | ||||
634 | if (result.isInvalid()) return ExprError(); | ||||
635 | E = result.get(); | ||||
636 | } | ||||
637 | |||||
638 | // C++ [conv.lval]p1: | ||||
639 | // A glvalue of a non-function, non-array type T can be | ||||
640 | // converted to a prvalue. | ||||
641 | if (!E->isGLValue()) return E; | ||||
642 | |||||
643 | QualType T = E->getType(); | ||||
644 | assert(!T.isNull() && "r-value conversion on typeless expression?")(static_cast <bool> (!T.isNull() && "r-value conversion on typeless expression?" ) ? void (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "clang/lib/Sema/SemaExpr.cpp", 644, __extension__ __PRETTY_FUNCTION__ )); | ||||
645 | |||||
646 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||
647 | if (T->isFunctionType() || T->isArrayType()) | ||||
648 | return E; | ||||
649 | |||||
650 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||
651 | // expressions of certain types in C++. | ||||
652 | if (getLangOpts().CPlusPlus && | ||||
653 | (E->getType() == Context.OverloadTy || | ||||
654 | T->isDependentType() || | ||||
655 | T->isRecordType())) | ||||
656 | return E; | ||||
657 | |||||
658 | // The C standard is actually really unclear on this point, and | ||||
659 | // DR106 tells us what the result should be but not why. It's | ||||
660 | // generally best to say that void types just doesn't undergo | ||||
661 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||
662 | // 'void' type are never l-values, but qualified void can be. | ||||
663 | if (T->isVoidType()) | ||||
664 | return E; | ||||
665 | |||||
666 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||
667 | if (getLangOpts().OpenCL && | ||||
668 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
669 | T->isHalfType()) { | ||||
670 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||
671 | << 0 << T; | ||||
672 | return ExprError(); | ||||
673 | } | ||||
674 | |||||
675 | CheckForNullPointerDereference(*this, E); | ||||
676 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||
677 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||
678 | &Context.Idents.get("object_getClass"), | ||||
679 | SourceLocation(), LookupOrdinaryName); | ||||
680 | if (ObjectGetClass) | ||||
681 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||
682 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||
683 | << FixItHint::CreateReplacement( | ||||
684 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||
685 | else | ||||
686 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||
687 | } | ||||
688 | else if (const ObjCIvarRefExpr *OIRE = | ||||
689 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||
690 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||
691 | |||||
692 | // C++ [conv.lval]p1: | ||||
693 | // [...] If T is a non-class type, the type of the prvalue is the | ||||
694 | // cv-unqualified version of T. Otherwise, the type of the | ||||
695 | // rvalue is T. | ||||
696 | // | ||||
697 | // C99 6.3.2.1p2: | ||||
698 | // If the lvalue has qualified type, the value has the unqualified | ||||
699 | // version of the type of the lvalue; otherwise, the value has the | ||||
700 | // type of the lvalue. | ||||
701 | if (T.hasQualifiers()) | ||||
702 | T = T.getUnqualifiedType(); | ||||
703 | |||||
704 | // Under the MS ABI, lock down the inheritance model now. | ||||
705 | if (T->isMemberPointerType() && | ||||
706 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
707 | (void)isCompleteType(E->getExprLoc(), T); | ||||
708 | |||||
709 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||
710 | if (Res.isInvalid()) | ||||
711 | return Res; | ||||
712 | E = Res.get(); | ||||
713 | |||||
714 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||
715 | // balance that. | ||||
716 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
717 | Cleanup.setExprNeedsCleanups(true); | ||||
718 | |||||
719 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
720 | Cleanup.setExprNeedsCleanups(true); | ||||
721 | |||||
722 | // C++ [conv.lval]p3: | ||||
723 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||
724 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||
725 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, | ||||
726 | CurFPFeatureOverrides()); | ||||
727 | |||||
728 | // C11 6.3.2.1p2: | ||||
729 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||
730 | // of the type of the lvalue ... | ||||
731 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||
732 | T = Atomic->getValueType().getUnqualifiedType(); | ||||
733 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||
734 | nullptr, VK_PRValue, FPOptionsOverride()); | ||||
735 | } | ||||
736 | |||||
737 | return Res; | ||||
738 | } | ||||
739 | |||||
740 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||
741 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||
742 | if (Res.isInvalid()) | ||||
743 | return ExprError(); | ||||
744 | Res = DefaultLvalueConversion(Res.get()); | ||||
745 | if (Res.isInvalid()) | ||||
746 | return ExprError(); | ||||
747 | return Res; | ||||
748 | } | ||||
749 | |||||
750 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||
751 | /// performed on a function designator of a call expression. | ||||
752 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||
753 | QualType Ty = E->getType(); | ||||
754 | ExprResult Res = E; | ||||
755 | // Only do implicit cast for a function type, but not for a pointer | ||||
756 | // to function type. | ||||
757 | if (Ty->isFunctionType()) { | ||||
758 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
759 | CK_FunctionToPointerDecay); | ||||
760 | if (Res.isInvalid()) | ||||
761 | return ExprError(); | ||||
762 | } | ||||
763 | Res = DefaultLvalueConversion(Res.get()); | ||||
764 | if (Res.isInvalid()) | ||||
765 | return ExprError(); | ||||
766 | return Res.get(); | ||||
767 | } | ||||
768 | |||||
769 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||
770 | /// operators (C99 6.3). The conversions of array and function types are | ||||
771 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||
772 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||
773 | /// In these instances, this routine should *not* be called. | ||||
774 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||
775 | // First, convert to an r-value. | ||||
776 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||
777 | if (Res.isInvalid()) | ||||
778 | return ExprError(); | ||||
779 | E = Res.get(); | ||||
780 | |||||
781 | QualType Ty = E->getType(); | ||||
782 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 782, __extension__ __PRETTY_FUNCTION__ )); | ||||
783 | |||||
784 | LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); | ||||
785 | if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && | ||||
786 | (getLangOpts().getFPEvalMethod() != | ||||
787 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || | ||||
788 | PP.getLastFPEvalPragmaLocation().isValid())) { | ||||
789 | switch (EvalMethod) { | ||||
790 | default: | ||||
791 | llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method" , "clang/lib/Sema/SemaExpr.cpp", 791); | ||||
792 | break; | ||||
793 | case LangOptions::FEM_UnsetOnCommandLine: | ||||
794 | llvm_unreachable("Float evaluation method should be set by now")::llvm::llvm_unreachable_internal("Float evaluation method should be set by now" , "clang/lib/Sema/SemaExpr.cpp", 794); | ||||
795 | break; | ||||
796 | case LangOptions::FEM_Double: | ||||
797 | if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) | ||||
798 | // Widen the expression to double. | ||||
799 | return Ty->isComplexType() | ||||
800 | ? ImpCastExprToType(E, | ||||
801 | Context.getComplexType(Context.DoubleTy), | ||||
802 | CK_FloatingComplexCast) | ||||
803 | : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); | ||||
804 | break; | ||||
805 | case LangOptions::FEM_Extended: | ||||
806 | if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) | ||||
807 | // Widen the expression to long double. | ||||
808 | return Ty->isComplexType() | ||||
809 | ? ImpCastExprToType( | ||||
810 | E, Context.getComplexType(Context.LongDoubleTy), | ||||
811 | CK_FloatingComplexCast) | ||||
812 | : ImpCastExprToType(E, Context.LongDoubleTy, | ||||
813 | CK_FloatingCast); | ||||
814 | break; | ||||
815 | } | ||||
816 | } | ||||
817 | |||||
818 | // Half FP have to be promoted to float unless it is natively supported | ||||
819 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||
820 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||
821 | |||||
822 | // Try to perform integral promotions if the object has a theoretically | ||||
823 | // promotable type. | ||||
824 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||
825 | // C99 6.3.1.1p2: | ||||
826 | // | ||||
827 | // The following may be used in an expression wherever an int or | ||||
828 | // unsigned int may be used: | ||||
829 | // - an object or expression with an integer type whose integer | ||||
830 | // conversion rank is less than or equal to the rank of int | ||||
831 | // and unsigned int. | ||||
832 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||
833 | // | ||||
834 | // If an int can represent all values of the original type, the | ||||
835 | // value is converted to an int; otherwise, it is converted to an | ||||
836 | // unsigned int. These are called the integer promotions. All | ||||
837 | // other types are unchanged by the integer promotions. | ||||
838 | |||||
839 | QualType PTy = Context.isPromotableBitField(E); | ||||
840 | if (!PTy.isNull()) { | ||||
841 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||
842 | return E; | ||||
843 | } | ||||
844 | if (Context.isPromotableIntegerType(Ty)) { | ||||
845 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||
846 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||
847 | return E; | ||||
848 | } | ||||
849 | } | ||||
850 | return E; | ||||
851 | } | ||||
852 | |||||
853 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||
854 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||
855 | /// are promoted to double. All other argument types are converted by | ||||
856 | /// UsualUnaryConversions(). | ||||
857 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||
858 | QualType Ty = E->getType(); | ||||
859 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 859, __extension__ __PRETTY_FUNCTION__ )); | ||||
860 | |||||
861 | ExprResult Res = UsualUnaryConversions(E); | ||||
862 | if (Res.isInvalid()) | ||||
863 | return ExprError(); | ||||
864 | E = Res.get(); | ||||
865 | |||||
866 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||
867 | // promote to double. | ||||
868 | // Note that default argument promotion applies only to float (and | ||||
869 | // half/fp16); it does not apply to _Float16. | ||||
870 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||
871 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||
872 | BTy->getKind() == BuiltinType::Float)) { | ||||
873 | if (getLangOpts().OpenCL && | ||||
874 | !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { | ||||
875 | if (BTy->getKind() == BuiltinType::Half) { | ||||
876 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||
877 | } | ||||
878 | } else { | ||||
879 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||
880 | } | ||||
881 | } | ||||
882 | if (BTy && | ||||
883 | getLangOpts().getExtendIntArgs() == | ||||
884 | LangOptions::ExtendArgsKind::ExtendTo64 && | ||||
885 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && | ||||
886 | Context.getTypeSizeInChars(BTy) < | ||||
887 | Context.getTypeSizeInChars(Context.LongLongTy)) { | ||||
888 | E = (Ty->isUnsignedIntegerType()) | ||||
889 | ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) | ||||
890 | .get() | ||||
891 | : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); | ||||
892 | assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&(static_cast <bool> (8 == Context.getTypeSizeInChars(Context .LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy" ) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\"" , "clang/lib/Sema/SemaExpr.cpp", 893, __extension__ __PRETTY_FUNCTION__ )) | ||||
893 | "Unexpected typesize for LongLongTy")(static_cast <bool> (8 == Context.getTypeSizeInChars(Context .LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy" ) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\"" , "clang/lib/Sema/SemaExpr.cpp", 893, __extension__ __PRETTY_FUNCTION__ )); | ||||
894 | } | ||||
895 | |||||
896 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||
897 | // promotion, even on class types, but note: | ||||
898 | // C++11 [conv.lval]p2: | ||||
899 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||
900 | // operand or a subexpression thereof the value contained in the | ||||
901 | // referenced object is not accessed. Otherwise, if the glvalue | ||||
902 | // has a class type, the conversion copy-initializes a temporary | ||||
903 | // of type T from the glvalue and the result of the conversion | ||||
904 | // is a prvalue for the temporary. | ||||
905 | // FIXME: add some way to gate this entire thing for correctness in | ||||
906 | // potentially potentially evaluated contexts. | ||||
907 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||
908 | ExprResult Temp = PerformCopyInitialization( | ||||
909 | InitializedEntity::InitializeTemporary(E->getType()), | ||||
910 | E->getExprLoc(), E); | ||||
911 | if (Temp.isInvalid()) | ||||
912 | return ExprError(); | ||||
913 | E = Temp.get(); | ||||
914 | } | ||||
915 | |||||
916 | return E; | ||||
917 | } | ||||
918 | |||||
919 | /// Determine the degree of POD-ness for an expression. | ||||
920 | /// Incomplete types are considered POD, since this check can be performed | ||||
921 | /// when we're in an unevaluated context. | ||||
922 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||
923 | if (Ty->isIncompleteType()) { | ||||
924 | // C++11 [expr.call]p7: | ||||
925 | // After these conversions, if the argument does not have arithmetic, | ||||
926 | // enumeration, pointer, pointer to member, or class type, the program | ||||
927 | // is ill-formed. | ||||
928 | // | ||||
929 | // Since we've already performed array-to-pointer and function-to-pointer | ||||
930 | // decay, the only such type in C++ is cv void. This also handles | ||||
931 | // initializer lists as variadic arguments. | ||||
932 | if (Ty->isVoidType()) | ||||
933 | return VAK_Invalid; | ||||
934 | |||||
935 | if (Ty->isObjCObjectType()) | ||||
936 | return VAK_Invalid; | ||||
937 | return VAK_Valid; | ||||
938 | } | ||||
939 | |||||
940 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
941 | return VAK_Invalid; | ||||
942 | |||||
943 | if (Context.getTargetInfo().getTriple().isWasm() && | ||||
944 | Ty->isWebAssemblyReferenceType()) { | ||||
945 | return VAK_Invalid; | ||||
946 | } | ||||
947 | |||||
948 | if (Ty.isCXX98PODType(Context)) | ||||
949 | return VAK_Valid; | ||||
950 | |||||
951 | // C++11 [expr.call]p7: | ||||
952 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||
953 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||
954 | // or a non-trivial destructor, with no corresponding parameter, | ||||
955 | // is conditionally-supported with implementation-defined semantics. | ||||
956 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||
957 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||
958 | if (!Record->hasNonTrivialCopyConstructor() && | ||||
959 | !Record->hasNonTrivialMoveConstructor() && | ||||
960 | !Record->hasNonTrivialDestructor()) | ||||
961 | return VAK_ValidInCXX11; | ||||
962 | |||||
963 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||
964 | return VAK_Valid; | ||||
965 | |||||
966 | if (Ty->isObjCObjectType()) | ||||
967 | return VAK_Invalid; | ||||
968 | |||||
969 | if (getLangOpts().MSVCCompat) | ||||
970 | return VAK_MSVCUndefined; | ||||
971 | |||||
972 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||
973 | // permitted to reject them. We should consider doing so. | ||||
974 | return VAK_Undefined; | ||||
975 | } | ||||
976 | |||||
977 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||
978 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||
979 | const QualType &Ty = E->getType(); | ||||
980 | VarArgKind VAK = isValidVarArgType(Ty); | ||||
981 | |||||
982 | // Complain about passing non-POD types through varargs. | ||||
983 | switch (VAK) { | ||||
984 | case VAK_ValidInCXX11: | ||||
985 | DiagRuntimeBehavior( | ||||
986 | E->getBeginLoc(), nullptr, | ||||
987 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||
988 | [[fallthrough]]; | ||||
989 | case VAK_Valid: | ||||
990 | if (Ty->isRecordType()) { | ||||
991 | // This is unlikely to be what the user intended. If the class has a | ||||
992 | // 'c_str' member function, the user probably meant to call that. | ||||
993 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
994 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||
995 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||
996 | } | ||||
997 | break; | ||||
998 | |||||
999 | case VAK_Undefined: | ||||
1000 | case VAK_MSVCUndefined: | ||||
1001 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
1002 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||
1003 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||
1004 | break; | ||||
1005 | |||||
1006 | case VAK_Invalid: | ||||
1007 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
1008 | Diag(E->getBeginLoc(), | ||||
1009 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||
1010 | << Ty << CT; | ||||
1011 | else if (Ty->isObjCObjectType()) | ||||
1012 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
1013 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||
1014 | << Ty << CT); | ||||
1015 | else | ||||
1016 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||
1017 | << isa<InitListExpr>(E) << Ty << CT; | ||||
1018 | break; | ||||
1019 | } | ||||
1020 | } | ||||
1021 | |||||
1022 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||
1023 | /// will create a trap if the resulting type is not a POD type. | ||||
1024 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||
1025 | FunctionDecl *FDecl) { | ||||
1026 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||
1027 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
1028 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||
1029 | (CT == VariadicMethod || | ||||
1030 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||
1031 | E = stripARCUnbridgedCast(E); | ||||
1032 | |||||
1033 | // Otherwise, do normal placeholder checking. | ||||
1034 | } else { | ||||
1035 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||
1036 | if (ExprRes.isInvalid()) | ||||
1037 | return ExprError(); | ||||
1038 | E = ExprRes.get(); | ||||
1039 | } | ||||
1040 | } | ||||
1041 | |||||
1042 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||
1043 | if (ExprRes.isInvalid()) | ||||
1044 | return ExprError(); | ||||
1045 | |||||
1046 | // Copy blocks to the heap. | ||||
1047 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||
1048 | maybeExtendBlockObject(ExprRes); | ||||
1049 | |||||
1050 | E = ExprRes.get(); | ||||
1051 | |||||
1052 | // Diagnostics regarding non-POD argument types are | ||||
1053 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||
1054 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||
1055 | // Turn this into a trap. | ||||
1056 | CXXScopeSpec SS; | ||||
1057 | SourceLocation TemplateKWLoc; | ||||
1058 | UnqualifiedId Name; | ||||
1059 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||
1060 | E->getBeginLoc()); | ||||
1061 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||
1062 | /*HasTrailingLParen=*/true, | ||||
1063 | /*IsAddressOfOperand=*/false); | ||||
1064 | if (TrapFn.isInvalid()) | ||||
1065 | return ExprError(); | ||||
1066 | |||||
1067 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||
1068 | std::nullopt, E->getEndLoc()); | ||||
1069 | if (Call.isInvalid()) | ||||
1070 | return ExprError(); | ||||
1071 | |||||
1072 | ExprResult Comma = | ||||
1073 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||
1074 | if (Comma.isInvalid()) | ||||
1075 | return ExprError(); | ||||
1076 | return Comma.get(); | ||||
1077 | } | ||||
1078 | |||||
1079 | if (!getLangOpts().CPlusPlus && | ||||
1080 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||
1081 | diag::err_call_incomplete_argument)) | ||||
1082 | return ExprError(); | ||||
1083 | |||||
1084 | return E; | ||||
1085 | } | ||||
1086 | |||||
1087 | /// Converts an integer to complex float type. Helper function of | ||||
1088 | /// UsualArithmeticConversions() | ||||
1089 | /// | ||||
1090 | /// \return false if the integer expression is an integer type and is | ||||
1091 | /// successfully converted to the complex type. | ||||
1092 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||
1093 | ExprResult &ComplexExpr, | ||||
1094 | QualType IntTy, | ||||
1095 | QualType ComplexTy, | ||||
1096 | bool SkipCast) { | ||||
1097 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||
1098 | if (SkipCast) return false; | ||||
1099 | if (IntTy->isIntegerType()) { | ||||
1100 | QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); | ||||
1101 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||
1102 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1103 | CK_FloatingRealToComplex); | ||||
1104 | } else { | ||||
1105 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "clang/lib/Sema/SemaExpr.cpp", 1105, __extension__ __PRETTY_FUNCTION__ )); | ||||
1106 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1107 | CK_IntegralComplexToFloatingComplex); | ||||
1108 | } | ||||
1109 | return false; | ||||
1110 | } | ||||
1111 | |||||
1112 | // This handles complex/complex, complex/float, or float/complex. | ||||
1113 | // When both operands are complex, the shorter operand is converted to the | ||||
1114 | // type of the longer, and that is the type of the result. This corresponds | ||||
1115 | // to what is done when combining two real floating-point operands. | ||||
1116 | // The fun begins when size promotion occur across type domains. | ||||
1117 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||
1118 | // floating-point type, the less precise type is converted, within it's | ||||
1119 | // real or complex domain, to the precision of the other type. For example, | ||||
1120 | // when combining a "long double" with a "double _Complex", the | ||||
1121 | // "double _Complex" is promoted to "long double _Complex". | ||||
1122 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, | ||||
1123 | QualType ShorterType, | ||||
1124 | QualType LongerType, | ||||
1125 | bool PromotePrecision) { | ||||
1126 | bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType()); | ||||
1127 | QualType Result = | ||||
1128 | LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType); | ||||
1129 | |||||
1130 | if (PromotePrecision) { | ||||
1131 | if (isa<ComplexType>(ShorterType.getCanonicalType())) { | ||||
1132 | Shorter = | ||||
1133 | S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast); | ||||
1134 | } else { | ||||
1135 | if (LongerIsComplex) | ||||
1136 | LongerType = LongerType->castAs<ComplexType>()->getElementType(); | ||||
1137 | Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast); | ||||
1138 | } | ||||
1139 | } | ||||
1140 | return Result; | ||||
1141 | } | ||||
1142 | |||||
1143 | /// Handle arithmetic conversion with complex types. Helper function of | ||||
1144 | /// UsualArithmeticConversions() | ||||
1145 | static QualType handleComplexConversion(Sema &S, ExprResult &LHS, | ||||
1146 | ExprResult &RHS, QualType LHSType, | ||||
1147 | QualType RHSType, bool IsCompAssign) { | ||||
1148 | // if we have an integer operand, the result is the complex type. | ||||
1149 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1150 | /*SkipCast=*/false)) | ||||
1151 | return LHSType; | ||||
1152 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1153 | /*SkipCast=*/IsCompAssign)) | ||||
1154 | return RHSType; | ||||
1155 | |||||
1156 | // Compute the rank of the two types, regardless of whether they are complex. | ||||
1157 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1158 | if (Order < 0) | ||||
1159 | // Promote the precision of the LHS if not an assignment. | ||||
1160 | return handleComplexFloatConversion(S, LHS, LHSType, RHSType, | ||||
1161 | /*PromotePrecision=*/!IsCompAssign); | ||||
1162 | // Promote the precision of the RHS unless it is already the same as the LHS. | ||||
1163 | return handleComplexFloatConversion(S, RHS, RHSType, LHSType, | ||||
1164 | /*PromotePrecision=*/Order > 0); | ||||
1165 | } | ||||
1166 | |||||
1167 | /// Handle arithmetic conversion from integer to float. Helper function | ||||
1168 | /// of UsualArithmeticConversions() | ||||
1169 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||
1170 | ExprResult &IntExpr, | ||||
1171 | QualType FloatTy, QualType IntTy, | ||||
1172 | bool ConvertFloat, bool ConvertInt) { | ||||
1173 | if (IntTy->isIntegerType()) { | ||||
1174 | if (ConvertInt) | ||||
1175 | // Convert intExpr to the lhs floating point type. | ||||
1176 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||
1177 | CK_IntegralToFloating); | ||||
1178 | return FloatTy; | ||||
1179 | } | ||||
1180 | |||||
1181 | // Convert both sides to the appropriate complex float. | ||||
1182 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "clang/lib/Sema/SemaExpr.cpp", 1182, __extension__ __PRETTY_FUNCTION__ )); | ||||
1183 | QualType result = S.Context.getComplexType(FloatTy); | ||||
1184 | |||||
1185 | // _Complex int -> _Complex float | ||||
1186 | if (ConvertInt) | ||||
1187 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||
1188 | CK_IntegralComplexToFloatingComplex); | ||||
1189 | |||||
1190 | // float -> _Complex float | ||||
1191 | if (ConvertFloat) | ||||
1192 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||
1193 | CK_FloatingRealToComplex); | ||||
1194 | |||||
1195 | return result; | ||||
1196 | } | ||||
1197 | |||||
1198 | /// Handle arithmethic conversion with floating point types. Helper | ||||
1199 | /// function of UsualArithmeticConversions() | ||||
1200 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||
1201 | ExprResult &RHS, QualType LHSType, | ||||
1202 | QualType RHSType, bool IsCompAssign) { | ||||
1203 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||
1204 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||
1205 | |||||
1206 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||
1207 | // operand has a fixed-point type, the fixed-point operand | ||||
1208 | // is converted to the floating type [...] | ||||
1209 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||
1210 | if (LHSFloat) | ||||
1211 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||
1212 | else if (!IsCompAssign) | ||||
1213 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||
1214 | return LHSFloat ? LHSType : RHSType; | ||||
1215 | } | ||||
1216 | |||||
1217 | // If we have two real floating types, convert the smaller operand | ||||
1218 | // to the bigger result. | ||||
1219 | if (LHSFloat && RHSFloat) { | ||||
1220 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1221 | if (order > 0) { | ||||
1222 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||
1223 | return LHSType; | ||||
1224 | } | ||||
1225 | |||||
1226 | assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison" ) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "clang/lib/Sema/SemaExpr.cpp", 1226, __extension__ __PRETTY_FUNCTION__ )); | ||||
1227 | if (!IsCompAssign) | ||||
1228 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||
1229 | return RHSType; | ||||
1230 | } | ||||
1231 | |||||
1232 | if (LHSFloat) { | ||||
1233 | // Half FP has to be promoted to float unless it is natively supported | ||||
1234 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||
1235 | LHSType = S.Context.FloatTy; | ||||
1236 | |||||
1237 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1238 | /*ConvertFloat=*/!IsCompAssign, | ||||
1239 | /*ConvertInt=*/ true); | ||||
1240 | } | ||||
1241 | assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail ("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1241, __extension__ __PRETTY_FUNCTION__)); | ||||
1242 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1243 | /*ConvertFloat=*/ true, | ||||
1244 | /*ConvertInt=*/!IsCompAssign); | ||||
1245 | } | ||||
1246 | |||||
1247 | /// Diagnose attempts to convert between __float128, __ibm128 and | ||||
1248 | /// long double if there is no support for such conversion. | ||||
1249 | /// Helper function of UsualArithmeticConversions(). | ||||
1250 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||
1251 | QualType RHSType) { | ||||
1252 | // No issue if either is not a floating point type. | ||||
1253 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) | ||||
1254 | return false; | ||||
1255 | |||||
1256 | // No issue if both have the same 128-bit float semantics. | ||||
1257 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||
1258 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||
1259 | |||||
1260 | QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; | ||||
1261 | QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; | ||||
1262 | |||||
1263 | const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); | ||||
1264 | const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); | ||||
1265 | |||||
1266 | if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || | ||||
1267 | &RHSSem != &llvm::APFloat::IEEEquad()) && | ||||
1268 | (&LHSSem != &llvm::APFloat::IEEEquad() || | ||||
1269 | &RHSSem != &llvm::APFloat::PPCDoubleDouble())) | ||||
1270 | return false; | ||||
1271 | |||||
1272 | return true; | ||||
1273 | } | ||||
1274 | |||||
1275 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||
1276 | |||||
1277 | namespace { | ||||
1278 | /// These helper callbacks are placed in an anonymous namespace to | ||||
1279 | /// permit their use as function template parameters. | ||||
1280 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1281 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||
1282 | } | ||||
1283 | |||||
1284 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1285 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||
1286 | CK_IntegralComplexCast); | ||||
1287 | } | ||||
1288 | } | ||||
1289 | |||||
1290 | /// Handle integer arithmetic conversions. Helper function of | ||||
1291 | /// UsualArithmeticConversions() | ||||
1292 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||
1293 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||
1294 | ExprResult &RHS, QualType LHSType, | ||||
1295 | QualType RHSType, bool IsCompAssign) { | ||||
1296 | // The rules for this case are in C99 6.3.1.8 | ||||
1297 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||
1298 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||
1299 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||
1300 | if (LHSSigned == RHSSigned) { | ||||
1301 | // Same signedness; use the higher-ranked type | ||||
1302 | if (order >= 0) { | ||||
1303 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1304 | return LHSType; | ||||
1305 | } else if (!IsCompAssign) | ||||
1306 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1307 | return RHSType; | ||||
1308 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||
1309 | // The unsigned type has greater than or equal rank to the | ||||
1310 | // signed type, so use the unsigned type | ||||
1311 | if (RHSSigned) { | ||||
1312 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1313 | return LHSType; | ||||
1314 | } else if (!IsCompAssign) | ||||
1315 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1316 | return RHSType; | ||||
1317 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||
1318 | // The two types are different widths; if we are here, that | ||||
1319 | // means the signed type is larger than the unsigned type, so | ||||
1320 | // use the signed type. | ||||
1321 | if (LHSSigned) { | ||||
1322 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1323 | return LHSType; | ||||
1324 | } else if (!IsCompAssign) | ||||
1325 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1326 | return RHSType; | ||||
1327 | } else { | ||||
1328 | // The signed type is higher-ranked than the unsigned type, | ||||
1329 | // but isn't actually any bigger (like unsigned int and long | ||||
1330 | // on most 32-bit systems). Use the unsigned type corresponding | ||||
1331 | // to the signed type. | ||||
1332 | QualType result = | ||||
1333 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||
1334 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||
1335 | if (!IsCompAssign) | ||||
1336 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||
1337 | return result; | ||||
1338 | } | ||||
1339 | } | ||||
1340 | |||||
1341 | /// Handle conversions with GCC complex int extension. Helper function | ||||
1342 | /// of UsualArithmeticConversions() | ||||
1343 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||
1344 | ExprResult &RHS, QualType LHSType, | ||||
1345 | QualType RHSType, | ||||
1346 | bool IsCompAssign) { | ||||
1347 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||
1348 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||
1349 | |||||
1350 | if (LHSComplexInt && RHSComplexInt) { | ||||
1351 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1352 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1353 | QualType ScalarType = | ||||
1354 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||
1355 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||
1356 | |||||
1357 | return S.Context.getComplexType(ScalarType); | ||||
1358 | } | ||||
1359 | |||||
1360 | if (LHSComplexInt) { | ||||
1361 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1362 | QualType ScalarType = | ||||
1363 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||
1364 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||
1365 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1366 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||
1367 | CK_IntegralRealToComplex); | ||||
1368 | |||||
1369 | return ComplexType; | ||||
1370 | } | ||||
1371 | |||||
1372 | assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail ("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1372, __extension__ __PRETTY_FUNCTION__)); | ||||
1373 | |||||
1374 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1375 | QualType ScalarType = | ||||
1376 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||
1377 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||
1378 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1379 | |||||
1380 | if (!IsCompAssign) | ||||
1381 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||
1382 | CK_IntegralRealToComplex); | ||||
1383 | return ComplexType; | ||||
1384 | } | ||||
1385 | |||||
1386 | /// Return the rank of a given fixed point or integer type. The value itself | ||||
1387 | /// doesn't matter, but the values must be increasing with proper increasing | ||||
1388 | /// rank as described in N1169 4.1.1. | ||||
1389 | static unsigned GetFixedPointRank(QualType Ty) { | ||||
1390 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||
1391 | assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type." ) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "clang/lib/Sema/SemaExpr.cpp", 1391, __extension__ __PRETTY_FUNCTION__ )); | ||||
1392 | |||||
1393 | switch (BTy->getKind()) { | ||||
1394 | case BuiltinType::ShortFract: | ||||
1395 | case BuiltinType::UShortFract: | ||||
1396 | case BuiltinType::SatShortFract: | ||||
1397 | case BuiltinType::SatUShortFract: | ||||
1398 | return 1; | ||||
1399 | case BuiltinType::Fract: | ||||
1400 | case BuiltinType::UFract: | ||||
1401 | case BuiltinType::SatFract: | ||||
1402 | case BuiltinType::SatUFract: | ||||
1403 | return 2; | ||||
1404 | case BuiltinType::LongFract: | ||||
1405 | case BuiltinType::ULongFract: | ||||
1406 | case BuiltinType::SatLongFract: | ||||
1407 | case BuiltinType::SatULongFract: | ||||
1408 | return 3; | ||||
1409 | case BuiltinType::ShortAccum: | ||||
1410 | case BuiltinType::UShortAccum: | ||||
1411 | case BuiltinType::SatShortAccum: | ||||
1412 | case BuiltinType::SatUShortAccum: | ||||
1413 | return 4; | ||||
1414 | case BuiltinType::Accum: | ||||
1415 | case BuiltinType::UAccum: | ||||
1416 | case BuiltinType::SatAccum: | ||||
1417 | case BuiltinType::SatUAccum: | ||||
1418 | return 5; | ||||
1419 | case BuiltinType::LongAccum: | ||||
1420 | case BuiltinType::ULongAccum: | ||||
1421 | case BuiltinType::SatLongAccum: | ||||
1422 | case BuiltinType::SatULongAccum: | ||||
1423 | return 6; | ||||
1424 | default: | ||||
1425 | if (BTy->isInteger()) | ||||
1426 | return 0; | ||||
1427 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "clang/lib/Sema/SemaExpr.cpp", 1427); | ||||
1428 | } | ||||
1429 | } | ||||
1430 | |||||
1431 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||
1432 | /// point types and integers or other fixed point types do not fall under | ||||
1433 | /// usual arithmetic conversion since these conversions could result in loss | ||||
1434 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||
1435 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||
1436 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||
1437 | QualType RHSTy) { | ||||
1438 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy ->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type" ) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "clang/lib/Sema/SemaExpr.cpp", 1439, __extension__ __PRETTY_FUNCTION__ )) | ||||
1439 | "Expected at least one of the operands to be a fixed point type")(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy ->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type" ) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "clang/lib/Sema/SemaExpr.cpp", 1439, __extension__ __PRETTY_FUNCTION__ )); | ||||
1440 | assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1443, __extension__ __PRETTY_FUNCTION__ )) | ||||
1441 | RHSTy->isFixedPointOrIntegerType()) &&(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1443, __extension__ __PRETTY_FUNCTION__ )) | ||||
1442 | "Special fixed point arithmetic operation conversions are only "(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1443, __extension__ __PRETTY_FUNCTION__ )) | ||||
1443 | "applied to ints or other fixed point types")(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1443, __extension__ __PRETTY_FUNCTION__ )); | ||||
1444 | |||||
1445 | // If one operand has signed fixed-point type and the other operand has | ||||
1446 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||
1447 | // converted to its corresponding signed fixed-point type and the resulting | ||||
1448 | // type is the type of the converted operand. | ||||
1449 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||
1450 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||
1451 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||
1452 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||
1453 | |||||
1454 | // The result type is the type with the highest rank, whereby a fixed-point | ||||
1455 | // conversion rank is always greater than an integer conversion rank; if the | ||||
1456 | // type of either of the operands is a saturating fixedpoint type, the result | ||||
1457 | // type shall be the saturating fixed-point type corresponding to the type | ||||
1458 | // with the highest rank; the resulting value is converted (taking into | ||||
1459 | // account rounding and overflow) to the precision of the resulting type. | ||||
1460 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||
1461 | // types are either signed or both unsigned at this point. | ||||
1462 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||
1463 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||
1464 | |||||
1465 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||
1466 | |||||
1467 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||
1468 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||
1469 | |||||
1470 | return ResultTy; | ||||
1471 | } | ||||
1472 | |||||
1473 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||
1474 | /// expressions that might be of enumeration type. | ||||
1475 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||
1476 | SourceLocation Loc, | ||||
1477 | Sema::ArithConvKind ACK) { | ||||
1478 | // C++2a [expr.arith.conv]p1: | ||||
1479 | // If one operand is of enumeration type and the other operand is of a | ||||
1480 | // different enumeration type or a floating-point type, this behavior is | ||||
1481 | // deprecated ([depr.arith.conv.enum]). | ||||
1482 | // | ||||
1483 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||
1484 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||
1485 | QualType L = LHS->getType(), R = RHS->getType(); | ||||
1486 | bool LEnum = L->isUnscopedEnumerationType(), | ||||
1487 | REnum = R->isUnscopedEnumerationType(); | ||||
1488 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||
1489 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||
1490 | (REnum && L->isFloatingType())) { | ||||
1491 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||
1492 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||
1493 | : diag::warn_arith_conv_enum_float) | ||||
1494 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1495 | << (int)ACK << LEnum << L << R; | ||||
1496 | } else if (!IsCompAssign && LEnum && REnum && | ||||
1497 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||
1498 | unsigned DiagID; | ||||
1499 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||
1500 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||
1501 | // If either enumeration type is unnamed, it's less likely that the | ||||
1502 | // user cares about this, but this situation is still deprecated in | ||||
1503 | // C++2a. Use a different warning group. | ||||
1504 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1505 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||
1506 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||
1507 | } else if (ACK == Sema::ACK_Conditional) { | ||||
1508 | // Conditional expressions are separated out because they have | ||||
1509 | // historically had a different warning flag. | ||||
1510 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1511 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||
1512 | : diag::warn_conditional_mixed_enum_types; | ||||
1513 | } else if (ACK == Sema::ACK_Comparison) { | ||||
1514 | // Comparison expressions are separated out because they have | ||||
1515 | // historically had a different warning flag. | ||||
1516 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1517 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||
1518 | : diag::warn_comparison_mixed_enum_types; | ||||
1519 | } else { | ||||
1520 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1521 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||
1522 | : diag::warn_arith_conv_mixed_enum_types; | ||||
1523 | } | ||||
1524 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1525 | << (int)ACK << L << R; | ||||
1526 | } | ||||
1527 | } | ||||
1528 | |||||
1529 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||
1530 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||
1531 | /// routine returns the first non-arithmetic type found. The client is | ||||
1532 | /// responsible for emitting appropriate error diagnostics. | ||||
1533 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||
1534 | SourceLocation Loc, | ||||
1535 | ArithConvKind ACK) { | ||||
1536 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||
1537 | |||||
1538 | if (ACK != ACK_CompAssign) { | ||||
1539 | LHS = UsualUnaryConversions(LHS.get()); | ||||
1540 | if (LHS.isInvalid()) | ||||
1541 | return QualType(); | ||||
1542 | } | ||||
1543 | |||||
1544 | RHS = UsualUnaryConversions(RHS.get()); | ||||
1545 | if (RHS.isInvalid()) | ||||
1546 | return QualType(); | ||||
1547 | |||||
1548 | // For conversion purposes, we ignore any qualifiers. | ||||
1549 | // For example, "const float" and "float" are equivalent. | ||||
1550 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
1551 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
1552 | |||||
1553 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||
1554 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||
1555 | LHSType = AtomicLHS->getValueType(); | ||||
1556 | |||||
1557 | // If both types are identical, no conversion is needed. | ||||
1558 | if (Context.hasSameType(LHSType, RHSType)) | ||||
1559 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
1560 | |||||
1561 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||
1562 | // The caller can deal with this (e.g. pointer + int). | ||||
1563 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||
1564 | return QualType(); | ||||
1565 | |||||
1566 | // Apply unary and bitfield promotions to the LHS's type. | ||||
1567 | QualType LHSUnpromotedType = LHSType; | ||||
1568 | if (Context.isPromotableIntegerType(LHSType)) | ||||
1569 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||
1570 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||
1571 | if (!LHSBitfieldPromoteTy.isNull()) | ||||
1572 | LHSType = LHSBitfieldPromoteTy; | ||||
1573 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||
1574 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||
1575 | |||||
1576 | // If both types are identical, no conversion is needed. | ||||
1577 | if (Context.hasSameType(LHSType, RHSType)) | ||||
1578 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
1579 | |||||
1580 | // At this point, we have two different arithmetic types. | ||||
1581 | |||||
1582 | // Diagnose attempts to convert between __ibm128, __float128 and long double | ||||
1583 | // where such conversions currently can't be handled. | ||||
1584 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
1585 | return QualType(); | ||||
1586 | |||||
1587 | // Handle complex types first (C99 6.3.1.8p1). | ||||
1588 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||
1589 | return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1590 | ACK == ACK_CompAssign); | ||||
1591 | |||||
1592 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
1593 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
1594 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1595 | ACK == ACK_CompAssign); | ||||
1596 | |||||
1597 | // Handle GCC complex int extension. | ||||
1598 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||
1599 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1600 | ACK == ACK_CompAssign); | ||||
1601 | |||||
1602 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||
1603 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||
1604 | |||||
1605 | // Finally, we have two differing integer types. | ||||
1606 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
1607 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||
1608 | } | ||||
1609 | |||||
1610 | //===----------------------------------------------------------------------===// | ||||
1611 | // Semantic Analysis for various Expression Types | ||||
1612 | //===----------------------------------------------------------------------===// | ||||
1613 | |||||
1614 | |||||
1615 | ExprResult | ||||
1616 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1617 | SourceLocation DefaultLoc, | ||||
1618 | SourceLocation RParenLoc, | ||||
1619 | Expr *ControllingExpr, | ||||
1620 | ArrayRef<ParsedType> ArgTypes, | ||||
1621 | ArrayRef<Expr *> ArgExprs) { | ||||
1622 | unsigned NumAssocs = ArgTypes.size(); | ||||
1623 | assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp" , 1623, __extension__ __PRETTY_FUNCTION__)); | ||||
1624 | |||||
1625 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||
1626 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1627 | if (ArgTypes[i]) | ||||
1628 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||
1629 | else | ||||
1630 | Types[i] = nullptr; | ||||
1631 | } | ||||
1632 | |||||
1633 | ExprResult ER = | ||||
1634 | CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr, | ||||
1635 | llvm::ArrayRef(Types, NumAssocs), ArgExprs); | ||||
1636 | delete [] Types; | ||||
1637 | return ER; | ||||
1638 | } | ||||
1639 | |||||
1640 | ExprResult | ||||
1641 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1642 | SourceLocation DefaultLoc, | ||||
1643 | SourceLocation RParenLoc, | ||||
1644 | Expr *ControllingExpr, | ||||
1645 | ArrayRef<TypeSourceInfo *> Types, | ||||
1646 | ArrayRef<Expr *> Exprs) { | ||||
1647 | unsigned NumAssocs = Types.size(); | ||||
1648 | assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void ( 0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp" , 1648, __extension__ __PRETTY_FUNCTION__)); | ||||
1649 | |||||
1650 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||
1651 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||
1652 | { | ||||
1653 | EnterExpressionEvaluationContext Unevaluated( | ||||
1654 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||
1655 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||
1656 | if (R.isInvalid()) | ||||
1657 | return ExprError(); | ||||
1658 | ControllingExpr = R.get(); | ||||
1659 | } | ||||
1660 | |||||
1661 | bool TypeErrorFound = false, | ||||
1662 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||
1663 | ContainsUnexpandedParameterPack | ||||
1664 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||
1665 | |||||
1666 | // The controlling expression is an unevaluated operand, so side effects are | ||||
1667 | // likely unintended. | ||||
1668 | if (!inTemplateInstantiation() && !IsResultDependent && | ||||
1669 | ControllingExpr->HasSideEffects(Context, false)) | ||||
1670 | Diag(ControllingExpr->getExprLoc(), | ||||
1671 | diag::warn_side_effects_unevaluated_context); | ||||
1672 | |||||
1673 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1674 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||
1675 | ContainsUnexpandedParameterPack = true; | ||||
1676 | |||||
1677 | if (Types[i]) { | ||||
1678 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||
1679 | ContainsUnexpandedParameterPack = true; | ||||
1680 | |||||
1681 | if (Types[i]->getType()->isDependentType()) { | ||||
1682 | IsResultDependent = true; | ||||
1683 | } else { | ||||
1684 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||
1685 | // complete object type other than a variably modified type." | ||||
1686 | unsigned D = 0; | ||||
1687 | if (Types[i]->getType()->isIncompleteType()) | ||||
1688 | D = diag::err_assoc_type_incomplete; | ||||
1689 | else if (!Types[i]->getType()->isObjectType()) | ||||
1690 | D = diag::err_assoc_type_nonobject; | ||||
1691 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||
1692 | D = diag::err_assoc_type_variably_modified; | ||||
1693 | else { | ||||
1694 | // Because the controlling expression undergoes lvalue conversion, | ||||
1695 | // array conversion, and function conversion, an association which is | ||||
1696 | // of array type, function type, or is qualified can never be | ||||
1697 | // reached. We will warn about this so users are less surprised by | ||||
1698 | // the unreachable association. However, we don't have to handle | ||||
1699 | // function types; that's not an object type, so it's handled above. | ||||
1700 | // | ||||
1701 | // The logic is somewhat different for C++ because C++ has different | ||||
1702 | // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, | ||||
1703 | // If T is a non-class type, the type of the prvalue is the cv- | ||||
1704 | // unqualified version of T. Otherwise, the type of the prvalue is T. | ||||
1705 | // The result of these rules is that all qualified types in an | ||||
1706 | // association in C are unreachable, and in C++, only qualified non- | ||||
1707 | // class types are unreachable. | ||||
1708 | unsigned Reason = 0; | ||||
1709 | QualType QT = Types[i]->getType(); | ||||
1710 | if (QT->isArrayType()) | ||||
1711 | Reason = 1; | ||||
1712 | else if (QT.hasQualifiers() && | ||||
1713 | (!LangOpts.CPlusPlus || !QT->isRecordType())) | ||||
1714 | Reason = 2; | ||||
1715 | |||||
1716 | if (Reason) | ||||
1717 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1718 | diag::warn_unreachable_association) | ||||
1719 | << QT << (Reason - 1); | ||||
1720 | } | ||||
1721 | |||||
1722 | if (D != 0) { | ||||
1723 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||
1724 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1725 | << Types[i]->getType(); | ||||
1726 | TypeErrorFound = true; | ||||
1727 | } | ||||
1728 | |||||
1729 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||
1730 | // selection shall specify compatible types." | ||||
1731 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||
1732 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||
1733 | Context.typesAreCompatible(Types[i]->getType(), | ||||
1734 | Types[j]->getType())) { | ||||
1735 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||
1736 | diag::err_assoc_compatible_types) | ||||
1737 | << Types[j]->getTypeLoc().getSourceRange() | ||||
1738 | << Types[j]->getType() | ||||
1739 | << Types[i]->getType(); | ||||
1740 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1741 | diag::note_compat_assoc) | ||||
1742 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1743 | << Types[i]->getType(); | ||||
1744 | TypeErrorFound = true; | ||||
1745 | } | ||||
1746 | } | ||||
1747 | } | ||||
1748 | } | ||||
1749 | if (TypeErrorFound) | ||||
1750 | return ExprError(); | ||||
1751 | |||||
1752 | // If we determined that the generic selection is result-dependent, don't | ||||
1753 | // try to compute the result expression. | ||||
1754 | if (IsResultDependent) | ||||
1755 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||
1756 | Exprs, DefaultLoc, RParenLoc, | ||||
1757 | ContainsUnexpandedParameterPack); | ||||
1758 | |||||
1759 | SmallVector<unsigned, 1> CompatIndices; | ||||
1760 | unsigned DefaultIndex = -1U; | ||||
1761 | // Look at the canonical type of the controlling expression in case it was a | ||||
1762 | // deduced type like __auto_type. However, when issuing diagnostics, use the | ||||
1763 | // type the user wrote in source rather than the canonical one. | ||||
1764 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1765 | if (!Types[i]) | ||||
1766 | DefaultIndex = i; | ||||
1767 | else if (Context.typesAreCompatible( | ||||
1768 | ControllingExpr->getType().getCanonicalType(), | ||||
1769 | Types[i]->getType())) | ||||
1770 | CompatIndices.push_back(i); | ||||
1771 | } | ||||
1772 | |||||
1773 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||
1774 | // type compatible with at most one of the types named in its generic | ||||
1775 | // association list." | ||||
1776 | if (CompatIndices.size() > 1) { | ||||
1777 | // We strip parens here because the controlling expression is typically | ||||
1778 | // parenthesized in macro definitions. | ||||
1779 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1780 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||
1781 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||
1782 | << (unsigned)CompatIndices.size(); | ||||
1783 | for (unsigned I : CompatIndices) { | ||||
1784 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||
1785 | diag::note_compat_assoc) | ||||
1786 | << Types[I]->getTypeLoc().getSourceRange() | ||||
1787 | << Types[I]->getType(); | ||||
1788 | } | ||||
1789 | return ExprError(); | ||||
1790 | } | ||||
1791 | |||||
1792 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||
1793 | // its controlling expression shall have type compatible with exactly one of | ||||
1794 | // the types named in its generic association list." | ||||
1795 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||
1796 | // We strip parens here because the controlling expression is typically | ||||
1797 | // parenthesized in macro definitions. | ||||
1798 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1799 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||
1800 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||
1801 | return ExprError(); | ||||
1802 | } | ||||
1803 | |||||
1804 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||
1805 | // type name that is compatible with the type of the controlling expression, | ||||
1806 | // then the result expression of the generic selection is the expression | ||||
1807 | // in that generic association. Otherwise, the result expression of the | ||||
1808 | // generic selection is the expression in the default generic association." | ||||
1809 | unsigned ResultIndex = | ||||
1810 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||
1811 | |||||
1812 | return GenericSelectionExpr::Create( | ||||
1813 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||
1814 | ContainsUnexpandedParameterPack, ResultIndex); | ||||
1815 | } | ||||
1816 | |||||
1817 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||
1818 | /// location of the token and the offset of the ud-suffix within it. | ||||
1819 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||
1820 | unsigned Offset) { | ||||
1821 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||
1822 | S.getLangOpts()); | ||||
1823 | } | ||||
1824 | |||||
1825 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||
1826 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||
1827 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||
1828 | IdentifierInfo *UDSuffix, | ||||
1829 | SourceLocation UDSuffixLoc, | ||||
1830 | ArrayRef<Expr*> Args, | ||||
1831 | SourceLocation LitEndLoc) { | ||||
1832 | assert(Args.size() <= 2 && "too many arguments for literal operator")(static_cast <bool> (Args.size() <= 2 && "too many arguments for literal operator" ) ? void (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "clang/lib/Sema/SemaExpr.cpp", 1832, __extension__ __PRETTY_FUNCTION__ )); | ||||
1833 | |||||
1834 | QualType ArgTy[2]; | ||||
1835 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||
1836 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||
1837 | if (ArgTy[ArgIdx]->isArrayType()) | ||||
1838 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||
1839 | } | ||||
1840 | |||||
1841 | DeclarationName OpName = | ||||
1842 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1843 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1844 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1845 | |||||
1846 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||
1847 | if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()), | ||||
1848 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||
1849 | /*AllowStringTemplatePack*/ false, | ||||
1850 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||
1851 | return ExprError(); | ||||
1852 | |||||
1853 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||
1854 | } | ||||
1855 | |||||
1856 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||
1857 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||
1858 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||
1859 | /// multiple tokens. However, the common case is that StringToks points to one | ||||
1860 | /// string. | ||||
1861 | /// | ||||
1862 | ExprResult | ||||
1863 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||
1864 | assert(!StringToks.empty() && "Must have at least one string!")(static_cast <bool> (!StringToks.empty() && "Must have at least one string!" ) ? void (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "clang/lib/Sema/SemaExpr.cpp", 1864, __extension__ __PRETTY_FUNCTION__ )); | ||||
1865 | |||||
1866 | StringLiteralParser Literal(StringToks, PP); | ||||
1867 | if (Literal.hadError) | ||||
1868 | return ExprError(); | ||||
1869 | |||||
1870 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||
1871 | for (const Token &Tok : StringToks) | ||||
1872 | StringTokLocs.push_back(Tok.getLocation()); | ||||
1873 | |||||
1874 | QualType CharTy = Context.CharTy; | ||||
1875 | StringLiteral::StringKind Kind = StringLiteral::Ordinary; | ||||
1876 | if (Literal.isWide()) { | ||||
1877 | CharTy = Context.getWideCharType(); | ||||
1878 | Kind = StringLiteral::Wide; | ||||
1879 | } else if (Literal.isUTF8()) { | ||||
1880 | if (getLangOpts().Char8) | ||||
1881 | CharTy = Context.Char8Ty; | ||||
1882 | Kind = StringLiteral::UTF8; | ||||
1883 | } else if (Literal.isUTF16()) { | ||||
1884 | CharTy = Context.Char16Ty; | ||||
1885 | Kind = StringLiteral::UTF16; | ||||
1886 | } else if (Literal.isUTF32()) { | ||||
1887 | CharTy = Context.Char32Ty; | ||||
1888 | Kind = StringLiteral::UTF32; | ||||
1889 | } else if (Literal.isPascal()) { | ||||
1890 | CharTy = Context.UnsignedCharTy; | ||||
1891 | } | ||||
1892 | |||||
1893 | // Warn on initializing an array of char from a u8 string literal; this | ||||
1894 | // becomes ill-formed in C++2a. | ||||
1895 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||
1896 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||
1897 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||
1898 | |||||
1899 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||
1900 | // ensures C++2a compatibility (but may change the program behavior when | ||||
1901 | // built by non-Clang compilers for which the execution character set is | ||||
1902 | // not always UTF-8). | ||||
1903 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||
1904 | SourceLocation RemovalDiagLoc; | ||||
1905 | for (const Token &Tok : StringToks) { | ||||
1906 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||
1907 | if (RemovalDiagLoc.isInvalid()) | ||||
1908 | RemovalDiagLoc = Tok.getLocation(); | ||||
1909 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||
1910 | Tok.getLocation(), | ||||
1911 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||
1912 | getSourceManager(), getLangOpts()))); | ||||
1913 | } | ||||
1914 | } | ||||
1915 | Diag(RemovalDiagLoc, RemovalDiag); | ||||
1916 | } | ||||
1917 | |||||
1918 | QualType StrTy = | ||||
1919 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||
1920 | |||||
1921 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||
1922 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||
1923 | Kind, Literal.Pascal, StrTy, | ||||
1924 | &StringTokLocs[0], | ||||
1925 | StringTokLocs.size()); | ||||
1926 | if (Literal.getUDSuffix().empty()) | ||||
1927 | return Lit; | ||||
1928 | |||||
1929 | // We're building a user-defined literal. | ||||
1930 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
1931 | SourceLocation UDSuffixLoc = | ||||
1932 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||
1933 | Literal.getUDSuffixOffset()); | ||||
1934 | |||||
1935 | // Make sure we're allowed user-defined literals here. | ||||
1936 | if (!UDLScope) | ||||
1937 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||
1938 | |||||
1939 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||
1940 | // operator "" X (str, len) | ||||
1941 | QualType SizeType = Context.getSizeType(); | ||||
1942 | |||||
1943 | DeclarationName OpName = | ||||
1944 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1945 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1946 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1947 | |||||
1948 | QualType ArgTy[] = { | ||||
1949 | Context.getArrayDecayedType(StrTy), SizeType | ||||
1950 | }; | ||||
1951 | |||||
1952 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
1953 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||
1954 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||
1955 | /*AllowStringTemplatePack*/ true, | ||||
1956 | /*DiagnoseMissing*/ true, Lit)) { | ||||
1957 | |||||
1958 | case LOLR_Cooked: { | ||||
1959 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||
1960 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||
1961 | StringTokLocs[0]); | ||||
1962 | Expr *Args[] = { Lit, LenArg }; | ||||
1963 | |||||
1964 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||
1965 | } | ||||
1966 | |||||
1967 | case LOLR_Template: { | ||||
1968 | TemplateArgumentListInfo ExplicitArgs; | ||||
1969 | TemplateArgument Arg(Lit); | ||||
1970 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||
1971 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1972 | return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, | ||||
1973 | StringTokLocs.back(), &ExplicitArgs); | ||||
1974 | } | ||||
1975 | |||||
1976 | case LOLR_StringTemplatePack: { | ||||
1977 | TemplateArgumentListInfo ExplicitArgs; | ||||
1978 | |||||
1979 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||
1980 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||
1981 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
1982 | |||||
1983 | TemplateArgument TypeArg(CharTy); | ||||
1984 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||
1985 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||
1986 | |||||
1987 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||
1988 | Value = Lit->getCodeUnit(I); | ||||
1989 | TemplateArgument Arg(Context, Value, CharTy); | ||||
1990 | TemplateArgumentLocInfo ArgInfo; | ||||
1991 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1992 | } | ||||
1993 | return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, | ||||
1994 | StringTokLocs.back(), &ExplicitArgs); | ||||
1995 | } | ||||
1996 | case LOLR_Raw: | ||||
1997 | case LOLR_ErrorNoDiagnostic: | ||||
1998 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 1998); | ||||
1999 | case LOLR_Error: | ||||
2000 | return ExprError(); | ||||
2001 | } | ||||
2002 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 2002); | ||||
2003 | } | ||||
2004 | |||||
2005 | DeclRefExpr * | ||||
2006 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2007 | SourceLocation Loc, | ||||
2008 | const CXXScopeSpec *SS) { | ||||
2009 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||
2010 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||
2011 | } | ||||
2012 | |||||
2013 | DeclRefExpr * | ||||
2014 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2015 | const DeclarationNameInfo &NameInfo, | ||||
2016 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||
2017 | SourceLocation TemplateKWLoc, | ||||
2018 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2019 | NestedNameSpecifierLoc NNS = | ||||
2020 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||
2021 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||
2022 | TemplateArgs); | ||||
2023 | } | ||||
2024 | |||||
2025 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||
2026 | // host variable in a device or host device lambda. | ||||
2027 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||
2028 | VarDecl *VD) { | ||||
2029 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||
2030 | return false; | ||||
2031 | assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType ()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()" , "clang/lib/Sema/SemaExpr.cpp", 2031, __extension__ __PRETTY_FUNCTION__ )); | ||||
2032 | |||||
2033 | // Check whether the reference variable is referencing a host variable. | ||||
2034 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||
2035 | if (!DRE) | ||||
2036 | return false; | ||||
2037 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
2038 | if (!Referee || !Referee->hasGlobalStorage() || | ||||
2039 | Referee->hasAttr<CUDADeviceAttr>()) | ||||
2040 | return false; | ||||
2041 | |||||
2042 | // Check whether the current function is a device or host device lambda. | ||||
2043 | // Check whether the reference variable is a capture by getDeclContext() | ||||
2044 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||
2045 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||
2046 | if (MD && MD->getParent()->isLambda() && | ||||
2047 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||
2048 | VD->getDeclContext() != MD) | ||||
2049 | return true; | ||||
2050 | |||||
2051 | return false; | ||||
2052 | } | ||||
2053 | |||||
2054 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||
2055 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||
2056 | if (isUnevaluatedContext()) | ||||
2057 | return NOUR_Unevaluated; | ||||
2058 | |||||
2059 | // C++2a [basic.def.odr]p4: | ||||
2060 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
2061 | // is odr-used by e unless [...] x is a reference that is usable in | ||||
2062 | // constant expressions. | ||||
2063 | // CUDA/HIP: | ||||
2064 | // If a reference variable referencing a host variable is captured in a | ||||
2065 | // device or host device lambda, the value of the referee must be copied | ||||
2066 | // to the capture and the reference variable must be treated as odr-use | ||||
2067 | // since the value of the referee is not known at compile time and must | ||||
2068 | // be loaded from the captured. | ||||
2069 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2070 | if (VD->getType()->isReferenceType() && | ||||
2071 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||
2072 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||
2073 | VD->isUsableInConstantExpressions(Context)) | ||||
2074 | return NOUR_Constant; | ||||
2075 | } | ||||
2076 | |||||
2077 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||
2078 | // need to wait and see how the expression is used. | ||||
2079 | return NOUR_None; | ||||
2080 | } | ||||
2081 | |||||
2082 | /// BuildDeclRefExpr - Build an expression that references a | ||||
2083 | /// declaration that does not require a closure capture. | ||||
2084 | DeclRefExpr * | ||||
2085 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2086 | const DeclarationNameInfo &NameInfo, | ||||
2087 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||
2088 | SourceLocation TemplateKWLoc, | ||||
2089 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2090 | bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) && | ||||
2091 | NeedToCaptureVariable(D, NameInfo.getLoc()); | ||||
2092 | |||||
2093 | DeclRefExpr *E = DeclRefExpr::Create( | ||||
2094 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||
2095 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||
2096 | MarkDeclRefReferenced(E); | ||||
2097 | |||||
2098 | // C++ [except.spec]p17: | ||||
2099 | // An exception-specification is considered to be needed when: | ||||
2100 | // - in an expression, the function is the unique lookup result or | ||||
2101 | // the selected member of a set of overloaded functions. | ||||
2102 | // | ||||
2103 | // We delay doing this until after we've built the function reference and | ||||
2104 | // marked it as used so that: | ||||
2105 | // a) if the function is defaulted, we get errors from defining it before / | ||||
2106 | // instead of errors from computing its exception specification, and | ||||
2107 | // b) if the function is a defaulted comparison, we can use the body we | ||||
2108 | // build when defining it as input to the exception specification | ||||
2109 | // computation rather than computing a new body. | ||||
2110 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||
2111 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||
2112 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||
2113 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||
2114 | } | ||||
2115 | } | ||||
2116 | |||||
2117 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||
2118 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||
2119 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||
2120 | getCurFunction()->recordUseOfWeak(E); | ||||
2121 | |||||
2122 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||
2123 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||
2124 | FD = IFD->getAnonField(); | ||||
2125 | if (FD) { | ||||
2126 | UnusedPrivateFields.remove(FD); | ||||
2127 | // Just in case we're building an illegal pointer-to-member. | ||||
2128 | if (FD->isBitField()) | ||||
2129 | E->setObjectKind(OK_BitField); | ||||
2130 | } | ||||
2131 | |||||
2132 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||
2133 | // designates a bit-field. | ||||
2134 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||
2135 | if (auto *BE = BD->getBinding()) | ||||
2136 | E->setObjectKind(BE->getObjectKind()); | ||||
2137 | |||||
2138 | return E; | ||||
2139 | } | ||||
2140 | |||||
2141 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||
2142 | /// possibly a list of template arguments. | ||||
2143 | /// | ||||
2144 | /// If this produces template arguments, it is permitted to call | ||||
2145 | /// DecomposeTemplateName. | ||||
2146 | /// | ||||
2147 | /// This actually loses a lot of source location information for | ||||
2148 | /// non-standard name kinds; we should consider preserving that in | ||||
2149 | /// some way. | ||||
2150 | void | ||||
2151 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||
2152 | TemplateArgumentListInfo &Buffer, | ||||
2153 | DeclarationNameInfo &NameInfo, | ||||
2154 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||
2155 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
2156 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||
2157 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||
2158 | |||||
2159 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||
2160 | Id.TemplateId->NumArgs); | ||||
2161 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||
2162 | |||||
2163 | TemplateName TName = Id.TemplateId->Template.get(); | ||||
2164 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||
2165 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||
2166 | TemplateArgs = &Buffer; | ||||
2167 | } else { | ||||
2168 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||
2169 | TemplateArgs = nullptr; | ||||
2170 | } | ||||
2171 | } | ||||
2172 | |||||
2173 | static void emitEmptyLookupTypoDiagnostic( | ||||
2174 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||
2175 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||
2176 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||
2177 | DeclContext *Ctx = | ||||
2178 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||
2179 | if (!TC) { | ||||
2180 | // Emit a special diagnostic for failed member lookups. | ||||
2181 | // FIXME: computing the declaration context might fail here (?) | ||||
2182 | if (Ctx) | ||||
2183 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||
2184 | << SS.getRange(); | ||||
2185 | else | ||||
2186 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||
2187 | return; | ||||
2188 | } | ||||
2189 | |||||
2190 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||
2191 | bool DroppedSpecifier = | ||||
2192 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||
2193 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2194 | ? diag::note_implicit_param_decl | ||||
2195 | : diag::note_previous_decl; | ||||
2196 | if (!Ctx) | ||||
2197 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||
2198 | SemaRef.PDiag(NoteID)); | ||||
2199 | else | ||||
2200 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||
2201 | << Typo << Ctx << DroppedSpecifier | ||||
2202 | << SS.getRange(), | ||||
2203 | SemaRef.PDiag(NoteID)); | ||||
2204 | } | ||||
2205 | |||||
2206 | /// Diagnose a lookup that found results in an enclosing class during error | ||||
2207 | /// recovery. This usually indicates that the results were found in a dependent | ||||
2208 | /// base class that could not be searched as part of a template definition. | ||||
2209 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||
2210 | /// compatibility mode). | ||||
2211 | /// | ||||
2212 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||
2213 | /// should attempt to recover using these lookup results. | ||||
2214 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||
2215 | // During a default argument instantiation the CurContext points | ||||
2216 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||
2217 | // function parameter list, hence add an explicit check. | ||||
2218 | bool isDefaultArgument = | ||||
2219 | !CodeSynthesisContexts.empty() && | ||||
2220 | CodeSynthesisContexts.back().Kind == | ||||
2221 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||
2222 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||
2223 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||
2224 | R.getNamingClass() == CurMethod->getParent() && | ||||
2225 | !isDefaultArgument; | ||||
2226 | |||||
2227 | // There are two ways we can find a class-scope declaration during template | ||||
2228 | // instantiation that we did not find in the template definition: if it is a | ||||
2229 | // member of a dependent base class, or if it is declared after the point of | ||||
2230 | // use in the same class. Distinguish these by comparing the class in which | ||||
2231 | // the member was found to the naming class of the lookup. | ||||
2232 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||
2233 | unsigned NoteID = diag::note_member_declared_at; | ||||
2234 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||
2235 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||
2236 | : diag::err_found_later_in_class; | ||||
2237 | } else if (getLangOpts().MSVCCompat) { | ||||
2238 | DiagID = diag::ext_found_in_dependent_base; | ||||
2239 | NoteID = diag::note_dependent_member_use; | ||||
2240 | } | ||||
2241 | |||||
2242 | if (isInstance) { | ||||
2243 | // Give a code modification hint to insert 'this->'. | ||||
2244 | Diag(R.getNameLoc(), DiagID) | ||||
2245 | << R.getLookupName() | ||||
2246 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||
2247 | CheckCXXThisCapture(R.getNameLoc()); | ||||
2248 | } else { | ||||
2249 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||
2250 | // they're not shadowed). | ||||
2251 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||
2252 | } | ||||
2253 | |||||
2254 | for (NamedDecl *D : R) | ||||
2255 | Diag(D->getLocation(), NoteID); | ||||
2256 | |||||
2257 | // Return true if we are inside a default argument instantiation | ||||
2258 | // and the found name refers to an instance member function, otherwise | ||||
2259 | // the caller will try to create an implicit member call and this is wrong | ||||
2260 | // for default arguments. | ||||
2261 | // | ||||
2262 | // FIXME: Is this special case necessary? We could allow the caller to | ||||
2263 | // diagnose this. | ||||
2264 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||
2265 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||
2266 | return true; | ||||
2267 | } | ||||
2268 | |||||
2269 | // Tell the callee to try to recover. | ||||
2270 | return false; | ||||
2271 | } | ||||
2272 | |||||
2273 | /// Diagnose an empty lookup. | ||||
2274 | /// | ||||
2275 | /// \return false if new lookup candidates were found | ||||
2276 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||
2277 | CorrectionCandidateCallback &CCC, | ||||
2278 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||
2279 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||
2280 | DeclarationName Name = R.getLookupName(); | ||||
2281 | |||||
2282 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||
2283 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||
2284 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||
2285 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||
2286 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
2287 | diagnostic = diag::err_undeclared_use; | ||||
2288 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||
2289 | } | ||||
2290 | |||||
2291 | // If the original lookup was an unqualified lookup, fake an | ||||
2292 | // unqualified lookup. This is useful when (for example) the | ||||
2293 | // original lookup would not have found something because it was a | ||||
2294 | // dependent name. | ||||
2295 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||
2296 | while (DC) { | ||||
2297 | if (isa<CXXRecordDecl>(DC)) { | ||||
2298 | LookupQualifiedName(R, DC); | ||||
2299 | |||||
2300 | if (!R.empty()) { | ||||
2301 | // Don't give errors about ambiguities in this lookup. | ||||
2302 | R.suppressDiagnostics(); | ||||
2303 | |||||
2304 | // If there's a best viable function among the results, only mention | ||||
2305 | // that one in the notes. | ||||
2306 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||
2307 | OverloadCandidateSet::CSK_Normal); | ||||
2308 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||
2309 | OverloadCandidateSet::iterator Best; | ||||
2310 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||
2311 | OR_Success) { | ||||
2312 | R.clear(); | ||||
2313 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||
2314 | R.resolveKind(); | ||||
2315 | } | ||||
2316 | |||||
2317 | return DiagnoseDependentMemberLookup(R); | ||||
2318 | } | ||||
2319 | |||||
2320 | R.clear(); | ||||
2321 | } | ||||
2322 | |||||
2323 | DC = DC->getLookupParent(); | ||||
2324 | } | ||||
2325 | |||||
2326 | // We didn't find anything, so try to correct for a typo. | ||||
2327 | TypoCorrection Corrected; | ||||
2328 | if (S && Out) { | ||||
2329 | SourceLocation TypoLoc = R.getNameLoc(); | ||||
2330 | assert(!ExplicitTemplateArgs &&(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "clang/lib/Sema/SemaExpr.cpp", 2331, __extension__ __PRETTY_FUNCTION__ )) | ||||
2331 | "Diagnosing an empty lookup with explicit template args!")(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "clang/lib/Sema/SemaExpr.cpp", 2331, __extension__ __PRETTY_FUNCTION__ )); | ||||
2332 | *Out = CorrectTypoDelayed( | ||||
2333 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||
2334 | [=](const TypoCorrection &TC) { | ||||
2335 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||
2336 | diagnostic, diagnostic_suggest); | ||||
2337 | }, | ||||
2338 | nullptr, CTK_ErrorRecovery); | ||||
2339 | if (*Out) | ||||
2340 | return true; | ||||
2341 | } else if (S && | ||||
2342 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||
2343 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||
2344 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
2345 | bool DroppedSpecifier = | ||||
2346 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||
2347 | R.setLookupName(Corrected.getCorrection()); | ||||
2348 | |||||
2349 | bool AcceptableWithRecovery = false; | ||||
2350 | bool AcceptableWithoutRecovery = false; | ||||
2351 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||
2352 | if (ND) { | ||||
2353 | if (Corrected.isOverloaded()) { | ||||
2354 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||
2355 | OverloadCandidateSet::CSK_Normal); | ||||
2356 | OverloadCandidateSet::iterator Best; | ||||
2357 | for (NamedDecl *CD : Corrected) { | ||||
2358 | if (FunctionTemplateDecl *FTD = | ||||
2359 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||
2360 | AddTemplateOverloadCandidate( | ||||
2361 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||
2362 | Args, OCS); | ||||
2363 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
2364 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||
2365 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||
2366 | Args, OCS); | ||||
2367 | } | ||||
2368 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||
2369 | case OR_Success: | ||||
2370 | ND = Best->FoundDecl; | ||||
2371 | Corrected.setCorrectionDecl(ND); | ||||
2372 | break; | ||||
2373 | default: | ||||
2374 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||
2375 | Corrected.setCorrectionDecl(ND); | ||||
2376 | break; | ||||
2377 | } | ||||
2378 | } | ||||
2379 | R.addDecl(ND); | ||||
2380 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||
2381 | CXXRecordDecl *Record = nullptr; | ||||
2382 | if (Corrected.getCorrectionSpecifier()) { | ||||
2383 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||
2384 | Record = Ty->getAsCXXRecordDecl(); | ||||
2385 | } | ||||
2386 | if (!Record) | ||||
2387 | Record = cast<CXXRecordDecl>( | ||||
2388 | ND->getDeclContext()->getRedeclContext()); | ||||
2389 | R.setNamingClass(Record); | ||||
2390 | } | ||||
2391 | |||||
2392 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||
2393 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||
2394 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||
2395 | // FIXME: If we ended up with a typo for a type name or | ||||
2396 | // Objective-C class name, we're in trouble because the parser | ||||
2397 | // is in the wrong place to recover. Suggest the typo | ||||
2398 | // correction, but don't make it a fix-it since we're not going | ||||
2399 | // to recover well anyway. | ||||
2400 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||
2401 | getAsTypeTemplateDecl(UnderlyingND) || | ||||
2402 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||
2403 | } else { | ||||
2404 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||
2405 | // because we aren't able to recover. | ||||
2406 | AcceptableWithoutRecovery = true; | ||||
2407 | } | ||||
2408 | |||||
2409 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||
2410 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2411 | ? diag::note_implicit_param_decl | ||||
2412 | : diag::note_previous_decl; | ||||
2413 | if (SS.isEmpty()) | ||||
2414 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||
2415 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2416 | else | ||||
2417 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||
2418 | << Name << computeDeclContext(SS, false) | ||||
2419 | << DroppedSpecifier << SS.getRange(), | ||||
2420 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2421 | |||||
2422 | // Tell the callee whether to try to recover. | ||||
2423 | return !AcceptableWithRecovery; | ||||
2424 | } | ||||
2425 | } | ||||
2426 | R.clear(); | ||||
2427 | |||||
2428 | // Emit a special diagnostic for failed member lookups. | ||||
2429 | // FIXME: computing the declaration context might fail here (?) | ||||
2430 | if (!SS.isEmpty()) { | ||||
2431 | Diag(R.getNameLoc(), diag::err_no_member) | ||||
2432 | << Name << computeDeclContext(SS, false) | ||||
2433 | << SS.getRange(); | ||||
2434 | return true; | ||||
2435 | } | ||||
2436 | |||||
2437 | // Give up, we can't recover. | ||||
2438 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||
2439 | return true; | ||||
2440 | } | ||||
2441 | |||||
2442 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||
2443 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||
2444 | /// assume the identifier is a member of a dependent base class. We can only | ||||
2445 | /// recover successfully in static methods, instance methods, and other contexts | ||||
2446 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||
2447 | /// instantiation model, but it's close enough. | ||||
2448 | static Expr * | ||||
2449 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||
2450 | DeclarationNameInfo &NameInfo, | ||||
2451 | SourceLocation TemplateKWLoc, | ||||
2452 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2453 | // Only try to recover from lookup into dependent bases in static methods or | ||||
2454 | // contexts where 'this' is available. | ||||
2455 | QualType ThisType = S.getCurrentThisType(); | ||||
2456 | const CXXRecordDecl *RD = nullptr; | ||||
2457 | if (!ThisType.isNull()) | ||||
2458 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||
2459 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||
2460 | RD = MD->getParent(); | ||||
2461 | if (!RD || !RD->hasAnyDependentBases()) | ||||
2462 | return nullptr; | ||||
2463 | |||||
2464 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||
2465 | // is available, suggest inserting 'this->' as a fixit. | ||||
2466 | SourceLocation Loc = NameInfo.getLoc(); | ||||
2467 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||
2468 | DB << NameInfo.getName() << RD; | ||||
2469 | |||||
2470 | if (!ThisType.isNull()) { | ||||
2471 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||
2472 | return CXXDependentScopeMemberExpr::Create( | ||||
2473 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||
2474 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||
2475 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||
2476 | } | ||||
2477 | |||||
2478 | // Synthesize a fake NNS that points to the derived class. This will | ||||
2479 | // perform name lookup during template instantiation. | ||||
2480 | CXXScopeSpec SS; | ||||
2481 | auto *NNS = | ||||
2482 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||
2483 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||
2484 | return DependentScopeDeclRefExpr::Create( | ||||
2485 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||
2486 | TemplateArgs); | ||||
2487 | } | ||||
2488 | |||||
2489 | ExprResult | ||||
2490 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||
2491 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||
2492 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||
2493 | CorrectionCandidateCallback *CCC, | ||||
2494 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||
2495 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen ) && "cannot be direct & operand and have a trailing lparen" ) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "clang/lib/Sema/SemaExpr.cpp", 2496, __extension__ __PRETTY_FUNCTION__ )) | ||||
2496 | "cannot be direct & operand and have a trailing lparen")(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen ) && "cannot be direct & operand and have a trailing lparen" ) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "clang/lib/Sema/SemaExpr.cpp", 2496, __extension__ __PRETTY_FUNCTION__ )); | ||||
2497 | if (SS.isInvalid()) | ||||
2498 | return ExprError(); | ||||
2499 | |||||
2500 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||
2501 | |||||
2502 | // Decompose the UnqualifiedId into the following data. | ||||
2503 | DeclarationNameInfo NameInfo; | ||||
2504 | const TemplateArgumentListInfo *TemplateArgs; | ||||
2505 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||
2506 | |||||
2507 | DeclarationName Name = NameInfo.getName(); | ||||
2508 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
2509 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||
2510 | |||||
2511 | if (II && II->isEditorPlaceholder()) { | ||||
2512 | // FIXME: When typed placeholders are supported we can create a typed | ||||
2513 | // placeholder expression node. | ||||
2514 | return ExprError(); | ||||
2515 | } | ||||
2516 | |||||
2517 | // C++ [temp.dep.expr]p3: | ||||
2518 | // An id-expression is type-dependent if it contains: | ||||
2519 | // -- an identifier that was declared with a dependent type, | ||||
2520 | // (note: handled after lookup) | ||||
2521 | // -- a template-id that is dependent, | ||||
2522 | // (note: handled in BuildTemplateIdExpr) | ||||
2523 | // -- a conversion-function-id that specifies a dependent type, | ||||
2524 | // -- a nested-name-specifier that contains a class-name that | ||||
2525 | // names a dependent type. | ||||
2526 | // Determine whether this is a member of an unknown specialization; | ||||
2527 | // we need to handle these differently. | ||||
2528 | bool DependentID = false; | ||||
2529 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||
2530 | Name.getCXXNameType()->isDependentType()) { | ||||
2531 | DependentID = true; | ||||
2532 | } else if (SS.isSet()) { | ||||
2533 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||
2534 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2535 | return ExprError(); | ||||
2536 | } else { | ||||
2537 | DependentID = true; | ||||
2538 | } | ||||
2539 | } | ||||
2540 | |||||
2541 | if (DependentID) | ||||
2542 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2543 | IsAddressOfOperand, TemplateArgs); | ||||
2544 | |||||
2545 | // Perform the required lookup. | ||||
2546 | LookupResult R(*this, NameInfo, | ||||
2547 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||
2548 | ? LookupObjCImplicitSelfParam | ||||
2549 | : LookupOrdinaryName); | ||||
2550 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||
2551 | // Lookup the template name again to correctly establish the context in | ||||
2552 | // which it was found. This is really unfortunate as we already did the | ||||
2553 | // lookup to determine that it was a template name in the first place. If | ||||
2554 | // this becomes a performance hit, we can work harder to preserve those | ||||
2555 | // results until we get here but it's likely not worth it. | ||||
2556 | bool MemberOfUnknownSpecialization; | ||||
2557 | AssumedTemplateKind AssumedTemplate; | ||||
2558 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||
2559 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||
2560 | &AssumedTemplate)) | ||||
2561 | return ExprError(); | ||||
2562 | |||||
2563 | if (MemberOfUnknownSpecialization || | ||||
2564 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||
2565 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2566 | IsAddressOfOperand, TemplateArgs); | ||||
2567 | } else { | ||||
2568 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||
2569 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||
2570 | |||||
2571 | // If the result might be in a dependent base class, this is a dependent | ||||
2572 | // id-expression. | ||||
2573 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2574 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2575 | IsAddressOfOperand, TemplateArgs); | ||||
2576 | |||||
2577 | // If this reference is in an Objective-C method, then we need to do | ||||
2578 | // some special Objective-C lookup, too. | ||||
2579 | if (IvarLookupFollowUp) { | ||||
2580 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||
2581 | if (E.isInvalid()) | ||||
2582 | return ExprError(); | ||||
2583 | |||||
2584 | if (Expr *Ex = E.getAs<Expr>()) | ||||
2585 | return Ex; | ||||
2586 | } | ||||
2587 | } | ||||
2588 | |||||
2589 | if (R.isAmbiguous()) | ||||
2590 | return ExprError(); | ||||
2591 | |||||
2592 | // This could be an implicitly declared function reference if the language | ||||
2593 | // mode allows it as a feature. | ||||
2594 | if (R.empty() && HasTrailingLParen && II && | ||||
2595 | getLangOpts().implicitFunctionsAllowed()) { | ||||
2596 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||
2597 | if (D) R.addDecl(D); | ||||
2598 | } | ||||
2599 | |||||
2600 | // Determine whether this name might be a candidate for | ||||
2601 | // argument-dependent lookup. | ||||
2602 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||
2603 | |||||
2604 | if (R.empty() && !ADL) { | ||||
2605 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
2606 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||
2607 | TemplateKWLoc, TemplateArgs)) | ||||
2608 | return E; | ||||
2609 | } | ||||
2610 | |||||
2611 | // Don't diagnose an empty lookup for inline assembly. | ||||
2612 | if (IsInlineAsmIdentifier) | ||||
2613 | return ExprError(); | ||||
2614 | |||||
2615 | // If this name wasn't predeclared and if this is not a function | ||||
2616 | // call, diagnose the problem. | ||||
2617 | TypoExpr *TE = nullptr; | ||||
2618 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||
2619 | : nullptr); | ||||
2620 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||
2621 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured" ) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "clang/lib/Sema/SemaExpr.cpp", 2622, __extension__ __PRETTY_FUNCTION__ )) | ||||
2622 | "Typo correction callback misconfigured")(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured" ) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "clang/lib/Sema/SemaExpr.cpp", 2622, __extension__ __PRETTY_FUNCTION__ )); | ||||
2623 | if (CCC) { | ||||
2624 | // Make sure the callback knows what the typo being diagnosed is. | ||||
2625 | CCC->setTypoName(II); | ||||
2626 | if (SS.isValid()) | ||||
2627 | CCC->setTypoNNS(SS.getScopeRep()); | ||||
2628 | } | ||||
2629 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||
2630 | // a template name, but we happen to have always already looked up the name | ||||
2631 | // before we get here if it must be a template name. | ||||
2632 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||
2633 | std::nullopt, &TE)) { | ||||
2634 | if (TE && KeywordReplacement) { | ||||
2635 | auto &State = getTypoExprState(TE); | ||||
2636 | auto BestTC = State.Consumer->getNextCorrection(); | ||||
2637 | if (BestTC.isKeyword()) { | ||||
2638 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||
2639 | if (State.DiagHandler) | ||||
2640 | State.DiagHandler(BestTC); | ||||
2641 | KeywordReplacement->startToken(); | ||||
2642 | KeywordReplacement->setKind(II->getTokenID()); | ||||
2643 | KeywordReplacement->setIdentifierInfo(II); | ||||
2644 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||
2645 | // Clean up the state associated with the TypoExpr, since it has | ||||
2646 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||
2647 | clearDelayedTypo(TE); | ||||
2648 | // Signal that a correction to a keyword was performed by returning a | ||||
2649 | // valid-but-null ExprResult. | ||||
2650 | return (Expr*)nullptr; | ||||
2651 | } | ||||
2652 | State.Consumer->resetCorrectionStream(); | ||||
2653 | } | ||||
2654 | return TE ? TE : ExprError(); | ||||
2655 | } | ||||
2656 | |||||
2657 | assert(!R.empty() &&(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "clang/lib/Sema/SemaExpr.cpp", 2658, __extension__ __PRETTY_FUNCTION__ )) | ||||
2658 | "DiagnoseEmptyLookup returned false but added no results")(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "clang/lib/Sema/SemaExpr.cpp", 2658, __extension__ __PRETTY_FUNCTION__ )); | ||||
2659 | |||||
2660 | // If we found an Objective-C instance variable, let | ||||
2661 | // LookupInObjCMethod build the appropriate expression to | ||||
2662 | // reference the ivar. | ||||
2663 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||
2664 | R.clear(); | ||||
2665 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||
2666 | // In a hopelessly buggy code, Objective-C instance variable | ||||
2667 | // lookup fails and no expression will be built to reference it. | ||||
2668 | if (!E.isInvalid() && !E.get()) | ||||
2669 | return ExprError(); | ||||
2670 | return E; | ||||
2671 | } | ||||
2672 | } | ||||
2673 | |||||
2674 | // This is guaranteed from this point on. | ||||
2675 | assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail ("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2675, __extension__ __PRETTY_FUNCTION__)); | ||||
2676 | |||||
2677 | // Check whether this might be a C++ implicit instance member access. | ||||
2678 | // C++ [class.mfct.non-static]p3: | ||||
2679 | // When an id-expression that is not part of a class member access | ||||
2680 | // syntax and not used to form a pointer to member is used in the | ||||
2681 | // body of a non-static member function of class X, if name lookup | ||||
2682 | // resolves the name in the id-expression to a non-static non-type | ||||
2683 | // member of some class C, the id-expression is transformed into a | ||||
2684 | // class member access expression using (*this) as the | ||||
2685 | // postfix-expression to the left of the . operator. | ||||
2686 | // | ||||
2687 | // But we don't actually need to do this for '&' operands if R | ||||
2688 | // resolved to a function or overloaded function set, because the | ||||
2689 | // expression is ill-formed if it actually works out to be a | ||||
2690 | // non-static member function: | ||||
2691 | // | ||||
2692 | // C++ [expr.ref]p4: | ||||
2693 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||
2694 | // [t]he expression can be used only as the left-hand operand of a | ||||
2695 | // member function call. | ||||
2696 | // | ||||
2697 | // There are other safeguards against such uses, but it's important | ||||
2698 | // to get this right here so that we don't end up making a | ||||
2699 | // spuriously dependent expression if we're inside a dependent | ||||
2700 | // instance method. | ||||
2701 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||
2702 | bool MightBeImplicitMember; | ||||
2703 | if (!IsAddressOfOperand) | ||||
2704 | MightBeImplicitMember = true; | ||||
2705 | else if (!SS.isEmpty()) | ||||
2706 | MightBeImplicitMember = false; | ||||
2707 | else if (R.isOverloadedResult()) | ||||
2708 | MightBeImplicitMember = false; | ||||
2709 | else if (R.isUnresolvableResult()) | ||||
2710 | MightBeImplicitMember = true; | ||||
2711 | else | ||||
2712 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||
2713 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||
2714 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||
2715 | |||||
2716 | if (MightBeImplicitMember) | ||||
2717 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||
2718 | R, TemplateArgs, S); | ||||
2719 | } | ||||
2720 | |||||
2721 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||
2722 | |||||
2723 | // In C++1y, if this is a variable template id, then check it | ||||
2724 | // in BuildTemplateIdExpr(). | ||||
2725 | // The single lookup result must be a variable template declaration. | ||||
2726 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||
2727 | Id.TemplateId->Kind == TNK_Var_template) { | ||||
2728 | assert(R.getAsSingle<VarTemplateDecl>() &&(static_cast <bool> (R.getAsSingle<VarTemplateDecl> () && "There should only be one declaration found.") ? void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "clang/lib/Sema/SemaExpr.cpp", 2729, __extension__ __PRETTY_FUNCTION__ )) | ||||
2729 | "There should only be one declaration found.")(static_cast <bool> (R.getAsSingle<VarTemplateDecl> () && "There should only be one declaration found.") ? void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "clang/lib/Sema/SemaExpr.cpp", 2729, __extension__ __PRETTY_FUNCTION__ )); | ||||
2730 | } | ||||
2731 | |||||
2732 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||
2733 | } | ||||
2734 | |||||
2735 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||
2736 | } | ||||
2737 | |||||
2738 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||
2739 | /// declaration name, generally during template instantiation. | ||||
2740 | /// There's a large number of things which don't need to be done along | ||||
2741 | /// this path. | ||||
2742 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||
2743 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||
2744 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||
2745 | if (NameInfo.getName().isDependentName()) | ||||
2746 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2747 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2748 | |||||
2749 | DeclContext *DC = computeDeclContext(SS, false); | ||||
2750 | if (!DC) | ||||
2751 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2752 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2753 | |||||
2754 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2755 | return ExprError(); | ||||
2756 | |||||
2757 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
2758 | LookupQualifiedName(R, DC); | ||||
2759 | |||||
2760 | if (R.isAmbiguous()) | ||||
2761 | return ExprError(); | ||||
2762 | |||||
2763 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2764 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2765 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2766 | |||||
2767 | if (R.empty()) { | ||||
2768 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||
2769 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||
2770 | // is invalid because it's derived from an invalid base class, then missing | ||||
2771 | // members were likely supposed to be inherited. | ||||
2772 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||
2773 | if (CD->isInvalidDecl()) | ||||
2774 | return ExprError(); | ||||
2775 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||
2776 | << NameInfo.getName() << DC << SS.getRange(); | ||||
2777 | return ExprError(); | ||||
2778 | } | ||||
2779 | |||||
2780 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||
2781 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||
2782 | // a dependent context. If we can recover with a type, downgrade this to | ||||
2783 | // a warning in Microsoft compatibility mode. | ||||
2784 | unsigned DiagID = diag::err_typename_missing; | ||||
2785 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||
2786 | DiagID = diag::ext_typename_missing; | ||||
2787 | SourceLocation Loc = SS.getBeginLoc(); | ||||
2788 | auto D = Diag(Loc, DiagID); | ||||
2789 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||
2790 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||
2791 | |||||
2792 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||
2793 | // context. | ||||
2794 | if (!RecoveryTSI) | ||||
2795 | return ExprError(); | ||||
2796 | |||||
2797 | // Only issue the fixit if we're prepared to recover. | ||||
2798 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||
2799 | |||||
2800 | // Recover by pretending this was an elaborated type. | ||||
2801 | QualType Ty = Context.getTypeDeclType(TD); | ||||
2802 | TypeLocBuilder TLB; | ||||
2803 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||
2804 | |||||
2805 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||
2806 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||
2807 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
2808 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
2809 | |||||
2810 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||
2811 | |||||
2812 | return ExprEmpty(); | ||||
2813 | } | ||||
2814 | |||||
2815 | // Defend against this resolving to an implicit member access. We usually | ||||
2816 | // won't get here if this might be a legitimate a class member (we end up in | ||||
2817 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||
2818 | // a pointer-to-member or in an unevaluated context in C++11. | ||||
2819 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||
2820 | return BuildPossibleImplicitMemberExpr(SS, | ||||
2821 | /*TemplateKWLoc=*/SourceLocation(), | ||||
2822 | R, /*TemplateArgs=*/nullptr, S); | ||||
2823 | |||||
2824 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||
2825 | } | ||||
2826 | |||||
2827 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2828 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2829 | /// should form a reference to an ivar. | ||||
2830 | /// | ||||
2831 | /// Ideally, most of this would be done by lookup, but there's | ||||
2832 | /// actually quite a lot of extra work involved. | ||||
2833 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2834 | IdentifierInfo *II) { | ||||
2835 | SourceLocation Loc = Lookup.getNameLoc(); | ||||
2836 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2837 | |||||
2838 | // Check for error condition which is already reported. | ||||
2839 | if (!CurMethod) | ||||
2840 | return DeclResult(true); | ||||
2841 | |||||
2842 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||
2843 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||
2844 | // found a decl, but that decl is outside the current instance method (i.e. | ||||
2845 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||
2846 | // this name, if the lookup sucedes, we replace it our current decl. | ||||
2847 | |||||
2848 | // If we're in a class method, we don't normally want to look for | ||||
2849 | // ivars. But if we don't find anything else, and there's an | ||||
2850 | // ivar, that's an error. | ||||
2851 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||
2852 | |||||
2853 | bool LookForIvars; | ||||
2854 | if (Lookup.empty()) | ||||
2855 | LookForIvars = true; | ||||
2856 | else if (IsClassMethod) | ||||
2857 | LookForIvars = false; | ||||
2858 | else | ||||
2859 | LookForIvars = (Lookup.isSingleResult() && | ||||
2860 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||
2861 | ObjCInterfaceDecl *IFace = nullptr; | ||||
2862 | if (LookForIvars) { | ||||
2863 | IFace = CurMethod->getClassInterface(); | ||||
2864 | ObjCInterfaceDecl *ClassDeclared; | ||||
2865 | ObjCIvarDecl *IV = nullptr; | ||||
2866 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||
2867 | // Diagnose using an ivar in a class method. | ||||
2868 | if (IsClassMethod) { | ||||
2869 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2870 | return DeclResult(true); | ||||
2871 | } | ||||
2872 | |||||
2873 | // Diagnose the use of an ivar outside of the declaring class. | ||||
2874 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||
2875 | !declaresSameEntity(ClassDeclared, IFace) && | ||||
2876 | !getLangOpts().DebuggerSupport) | ||||
2877 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||
2878 | |||||
2879 | // Success. | ||||
2880 | return IV; | ||||
2881 | } | ||||
2882 | } else if (CurMethod->isInstanceMethod()) { | ||||
2883 | // We should warn if a local variable hides an ivar. | ||||
2884 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||
2885 | ObjCInterfaceDecl *ClassDeclared; | ||||
2886 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||
2887 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||
2888 | declaresSameEntity(IFace, ClassDeclared)) | ||||
2889 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||
2890 | } | ||||
2891 | } | ||||
2892 | } else if (Lookup.isSingleResult() && | ||||
2893 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||
2894 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||
2895 | if (const ObjCIvarDecl *IV = | ||||
2896 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||
2897 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2898 | return DeclResult(true); | ||||
2899 | } | ||||
2900 | } | ||||
2901 | |||||
2902 | // Didn't encounter an error, didn't find an ivar. | ||||
2903 | return DeclResult(false); | ||||
2904 | } | ||||
2905 | |||||
2906 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||
2907 | ObjCIvarDecl *IV) { | ||||
2908 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2909 | assert(CurMethod && CurMethod->isInstanceMethod() &&(static_cast <bool> (CurMethod && CurMethod-> isInstanceMethod() && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "clang/lib/Sema/SemaExpr.cpp", 2910, __extension__ __PRETTY_FUNCTION__ )) | ||||
2910 | "should not reference ivar from this context")(static_cast <bool> (CurMethod && CurMethod-> isInstanceMethod() && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "clang/lib/Sema/SemaExpr.cpp", 2910, __extension__ __PRETTY_FUNCTION__ )); | ||||
2911 | |||||
2912 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||
2913 | assert(IFace && "should not reference ivar from this context")(static_cast <bool> (IFace && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "clang/lib/Sema/SemaExpr.cpp", 2913, __extension__ __PRETTY_FUNCTION__ )); | ||||
2914 | |||||
2915 | // If we're referencing an invalid decl, just return this as a silent | ||||
2916 | // error node. The error diagnostic was already emitted on the decl. | ||||
2917 | if (IV->isInvalidDecl()) | ||||
2918 | return ExprError(); | ||||
2919 | |||||
2920 | // Check if referencing a field with __attribute__((deprecated)). | ||||
2921 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||
2922 | return ExprError(); | ||||
2923 | |||||
2924 | // FIXME: This should use a new expr for a direct reference, don't | ||||
2925 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||
2926 | IdentifierInfo &II = Context.Idents.get("self"); | ||||
2927 | UnqualifiedId SelfName; | ||||
2928 | SelfName.setImplicitSelfParam(&II); | ||||
2929 | CXXScopeSpec SelfScopeSpec; | ||||
2930 | SourceLocation TemplateKWLoc; | ||||
2931 | ExprResult SelfExpr = | ||||
2932 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||
2933 | /*HasTrailingLParen=*/false, | ||||
2934 | /*IsAddressOfOperand=*/false); | ||||
2935 | if (SelfExpr.isInvalid()) | ||||
2936 | return ExprError(); | ||||
2937 | |||||
2938 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||
2939 | if (SelfExpr.isInvalid()) | ||||
2940 | return ExprError(); | ||||
2941 | |||||
2942 | MarkAnyDeclReferenced(Loc, IV, true); | ||||
2943 | |||||
2944 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||
2945 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||
2946 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||
2947 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||
2948 | |||||
2949 | ObjCIvarRefExpr *Result = new (Context) | ||||
2950 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||
2951 | IV->getLocation(), SelfExpr.get(), true, true); | ||||
2952 | |||||
2953 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||
2954 | if (!isUnevaluatedContext() && | ||||
2955 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||
2956 | getCurFunction()->recordUseOfWeak(Result); | ||||
2957 | } | ||||
2958 | if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext()) | ||||
2959 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||
2960 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||
2961 | |||||
2962 | return Result; | ||||
2963 | } | ||||
2964 | |||||
2965 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2966 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2967 | /// should form a reference to an ivar. If so, build an expression referencing | ||||
2968 | /// that ivar. | ||||
2969 | ExprResult | ||||
2970 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2971 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||
2972 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||
2973 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||
2974 | if (Ivar.isInvalid()) | ||||
2975 | return ExprError(); | ||||
2976 | if (Ivar.isUsable()) | ||||
2977 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||
2978 | cast<ObjCIvarDecl>(Ivar.get())); | ||||
2979 | |||||
2980 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||
2981 | LookupBuiltin(Lookup); | ||||
2982 | |||||
2983 | // Sentinel value saying that we didn't do anything special. | ||||
2984 | return ExprResult(false); | ||||
2985 | } | ||||
2986 | |||||
2987 | /// Cast a base object to a member's actual type. | ||||
2988 | /// | ||||
2989 | /// There are two relevant checks: | ||||
2990 | /// | ||||
2991 | /// C++ [class.access.base]p7: | ||||
2992 | /// | ||||
2993 | /// If a class member access operator [...] is used to access a non-static | ||||
2994 | /// data member or non-static member function, the reference is ill-formed if | ||||
2995 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||
2996 | /// naming class of the right operand. | ||||
2997 | /// | ||||
2998 | /// C++ [expr.ref]p7: | ||||
2999 | /// | ||||
3000 | /// If E2 is a non-static data member or a non-static member function, the | ||||
3001 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||
3002 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||
3003 | /// | ||||
3004 | /// Note that the latter check does not consider access; the access of the | ||||
3005 | /// "real" base class is checked as appropriate when checking the access of the | ||||
3006 | /// member name. | ||||
3007 | ExprResult | ||||
3008 | Sema::PerformObjectMemberConversion(Expr *From, | ||||
3009 | NestedNameSpecifier *Qualifier, | ||||
3010 | NamedDecl *FoundDecl, | ||||
3011 | NamedDecl *Member) { | ||||
3012 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||
3013 | if (!RD) | ||||
3014 | return From; | ||||
3015 | |||||
3016 | QualType DestRecordType; | ||||
3017 | QualType DestType; | ||||
3018 | QualType FromRecordType; | ||||
3019 | QualType FromType = From->getType(); | ||||
3020 | bool PointerConversions = false; | ||||
3021 | if (isa<FieldDecl>(Member)) { | ||||
3022 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||
3023 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||
3024 | DestRecordType = Context.getAddrSpaceQualType( | ||||
3025 | DestRecordType, FromPtrType | ||||
3026 | ? FromType->getPointeeType().getAddressSpace() | ||||
3027 | : FromType.getAddressSpace()); | ||||
3028 | |||||
3029 | if (FromPtrType) { | ||||
3030 | DestType = Context.getPointerType(DestRecordType); | ||||
3031 | FromRecordType = FromPtrType->getPointeeType(); | ||||
3032 | PointerConversions = true; | ||||
3033 | } else { | ||||
3034 | DestType = DestRecordType; | ||||
3035 | FromRecordType = FromType; | ||||
3036 | } | ||||
3037 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||
3038 | if (Method->isStatic()) | ||||
3039 | return From; | ||||
3040 | |||||
3041 | DestType = Method->getThisType(); | ||||
3042 | DestRecordType = DestType->getPointeeType(); | ||||
3043 | |||||
3044 | if (FromType->getAs<PointerType>()) { | ||||
3045 | FromRecordType = FromType->getPointeeType(); | ||||
3046 | PointerConversions = true; | ||||
3047 | } else { | ||||
3048 | FromRecordType = FromType; | ||||
3049 | DestType = DestRecordType; | ||||
3050 | } | ||||
3051 | |||||
3052 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||
3053 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||
3054 | if (FromAS != DestAS) { | ||||
3055 | QualType FromRecordTypeWithoutAS = | ||||
3056 | Context.removeAddrSpaceQualType(FromRecordType); | ||||
3057 | QualType FromTypeWithDestAS = | ||||
3058 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||
3059 | if (PointerConversions) | ||||
3060 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||
3061 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||
3062 | CK_AddressSpaceConversion, From->getValueKind()) | ||||
3063 | .get(); | ||||
3064 | } | ||||
3065 | } else { | ||||
3066 | // No conversion necessary. | ||||
3067 | return From; | ||||
3068 | } | ||||
3069 | |||||
3070 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||
3071 | return From; | ||||
3072 | |||||
3073 | // If the unqualified types are the same, no conversion is necessary. | ||||
3074 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3075 | return From; | ||||
3076 | |||||
3077 | SourceRange FromRange = From->getSourceRange(); | ||||
3078 | SourceLocation FromLoc = FromRange.getBegin(); | ||||
3079 | |||||
3080 | ExprValueKind VK = From->getValueKind(); | ||||
3081 | |||||
3082 | // C++ [class.member.lookup]p8: | ||||
3083 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||
3084 | // class name. | ||||
3085 | // | ||||
3086 | // If the member was a qualified name and the qualified referred to a | ||||
3087 | // specific base subobject type, we'll cast to that intermediate type | ||||
3088 | // first and then to the object in which the member is declared. That allows | ||||
3089 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||
3090 | // | ||||
3091 | // class Base { public: int x; }; | ||||
3092 | // class Derived1 : public Base { }; | ||||
3093 | // class Derived2 : public Base { }; | ||||
3094 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||
3095 | // | ||||
3096 | // void VeryDerived::f() { | ||||
3097 | // x = 17; // error: ambiguous base subobjects | ||||
3098 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||
3099 | // } | ||||
3100 | if (Qualifier && Qualifier->getAsType()) { | ||||
3101 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||
3102 | assert(QType->isRecordType() && "lookup done with non-record type")(static_cast <bool> (QType->isRecordType() && "lookup done with non-record type") ? void (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "clang/lib/Sema/SemaExpr.cpp", 3102, __extension__ __PRETTY_FUNCTION__ )); | ||||
3103 | |||||
3104 | QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); | ||||
3105 | |||||
3106 | // In C++98, the qualifier type doesn't actually have to be a base | ||||
3107 | // type of the object type, in which case we just ignore it. | ||||
3108 | // Otherwise build the appropriate casts. | ||||
3109 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||
3110 | CXXCastPath BasePath; | ||||
3111 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||
3112 | FromLoc, FromRange, &BasePath)) | ||||
3113 | return ExprError(); | ||||
3114 | |||||
3115 | if (PointerConversions) | ||||
3116 | QType = Context.getPointerType(QType); | ||||
3117 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||
3118 | VK, &BasePath).get(); | ||||
3119 | |||||
3120 | FromType = QType; | ||||
3121 | FromRecordType = QRecordType; | ||||
3122 | |||||
3123 | // If the qualifier type was the same as the destination type, | ||||
3124 | // we're done. | ||||
3125 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3126 | return From; | ||||
3127 | } | ||||
3128 | } | ||||
3129 | |||||
3130 | CXXCastPath BasePath; | ||||
3131 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||
3132 | FromLoc, FromRange, &BasePath, | ||||
3133 | /*IgnoreAccess=*/true)) | ||||
3134 | return ExprError(); | ||||
3135 | |||||
3136 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||
3137 | VK, &BasePath); | ||||
3138 | } | ||||
3139 | |||||
3140 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||
3141 | const LookupResult &R, | ||||
3142 | bool HasTrailingLParen) { | ||||
3143 | // Only when used directly as the postfix-expression of a call. | ||||
3144 | if (!HasTrailingLParen) | ||||
3145 | return false; | ||||
3146 | |||||
3147 | // Never if a scope specifier was provided. | ||||
3148 | if (SS.isSet()) | ||||
3149 | return false; | ||||
3150 | |||||
3151 | // Only in C++ or ObjC++. | ||||
3152 | if (!getLangOpts().CPlusPlus) | ||||
3153 | return false; | ||||
3154 | |||||
3155 | // Turn off ADL when we find certain kinds of declarations during | ||||
3156 | // normal lookup: | ||||
3157 | for (NamedDecl *D : R) { | ||||
3158 | // C++0x [basic.lookup.argdep]p3: | ||||
3159 | // -- a declaration of a class member | ||||
3160 | // Since using decls preserve this property, we check this on the | ||||
3161 | // original decl. | ||||
3162 | if (D->isCXXClassMember()) | ||||
3163 | return false; | ||||
3164 | |||||
3165 | // C++0x [basic.lookup.argdep]p3: | ||||
3166 | // -- a block-scope function declaration that is not a | ||||
3167 | // using-declaration | ||||
3168 | // NOTE: we also trigger this for function templates (in fact, we | ||||
3169 | // don't check the decl type at all, since all other decl types | ||||
3170 | // turn off ADL anyway). | ||||
3171 | if (isa<UsingShadowDecl>(D)) | ||||
3172 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
3173 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
3174 | return false; | ||||
3175 | |||||
3176 | // C++0x [basic.lookup.argdep]p3: | ||||
3177 | // -- a declaration that is neither a function or a function | ||||
3178 | // template | ||||
3179 | // And also for builtin functions. | ||||
3180 | if (isa<FunctionDecl>(D)) { | ||||
3181 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||
3182 | |||||
3183 | // But also builtin functions. | ||||
3184 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||
3185 | return false; | ||||
3186 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||
3187 | return false; | ||||
3188 | } | ||||
3189 | |||||
3190 | return true; | ||||
3191 | } | ||||
3192 | |||||
3193 | |||||
3194 | /// Diagnoses obvious problems with the use of the given declaration | ||||
3195 | /// as an expression. This is only actually called for lookups that | ||||
3196 | /// were not overloaded, and it doesn't promise that the declaration | ||||
3197 | /// will in fact be used. | ||||
3198 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, | ||||
3199 | bool AcceptInvalid) { | ||||
3200 | if (D->isInvalidDecl() && !AcceptInvalid) | ||||
3201 | return true; | ||||
3202 | |||||
3203 | if (isa<TypedefNameDecl>(D)) { | ||||
3204 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||
3205 | return true; | ||||
3206 | } | ||||
3207 | |||||
3208 | if (isa<ObjCInterfaceDecl>(D)) { | ||||
3209 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||
3210 | return true; | ||||
3211 | } | ||||
3212 | |||||
3213 | if (isa<NamespaceDecl>(D)) { | ||||
3214 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||
3215 | return true; | ||||
3216 | } | ||||
3217 | |||||
3218 | return false; | ||||
3219 | } | ||||
3220 | |||||
3221 | // Certain multiversion types should be treated as overloaded even when there is | ||||
3222 | // only one result. | ||||
3223 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||
3224 | assert(R.isSingleResult() && "Expected only a single result")(static_cast <bool> (R.isSingleResult() && "Expected only a single result" ) ? void (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "clang/lib/Sema/SemaExpr.cpp", 3224, __extension__ __PRETTY_FUNCTION__ )); | ||||
3225 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||
3226 | return FD && | ||||
3227 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||
3228 | } | ||||
3229 | |||||
3230 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||
3231 | LookupResult &R, bool NeedsADL, | ||||
3232 | bool AcceptInvalidDecl) { | ||||
3233 | // If this is a single, fully-resolved result and we don't need ADL, | ||||
3234 | // just build an ordinary singleton decl ref. | ||||
3235 | if (!NeedsADL && R.isSingleResult() && | ||||
3236 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||
3237 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||
3238 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||
3239 | R.getRepresentativeDecl(), nullptr, | ||||
3240 | AcceptInvalidDecl); | ||||
3241 | |||||
3242 | // We only need to check the declaration if there's exactly one | ||||
3243 | // result, because in the overloaded case the results can only be | ||||
3244 | // functions and function templates. | ||||
3245 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||
3246 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(), | ||||
3247 | AcceptInvalidDecl)) | ||||
3248 | return ExprError(); | ||||
3249 | |||||
3250 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||
3251 | // any lookup-related diagnostics; we'll hash these out later, when | ||||
3252 | // we've picked a target. | ||||
3253 | R.suppressDiagnostics(); | ||||
3254 | |||||
3255 | UnresolvedLookupExpr *ULE | ||||
3256 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||
3257 | SS.getWithLocInContext(Context), | ||||
3258 | R.getLookupNameInfo(), | ||||
3259 | NeedsADL, R.isOverloadedResult(), | ||||
3260 | R.begin(), R.end()); | ||||
3261 | |||||
3262 | return ULE; | ||||
3263 | } | ||||
3264 | |||||
3265 | static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, | ||||
3266 | SourceLocation loc, | ||||
3267 | ValueDecl *var); | ||||
3268 | |||||
3269 | /// Complete semantic analysis for a reference to the given declaration. | ||||
3270 | ExprResult Sema::BuildDeclarationNameExpr( | ||||
3271 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||
3272 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||
3273 | bool AcceptInvalidDecl) { | ||||
3274 | assert(D && "Cannot refer to a NULL declaration")(static_cast <bool> (D && "Cannot refer to a NULL declaration" ) ? void (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "clang/lib/Sema/SemaExpr.cpp", 3274, __extension__ __PRETTY_FUNCTION__ )); | ||||
3275 | assert(!isa<FunctionTemplateDecl>(D) &&(static_cast <bool> (!isa<FunctionTemplateDecl>(D ) && "Cannot refer unambiguously to a function template" ) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "clang/lib/Sema/SemaExpr.cpp", 3276, __extension__ __PRETTY_FUNCTION__ )) | ||||
3276 | "Cannot refer unambiguously to a function template")(static_cast <bool> (!isa<FunctionTemplateDecl>(D ) && "Cannot refer unambiguously to a function template" ) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "clang/lib/Sema/SemaExpr.cpp", 3276, __extension__ __PRETTY_FUNCTION__ )); | ||||
3277 | |||||
3278 | SourceLocation Loc = NameInfo.getLoc(); | ||||
3279 | if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) { | ||||
3280 | // Recovery from invalid cases (e.g. D is an invalid Decl). | ||||
3281 | // We use the dependent type for the RecoveryExpr to prevent bogus follow-up | ||||
3282 | // diagnostics, as invalid decls use int as a fallback type. | ||||
3283 | return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); | ||||
3284 | } | ||||
3285 | |||||
3286 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||
3287 | // Specifically diagnose references to class templates that are missing | ||||
3288 | // a template argument list. | ||||
3289 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||
3290 | return ExprError(); | ||||
3291 | } | ||||
3292 | |||||
3293 | // Make sure that we're referring to a value. | ||||
3294 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { | ||||
3295 | Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); | ||||
3296 | Diag(D->getLocation(), diag::note_declared_at); | ||||
3297 | return ExprError(); | ||||
3298 | } | ||||
3299 | |||||
3300 | // Check whether this declaration can be used. Note that we suppress | ||||
3301 | // this check when we're going to perform argument-dependent lookup | ||||
3302 | // on this function name, because this might not be the function | ||||
3303 | // that overload resolution actually selects. | ||||
3304 | if (DiagnoseUseOfDecl(D, Loc)) | ||||
3305 | return ExprError(); | ||||
3306 | |||||
3307 | auto *VD = cast<ValueDecl>(D); | ||||
3308 | |||||
3309 | // Only create DeclRefExpr's for valid Decl's. | ||||
3310 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||
3311 | return ExprError(); | ||||
3312 | |||||
3313 | // Handle members of anonymous structs and unions. If we got here, | ||||
3314 | // and the reference is to a class member indirect field, then this | ||||
3315 | // must be the subject of a pointer-to-member expression. | ||||
3316 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||
3317 | if (!indirectField->isCXXClassMember()) | ||||
3318 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||
3319 | indirectField); | ||||
3320 | |||||
3321 | QualType type = VD->getType(); | ||||
3322 | if (type.isNull()) | ||||
3323 | return ExprError(); | ||||
3324 | ExprValueKind valueKind = VK_PRValue; | ||||
3325 | |||||
3326 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||
3327 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||
3328 | // is expanded by some outer '...' in the context of the use. | ||||
3329 | type = type.getNonPackExpansionType(); | ||||
3330 | |||||
3331 | switch (D->getKind()) { | ||||
3332 | // Ignore all the non-ValueDecl kinds. | ||||
3333 | #define ABSTRACT_DECL(kind) | ||||
3334 | #define VALUE(type, base) | ||||
3335 | #define DECL(type, base) case Decl::type: | ||||
3336 | #include "clang/AST/DeclNodes.inc" | ||||
3337 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp" , 3337); | ||||
3338 | |||||
3339 | // These shouldn't make it here. | ||||
3340 | case Decl::ObjCAtDefsField: | ||||
3341 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "clang/lib/Sema/SemaExpr.cpp", 3341); | ||||
3342 | |||||
3343 | // Enum constants are always r-values and never references. | ||||
3344 | // Unresolved using declarations are dependent. | ||||
3345 | case Decl::EnumConstant: | ||||
3346 | case Decl::UnresolvedUsingValue: | ||||
3347 | case Decl::OMPDeclareReduction: | ||||
3348 | case Decl::OMPDeclareMapper: | ||||
3349 | valueKind = VK_PRValue; | ||||
3350 | break; | ||||
3351 | |||||
3352 | // Fields and indirect fields that got here must be for | ||||
3353 | // pointer-to-member expressions; we just call them l-values for | ||||
3354 | // internal consistency, because this subexpression doesn't really | ||||
3355 | // exist in the high-level semantics. | ||||
3356 | case Decl::Field: | ||||
3357 | case Decl::IndirectField: | ||||
3358 | case Decl::ObjCIvar: | ||||
3359 | assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast <bool> (getLangOpts().CPlusPlus && "building reference to field in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "clang/lib/Sema/SemaExpr.cpp", 3359, __extension__ __PRETTY_FUNCTION__ )); | ||||
3360 | |||||
3361 | // These can't have reference type in well-formed programs, but | ||||
3362 | // for internal consistency we do this anyway. | ||||
3363 | type = type.getNonReferenceType(); | ||||
3364 | valueKind = VK_LValue; | ||||
3365 | break; | ||||
3366 | |||||
3367 | // Non-type template parameters are either l-values or r-values | ||||
3368 | // depending on the type. | ||||
3369 | case Decl::NonTypeTemplateParm: { | ||||
3370 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||
3371 | type = reftype->getPointeeType(); | ||||
3372 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||
3373 | break; | ||||
3374 | } | ||||
3375 | |||||
3376 | // [expr.prim.id.unqual]p2: | ||||
3377 | // If the entity is a template parameter object for a template | ||||
3378 | // parameter of type T, the type of the expression is const T. | ||||
3379 | // [...] The expression is an lvalue if the entity is a [...] template | ||||
3380 | // parameter object. | ||||
3381 | if (type->isRecordType()) { | ||||
3382 | type = type.getUnqualifiedType().withConst(); | ||||
3383 | valueKind = VK_LValue; | ||||
3384 | break; | ||||
3385 | } | ||||
3386 | |||||
3387 | // For non-references, we need to strip qualifiers just in case | ||||
3388 | // the template parameter was declared as 'const int' or whatever. | ||||
3389 | valueKind = VK_PRValue; | ||||
3390 | type = type.getUnqualifiedType(); | ||||
3391 | break; | ||||
3392 | } | ||||
3393 | |||||
3394 | case Decl::Var: | ||||
3395 | case Decl::VarTemplateSpecialization: | ||||
3396 | case Decl::VarTemplatePartialSpecialization: | ||||
3397 | case Decl::Decomposition: | ||||
3398 | case Decl::OMPCapturedExpr: | ||||
3399 | // In C, "extern void blah;" is valid and is an r-value. | ||||
3400 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && | ||||
3401 | type->isVoidType()) { | ||||
3402 | valueKind = VK_PRValue; | ||||
3403 | break; | ||||
3404 | } | ||||
3405 | [[fallthrough]]; | ||||
3406 | |||||
3407 | case Decl::ImplicitParam: | ||||
3408 | case Decl::ParmVar: { | ||||
3409 | // These are always l-values. | ||||
3410 | valueKind = VK_LValue; | ||||
3411 | type = type.getNonReferenceType(); | ||||
3412 | |||||
3413 | // FIXME: Does the addition of const really only apply in | ||||
3414 | // potentially-evaluated contexts? Since the variable isn't actually | ||||
3415 | // captured in an unevaluated context, it seems that the answer is no. | ||||
3416 | if (!isUnevaluatedContext()) { | ||||
3417 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||
3418 | if (!CapturedType.isNull()) | ||||
3419 | type = CapturedType; | ||||
3420 | } | ||||
3421 | |||||
3422 | break; | ||||
3423 | } | ||||
3424 | |||||
3425 | case Decl::Binding: | ||||
3426 | // These are always lvalues. | ||||
3427 | valueKind = VK_LValue; | ||||
3428 | type = type.getNonReferenceType(); | ||||
3429 | break; | ||||
3430 | |||||
3431 | case Decl::Function: { | ||||
3432 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||
3433 | if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { | ||||
3434 | type = Context.BuiltinFnTy; | ||||
3435 | valueKind = VK_PRValue; | ||||
3436 | break; | ||||
3437 | } | ||||
3438 | } | ||||
3439 | |||||
3440 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||
3441 | |||||
3442 | // If we're referring to a function with an __unknown_anytype | ||||
3443 | // result type, make the entire expression __unknown_anytype. | ||||
3444 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||
3445 | type = Context.UnknownAnyTy; | ||||
3446 | valueKind = VK_PRValue; | ||||
3447 | break; | ||||
3448 | } | ||||
3449 | |||||
3450 | // Functions are l-values in C++. | ||||
3451 | if (getLangOpts().CPlusPlus) { | ||||
3452 | valueKind = VK_LValue; | ||||
3453 | break; | ||||
3454 | } | ||||
3455 | |||||
3456 | // C99 DR 316 says that, if a function type comes from a | ||||
3457 | // function definition (without a prototype), that type is only | ||||
3458 | // used for checking compatibility. Therefore, when referencing | ||||
3459 | // the function, we pretend that we don't have the full function | ||||
3460 | // type. | ||||
3461 | if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) | ||||
3462 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||
3463 | fty->getExtInfo()); | ||||
3464 | |||||
3465 | // Functions are r-values in C. | ||||
3466 | valueKind = VK_PRValue; | ||||
3467 | break; | ||||
3468 | } | ||||
3469 | |||||
3470 | case Decl::CXXDeductionGuide: | ||||
3471 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "clang/lib/Sema/SemaExpr.cpp", 3471); | ||||
3472 | |||||
3473 | case Decl::MSProperty: | ||||
3474 | case Decl::MSGuid: | ||||
3475 | case Decl::TemplateParamObject: | ||||
3476 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||
3477 | // capture in OpenMP, or duplicated between host and device? | ||||
3478 | valueKind = VK_LValue; | ||||
3479 | break; | ||||
3480 | |||||
3481 | case Decl::UnnamedGlobalConstant: | ||||
3482 | valueKind = VK_LValue; | ||||
3483 | break; | ||||
3484 | |||||
3485 | case Decl::CXXMethod: | ||||
3486 | // If we're referring to a method with an __unknown_anytype | ||||
3487 | // result type, make the entire expression __unknown_anytype. | ||||
3488 | // This should only be possible with a type written directly. | ||||
3489 | if (const FunctionProtoType *proto = | ||||
3490 | dyn_cast<FunctionProtoType>(VD->getType())) | ||||
3491 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||
3492 | type = Context.UnknownAnyTy; | ||||
3493 | valueKind = VK_PRValue; | ||||
3494 | break; | ||||
3495 | } | ||||
3496 | |||||
3497 | // C++ methods are l-values if static, r-values if non-static. | ||||
3498 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||
3499 | valueKind = VK_LValue; | ||||
3500 | break; | ||||
3501 | } | ||||
3502 | [[fallthrough]]; | ||||
3503 | |||||
3504 | case Decl::CXXConversion: | ||||
3505 | case Decl::CXXDestructor: | ||||
3506 | case Decl::CXXConstructor: | ||||
3507 | valueKind = VK_PRValue; | ||||
3508 | break; | ||||
3509 | } | ||||
3510 | |||||
3511 | auto *E = | ||||
3512 | BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||
3513 | /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs); | ||||
3514 | // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We | ||||
3515 | // wrap a DeclRefExpr referring to an invalid decl with a dependent-type | ||||
3516 | // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus | ||||
3517 | // diagnostics). | ||||
3518 | if (VD->isInvalidDecl() && E) | ||||
3519 | return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E}); | ||||
3520 | return E; | ||||
3521 | } | ||||
3522 | |||||
3523 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||
3524 | SmallString<32> &Target) { | ||||
3525 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||
3526 | char *ResultPtr = &Target[0]; | ||||
3527 | const llvm::UTF8 *ErrorPtr; | ||||
3528 | bool success = | ||||
3529 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||
3530 | (void)success; | ||||
3531 | assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail ("success", "clang/lib/Sema/SemaExpr.cpp", 3531, __extension__ __PRETTY_FUNCTION__)); | ||||
3532 | Target.resize(ResultPtr - &Target[0]); | ||||
3533 | } | ||||
3534 | |||||
3535 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||
3536 | PredefinedExpr::IdentKind IK) { | ||||
3537 | // Pick the current block, lambda, captured statement or function. | ||||
3538 | Decl *currentDecl = nullptr; | ||||
3539 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||
3540 | currentDecl = BSI->TheDecl; | ||||
3541 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||
3542 | currentDecl = LSI->CallOperator; | ||||
3543 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||
3544 | currentDecl = CSI->TheCapturedDecl; | ||||
3545 | else | ||||
3546 | currentDecl = getCurFunctionOrMethodDecl(); | ||||
3547 | |||||
3548 | if (!currentDecl) { | ||||
3549 | Diag(Loc, diag::ext_predef_outside_function); | ||||
3550 | currentDecl = Context.getTranslationUnitDecl(); | ||||
3551 | } | ||||
3552 | |||||
3553 | QualType ResTy; | ||||
3554 | StringLiteral *SL = nullptr; | ||||
3555 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||
3556 | ResTy = Context.DependentTy; | ||||
3557 | else { | ||||
3558 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||
3559 | // the string. | ||||
3560 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||
3561 | unsigned Length = Str.length(); | ||||
3562 | |||||
3563 | llvm::APInt LengthI(32, Length + 1); | ||||
3564 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||
3565 | ResTy = | ||||
3566 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||
3567 | SmallString<32> RawChars; | ||||
3568 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||
3569 | Str, RawChars); | ||||
3570 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3571 | ArrayType::Normal, | ||||
3572 | /*IndexTypeQuals*/ 0); | ||||
3573 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||
3574 | /*Pascal*/ false, ResTy, Loc); | ||||
3575 | } else { | ||||
3576 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||
3577 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3578 | ArrayType::Normal, | ||||
3579 | /*IndexTypeQuals*/ 0); | ||||
3580 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary, | ||||
3581 | /*Pascal*/ false, ResTy, Loc); | ||||
3582 | } | ||||
3583 | } | ||||
3584 | |||||
3585 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||
3586 | } | ||||
3587 | |||||
3588 | ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, | ||||
3589 | SourceLocation LParen, | ||||
3590 | SourceLocation RParen, | ||||
3591 | TypeSourceInfo *TSI) { | ||||
3592 | return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); | ||||
3593 | } | ||||
3594 | |||||
3595 | ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, | ||||
3596 | SourceLocation LParen, | ||||
3597 | SourceLocation RParen, | ||||
3598 | ParsedType ParsedTy) { | ||||
3599 | TypeSourceInfo *TSI = nullptr; | ||||
3600 | QualType Ty = GetTypeFromParser(ParsedTy, &TSI); | ||||
3601 | |||||
3602 | if (Ty.isNull()) | ||||
3603 | return ExprError(); | ||||
3604 | if (!TSI) | ||||
3605 | TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); | ||||
3606 | |||||
3607 | return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); | ||||
3608 | } | ||||
3609 | |||||
3610 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||
3611 | PredefinedExpr::IdentKind IK; | ||||
3612 | |||||
3613 | switch (Kind) { | ||||
3614 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "clang/lib/Sema/SemaExpr.cpp", 3614); | ||||
3615 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||
3616 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||
3617 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||
3618 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||
3619 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||
3620 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||
3621 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||
3622 | } | ||||
3623 | |||||
3624 | return BuildPredefinedExpr(Loc, IK); | ||||
3625 | } | ||||
3626 | |||||
3627 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||
3628 | SmallString<16> CharBuffer; | ||||
3629 | bool Invalid = false; | ||||
3630 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||
3631 | if (Invalid) | ||||
3632 | return ExprError(); | ||||
3633 | |||||
3634 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||
3635 | PP, Tok.getKind()); | ||||
3636 | if (Literal.hadError()) | ||||
3637 | return ExprError(); | ||||
3638 | |||||
3639 | QualType Ty; | ||||
3640 | if (Literal.isWide()) | ||||
3641 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||
3642 | else if (Literal.isUTF8() && getLangOpts().C2x) | ||||
3643 | Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x | ||||
3644 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||
3645 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||
3646 | else if (Literal.isUTF16()) | ||||
3647 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||
3648 | else if (Literal.isUTF32()) | ||||
3649 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||
3650 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||
3651 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||
3652 | else | ||||
3653 | Ty = Context.CharTy; // 'x' -> char in C++; | ||||
3654 | // u8'x' -> char in C11-C17 and in C++ without char8_t. | ||||
3655 | |||||
3656 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||
3657 | if (Literal.isWide()) | ||||
3658 | Kind = CharacterLiteral::Wide; | ||||
3659 | else if (Literal.isUTF16()) | ||||
3660 | Kind = CharacterLiteral::UTF16; | ||||
3661 | else if (Literal.isUTF32()) | ||||
3662 | Kind = CharacterLiteral::UTF32; | ||||
3663 | else if (Literal.isUTF8()) | ||||
3664 | Kind = CharacterLiteral::UTF8; | ||||
3665 | |||||
3666 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||
3667 | Tok.getLocation()); | ||||
3668 | |||||
3669 | if (Literal.getUDSuffix().empty()) | ||||
3670 | return Lit; | ||||
3671 | |||||
3672 | // We're building a user-defined literal. | ||||
3673 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3674 | SourceLocation UDSuffixLoc = | ||||
3675 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3676 | |||||
3677 | // Make sure we're allowed user-defined literals here. | ||||
3678 | if (!UDLScope) | ||||
3679 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||
3680 | |||||
3681 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||
3682 | // operator "" X (ch) | ||||
3683 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||
3684 | Lit, Tok.getLocation()); | ||||
3685 | } | ||||
3686 | |||||
3687 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||
3688 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3689 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||
3690 | Context.IntTy, Loc); | ||||
3691 | } | ||||
3692 | |||||
3693 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||
3694 | QualType Ty, SourceLocation Loc) { | ||||
3695 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||
3696 | |||||
3697 | using llvm::APFloat; | ||||
3698 | APFloat Val(Format); | ||||
3699 | |||||
3700 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||
3701 | |||||
3702 | // Overflow is always an error, but underflow is only an error if | ||||
3703 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||
3704 | if ((result & APFloat::opOverflow) || | ||||
3705 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||
3706 | unsigned diagnostic; | ||||
3707 | SmallString<20> buffer; | ||||
3708 | if (result & APFloat::opOverflow) { | ||||
3709 | diagnostic = diag::warn_float_overflow; | ||||
3710 | APFloat::getLargest(Format).toString(buffer); | ||||
3711 | } else { | ||||
3712 | diagnostic = diag::warn_float_underflow; | ||||
3713 | APFloat::getSmallest(Format).toString(buffer); | ||||
3714 | } | ||||
3715 | |||||
3716 | S.Diag(Loc, diagnostic) | ||||
3717 | << Ty | ||||
3718 | << StringRef(buffer.data(), buffer.size()); | ||||
3719 | } | ||||
3720 | |||||
3721 | bool isExact = (result == APFloat::opOK); | ||||
3722 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||
3723 | } | ||||
3724 | |||||
3725 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||
3726 | assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression") ? void (0) : __assert_fail ("E && \"Invalid expression\"" , "clang/lib/Sema/SemaExpr.cpp", 3726, __extension__ __PRETTY_FUNCTION__ )); | ||||
3727 | |||||
3728 | if (E->isValueDependent()) | ||||
3729 | return false; | ||||
3730 | |||||
3731 | QualType QT = E->getType(); | ||||
3732 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||
3733 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||
3734 | return true; | ||||
3735 | } | ||||
3736 | |||||
3737 | llvm::APSInt ValueAPS; | ||||
3738 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||
3739 | |||||
3740 | if (R.isInvalid()) | ||||
3741 | return true; | ||||
3742 | |||||
3743 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||
3744 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||
3745 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||
3746 | << toString(ValueAPS, 10) << ValueIsPositive; | ||||
3747 | return true; | ||||
3748 | } | ||||
3749 | |||||
3750 | return false; | ||||
3751 | } | ||||
3752 | |||||
3753 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||
3754 | // Fast path for a single digit (which is quite common). A single digit | ||||
3755 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||
3756 | if (Tok.getLength() == 1) { | ||||
3757 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||
3758 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||
3759 | } | ||||
3760 | |||||
3761 | SmallString<128> SpellingBuffer; | ||||
3762 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||
3763 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||
3764 | // returns a StringRef to the memory buffer, it should have a null char at | ||||
3765 | // the EOF, so it is also safe. | ||||
3766 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||
3767 | |||||
3768 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||
3769 | bool Invalid = false; | ||||
3770 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||
3771 | if (Invalid) | ||||
3772 | return ExprError(); | ||||
3773 | |||||
3774 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||
3775 | PP.getSourceManager(), PP.getLangOpts(), | ||||
3776 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||
3777 | if (Literal.hadError) | ||||
3778 | return ExprError(); | ||||
3779 | |||||
3780 | if (Literal.hasUDSuffix()) { | ||||
3781 | // We're building a user-defined literal. | ||||
3782 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3783 | SourceLocation UDSuffixLoc = | ||||
3784 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3785 | |||||
3786 | // Make sure we're allowed user-defined literals here. | ||||
3787 | if (!UDLScope) | ||||
3788 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||
3789 | |||||
3790 | QualType CookedTy; | ||||
3791 | if (Literal.isFloatingLiteral()) { | ||||
3792 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||
3793 | // long double, the literal is treated as a call of the form | ||||
3794 | // operator "" X (f L) | ||||
3795 | CookedTy = Context.LongDoubleTy; | ||||
3796 | } else { | ||||
3797 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||
3798 | // unsigned long long, the literal is treated as a call of the form | ||||
3799 | // operator "" X (n ULL) | ||||
3800 | CookedTy = Context.UnsignedLongLongTy; | ||||
3801 | } | ||||
3802 | |||||
3803 | DeclarationName OpName = | ||||
3804 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
3805 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
3806 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
3807 | |||||
3808 | SourceLocation TokLoc = Tok.getLocation(); | ||||
3809 | |||||
3810 | // Perform literal operator lookup to determine if we're building a raw | ||||
3811 | // literal or a cooked one. | ||||
3812 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
3813 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||
3814 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||
3815 | /*AllowStringTemplatePack*/ false, | ||||
3816 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||
3817 | case LOLR_ErrorNoDiagnostic: | ||||
3818 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||
3819 | // GNU extension producing _Complex types. | ||||
3820 | break; | ||||
3821 | case LOLR_Error: | ||||
3822 | return ExprError(); | ||||
3823 | case LOLR_Cooked: { | ||||
3824 | Expr *Lit; | ||||
3825 | if (Literal.isFloatingLiteral()) { | ||||
3826 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||
3827 | } else { | ||||
3828 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||
3829 | if (Literal.GetIntegerValue(ResultVal)) | ||||
3830 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3831 | << /* Unsigned */ 1; | ||||
3832 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||
3833 | Tok.getLocation()); | ||||
3834 | } | ||||
3835 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3836 | } | ||||
3837 | |||||
3838 | case LOLR_Raw: { | ||||
3839 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||
3840 | // literal is treated as a call of the form | ||||
3841 | // operator "" X ("n") | ||||
3842 | unsigned Length = Literal.getUDSuffixOffset(); | ||||
3843 | QualType StrTy = Context.getConstantArrayType( | ||||
3844 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||
3845 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||
3846 | Expr *Lit = | ||||
3847 | StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length), | ||||
3848 | StringLiteral::Ordinary, | ||||
3849 | /*Pascal*/ false, StrTy, &TokLoc, 1); | ||||
3850 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3851 | } | ||||
3852 | |||||
3853 | case LOLR_Template: { | ||||
3854 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||
3855 | // template), L is treated as a call fo the form | ||||
3856 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||
3857 | // where n is the source character sequence c1 c2 ... ck. | ||||
3858 | TemplateArgumentListInfo ExplicitArgs; | ||||
3859 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||
3860 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||
3861 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
3862 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||
3863 | Value = TokSpelling[I]; | ||||
3864 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||
3865 | TemplateArgumentLocInfo ArgInfo; | ||||
3866 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
3867 | } | ||||
3868 | return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc, | ||||
3869 | &ExplicitArgs); | ||||
3870 | } | ||||
3871 | case LOLR_StringTemplatePack: | ||||
3872 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 3872); | ||||
3873 | } | ||||
3874 | } | ||||
3875 | |||||
3876 | Expr *Res; | ||||
3877 | |||||
3878 | if (Literal.isFixedPointLiteral()) { | ||||
3879 | QualType Ty; | ||||
3880 | |||||
3881 | if (Literal.isAccum) { | ||||
3882 | if (Literal.isHalf) { | ||||
3883 | Ty = Context.ShortAccumTy; | ||||
3884 | } else if (Literal.isLong) { | ||||
3885 | Ty = Context.LongAccumTy; | ||||
3886 | } else { | ||||
3887 | Ty = Context.AccumTy; | ||||
3888 | } | ||||
3889 | } else if (Literal.isFract) { | ||||
3890 | if (Literal.isHalf) { | ||||
3891 | Ty = Context.ShortFractTy; | ||||
3892 | } else if (Literal.isLong) { | ||||
3893 | Ty = Context.LongFractTy; | ||||
3894 | } else { | ||||
3895 | Ty = Context.FractTy; | ||||
3896 | } | ||||
3897 | } | ||||
3898 | |||||
3899 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||
3900 | |||||
3901 | bool isSigned = !Literal.isUnsigned; | ||||
3902 | unsigned scale = Context.getFixedPointScale(Ty); | ||||
3903 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||
3904 | |||||
3905 | llvm::APInt Val(bit_width, 0, isSigned); | ||||
3906 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||
3907 | bool ValIsZero = Val.isZero() && !Overflowed; | ||||
3908 | |||||
3909 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||
3910 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||
3911 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||
3912 | // representable values for its type, with exception for constants of a | ||||
3913 | // fract type with a value of exactly 1; such a constant shall denote | ||||
3914 | // the maximal value for the type. | ||||
3915 | --Val; | ||||
3916 | else if (Val.ugt(MaxVal) || Overflowed) | ||||
3917 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||
3918 | |||||
3919 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||
3920 | Tok.getLocation(), scale); | ||||
3921 | } else if (Literal.isFloatingLiteral()) { | ||||
3922 | QualType Ty; | ||||
3923 | if (Literal.isHalf){ | ||||
3924 | if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) | ||||
3925 | Ty = Context.HalfTy; | ||||
3926 | else { | ||||
3927 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||
3928 | return ExprError(); | ||||
3929 | } | ||||
3930 | } else if (Literal.isFloat) | ||||
3931 | Ty = Context.FloatTy; | ||||
3932 | else if (Literal.isLong) | ||||
3933 | Ty = Context.LongDoubleTy; | ||||
3934 | else if (Literal.isFloat16) | ||||
3935 | Ty = Context.Float16Ty; | ||||
3936 | else if (Literal.isFloat128) | ||||
3937 | Ty = Context.Float128Ty; | ||||
3938 | else | ||||
3939 | Ty = Context.DoubleTy; | ||||
3940 | |||||
3941 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||
3942 | |||||
3943 | if (Ty == Context.DoubleTy) { | ||||
3944 | if (getLangOpts().SinglePrecisionConstants) { | ||||
3945 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||
3946 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3947 | } | ||||
3948 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( | ||||
3949 | "cl_khr_fp64", getLangOpts())) { | ||||
3950 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||
3951 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) | ||||
3952 | << (getLangOpts().getOpenCLCompatibleVersion() >= 300); | ||||
3953 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3954 | } | ||||
3955 | } | ||||
3956 | } else if (!Literal.isIntegerLiteral()) { | ||||
3957 | return ExprError(); | ||||
3958 | } else { | ||||
3959 | QualType Ty; | ||||
3960 | |||||
3961 | // 'z/uz' literals are a C++2b feature. | ||||
3962 | if (Literal.isSizeT) | ||||
3963 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus | ||||
3964 | ? getLangOpts().CPlusPlus2b | ||||
3965 | ? diag::warn_cxx20_compat_size_t_suffix | ||||
3966 | : diag::ext_cxx2b_size_t_suffix | ||||
3967 | : diag::err_cxx2b_size_t_suffix); | ||||
3968 | |||||
3969 | // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, | ||||
3970 | // but we do not currently support the suffix in C++ mode because it's not | ||||
3971 | // entirely clear whether WG21 will prefer this suffix to return a library | ||||
3972 | // type such as std::bit_int instead of returning a _BitInt. | ||||
3973 | if (Literal.isBitInt && !getLangOpts().CPlusPlus) | ||||
3974 | PP.Diag(Tok.getLocation(), getLangOpts().C2x | ||||
3975 | ? diag::warn_c2x_compat_bitint_suffix | ||||
3976 | : diag::ext_c2x_bitint_suffix); | ||||
3977 | |||||
3978 | // Get the value in the widest-possible width. What is "widest" depends on | ||||
3979 | // whether the literal is a bit-precise integer or not. For a bit-precise | ||||
3980 | // integer type, try to scan the source to determine how many bits are | ||||
3981 | // needed to represent the value. This may seem a bit expensive, but trying | ||||
3982 | // to get the integer value from an overly-wide APInt is *extremely* | ||||
3983 | // expensive, so the naive approach of assuming | ||||
3984 | // llvm::IntegerType::MAX_INT_BITS is a big performance hit. | ||||
3985 | unsigned BitsNeeded = | ||||
3986 | Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( | ||||
3987 | Literal.getLiteralDigits(), Literal.getRadix()) | ||||
3988 | : Context.getTargetInfo().getIntMaxTWidth(); | ||||
3989 | llvm::APInt ResultVal(BitsNeeded, 0); | ||||
3990 | |||||
3991 | if (Literal.GetIntegerValue(ResultVal)) { | ||||
3992 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||
3993 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3994 | << /* Unsigned */ 1; | ||||
3995 | Ty = Context.UnsignedLongLongTy; | ||||
3996 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal .getBitWidth() && "long long is not intmax_t?") ? void (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "clang/lib/Sema/SemaExpr.cpp", 3997, __extension__ __PRETTY_FUNCTION__ )) | ||||
3997 | "long long is not intmax_t?")(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal .getBitWidth() && "long long is not intmax_t?") ? void (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "clang/lib/Sema/SemaExpr.cpp", 3997, __extension__ __PRETTY_FUNCTION__ )); | ||||
3998 | } else { | ||||
3999 | // If this value fits into a ULL, try to figure out what else it fits into | ||||
4000 | // according to the rules of C99 6.4.4.1p5. | ||||
4001 | |||||
4002 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||
4003 | // be an unsigned int. | ||||
4004 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||
4005 | |||||
4006 | // Check from smallest to largest, picking the smallest type we can. | ||||
4007 | unsigned Width = 0; | ||||
4008 | |||||
4009 | // Microsoft specific integer suffixes are explicitly sized. | ||||
4010 | if (Literal.MicrosoftInteger) { | ||||
4011 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||
4012 | Width = 8; | ||||
4013 | Ty = Context.CharTy; | ||||
4014 | } else { | ||||
4015 | Width = Literal.MicrosoftInteger; | ||||
4016 | Ty = Context.getIntTypeForBitwidth(Width, | ||||
4017 | /*Signed=*/!Literal.isUnsigned); | ||||
4018 | } | ||||
4019 | } | ||||
4020 | |||||
4021 | // Bit-precise integer literals are automagically-sized based on the | ||||
4022 | // width required by the literal. | ||||
4023 | if (Literal.isBitInt) { | ||||
4024 | // The signed version has one more bit for the sign value. There are no | ||||
4025 | // zero-width bit-precise integers, even if the literal value is 0. | ||||
4026 | Width = std::max(ResultVal.getActiveBits(), 1u) + | ||||
4027 | (Literal.isUnsigned ? 0u : 1u); | ||||
4028 | |||||
4029 | // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, | ||||
4030 | // and reset the type to the largest supported width. | ||||
4031 | unsigned int MaxBitIntWidth = | ||||
4032 | Context.getTargetInfo().getMaxBitIntWidth(); | ||||
4033 | if (Width > MaxBitIntWidth) { | ||||
4034 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
4035 | << Literal.isUnsigned; | ||||
4036 | Width = MaxBitIntWidth; | ||||
4037 | } | ||||
4038 | |||||
4039 | // Reset the result value to the smaller APInt and select the correct | ||||
4040 | // type to be used. Note, we zext even for signed values because the | ||||
4041 | // literal itself is always an unsigned value (a preceeding - is a | ||||
4042 | // unary operator, not part of the literal). | ||||
4043 | ResultVal = ResultVal.zextOrTrunc(Width); | ||||
4044 | Ty = Context.getBitIntType(Literal.isUnsigned, Width); | ||||
4045 | } | ||||
4046 | |||||
4047 | // Check C++2b size_t literals. | ||||
4048 | if (Literal.isSizeT) { | ||||
4049 | assert(!Literal.MicrosoftInteger &&(static_cast <bool> (!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals") ? void (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "clang/lib/Sema/SemaExpr.cpp", 4050, __extension__ __PRETTY_FUNCTION__ )) | ||||
4050 | "size_t literals can't be Microsoft literals")(static_cast <bool> (!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals") ? void (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "clang/lib/Sema/SemaExpr.cpp", 4050, __extension__ __PRETTY_FUNCTION__ )); | ||||
4051 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( | ||||
4052 | Context.getTargetInfo().getSizeType()); | ||||
4053 | |||||
4054 | // Does it fit in size_t? | ||||
4055 | if (ResultVal.isIntN(SizeTSize)) { | ||||
4056 | // Does it fit in ssize_t? | ||||
4057 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) | ||||
4058 | Ty = Context.getSignedSizeType(); | ||||
4059 | else if (AllowUnsigned) | ||||
4060 | Ty = Context.getSizeType(); | ||||
4061 | Width = SizeTSize; | ||||
4062 | } | ||||
4063 | } | ||||
4064 | |||||
4065 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && | ||||
4066 | !Literal.isSizeT) { | ||||
4067 | // Are int/unsigned possibilities? | ||||
4068 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
4069 | |||||
4070 | // Does it fit in a unsigned int? | ||||
4071 | if (ResultVal.isIntN(IntSize)) { | ||||
4072 | // Does it fit in a signed int? | ||||
4073 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||
4074 | Ty = Context.IntTy; | ||||
4075 | else if (AllowUnsigned) | ||||
4076 | Ty = Context.UnsignedIntTy; | ||||
4077 | Width = IntSize; | ||||
4078 | } | ||||
4079 | } | ||||
4080 | |||||
4081 | // Are long/unsigned long possibilities? | ||||
4082 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { | ||||
4083 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||
4084 | |||||
4085 | // Does it fit in a unsigned long? | ||||
4086 | if (ResultVal.isIntN(LongSize)) { | ||||
4087 | // Does it fit in a signed long? | ||||
4088 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||
4089 | Ty = Context.LongTy; | ||||
4090 | else if (AllowUnsigned) | ||||
4091 | Ty = Context.UnsignedLongTy; | ||||
4092 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||
4093 | // is compatible. | ||||
4094 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||
4095 | const unsigned LongLongSize = | ||||
4096 | Context.getTargetInfo().getLongLongWidth(); | ||||
4097 | Diag(Tok.getLocation(), | ||||
4098 | getLangOpts().CPlusPlus | ||||
4099 | ? Literal.isLong | ||||
4100 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||
4101 | : /*C++98 UB*/ diag:: | ||||
4102 | ext_old_implicitly_unsigned_long_cxx | ||||
4103 | : diag::warn_old_implicitly_unsigned_long) | ||||
4104 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||
4105 | : /*will be ill-formed*/ 1); | ||||
4106 | Ty = Context.UnsignedLongTy; | ||||
4107 | } | ||||
4108 | Width = LongSize; | ||||
4109 | } | ||||
4110 | } | ||||
4111 | |||||
4112 | // Check long long if needed. | ||||
4113 | if (Ty.isNull() && !Literal.isSizeT) { | ||||
4114 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||
4115 | |||||
4116 | // Does it fit in a unsigned long long? | ||||
4117 | if (ResultVal.isIntN(LongLongSize)) { | ||||
4118 | // Does it fit in a signed long long? | ||||
4119 | // To be compatible with MSVC, hex integer literals ending with the | ||||
4120 | // LL or i64 suffix are always signed in Microsoft mode. | ||||
4121 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||
4122 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||
4123 | Ty = Context.LongLongTy; | ||||
4124 | else if (AllowUnsigned) | ||||
4125 | Ty = Context.UnsignedLongLongTy; | ||||
4126 | Width = LongLongSize; | ||||
4127 | |||||
4128 | // 'long long' is a C99 or C++11 feature, whether the literal | ||||
4129 | // explicitly specified 'long long' or we needed the extra width. | ||||
4130 | if (getLangOpts().CPlusPlus) | ||||
4131 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 | ||||
4132 | ? diag::warn_cxx98_compat_longlong | ||||
4133 | : diag::ext_cxx11_longlong); | ||||
4134 | else if (!getLangOpts().C99) | ||||
4135 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||
4136 | } | ||||
4137 | } | ||||
4138 | |||||
4139 | // If we still couldn't decide a type, we either have 'size_t' literal | ||||
4140 | // that is out of range, or a decimal literal that does not fit in a | ||||
4141 | // signed long long and has no U suffix. | ||||
4142 | if (Ty.isNull()) { | ||||
4143 | if (Literal.isSizeT) | ||||
4144 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) | ||||
4145 | << Literal.isUnsigned; | ||||
4146 | else | ||||
4147 | Diag(Tok.getLocation(), | ||||
4148 | diag::ext_integer_literal_too_large_for_signed); | ||||
4149 | Ty = Context.UnsignedLongLongTy; | ||||
4150 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||
4151 | } | ||||
4152 | |||||
4153 | if (ResultVal.getBitWidth() != Width) | ||||
4154 | ResultVal = ResultVal.trunc(Width); | ||||
4155 | } | ||||
4156 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||
4157 | } | ||||
4158 | |||||
4159 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||
4160 | if (Literal.isImaginary) { | ||||
4161 | Res = new (Context) ImaginaryLiteral(Res, | ||||
4162 | Context.getComplexType(Res->getType())); | ||||
4163 | |||||
4164 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||
4165 | } | ||||
4166 | return Res; | ||||
4167 | } | ||||
4168 | |||||
4169 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||
4170 | assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr" ) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "clang/lib/Sema/SemaExpr.cpp", 4170, __extension__ __PRETTY_FUNCTION__ )); | ||||
4171 | QualType ExprTy = E->getType(); | ||||
4172 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && | ||||
4173 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) | ||||
4174 | return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); | ||||
4175 | return new (Context) ParenExpr(L, R, E); | ||||
4176 | } | ||||
4177 | |||||
4178 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||
4179 | SourceLocation Loc, | ||||
4180 | SourceRange ArgRange) { | ||||
4181 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||
4182 | // scalar or vector data type argument..." | ||||
4183 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||
4184 | // type (C99 6.2.5p18) or void. | ||||
4185 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||
4186 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||
4187 | << T << ArgRange; | ||||
4188 | return true; | ||||
4189 | } | ||||
4190 | |||||
4191 | assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType ()) && "Scalar types should always be complete") ? void (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "clang/lib/Sema/SemaExpr.cpp", 4192, __extension__ __PRETTY_FUNCTION__ )) | ||||
4192 | "Scalar types should always be complete")(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType ()) && "Scalar types should always be complete") ? void (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "clang/lib/Sema/SemaExpr.cpp", 4192, __extension__ __PRETTY_FUNCTION__ )); | ||||
4193 | return false; | ||||
4194 | } | ||||
4195 | |||||
4196 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||
4197 | SourceLocation Loc, | ||||
4198 | SourceRange ArgRange, | ||||
4199 | UnaryExprOrTypeTrait TraitKind) { | ||||
4200 | // Invalid types must be hard errors for SFINAE in C++. | ||||
4201 | if (S.LangOpts.CPlusPlus) | ||||
4202 | return true; | ||||
4203 | |||||
4204 | // C99 6.5.3.4p1: | ||||
4205 | if (T->isFunctionType() && | ||||
4206 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||
4207 | TraitKind == UETT_PreferredAlignOf)) { | ||||
4208 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||
4209 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||
4210 | << getTraitSpelling(TraitKind) << ArgRange; | ||||
4211 | return false; | ||||
4212 | } | ||||
4213 | |||||
4214 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||
4215 | // this is an error (OpenCL v1.1 s6.3.k) | ||||
4216 | if (T->isVoidType()) { | ||||
4217 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||
4218 | : diag::ext_sizeof_alignof_void_type; | ||||
4219 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||
4220 | return false; | ||||
4221 | } | ||||
4222 | |||||
4223 | return true; | ||||
4224 | } | ||||
4225 | |||||
4226 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||
4227 | SourceLocation Loc, | ||||
4228 | SourceRange ArgRange, | ||||
4229 | UnaryExprOrTypeTrait TraitKind) { | ||||
4230 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||
4231 | // runtime doesn't allow it. | ||||
4232 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||
4233 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||
4234 | << T << (TraitKind == UETT_SizeOf) | ||||
4235 | << ArgRange; | ||||
4236 | return true; | ||||
4237 | } | ||||
4238 | |||||
4239 | return false; | ||||
4240 | } | ||||
4241 | |||||
4242 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||
4243 | /// pointer type is equal to T) and emit a warning if it is. | ||||
4244 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||
4245 | Expr *E) { | ||||
4246 | // Don't warn if the operation changed the type. | ||||
4247 | if (T != E->getType()) | ||||
4248 | return; | ||||
4249 | |||||
4250 | // Now look for array decays. | ||||
4251 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||
4252 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||
4253 | return; | ||||
4254 | |||||
4255 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||
4256 | << ICE->getType() | ||||
4257 | << ICE->getSubExpr()->getType(); | ||||
4258 | } | ||||
4259 | |||||
4260 | /// Check the constraints on expression operands to unary type expression | ||||
4261 | /// and type traits. | ||||
4262 | /// | ||||
4263 | /// Completes any types necessary and validates the constraints on the operand | ||||
4264 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||
4265 | /// the expression as it completes the type for that expression through template | ||||
4266 | /// instantiation, etc. | ||||
4267 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||
4268 | UnaryExprOrTypeTrait ExprKind) { | ||||
4269 | QualType ExprTy = E->getType(); | ||||
4270 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp" , 4270, __extension__ __PRETTY_FUNCTION__)); | ||||
4271 | |||||
4272 | bool IsUnevaluatedOperand = | ||||
4273 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||
4274 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||
4275 | if (IsUnevaluatedOperand) { | ||||
4276 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||
4277 | if (Result.isInvalid()) | ||||
4278 | return true; | ||||
4279 | E = Result.get(); | ||||
4280 | } | ||||
4281 | |||||
4282 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||
4283 | // so side effects could result in unintended consequences. | ||||
4284 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||
4285 | // used to build SFINAE gadgets. | ||||
4286 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||
4287 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||
4288 | !E->isInstantiationDependent() && | ||||
4289 | !E->getType()->isVariableArrayType() && | ||||
4290 | E->HasSideEffects(Context, false)) | ||||
4291 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||
4292 | |||||
4293 | if (ExprKind == UETT_VecStep) | ||||
4294 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4295 | E->getSourceRange()); | ||||
4296 | |||||
4297 | // Explicitly list some types as extensions. | ||||
4298 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4299 | E->getSourceRange(), ExprKind)) | ||||
4300 | return false; | ||||
4301 | |||||
4302 | // 'alignof' applied to an expression only requires the base element type of | ||||
4303 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||
4304 | // be complete (and will attempt to complete it if it's an array of unknown | ||||
4305 | // bound). | ||||
4306 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4307 | if (RequireCompleteSizedType( | ||||
4308 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||
4309 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4310 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4311 | return true; | ||||
4312 | } else { | ||||
4313 | if (RequireCompleteSizedExprType( | ||||
4314 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4315 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4316 | return true; | ||||
4317 | } | ||||
4318 | |||||
4319 | // Completing the expression's type may have changed it. | ||||
4320 | ExprTy = E->getType(); | ||||
4321 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp" , 4321, __extension__ __PRETTY_FUNCTION__)); | ||||
4322 | |||||
4323 | if (ExprTy->isFunctionType()) { | ||||
4324 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||
4325 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||
4326 | return true; | ||||
4327 | } | ||||
4328 | |||||
4329 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||
4330 | E->getSourceRange(), ExprKind)) | ||||
4331 | return true; | ||||
4332 | |||||
4333 | if (ExprKind == UETT_SizeOf) { | ||||
4334 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
4335 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||
4336 | QualType OType = PVD->getOriginalType(); | ||||
4337 | QualType Type = PVD->getType(); | ||||
4338 | if (Type->isPointerType() && OType->isArrayType()) { | ||||
4339 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||
4340 | << Type << OType; | ||||
4341 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||
4342 | } | ||||
4343 | } | ||||
4344 | } | ||||
4345 | |||||
4346 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||
4347 | // decays into a pointer and returns an unintended result. This is most | ||||
4348 | // likely a typo for "sizeof(array) op x". | ||||
4349 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||
4350 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4351 | BO->getLHS()); | ||||
4352 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4353 | BO->getRHS()); | ||||
4354 | } | ||||
4355 | } | ||||
4356 | |||||
4357 | return false; | ||||
4358 | } | ||||
4359 | |||||
4360 | /// Check the constraints on operands to unary expression and type | ||||
4361 | /// traits. | ||||
4362 | /// | ||||
4363 | /// This will complete any types necessary, and validate the various constraints | ||||
4364 | /// on those operands. | ||||
4365 | /// | ||||
4366 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||
4367 | /// C99 6.3.2.1p[2-4] all state: | ||||
4368 | /// Except when it is the operand of the sizeof operator ... | ||||
4369 | /// | ||||
4370 | /// C++ [expr.sizeof]p4 | ||||
4371 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||
4372 | /// standard conversions are not applied to the operand of sizeof. | ||||
4373 | /// | ||||
4374 | /// This policy is followed for all of the unary trait expressions. | ||||
4375 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||
4376 | SourceLocation OpLoc, | ||||
4377 | SourceRange ExprRange, | ||||
4378 | UnaryExprOrTypeTrait ExprKind) { | ||||
4379 | if (ExprType->isDependentType()) | ||||
4380 | return false; | ||||
4381 | |||||
4382 | // C++ [expr.sizeof]p2: | ||||
4383 | // When applied to a reference or a reference type, the result | ||||
4384 | // is the size of the referenced type. | ||||
4385 | // C++11 [expr.alignof]p3: | ||||
4386 | // When alignof is applied to a reference type, the result | ||||
4387 | // shall be the alignment of the referenced type. | ||||
4388 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||
4389 | ExprType = Ref->getPointeeType(); | ||||
4390 | |||||
4391 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||
4392 | // When alignof or _Alignof is applied to an array type, the result | ||||
4393 | // is the alignment of the element type. | ||||
4394 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||
4395 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||
4396 | ExprType = Context.getBaseElementType(ExprType); | ||||
4397 | |||||
4398 | if (ExprKind == UETT_VecStep) | ||||
4399 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||
4400 | |||||
4401 | // Explicitly list some types as extensions. | ||||
4402 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||
4403 | ExprKind)) | ||||
4404 | return false; | ||||
4405 | |||||
4406 | if (RequireCompleteSizedType( | ||||
4407 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4408 | getTraitSpelling(ExprKind), ExprRange)) | ||||
4409 | return true; | ||||
4410 | |||||
4411 | if (ExprType->isFunctionType()) { | ||||
4412 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||
4413 | << getTraitSpelling(ExprKind) << ExprRange; | ||||
4414 | return true; | ||||
4415 | } | ||||
4416 | |||||
4417 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||
4418 | ExprKind)) | ||||
4419 | return true; | ||||
4420 | |||||
4421 | return false; | ||||
4422 | } | ||||
4423 | |||||
4424 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||
4425 | // Cannot know anything else if the expression is dependent. | ||||
4426 | if (E->isTypeDependent()) | ||||
4427 | return false; | ||||
4428 | |||||
4429 | if (E->getObjectKind() == OK_BitField) { | ||||
4430 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||
4431 | << 1 << E->getSourceRange(); | ||||
4432 | return true; | ||||
4433 | } | ||||
4434 | |||||
4435 | ValueDecl *D = nullptr; | ||||
4436 | Expr *Inner = E->IgnoreParens(); | ||||
4437 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||
4438 | D = DRE->getDecl(); | ||||
4439 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||
4440 | D = ME->getMemberDecl(); | ||||
4441 | } | ||||
4442 | |||||
4443 | // If it's a field, require the containing struct to have a | ||||
4444 | // complete definition so that we can compute the layout. | ||||
4445 | // | ||||
4446 | // This can happen in C++11 onwards, either by naming the member | ||||
4447 | // in a way that is not transformed into a member access expression | ||||
4448 | // (in an unevaluated operand, for instance), or by naming the member | ||||
4449 | // in a trailing-return-type. | ||||
4450 | // | ||||
4451 | // For the record, since __alignof__ on expressions is a GCC | ||||
4452 | // extension, GCC seems to permit this but always gives the | ||||
4453 | // nonsensical answer 0. | ||||
4454 | // | ||||
4455 | // We don't really need the layout here --- we could instead just | ||||
4456 | // directly check for all the appropriate alignment-lowing | ||||
4457 | // attributes --- but that would require duplicating a lot of | ||||
4458 | // logic that just isn't worth duplicating for such a marginal | ||||
4459 | // use-case. | ||||
4460 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||
4461 | // Fast path this check, since we at least know the record has a | ||||
4462 | // definition if we can find a member of it. | ||||
4463 | if (!FD->getParent()->isCompleteDefinition()) { | ||||
4464 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||
4465 | << E->getSourceRange(); | ||||
4466 | return true; | ||||
4467 | } | ||||
4468 | |||||
4469 | // Otherwise, if it's a field, and the field doesn't have | ||||
4470 | // reference type, then it must have a complete type (or be a | ||||
4471 | // flexible array member, which we explicitly want to | ||||
4472 | // white-list anyway), which makes the following checks trivial. | ||||
4473 | if (!FD->getType()->isReferenceType()) | ||||
4474 | return false; | ||||
4475 | } | ||||
4476 | |||||
4477 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||
4478 | } | ||||
4479 | |||||
4480 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||
4481 | E = E->IgnoreParens(); | ||||
4482 | |||||
4483 | // Cannot know anything else if the expression is dependent. | ||||
4484 | if (E->isTypeDependent()) | ||||
4485 | return false; | ||||
4486 | |||||
4487 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||
4488 | } | ||||
4489 | |||||
4490 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||
4491 | CapturingScopeInfo *CSI) { | ||||
4492 | assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void (0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp" , 4492, __extension__ __PRETTY_FUNCTION__)); | ||||
4493 | assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail ("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4493, __extension__ __PRETTY_FUNCTION__)); | ||||
4494 | |||||
4495 | // We're going to walk down into the type and look for VLA expressions. | ||||
4496 | do { | ||||
4497 | const Type *Ty = T.getTypePtr(); | ||||
4498 | switch (Ty->getTypeClass()) { | ||||
4499 | #define TYPE(Class, Base) | ||||
4500 | #define ABSTRACT_TYPE(Class, Base) | ||||
4501 | #define NON_CANONICAL_TYPE(Class, Base) | ||||
4502 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||
4503 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||
4504 | #include "clang/AST/TypeNodes.inc" | ||||
4505 | T = QualType(); | ||||
4506 | break; | ||||
4507 | // These types are never variably-modified. | ||||
4508 | case Type::Builtin: | ||||
4509 | case Type::Complex: | ||||
4510 | case Type::Vector: | ||||
4511 | case Type::ExtVector: | ||||
4512 | case Type::ConstantMatrix: | ||||
4513 | case Type::Record: | ||||
4514 | case Type::Enum: | ||||
4515 | case Type::TemplateSpecialization: | ||||
4516 | case Type::ObjCObject: | ||||
4517 | case Type::ObjCInterface: | ||||
4518 | case Type::ObjCObjectPointer: | ||||
4519 | case Type::ObjCTypeParam: | ||||
4520 | case Type::Pipe: | ||||
4521 | case Type::BitInt: | ||||
4522 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "clang/lib/Sema/SemaExpr.cpp", 4522); | ||||
4523 | case Type::Elaborated: | ||||
4524 | T = cast<ElaboratedType>(Ty)->getNamedType(); | ||||
4525 | break; | ||||
4526 | case Type::Adjusted: | ||||
4527 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||
4528 | break; | ||||
4529 | case Type::Decayed: | ||||
4530 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||
4531 | break; | ||||
4532 | case Type::Pointer: | ||||
4533 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||
4534 | break; | ||||
4535 | case Type::BlockPointer: | ||||
4536 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||
4537 | break; | ||||
4538 | case Type::LValueReference: | ||||
4539 | case Type::RValueReference: | ||||
4540 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||
4541 | break; | ||||
4542 | case Type::MemberPointer: | ||||
4543 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||
4544 | break; | ||||
4545 | case Type::ConstantArray: | ||||
4546 | case Type::IncompleteArray: | ||||
4547 | // Losing element qualification here is fine. | ||||
4548 | T = cast<ArrayType>(Ty)->getElementType(); | ||||
4549 | break; | ||||
4550 | case Type::VariableArray: { | ||||
4551 | // Losing element qualification here is fine. | ||||
4552 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||
4553 | |||||
4554 | // Unknown size indication requires no size computation. | ||||
4555 | // Otherwise, evaluate and record it. | ||||
4556 | auto Size = VAT->getSizeExpr(); | ||||
4557 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||
4558 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||
4559 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||
4560 | |||||
4561 | T = VAT->getElementType(); | ||||
4562 | break; | ||||
4563 | } | ||||
4564 | case Type::FunctionProto: | ||||
4565 | case Type::FunctionNoProto: | ||||
4566 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||
4567 | break; | ||||
4568 | case Type::Paren: | ||||
4569 | case Type::TypeOf: | ||||
4570 | case Type::UnaryTransform: | ||||
4571 | case Type::Attributed: | ||||
4572 | case Type::BTFTagAttributed: | ||||
4573 | case Type::SubstTemplateTypeParm: | ||||
4574 | case Type::MacroQualified: | ||||
4575 | // Keep walking after single level desugaring. | ||||
4576 | T = T.getSingleStepDesugaredType(Context); | ||||
4577 | break; | ||||
4578 | case Type::Typedef: | ||||
4579 | T = cast<TypedefType>(Ty)->desugar(); | ||||
4580 | break; | ||||
4581 | case Type::Decltype: | ||||
4582 | T = cast<DecltypeType>(Ty)->desugar(); | ||||
4583 | break; | ||||
4584 | case Type::Using: | ||||
4585 | T = cast<UsingType>(Ty)->desugar(); | ||||
4586 | break; | ||||
4587 | case Type::Auto: | ||||
4588 | case Type::DeducedTemplateSpecialization: | ||||
4589 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||
4590 | break; | ||||
4591 | case Type::TypeOfExpr: | ||||
4592 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||
4593 | break; | ||||
4594 | case Type::Atomic: | ||||
4595 | T = cast<AtomicType>(Ty)->getValueType(); | ||||
4596 | break; | ||||
4597 | } | ||||
4598 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||
4599 | } | ||||
4600 | |||||
4601 | /// Build a sizeof or alignof expression given a type operand. | ||||
4602 | ExprResult | ||||
4603 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||
4604 | SourceLocation OpLoc, | ||||
4605 | UnaryExprOrTypeTrait ExprKind, | ||||
4606 | SourceRange R) { | ||||
4607 | if (!TInfo) | ||||
4608 | return ExprError(); | ||||
4609 | |||||
4610 | QualType T = TInfo->getType(); | ||||
4611 | |||||
4612 | if (!T->isDependentType() && | ||||
4613 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||
4614 | return ExprError(); | ||||
4615 | |||||
4616 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||
4617 | if (auto *TT = T->getAs<TypedefType>()) { | ||||
4618 | for (auto I = FunctionScopes.rbegin(), | ||||
4619 | E = std::prev(FunctionScopes.rend()); | ||||
4620 | I != E; ++I) { | ||||
4621 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
4622 | if (CSI == nullptr) | ||||
4623 | break; | ||||
4624 | DeclContext *DC = nullptr; | ||||
4625 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
4626 | DC = LSI->CallOperator; | ||||
4627 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
4628 | DC = CRSI->TheCapturedDecl; | ||||
4629 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
4630 | DC = BSI->TheDecl; | ||||
4631 | if (DC) { | ||||
4632 | if (DC->containsDecl(TT->getDecl())) | ||||
4633 | break; | ||||
4634 | captureVariablyModifiedType(Context, T, CSI); | ||||
4635 | } | ||||
4636 | } | ||||
4637 | } | ||||
4638 | } | ||||
4639 | |||||
4640 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4641 | if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && | ||||
4642 | TInfo->getType()->isVariablyModifiedType()) | ||||
4643 | TInfo = TransformToPotentiallyEvaluated(TInfo); | ||||
4644 | |||||
4645 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4646 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||
4647 | } | ||||
4648 | |||||
4649 | /// Build a sizeof or alignof expression given an expression | ||||
4650 | /// operand. | ||||
4651 | ExprResult | ||||
4652 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||
4653 | UnaryExprOrTypeTrait ExprKind) { | ||||
4654 | ExprResult PE = CheckPlaceholderExpr(E); | ||||
4655 | if (PE.isInvalid()) | ||||
4656 | return ExprError(); | ||||
4657 | |||||
4658 | E = PE.get(); | ||||
4659 | |||||
4660 | // Verify that the operand is valid. | ||||
4661 | bool isInvalid = false; | ||||
4662 | if (E->isTypeDependent()) { | ||||
4663 | // Delay type-checking for type-dependent expressions. | ||||
4664 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4665 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||
4666 | } else if (ExprKind == UETT_VecStep) { | ||||
4667 | isInvalid = CheckVecStepExpr(E); | ||||
4668 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||
4669 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||
4670 | isInvalid = true; | ||||
4671 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||
4672 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||
4673 | isInvalid = true; | ||||
4674 | } else { | ||||
4675 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||
4676 | } | ||||
4677 | |||||
4678 | if (isInvalid) | ||||
4679 | return ExprError(); | ||||
4680 | |||||
4681 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||
4682 | PE = TransformToPotentiallyEvaluated(E); | ||||
4683 | if (PE.isInvalid()) return ExprError(); | ||||
4684 | E = PE.get(); | ||||
4685 | } | ||||
4686 | |||||
4687 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4688 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4689 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||
4690 | } | ||||
4691 | |||||
4692 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||
4693 | /// expr and the same for @c alignof and @c __alignof | ||||
4694 | /// Note that the ArgRange is invalid if isType is false. | ||||
4695 | ExprResult | ||||
4696 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||
4697 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||
4698 | void *TyOrEx, SourceRange ArgRange) { | ||||
4699 | // If error parsing type, ignore. | ||||
4700 | if (!TyOrEx) return ExprError(); | ||||
4701 | |||||
4702 | if (IsType) { | ||||
4703 | TypeSourceInfo *TInfo; | ||||
4704 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||
4705 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||
4706 | } | ||||
4707 | |||||
4708 | Expr *ArgEx = (Expr *)TyOrEx; | ||||
4709 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||
4710 | return Result; | ||||
4711 | } | ||||
4712 | |||||
4713 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||
4714 | bool IsReal) { | ||||
4715 | if (V.get()->isTypeDependent()) | ||||
4716 | return S.Context.DependentTy; | ||||
4717 | |||||
4718 | // _Real and _Imag are only l-values for normal l-values. | ||||
4719 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||
4720 | V = S.DefaultLvalueConversion(V.get()); | ||||
4721 | if (V.isInvalid()) | ||||
4722 | return QualType(); | ||||
4723 | } | ||||
4724 | |||||
4725 | // These operators return the element type of a complex type. | ||||
4726 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||
4727 | return CT->getElementType(); | ||||
4728 | |||||
4729 | // Otherwise they pass through real integer and floating point types here. | ||||
4730 | if (V.get()->getType()->isArithmeticType()) | ||||
4731 | return V.get()->getType(); | ||||
4732 | |||||
4733 | // Test for placeholders. | ||||
4734 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||
4735 | if (PR.isInvalid()) return QualType(); | ||||
4736 | if (PR.get() != V.get()) { | ||||
4737 | V = PR; | ||||
4738 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||
4739 | } | ||||
4740 | |||||
4741 | // Reject anything else. | ||||
4742 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||
4743 | << (IsReal ? "__real" : "__imag"); | ||||
4744 | return QualType(); | ||||
4745 | } | ||||
4746 | |||||
4747 | |||||
4748 | |||||
4749 | ExprResult | ||||
4750 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
4751 | tok::TokenKind Kind, Expr *Input) { | ||||
4752 | UnaryOperatorKind Opc; | ||||
4753 | switch (Kind) { | ||||
4754 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp" , 4754); | ||||
4755 | case tok::plusplus: Opc = UO_PostInc; break; | ||||
4756 | case tok::minusminus: Opc = UO_PostDec; break; | ||||
4757 | } | ||||
4758 | |||||
4759 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||
4760 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||
4761 | if (Result.isInvalid()) return ExprError(); | ||||
4762 | Input = Result.get(); | ||||
4763 | |||||
4764 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||
4765 | } | ||||
4766 | |||||
4767 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||
4768 | /// | ||||
4769 | /// \return true on error | ||||
4770 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||
4771 | SourceLocation opLoc, | ||||
4772 | Expr *op) { | ||||
4773 | assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType ()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 4773, __extension__ __PRETTY_FUNCTION__ )); | ||||
4774 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||
4775 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||
4776 | return false; | ||||
4777 | |||||
4778 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||
4779 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||
4780 | << op->getSourceRange(); | ||||
4781 | return true; | ||||
4782 | } | ||||
4783 | |||||
4784 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||
4785 | auto *BaseNoParens = Base->IgnoreParens(); | ||||
4786 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||
4787 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||
4788 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||
4789 | } | ||||
4790 | |||||
4791 | // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. | ||||
4792 | // Typically this is DependentTy, but can sometimes be more precise. | ||||
4793 | // | ||||
4794 | // There are cases when we could determine a non-dependent type: | ||||
4795 | // - LHS and RHS may have non-dependent types despite being type-dependent | ||||
4796 | // (e.g. unbounded array static members of the current instantiation) | ||||
4797 | // - one may be a dependent-sized array with known element type | ||||
4798 | // - one may be a dependent-typed valid index (enum in current instantiation) | ||||
4799 | // | ||||
4800 | // We *always* return a dependent type, in such cases it is DependentTy. | ||||
4801 | // This avoids creating type-dependent expressions with non-dependent types. | ||||
4802 | // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 | ||||
4803 | static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, | ||||
4804 | const ASTContext &Ctx) { | ||||
4805 | assert(LHS->isTypeDependent() || RHS->isTypeDependent())(static_cast <bool> (LHS->isTypeDependent() || RHS-> isTypeDependent()) ? void (0) : __assert_fail ("LHS->isTypeDependent() || RHS->isTypeDependent()" , "clang/lib/Sema/SemaExpr.cpp", 4805, __extension__ __PRETTY_FUNCTION__ )); | ||||
4806 | QualType LTy = LHS->getType(), RTy = RHS->getType(); | ||||
4807 | QualType Result = Ctx.DependentTy; | ||||
4808 | if (RTy->isIntegralOrUnscopedEnumerationType()) { | ||||
4809 | if (const PointerType *PT = LTy->getAs<PointerType>()) | ||||
4810 | Result = PT->getPointeeType(); | ||||
4811 | else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) | ||||
4812 | Result = AT->getElementType(); | ||||
4813 | } else if (LTy->isIntegralOrUnscopedEnumerationType()) { | ||||
4814 | if (const PointerType *PT = RTy->getAs<PointerType>()) | ||||
4815 | Result = PT->getPointeeType(); | ||||
4816 | else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) | ||||
4817 | Result = AT->getElementType(); | ||||
4818 | } | ||||
4819 | // Ensure we return a dependent type. | ||||
4820 | return Result->isDependentType() ? Result : Ctx.DependentTy; | ||||
4821 | } | ||||
4822 | |||||
4823 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); | ||||
4824 | |||||
4825 | ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, | ||||
4826 | SourceLocation lbLoc, | ||||
4827 | MultiExprArg ArgExprs, | ||||
4828 | SourceLocation rbLoc) { | ||||
4829 | |||||
4830 | if (base && !base->getType().isNull() && | ||||
4831 | base->hasPlaceholderType(BuiltinType::OMPArraySection)) | ||||
4832 | return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), | ||||
4833 | SourceLocation(), /*Length*/ nullptr, | ||||
4834 | /*Stride=*/nullptr, rbLoc); | ||||
4835 | |||||
4836 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
4837 | if (isa<ParenListExpr>(base)) { | ||||
4838 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||
4839 | if (result.isInvalid()) | ||||
4840 | return ExprError(); | ||||
4841 | base = result.get(); | ||||
4842 | } | ||||
4843 | |||||
4844 | // Check if base and idx form a MatrixSubscriptExpr. | ||||
4845 | // | ||||
4846 | // Helper to check for comma expressions, which are not allowed as indices for | ||||
4847 | // matrix subscript expressions. | ||||
4848 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||
4849 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||
4850 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||
4851 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4852 | return true; | ||||
4853 | } | ||||
4854 | return false; | ||||
4855 | }; | ||||
4856 | // The matrix subscript operator ([][])is considered a single operator. | ||||
4857 | // Separating the index expressions by parenthesis is not allowed. | ||||
4858 | if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && | ||||
4859 | !isa<MatrixSubscriptExpr>(base)) { | ||||
4860 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||
4861 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4862 | return ExprError(); | ||||
4863 | } | ||||
4864 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||
4865 | // MatrixSubscriptExpr. | ||||
4866 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||
4867 | if (matSubscriptE) { | ||||
4868 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4868, __extension__ __PRETTY_FUNCTION__)); | ||||
4869 | if (CheckAndReportCommaError(ArgExprs.front())) | ||||
4870 | return ExprError(); | ||||
4871 | |||||
4872 | assert(matSubscriptE->isIncomplete() &&(static_cast <bool> (matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript") ? void (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "clang/lib/Sema/SemaExpr.cpp", 4873, __extension__ __PRETTY_FUNCTION__ )) | ||||
4873 | "base has to be an incomplete matrix subscript")(static_cast <bool> (matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript") ? void (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "clang/lib/Sema/SemaExpr.cpp", 4873, __extension__ __PRETTY_FUNCTION__ )); | ||||
4874 | return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), | ||||
4875 | matSubscriptE->getRowIdx(), | ||||
4876 | ArgExprs.front(), rbLoc); | ||||
4877 | } | ||||
4878 | |||||
4879 | // Handle any non-overload placeholder types in the base and index | ||||
4880 | // expressions. We can't handle overloads here because the other | ||||
4881 | // operand might be an overloadable type, in which case the overload | ||||
4882 | // resolution for the operator overload should get the first crack | ||||
4883 | // at the overload. | ||||
4884 | bool IsMSPropertySubscript = false; | ||||
4885 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||
4886 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||
4887 | if (!IsMSPropertySubscript) { | ||||
4888 | ExprResult result = CheckPlaceholderExpr(base); | ||||
4889 | if (result.isInvalid()) | ||||
4890 | return ExprError(); | ||||
4891 | base = result.get(); | ||||
4892 | } | ||||
4893 | } | ||||
4894 | |||||
4895 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||
4896 | if (base->getType()->isMatrixType()) { | ||||
4897 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4897, __extension__ __PRETTY_FUNCTION__)); | ||||
4898 | if (CheckAndReportCommaError(ArgExprs.front())) | ||||
4899 | return ExprError(); | ||||
4900 | |||||
4901 | return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, | ||||
4902 | rbLoc); | ||||
4903 | } | ||||
4904 | |||||
4905 | if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { | ||||
4906 | Expr *idx = ArgExprs[0]; | ||||
4907 | if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||
4908 | (isa<CXXOperatorCallExpr>(idx) && | ||||
4909 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { | ||||
4910 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||
4911 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4912 | } | ||||
4913 | } | ||||
4914 | |||||
4915 | if (ArgExprs.size() == 1 && | ||||
4916 | ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { | ||||
4917 | ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); | ||||
4918 | if (result.isInvalid()) | ||||
4919 | return ExprError(); | ||||
4920 | ArgExprs[0] = result.get(); | ||||
4921 | } else { | ||||
4922 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
4923 | return ExprError(); | ||||
4924 | } | ||||
4925 | |||||
4926 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4927 | if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && | ||||
4928 | (base->isTypeDependent() || | ||||
4929 | Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
4930 | return new (Context) ArraySubscriptExpr( | ||||
4931 | base, ArgExprs.front(), | ||||
4932 | getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), | ||||
4933 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4934 | } | ||||
4935 | |||||
4936 | // MSDN, property (C++) | ||||
4937 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||
4938 | // This attribute can also be used in the declaration of an empty array in a | ||||
4939 | // class or structure definition. For example: | ||||
4940 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||
4941 | // The above statement indicates that x[] can be used with one or more array | ||||
4942 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||
4943 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||
4944 | if (IsMSPropertySubscript) { | ||||
4945 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4945, __extension__ __PRETTY_FUNCTION__)); | ||||
4946 | // Build MS property subscript expression if base is MS property reference | ||||
4947 | // or MS property subscript. | ||||
4948 | return new (Context) | ||||
4949 | MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, | ||||
4950 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4951 | } | ||||
4952 | |||||
4953 | // Use C++ overloaded-operator rules if either operand has record | ||||
4954 | // type. The spec says to do this if either type is *overloadable*, | ||||
4955 | // but enum types can't declare subscript operators or conversion | ||||
4956 | // operators, so there's nothing interesting for overload resolution | ||||
4957 | // to do if there aren't any record types involved. | ||||
4958 | // | ||||
4959 | // ObjC pointers have their own subscripting logic that is not tied | ||||
4960 | // to overload resolution and so should not take this path. | ||||
4961 | if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && | ||||
4962 | ((base->getType()->isRecordType() || | ||||
4963 | (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { | ||||
4964 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); | ||||
4965 | } | ||||
4966 | |||||
4967 | ExprResult Res = | ||||
4968 | CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); | ||||
4969 | |||||
4970 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||
4971 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||
4972 | |||||
4973 | return Res; | ||||
4974 | } | ||||
4975 | |||||
4976 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||
4977 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||
4978 | InitializationKind Kind = | ||||
4979 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||
4980 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||
4981 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||
4982 | } | ||||
4983 | |||||
4984 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||
4985 | Expr *ColumnIdx, | ||||
4986 | SourceLocation RBLoc) { | ||||
4987 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||
4988 | if (BaseR.isInvalid()) | ||||
4989 | return BaseR; | ||||
4990 | Base = BaseR.get(); | ||||
4991 | |||||
4992 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||
4993 | if (RowR.isInvalid()) | ||||
4994 | return RowR; | ||||
4995 | RowIdx = RowR.get(); | ||||
4996 | |||||
4997 | if (!ColumnIdx) | ||||
4998 | return new (Context) MatrixSubscriptExpr( | ||||
4999 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||
5000 | |||||
5001 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||
5002 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||
5003 | ColumnIdx->isTypeDependent()) | ||||
5004 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
5005 | Context.DependentTy, RBLoc); | ||||
5006 | |||||
5007 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||
5008 | if (ColumnR.isInvalid()) | ||||
5009 | return ColumnR; | ||||
5010 | ColumnIdx = ColumnR.get(); | ||||
5011 | |||||
5012 | // Check that IndexExpr is an integer expression. If it is a constant | ||||
5013 | // expression, check that it is less than Dim (= the number of elements in the | ||||
5014 | // corresponding dimension). | ||||
5015 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||
5016 | bool IsColumnIdx) -> Expr * { | ||||
5017 | if (!IndexExpr->getType()->isIntegerType() && | ||||
5018 | !IndexExpr->isTypeDependent()) { | ||||
5019 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||
5020 | << IsColumnIdx; | ||||
5021 | return nullptr; | ||||
5022 | } | ||||
5023 | |||||
5024 | if (std::optional<llvm::APSInt> Idx = | ||||
5025 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||
5026 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||
5027 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||
5028 | << IsColumnIdx << Dim; | ||||
5029 | return nullptr; | ||||
5030 | } | ||||
5031 | } | ||||
5032 | |||||
5033 | ExprResult ConvExpr = | ||||
5034 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||
5035 | assert(!ConvExpr.isInvalid() &&(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "clang/lib/Sema/SemaExpr.cpp", 5036, __extension__ __PRETTY_FUNCTION__ )) | ||||
5036 | "should be able to convert any integer type to size type")(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "clang/lib/Sema/SemaExpr.cpp", 5036, __extension__ __PRETTY_FUNCTION__ )); | ||||
5037 | return ConvExpr.get(); | ||||
5038 | }; | ||||
5039 | |||||
5040 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||
5041 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||
5042 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||
5043 | if (!RowIdx || !ColumnIdx) | ||||
5044 | return ExprError(); | ||||
5045 | |||||
5046 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
5047 | MTy->getElementType(), RBLoc); | ||||
5048 | } | ||||
5049 | |||||
5050 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||
5051 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
5052 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||
5053 | |||||
5054 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||
5055 | // checked. | ||||
5056 | const MemberExpr *Member = nullptr; | ||||
5057 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||
5058 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||
5059 | |||||
5060 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||
5061 | } | ||||
5062 | |||||
5063 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||
5064 | if (isUnevaluatedContext()) | ||||
5065 | return; | ||||
5066 | |||||
5067 | QualType ResultTy = E->getType(); | ||||
5068 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
5069 | |||||
5070 | // Bail if the element is an array since it is not memory access. | ||||
5071 | if (isa<ArrayType>(ResultTy)) | ||||
5072 | return; | ||||
5073 | |||||
5074 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||
5075 | LastRecord.PossibleDerefs.insert(E); | ||||
5076 | return; | ||||
5077 | } | ||||
5078 | |||||
5079 | // Check if the base type is a pointer to a member access of a struct | ||||
5080 | // marked with noderef. | ||||
5081 | const Expr *Base = E->getBase(); | ||||
5082 | QualType BaseTy = Base->getType(); | ||||
5083 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||
5084 | // Not a pointer access | ||||
5085 | return; | ||||
5086 | |||||
5087 | const MemberExpr *Member = nullptr; | ||||
5088 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||
5089 | Member->isArrow()) | ||||
5090 | Base = Member->getBase(); | ||||
5091 | |||||
5092 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||
5093 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||
5094 | LastRecord.PossibleDerefs.insert(E); | ||||
5095 | } | ||||
5096 | } | ||||
5097 | |||||
5098 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||
5099 | Expr *LowerBound, | ||||
5100 | SourceLocation ColonLocFirst, | ||||
5101 | SourceLocation ColonLocSecond, | ||||
5102 | Expr *Length, Expr *Stride, | ||||
5103 | SourceLocation RBLoc) { | ||||
5104 | if (Base->hasPlaceholderType() && | ||||
5105 | !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { | ||||
5106 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5107 | if (Result.isInvalid()) | ||||
5108 | return ExprError(); | ||||
5109 | Base = Result.get(); | ||||
5110 | } | ||||
5111 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||
5112 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||
5113 | if (Result.isInvalid()) | ||||
5114 | return ExprError(); | ||||
5115 | Result = DefaultLvalueConversion(Result.get()); | ||||
5116 | if (Result.isInvalid()) | ||||
5117 | return ExprError(); | ||||
5118 | LowerBound = Result.get(); | ||||
5119 | } | ||||
5120 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||
5121 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||
5122 | if (Result.isInvalid()) | ||||
5123 | return ExprError(); | ||||
5124 | Result = DefaultLvalueConversion(Result.get()); | ||||
5125 | if (Result.isInvalid()) | ||||
5126 | return ExprError(); | ||||
5127 | Length = Result.get(); | ||||
5128 | } | ||||
5129 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||
5130 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||
5131 | if (Result.isInvalid()) | ||||
5132 | return ExprError(); | ||||
5133 | Result = DefaultLvalueConversion(Result.get()); | ||||
5134 | if (Result.isInvalid()) | ||||
5135 | return ExprError(); | ||||
5136 | Stride = Result.get(); | ||||
5137 | } | ||||
5138 | |||||
5139 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
5140 | if (Base->isTypeDependent() || | ||||
5141 | (LowerBound && | ||||
5142 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||
5143 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||
5144 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||
5145 | return new (Context) OMPArraySectionExpr( | ||||
5146 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||
5147 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5148 | } | ||||
5149 | |||||
5150 | // Perform default conversions. | ||||
5151 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||
5152 | QualType ResultTy; | ||||
5153 | if (OriginalTy->isAnyPointerType()) { | ||||
5154 | ResultTy = OriginalTy->getPointeeType(); | ||||
5155 | } else if (OriginalTy->isArrayType()) { | ||||
5156 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||
5157 | } else { | ||||
5158 | return ExprError( | ||||
5159 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||
5160 | << Base->getSourceRange()); | ||||
5161 | } | ||||
5162 | // C99 6.5.2.1p1 | ||||
5163 | if (LowerBound) { | ||||
5164 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||
5165 | LowerBound); | ||||
5166 | if (Res.isInvalid()) | ||||
5167 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||
5168 | diag::err_omp_typecheck_section_not_integer) | ||||
5169 | << 0 << LowerBound->getSourceRange()); | ||||
5170 | LowerBound = Res.get(); | ||||
5171 | |||||
5172 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5173 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5174 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5175 | << 0 << LowerBound->getSourceRange(); | ||||
5176 | } | ||||
5177 | if (Length) { | ||||
5178 | auto Res = | ||||
5179 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||
5180 | if (Res.isInvalid()) | ||||
5181 | return ExprError(Diag(Length->getExprLoc(), | ||||
5182 | diag::err_omp_typecheck_section_not_integer) | ||||
5183 | << 1 << Length->getSourceRange()); | ||||
5184 | Length = Res.get(); | ||||
5185 | |||||
5186 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5187 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5188 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5189 | << 1 << Length->getSourceRange(); | ||||
5190 | } | ||||
5191 | if (Stride) { | ||||
5192 | ExprResult Res = | ||||
5193 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||
5194 | if (Res.isInvalid()) | ||||
5195 | return ExprError(Diag(Stride->getExprLoc(), | ||||
5196 | diag::err_omp_typecheck_section_not_integer) | ||||
5197 | << 1 << Stride->getSourceRange()); | ||||
5198 | Stride = Res.get(); | ||||
5199 | |||||
5200 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5201 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5202 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5203 | << 1 << Stride->getSourceRange(); | ||||
5204 | } | ||||
5205 | |||||
5206 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5207 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5208 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||
5209 | // incomplete types are not object types. | ||||
5210 | if (ResultTy->isFunctionType()) { | ||||
5211 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||
5212 | << ResultTy << Base->getSourceRange(); | ||||
5213 | return ExprError(); | ||||
5214 | } | ||||
5215 | |||||
5216 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||
5217 | diag::err_omp_section_incomplete_type, Base)) | ||||
5218 | return ExprError(); | ||||
5219 | |||||
5220 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||
5221 | Expr::EvalResult Result; | ||||
5222 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||
5223 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5224 | // The array section must be a subset of the original array. | ||||
5225 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||
5226 | if (LowerBoundValue.isNegative()) { | ||||
5227 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||
5228 | << LowerBound->getSourceRange(); | ||||
5229 | return ExprError(); | ||||
5230 | } | ||||
5231 | } | ||||
5232 | } | ||||
5233 | |||||
5234 | if (Length) { | ||||
5235 | Expr::EvalResult Result; | ||||
5236 | if (Length->EvaluateAsInt(Result, Context)) { | ||||
5237 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5238 | // The length must evaluate to non-negative integers. | ||||
5239 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||
5240 | if (LengthValue.isNegative()) { | ||||
5241 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||
5242 | << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) | ||||
5243 | << Length->getSourceRange(); | ||||
5244 | return ExprError(); | ||||
5245 | } | ||||
5246 | } | ||||
5247 | } else if (ColonLocFirst.isValid() && | ||||
5248 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||
5249 | !OriginalTy->isVariableArrayType()))) { | ||||
5250 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5251 | // When the size of the array dimension is not known, the length must be | ||||
5252 | // specified explicitly. | ||||
5253 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||
5254 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||
5255 | return ExprError(); | ||||
5256 | } | ||||
5257 | |||||
5258 | if (Stride) { | ||||
5259 | Expr::EvalResult Result; | ||||
5260 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||
5261 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5262 | // The stride must evaluate to a positive integer. | ||||
5263 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||
5264 | if (!StrideValue.isStrictlyPositive()) { | ||||
5265 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||
5266 | << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) | ||||
5267 | << Stride->getSourceRange(); | ||||
5268 | return ExprError(); | ||||
5269 | } | ||||
5270 | } | ||||
5271 | } | ||||
5272 | |||||
5273 | if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { | ||||
5274 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||
5275 | if (Result.isInvalid()) | ||||
5276 | return ExprError(); | ||||
5277 | Base = Result.get(); | ||||
5278 | } | ||||
5279 | return new (Context) OMPArraySectionExpr( | ||||
5280 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||
5281 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5282 | } | ||||
5283 | |||||
5284 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||
5285 | SourceLocation RParenLoc, | ||||
5286 | ArrayRef<Expr *> Dims, | ||||
5287 | ArrayRef<SourceRange> Brackets) { | ||||
5288 | if (Base->hasPlaceholderType()) { | ||||
5289 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5290 | if (Result.isInvalid()) | ||||
5291 | return ExprError(); | ||||
5292 | Result = DefaultLvalueConversion(Result.get()); | ||||
5293 | if (Result.isInvalid()) | ||||
5294 | return ExprError(); | ||||
5295 | Base = Result.get(); | ||||
5296 | } | ||||
5297 | QualType BaseTy = Base->getType(); | ||||
5298 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||
5299 | // required. | ||||
5300 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||
5301 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||
5302 | LParenLoc, RParenLoc, Dims, Brackets); | ||||
5303 | if (!BaseTy->isPointerType() || | ||||
5304 | (!Base->isTypeDependent() && | ||||
5305 | BaseTy->getPointeeType()->isIncompleteType())) | ||||
5306 | return ExprError(Diag(Base->getExprLoc(), | ||||
5307 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||
5308 | << Base->getSourceRange()); | ||||
5309 | |||||
5310 | SmallVector<Expr *, 4> NewDims; | ||||
5311 | bool ErrorFound = false; | ||||
5312 | for (Expr *Dim : Dims) { | ||||
5313 | if (Dim->hasPlaceholderType()) { | ||||
5314 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||
5315 | if (Result.isInvalid()) { | ||||
5316 | ErrorFound = true; | ||||
5317 | continue; | ||||
5318 | } | ||||
5319 | Result = DefaultLvalueConversion(Result.get()); | ||||
5320 | if (Result.isInvalid()) { | ||||
5321 | ErrorFound = true; | ||||
5322 | continue; | ||||
5323 | } | ||||
5324 | Dim = Result.get(); | ||||
5325 | } | ||||
5326 | if (!Dim->isTypeDependent()) { | ||||
5327 | ExprResult Result = | ||||
5328 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||
5329 | if (Result.isInvalid()) { | ||||
5330 | ErrorFound = true; | ||||
5331 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||
5332 | << Dim->getSourceRange(); | ||||
5333 | continue; | ||||
5334 | } | ||||
5335 | Dim = Result.get(); | ||||
5336 | Expr::EvalResult EvResult; | ||||
5337 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||
5338 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||
5339 | // Each si is an integral type expression that must evaluate to a | ||||
5340 | // positive integer. | ||||
5341 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||
5342 | if (!Value.isStrictlyPositive()) { | ||||
5343 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||
5344 | << toString(Value, /*Radix=*/10, /*Signed=*/true) | ||||
5345 | << Dim->getSourceRange(); | ||||
5346 | ErrorFound = true; | ||||
5347 | continue; | ||||
5348 | } | ||||
5349 | } | ||||
5350 | } | ||||
5351 | NewDims.push_back(Dim); | ||||
5352 | } | ||||
5353 | if (ErrorFound) | ||||
5354 | return ExprError(); | ||||
5355 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||
5356 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||
5357 | } | ||||
5358 | |||||
5359 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||
5360 | SourceLocation LLoc, SourceLocation RLoc, | ||||
5361 | ArrayRef<OMPIteratorData> Data) { | ||||
5362 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||
5363 | bool IsCorrect = true; | ||||
5364 | for (const OMPIteratorData &D : Data) { | ||||
5365 | TypeSourceInfo *TInfo = nullptr; | ||||
5366 | SourceLocation StartLoc; | ||||
5367 | QualType DeclTy; | ||||
5368 | if (!D.Type.getAsOpaquePtr()) { | ||||
5369 | // OpenMP 5.0, 2.1.6 Iterators | ||||
5370 | // In an iterator-specifier, if the iterator-type is not specified then | ||||
5371 | // the type of that iterator is of int type. | ||||
5372 | DeclTy = Context.IntTy; | ||||
5373 | StartLoc = D.DeclIdentLoc; | ||||
5374 | } else { | ||||
5375 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||
5376 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
5377 | } | ||||
5378 | |||||
5379 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||
5380 | DeclTy->containsUnexpandedParameterPack() || | ||||
5381 | DeclTy->isInstantiationDependentType(); | ||||
5382 | if (!IsDeclTyDependent) { | ||||
5383 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||
5384 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5385 | // The iterator-type must be an integral or pointer type. | ||||
5386 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5387 | << DeclTy; | ||||
5388 | IsCorrect = false; | ||||
5389 | continue; | ||||
5390 | } | ||||
5391 | if (DeclTy.isConstant(Context)) { | ||||
5392 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5393 | // The iterator-type must not be const qualified. | ||||
5394 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5395 | << DeclTy; | ||||
5396 | IsCorrect = false; | ||||
5397 | continue; | ||||
5398 | } | ||||
5399 | } | ||||
5400 | |||||
5401 | // Iterator declaration. | ||||
5402 | assert(D.DeclIdent && "Identifier expected.")(static_cast <bool> (D.DeclIdent && "Identifier expected." ) ? void (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "clang/lib/Sema/SemaExpr.cpp", 5402, __extension__ __PRETTY_FUNCTION__ )); | ||||
5403 | // Always try to create iterator declarator to avoid extra error messages | ||||
5404 | // about unknown declarations use. | ||||
5405 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||
5406 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||
5407 | VD->setImplicit(); | ||||
5408 | if (S) { | ||||
5409 | // Check for conflicting previous declaration. | ||||
5410 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||
5411 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5412 | ForVisibleRedeclaration); | ||||
5413 | Previous.suppressDiagnostics(); | ||||
5414 | LookupName(Previous, S); | ||||
5415 | |||||
5416 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||
5417 | /*AllowInlineNamespace=*/false); | ||||
5418 | if (!Previous.empty()) { | ||||
5419 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||
5420 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||
5421 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
5422 | } else { | ||||
5423 | PushOnScopeChains(VD, S); | ||||
5424 | } | ||||
5425 | } else { | ||||
5426 | CurContext->addDecl(VD); | ||||
5427 | } | ||||
5428 | |||||
5429 | /// Act on the iterator variable declaration. | ||||
5430 | ActOnOpenMPIteratorVarDecl(VD); | ||||
5431 | |||||
5432 | Expr *Begin = D.Range.Begin; | ||||
5433 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||
5434 | ExprResult BeginRes = | ||||
5435 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||
5436 | Begin = BeginRes.get(); | ||||
5437 | } | ||||
5438 | Expr *End = D.Range.End; | ||||
5439 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||
5440 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||
5441 | End = EndRes.get(); | ||||
5442 | } | ||||
5443 | Expr *Step = D.Range.Step; | ||||
5444 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||
5445 | if (!Step->getType()->isIntegralType(Context)) { | ||||
5446 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||
5447 | << Step << Step->getSourceRange(); | ||||
5448 | IsCorrect = false; | ||||
5449 | continue; | ||||
5450 | } | ||||
5451 | std::optional<llvm::APSInt> Result = | ||||
5452 | Step->getIntegerConstantExpr(Context); | ||||
5453 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||
5454 | // If the step expression of a range-specification equals zero, the | ||||
5455 | // behavior is unspecified. | ||||
5456 | if (Result && Result->isZero()) { | ||||
5457 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||
5458 | << Step << Step->getSourceRange(); | ||||
5459 | IsCorrect = false; | ||||
5460 | continue; | ||||
5461 | } | ||||
5462 | } | ||||
5463 | if (!Begin || !End || !IsCorrect) { | ||||
5464 | IsCorrect = false; | ||||
5465 | continue; | ||||
5466 | } | ||||
5467 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||
5468 | IDElem.IteratorDecl = VD; | ||||
5469 | IDElem.AssignmentLoc = D.AssignLoc; | ||||
5470 | IDElem.Range.Begin = Begin; | ||||
5471 | IDElem.Range.End = End; | ||||
5472 | IDElem.Range.Step = Step; | ||||
5473 | IDElem.ColonLoc = D.ColonLoc; | ||||
5474 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||
5475 | } | ||||
5476 | if (!IsCorrect) { | ||||
5477 | // Invalidate all created iterator declarations if error is found. | ||||
5478 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5479 | if (Decl *ID = D.IteratorDecl) | ||||
5480 | ID->setInvalidDecl(); | ||||
5481 | } | ||||
5482 | return ExprError(); | ||||
5483 | } | ||||
5484 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||
5485 | if (!CurContext->isDependentContext()) { | ||||
5486 | // Build number of ityeration for each iteration range. | ||||
5487 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||
5488 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||
5489 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5490 | // (Endi - Begini) | ||||
5491 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||
5492 | D.Range.Begin); | ||||
5493 | if(!Res.isUsable()) { | ||||
5494 | IsCorrect = false; | ||||
5495 | continue; | ||||
5496 | } | ||||
5497 | ExprResult St, St1; | ||||
5498 | if (D.Range.Step) { | ||||
5499 | St = D.Range.Step; | ||||
5500 | // (Endi - Begini) + Stepi | ||||
5501 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||
5502 | if (!Res.isUsable()) { | ||||
5503 | IsCorrect = false; | ||||
5504 | continue; | ||||
5505 | } | ||||
5506 | // (Endi - Begini) + Stepi - 1 | ||||
5507 | Res = | ||||
5508 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||
5509 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5510 | if (!Res.isUsable()) { | ||||
5511 | IsCorrect = false; | ||||
5512 | continue; | ||||
5513 | } | ||||
5514 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||
5515 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||
5516 | if (!Res.isUsable()) { | ||||
5517 | IsCorrect = false; | ||||
5518 | continue; | ||||
5519 | } | ||||
5520 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||
5521 | // (Begini - Endi) | ||||
5522 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||
5523 | D.Range.Begin, D.Range.End); | ||||
5524 | if (!Res1.isUsable()) { | ||||
5525 | IsCorrect = false; | ||||
5526 | continue; | ||||
5527 | } | ||||
5528 | // (Begini - Endi) - Stepi | ||||
5529 | Res1 = | ||||
5530 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||
5531 | if (!Res1.isUsable()) { | ||||
5532 | IsCorrect = false; | ||||
5533 | continue; | ||||
5534 | } | ||||
5535 | // (Begini - Endi) - Stepi - 1 | ||||
5536 | Res1 = | ||||
5537 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||
5538 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5539 | if (!Res1.isUsable()) { | ||||
5540 | IsCorrect = false; | ||||
5541 | continue; | ||||
5542 | } | ||||
5543 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||
5544 | Res1 = | ||||
5545 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||
5546 | if (!Res1.isUsable()) { | ||||
5547 | IsCorrect = false; | ||||
5548 | continue; | ||||
5549 | } | ||||
5550 | // Stepi > 0. | ||||
5551 | ExprResult CmpRes = | ||||
5552 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||
5553 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||
5554 | if (!CmpRes.isUsable()) { | ||||
5555 | IsCorrect = false; | ||||
5556 | continue; | ||||
5557 | } | ||||
5558 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||
5559 | Res.get(), Res1.get()); | ||||
5560 | if (!Res.isUsable()) { | ||||
5561 | IsCorrect = false; | ||||
5562 | continue; | ||||
5563 | } | ||||
5564 | } | ||||
5565 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||
5566 | if (!Res.isUsable()) { | ||||
5567 | IsCorrect = false; | ||||
5568 | continue; | ||||
5569 | } | ||||
5570 | |||||
5571 | // Build counter update. | ||||
5572 | // Build counter. | ||||
5573 | auto *CounterVD = | ||||
5574 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||
5575 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||
5576 | Res.get()->getType(), nullptr, SC_None); | ||||
5577 | CounterVD->setImplicit(); | ||||
5578 | ExprResult RefRes = | ||||
5579 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||
5580 | D.IteratorDecl->getBeginLoc()); | ||||
5581 | // Build counter update. | ||||
5582 | // I = Begini + counter * Stepi; | ||||
5583 | ExprResult UpdateRes; | ||||
5584 | if (D.Range.Step) { | ||||
5585 | UpdateRes = CreateBuiltinBinOp( | ||||
5586 | D.AssignmentLoc, BO_Mul, | ||||
5587 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||
5588 | } else { | ||||
5589 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||
5590 | } | ||||
5591 | if (!UpdateRes.isUsable()) { | ||||
5592 | IsCorrect = false; | ||||
5593 | continue; | ||||
5594 | } | ||||
5595 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||
5596 | UpdateRes.get()); | ||||
5597 | if (!UpdateRes.isUsable()) { | ||||
5598 | IsCorrect = false; | ||||
5599 | continue; | ||||
5600 | } | ||||
5601 | ExprResult VDRes = | ||||
5602 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||
5603 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||
5604 | D.IteratorDecl->getBeginLoc()); | ||||
5605 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||
5606 | UpdateRes.get()); | ||||
5607 | if (!UpdateRes.isUsable()) { | ||||
5608 | IsCorrect = false; | ||||
5609 | continue; | ||||
5610 | } | ||||
5611 | UpdateRes = | ||||
5612 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||
5613 | if (!UpdateRes.isUsable()) { | ||||
5614 | IsCorrect = false; | ||||
5615 | continue; | ||||
5616 | } | ||||
5617 | ExprResult CounterUpdateRes = | ||||
5618 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||
5619 | if (!CounterUpdateRes.isUsable()) { | ||||
5620 | IsCorrect = false; | ||||
5621 | continue; | ||||
5622 | } | ||||
5623 | CounterUpdateRes = | ||||
5624 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||
5625 | if (!CounterUpdateRes.isUsable()) { | ||||
5626 | IsCorrect = false; | ||||
5627 | continue; | ||||
5628 | } | ||||
5629 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||
5630 | HD.CounterVD = CounterVD; | ||||
5631 | HD.Upper = Res.get(); | ||||
5632 | HD.Update = UpdateRes.get(); | ||||
5633 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||
5634 | } | ||||
5635 | } else { | ||||
5636 | Helpers.assign(ID.size(), {}); | ||||
5637 | } | ||||
5638 | if (!IsCorrect) { | ||||
5639 | // Invalidate all created iterator declarations if error is found. | ||||
5640 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5641 | if (Decl *ID = D.IteratorDecl) | ||||
5642 | ID->setInvalidDecl(); | ||||
5643 | } | ||||
5644 | return ExprError(); | ||||
5645 | } | ||||
5646 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||
5647 | LLoc, RLoc, ID, Helpers); | ||||
5648 | } | ||||
5649 | |||||
5650 | ExprResult | ||||
5651 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||
5652 | Expr *Idx, SourceLocation RLoc) { | ||||
5653 | Expr *LHSExp = Base; | ||||
5654 | Expr *RHSExp = Idx; | ||||
5655 | |||||
5656 | ExprValueKind VK = VK_LValue; | ||||
5657 | ExprObjectKind OK = OK_Ordinary; | ||||
5658 | |||||
5659 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||
5660 | // a non-lvalue array, and an lvalue otherwise. | ||||
5661 | if (getLangOpts().CPlusPlus11) { | ||||
5662 | for (auto *Op : {LHSExp, RHSExp}) { | ||||
5663 | Op = Op->IgnoreImplicit(); | ||||
5664 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||
5665 | VK = VK_XValue; | ||||
5666 | } | ||||
5667 | } | ||||
5668 | |||||
5669 | // Perform default conversions. | ||||
5670 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||
5671 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||
5672 | if (Result.isInvalid()) | ||||
5673 | return ExprError(); | ||||
5674 | LHSExp = Result.get(); | ||||
5675 | } | ||||
5676 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||
5677 | if (Result.isInvalid()) | ||||
5678 | return ExprError(); | ||||
5679 | RHSExp = Result.get(); | ||||
5680 | |||||
5681 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||
5682 | |||||
5683 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||
5684 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||
5685 | // in the subscript position. As a result, we need to derive the array base | ||||
5686 | // and index from the expression types. | ||||
5687 | Expr *BaseExpr, *IndexExpr; | ||||
5688 | QualType ResultType; | ||||
5689 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||
5690 | BaseExpr = LHSExp; | ||||
5691 | IndexExpr = RHSExp; | ||||
5692 | ResultType = | ||||
5693 | getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); | ||||
5694 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||
5695 | BaseExpr = LHSExp; | ||||
5696 | IndexExpr = RHSExp; | ||||
5697 | ResultType = PTy->getPointeeType(); | ||||
5698 | } else if (const ObjCObjectPointerType *PTy = | ||||
5699 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5700 | BaseExpr = LHSExp; | ||||
5701 | IndexExpr = RHSExp; | ||||
5702 | |||||
5703 | // Use custom logic if this should be the pseudo-object subscript | ||||
5704 | // expression. | ||||
5705 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||
5706 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||
5707 | nullptr); | ||||
5708 | |||||
5709 | ResultType = PTy->getPointeeType(); | ||||
5710 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||
5711 | // Handle the uncommon case of "123[Ptr]". | ||||
5712 | BaseExpr = RHSExp; | ||||
5713 | IndexExpr = LHSExp; | ||||
5714 | ResultType = PTy->getPointeeType(); | ||||
5715 | } else if (const ObjCObjectPointerType *PTy = | ||||
5716 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5717 | // Handle the uncommon case of "123[Ptr]". | ||||
5718 | BaseExpr = RHSExp; | ||||
5719 | IndexExpr = LHSExp; | ||||
5720 | ResultType = PTy->getPointeeType(); | ||||
5721 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||
5722 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||
5723 | << ResultType << BaseExpr->getSourceRange(); | ||||
5724 | return ExprError(); | ||||
5725 | } | ||||
5726 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||
5727 | BaseExpr = LHSExp; // vectors: V[123] | ||||
5728 | IndexExpr = RHSExp; | ||||
5729 | // We apply C++ DR1213 to vector subscripting too. | ||||
5730 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { | ||||
5731 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5732 | if (Materialized.isInvalid()) | ||||
5733 | return ExprError(); | ||||
5734 | LHSExp = Materialized.get(); | ||||
5735 | } | ||||
5736 | VK = LHSExp->getValueKind(); | ||||
5737 | if (VK != VK_PRValue) | ||||
5738 | OK = OK_VectorComponent; | ||||
5739 | |||||
5740 | ResultType = VTy->getElementType(); | ||||
5741 | QualType BaseType = BaseExpr->getType(); | ||||
5742 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5743 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5744 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5745 | if (Combined != MemberQuals) | ||||
5746 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5747 | } else if (LHSTy->isBuiltinType() && | ||||
5748 | LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { | ||||
5749 | const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); | ||||
5750 | if (BTy->isSVEBool()) | ||||
5751 | return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) | ||||
5752 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5753 | |||||
5754 | BaseExpr = LHSExp; | ||||
5755 | IndexExpr = RHSExp; | ||||
5756 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { | ||||
5757 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5758 | if (Materialized.isInvalid()) | ||||
5759 | return ExprError(); | ||||
5760 | LHSExp = Materialized.get(); | ||||
5761 | } | ||||
5762 | VK = LHSExp->getValueKind(); | ||||
5763 | if (VK != VK_PRValue) | ||||
5764 | OK = OK_VectorComponent; | ||||
5765 | |||||
5766 | ResultType = BTy->getSveEltType(Context); | ||||
5767 | |||||
5768 | QualType BaseType = BaseExpr->getType(); | ||||
5769 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5770 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5771 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5772 | if (Combined != MemberQuals) | ||||
5773 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5774 | } else if (LHSTy->isArrayType()) { | ||||
5775 | // If we see an array that wasn't promoted by | ||||
5776 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||
5777 | // wasn't promoted because of the C90 rule that doesn't | ||||
5778 | // allow promoting non-lvalue arrays. Warn, then | ||||
5779 | // force the promotion here. | ||||
5780 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5781 | << LHSExp->getSourceRange(); | ||||
5782 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||
5783 | CK_ArrayToPointerDecay).get(); | ||||
5784 | LHSTy = LHSExp->getType(); | ||||
5785 | |||||
5786 | BaseExpr = LHSExp; | ||||
5787 | IndexExpr = RHSExp; | ||||
5788 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
5789 | } else if (RHSTy->isArrayType()) { | ||||
5790 | // Same as previous, except for 123[f().a] case | ||||
5791 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5792 | << RHSExp->getSourceRange(); | ||||
5793 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||
5794 | CK_ArrayToPointerDecay).get(); | ||||
5795 | RHSTy = RHSExp->getType(); | ||||
5796 | |||||
5797 | BaseExpr = RHSExp; | ||||
5798 | IndexExpr = LHSExp; | ||||
5799 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
5800 | } else { | ||||
5801 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||
5802 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5803 | } | ||||
5804 | // C99 6.5.2.1p1 | ||||
5805 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||
5806 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||
5807 | << IndexExpr->getSourceRange()); | ||||
5808 | |||||
5809 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5810 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5811 | && !IndexExpr->isTypeDependent()) | ||||
5812 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||
5813 | |||||
5814 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5815 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5816 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||
5817 | // incomplete types are not object types. | ||||
5818 | if (ResultType->isFunctionType()) { | ||||
5819 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||
5820 | << ResultType << BaseExpr->getSourceRange(); | ||||
5821 | return ExprError(); | ||||
5822 | } | ||||
5823 | |||||
5824 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||
5825 | // GNU extension: subscripting on pointer to void | ||||
5826 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||
5827 | << BaseExpr->getSourceRange(); | ||||
5828 | |||||
5829 | // C forbids expressions of unqualified void type from being l-values. | ||||
5830 | // See IsCForbiddenLValueType. | ||||
5831 | if (!ResultType.hasQualifiers()) | ||||
5832 | VK = VK_PRValue; | ||||
5833 | } else if (!ResultType->isDependentType() && | ||||
5834 | RequireCompleteSizedType( | ||||
5835 | LLoc, ResultType, | ||||
5836 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||
5837 | return ExprError(); | ||||
5838 | |||||
5839 | assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "clang/lib/Sema/SemaExpr.cpp", 5840, __extension__ __PRETTY_FUNCTION__ )) | ||||
5840 | !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "clang/lib/Sema/SemaExpr.cpp", 5840, __extension__ __PRETTY_FUNCTION__ )); | ||||
5841 | |||||
5842 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||
5843 | FunctionScopes.size() > 1) { | ||||
5844 | if (auto *TT = | ||||
5845 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||
5846 | for (auto I = FunctionScopes.rbegin(), | ||||
5847 | E = std::prev(FunctionScopes.rend()); | ||||
5848 | I != E; ++I) { | ||||
5849 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
5850 | if (CSI == nullptr) | ||||
5851 | break; | ||||
5852 | DeclContext *DC = nullptr; | ||||
5853 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
5854 | DC = LSI->CallOperator; | ||||
5855 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
5856 | DC = CRSI->TheCapturedDecl; | ||||
5857 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
5858 | DC = BSI->TheDecl; | ||||
5859 | if (DC) { | ||||
5860 | if (DC->containsDecl(TT->getDecl())) | ||||
5861 | break; | ||||
5862 | captureVariablyModifiedType( | ||||
5863 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||
5864 | } | ||||
5865 | } | ||||
5866 | } | ||||
5867 | } | ||||
5868 | |||||
5869 | return new (Context) | ||||
5870 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||
5871 | } | ||||
5872 | |||||
5873 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||
5874 | ParmVarDecl *Param, Expr *RewrittenInit, | ||||
5875 | bool SkipImmediateInvocations) { | ||||
5876 | if (Param->hasUnparsedDefaultArg()) { | ||||
5877 | assert(!RewrittenInit && "Should not have a rewritten init expression yet")(static_cast <bool> (!RewrittenInit && "Should not have a rewritten init expression yet" ) ? void (0) : __assert_fail ("!RewrittenInit && \"Should not have a rewritten init expression yet\"" , "clang/lib/Sema/SemaExpr.cpp", 5877, __extension__ __PRETTY_FUNCTION__ )); | ||||
5878 | // If we've already cleared out the location for the default argument, | ||||
5879 | // that means we're parsing it right now. | ||||
5880 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||
5881 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||
5882 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||
5883 | Param->setInvalidDecl(); | ||||
5884 | return true; | ||||
5885 | } | ||||
5886 | |||||
5887 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||
5888 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||
5889 | Diag(UnparsedDefaultArgLocs[Param], | ||||
5890 | diag::note_default_argument_declared_here); | ||||
5891 | return true; | ||||
5892 | } | ||||
5893 | |||||
5894 | if (Param->hasUninstantiatedDefaultArg()) { | ||||
5895 | assert(!RewrittenInit && "Should not have a rewitten init expression yet")(static_cast <bool> (!RewrittenInit && "Should not have a rewitten init expression yet" ) ? void (0) : __assert_fail ("!RewrittenInit && \"Should not have a rewitten init expression yet\"" , "clang/lib/Sema/SemaExpr.cpp", 5895, __extension__ __PRETTY_FUNCTION__ )); | ||||
5896 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||
5897 | return true; | ||||
5898 | } | ||||
5899 | |||||
5900 | Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit(); | ||||
5901 | assert(Init && "default argument but no initializer?")(static_cast <bool> (Init && "default argument but no initializer?" ) ? void (0) : __assert_fail ("Init && \"default argument but no initializer?\"" , "clang/lib/Sema/SemaExpr.cpp", 5901, __extension__ __PRETTY_FUNCTION__ )); | ||||
5902 | |||||
5903 | // If the default expression creates temporaries, we need to | ||||
5904 | // push them to the current stack of expression temporaries so they'll | ||||
5905 | // be properly destroyed. | ||||
5906 | // FIXME: We should really be rebuilding the default argument with new | ||||
5907 | // bound temporaries; see the comment in PR5810. | ||||
5908 | // We don't need to do that with block decls, though, because | ||||
5909 | // blocks in default argument expression can never capture anything. | ||||
5910 | if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) { | ||||
5911 | // Set the "needs cleanups" bit regardless of whether there are | ||||
5912 | // any explicit objects. | ||||
5913 | Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects()); | ||||
5914 | // Append all the objects to the cleanup list. Right now, this | ||||
5915 | // should always be a no-op, because blocks in default argument | ||||
5916 | // expressions should never be able to capture anything. | ||||
5917 | assert(!InitWithCleanup->getNumObjects() &&(static_cast <bool> (!InitWithCleanup->getNumObjects () && "default argument expression has capturing blocks?" ) ? void (0) : __assert_fail ("!InitWithCleanup->getNumObjects() && \"default argument expression has capturing blocks?\"" , "clang/lib/Sema/SemaExpr.cpp", 5918, __extension__ __PRETTY_FUNCTION__ )) | ||||
5918 | "default argument expression has capturing blocks?")(static_cast <bool> (!InitWithCleanup->getNumObjects () && "default argument expression has capturing blocks?" ) ? void (0) : __assert_fail ("!InitWithCleanup->getNumObjects() && \"default argument expression has capturing blocks?\"" , "clang/lib/Sema/SemaExpr.cpp", 5918, __extension__ __PRETTY_FUNCTION__ )); | ||||
5919 | } | ||||
5920 | EnterExpressionEvaluationContext EvalContext( | ||||
5921 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||
5922 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = | ||||
5923 | SkipImmediateInvocations; | ||||
5924 | MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables*/ true); | ||||
5925 | return false; | ||||
5926 | } | ||||
5927 | |||||
5928 | struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> { | ||||
5929 | bool HasImmediateCalls = false; | ||||
5930 | |||||
5931 | bool shouldVisitImplicitCode() const { return true; } | ||||
5932 | |||||
5933 | bool VisitCallExpr(CallExpr *E) { | ||||
5934 | if (const FunctionDecl *FD = E->getDirectCallee()) | ||||
5935 | HasImmediateCalls |= FD->isConsteval(); | ||||
5936 | return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E); | ||||
5937 | } | ||||
5938 | |||||
5939 | // SourceLocExpr are not immediate invocations | ||||
5940 | // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr | ||||
5941 | // need to be rebuilt so that they refer to the correct SourceLocation and | ||||
5942 | // DeclContext. | ||||
5943 | bool VisitSourceLocExpr(SourceLocExpr *E) { | ||||
5944 | HasImmediateCalls = true; | ||||
5945 | return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E); | ||||
5946 | } | ||||
5947 | |||||
5948 | // A nested lambda might have parameters with immediate invocations | ||||
5949 | // in their default arguments. | ||||
5950 | // The compound statement is not visited (as it does not constitute a | ||||
5951 | // subexpression). | ||||
5952 | // FIXME: We should consider visiting and transforming captures | ||||
5953 | // with init expressions. | ||||
5954 | bool VisitLambdaExpr(LambdaExpr *E) { | ||||
5955 | return VisitCXXMethodDecl(E->getCallOperator()); | ||||
5956 | } | ||||
5957 | |||||
5958 | // Blocks don't support default parameters, and, as for lambdas, | ||||
5959 | // we don't consider their body a subexpression. | ||||
5960 | bool VisitBlockDecl(BlockDecl *B) { return false; } | ||||
5961 | |||||
5962 | bool VisitCompoundStmt(CompoundStmt *B) { return false; } | ||||
5963 | |||||
5964 | bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { | ||||
5965 | return TraverseStmt(E->getExpr()); | ||||
5966 | } | ||||
5967 | |||||
5968 | bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { | ||||
5969 | return TraverseStmt(E->getExpr()); | ||||
5970 | } | ||||
5971 | }; | ||||
5972 | |||||
5973 | struct EnsureImmediateInvocationInDefaultArgs | ||||
5974 | : TreeTransform<EnsureImmediateInvocationInDefaultArgs> { | ||||
5975 | EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef) | ||||
5976 | : TreeTransform(SemaRef) {} | ||||
5977 | |||||
5978 | // Lambda can only have immediate invocations in the default | ||||
5979 | // args of their parameters, which is transformed upon calling the closure. | ||||
5980 | // The body is not a subexpression, so we have nothing to do. | ||||
5981 | // FIXME: Immediate calls in capture initializers should be transformed. | ||||
5982 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; } | ||||
5983 | ExprResult TransformBlockExpr(BlockExpr *E) { return E; } | ||||
5984 | |||||
5985 | // Make sure we don't rebuild the this pointer as it would | ||||
5986 | // cause it to incorrectly point it to the outermost class | ||||
5987 | // in the case of nested struct initialization. | ||||
5988 | ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; } | ||||
5989 | }; | ||||
5990 | |||||
5991 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||
5992 | FunctionDecl *FD, ParmVarDecl *Param, | ||||
5993 | Expr *Init) { | ||||
5994 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() && "can't build nonexistent default arg") ? void (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "clang/lib/Sema/SemaExpr.cpp", 5994, __extension__ __PRETTY_FUNCTION__ )); | ||||
5995 | |||||
5996 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); | ||||
5997 | |||||
5998 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> | ||||
5999 | InitializationContext = | ||||
6000 | OutermostDeclarationWithDelayedImmediateInvocations(); | ||||
6001 | if (!InitializationContext.has_value()) | ||||
6002 | InitializationContext.emplace(CallLoc, Param, CurContext); | ||||
6003 | |||||
6004 | if (!Init && !Param->hasUnparsedDefaultArg()) { | ||||
6005 | // Mark that we are replacing a default argument first. | ||||
6006 | // If we are instantiating a template we won't have to | ||||
6007 | // retransform immediate calls. | ||||
6008 | EnterExpressionEvaluationContext EvalContext( | ||||
6009 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||
6010 | |||||
6011 | if (Param->hasUninstantiatedDefaultArg()) { | ||||
6012 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||
6013 | return ExprError(); | ||||
6014 | } | ||||
6015 | // CWG2631 | ||||
6016 | // An immediate invocation that is not evaluated where it appears is | ||||
6017 | // evaluated and checked for whether it is a constant expression at the | ||||
6018 | // point where the enclosing initializer is used in a function call. | ||||
6019 | ImmediateCallVisitor V; | ||||
6020 | if (!NestedDefaultChecking) | ||||
6021 | V.TraverseDecl(Param); | ||||
6022 | if (V.HasImmediateCalls) { | ||||
6023 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { | ||||
6024 | CallLoc, Param, CurContext}; | ||||
6025 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); | ||||
6026 | ExprResult Res = Immediate.TransformInitializer(Param->getInit(), | ||||
6027 | /*NotCopy=*/false); | ||||
6028 | if (Res.isInvalid()) | ||||
6029 | return ExprError(); | ||||
6030 | Res = ConvertParamDefaultArgument(Param, Res.get(), | ||||
6031 | Res.get()->getBeginLoc()); | ||||
6032 | if (Res.isInvalid()) | ||||
6033 | return ExprError(); | ||||
6034 | Init = Res.get(); | ||||
6035 | } | ||||
6036 | } | ||||
6037 | |||||
6038 | if (CheckCXXDefaultArgExpr( | ||||
6039 | CallLoc, FD, Param, Init, | ||||
6040 | /*SkipImmediateInvocations=*/NestedDefaultChecking)) | ||||
6041 | return ExprError(); | ||||
6042 | |||||
6043 | return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param, | ||||
6044 | Init, InitializationContext->Context); | ||||
6045 | } | ||||
6046 | |||||
6047 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { | ||||
6048 | assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer()) ? void (0) : __assert_fail ("Field->hasInClassInitializer()" , "clang/lib/Sema/SemaExpr.cpp", 6048, __extension__ __PRETTY_FUNCTION__ )); | ||||
6049 | |||||
6050 | // If we might have already tried and failed to instantiate, don't try again. | ||||
6051 | if (Field->isInvalidDecl()) | ||||
6052 | return ExprError(); | ||||
6053 | |||||
6054 | auto *ParentRD = cast<CXXRecordDecl>(Field->getParent()); | ||||
6055 | |||||
6056 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> | ||||
6057 | InitializationContext = | ||||
6058 | OutermostDeclarationWithDelayedImmediateInvocations(); | ||||
6059 | if (!InitializationContext.has_value()) | ||||
6060 | InitializationContext.emplace(Loc, Field, CurContext); | ||||
6061 | |||||
6062 | Expr *Init = nullptr; | ||||
6063 | |||||
6064 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); | ||||
6065 | |||||
6066 | EnterExpressionEvaluationContext EvalContext( | ||||
6067 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field); | ||||
6068 | |||||
6069 | if (!Field->getInClassInitializer()) { | ||||
6070 | // Maybe we haven't instantiated the in-class initializer. Go check the | ||||
6071 | // pattern FieldDecl to see if it has one. | ||||
6072 | if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { | ||||
6073 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); | ||||
6074 | DeclContext::lookup_result Lookup = | ||||
6075 | ClassPattern->lookup(Field->getDeclName()); | ||||
6076 | |||||
6077 | FieldDecl *Pattern = nullptr; | ||||
6078 | for (auto *L : Lookup) { | ||||
6079 | if ((Pattern = dyn_cast<FieldDecl>(L))) | ||||
6080 | break; | ||||
6081 | } | ||||
6082 | assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!" ) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\"" , "clang/lib/Sema/SemaExpr.cpp", 6082, __extension__ __PRETTY_FUNCTION__ )); | ||||
6083 | if (!Pattern->hasInClassInitializer() || | ||||
6084 | InstantiateInClassInitializer(Loc, Field, Pattern, | ||||
6085 | getTemplateInstantiationArgs(Field))) { | ||||
6086 | Field->setInvalidDecl(); | ||||
6087 | return ExprError(); | ||||
6088 | } | ||||
6089 | } | ||||
6090 | } | ||||
6091 | |||||
6092 | // CWG2631 | ||||
6093 | // An immediate invocation that is not evaluated where it appears is | ||||
6094 | // evaluated and checked for whether it is a constant expression at the | ||||
6095 | // point where the enclosing initializer is used in a [...] a constructor | ||||
6096 | // definition, or an aggregate initialization. | ||||
6097 | ImmediateCallVisitor V; | ||||
6098 | if (!NestedDefaultChecking) | ||||
6099 | V.TraverseDecl(Field); | ||||
6100 | if (V.HasImmediateCalls) { | ||||
6101 | ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, | ||||
6102 | CurContext}; | ||||
6103 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = | ||||
6104 | NestedDefaultChecking; | ||||
6105 | |||||
6106 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); | ||||
6107 | |||||
6108 | ExprResult Res = | ||||
6109 | Immediate.TransformInitializer(Field->getInClassInitializer(), | ||||
6110 | /*CXXDirectInit=*/false); | ||||
6111 | if (!Res.isInvalid()) | ||||
6112 | Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc); | ||||
6113 | if (Res.isInvalid()) { | ||||
6114 | Field->setInvalidDecl(); | ||||
6115 | return ExprError(); | ||||
6116 | } | ||||
6117 | Init = Res.get(); | ||||
6118 | } | ||||
6119 | |||||
6120 | if (Field->getInClassInitializer()) { | ||||
6121 | Expr *E = Init ? Init : Field->getInClassInitializer(); | ||||
6122 | if (!NestedDefaultChecking) | ||||
6123 | MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false); | ||||
6124 | // C++11 [class.base.init]p7: | ||||
6125 | // The initialization of each base and member constitutes a | ||||
6126 | // full-expression. | ||||
6127 | ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false); | ||||
6128 | if (Res.isInvalid()) { | ||||
6129 | Field->setInvalidDecl(); | ||||
6130 | return ExprError(); | ||||
6131 | } | ||||
6132 | Init = Res.get(); | ||||
6133 | |||||
6134 | return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc, | ||||
6135 | Field, InitializationContext->Context, | ||||
6136 | Init); | ||||
6137 | } | ||||
6138 | |||||
6139 | // DR1351: | ||||
6140 | // If the brace-or-equal-initializer of a non-static data member | ||||
6141 | // invokes a defaulted default constructor of its class or of an | ||||
6142 | // enclosing class in a potentially evaluated subexpression, the | ||||
6143 | // program is ill-formed. | ||||
6144 | // | ||||
6145 | // This resolution is unworkable: the exception specification of the | ||||
6146 | // default constructor can be needed in an unevaluated context, in | ||||
6147 | // particular, in the operand of a noexcept-expression, and we can be | ||||
6148 | // unable to compute an exception specification for an enclosed class. | ||||
6149 | // | ||||
6150 | // Any attempt to resolve the exception specification of a defaulted default | ||||
6151 | // constructor before the initializer is lexically complete will ultimately | ||||
6152 | // come here at which point we can diagnose it. | ||||
6153 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); | ||||
6154 | Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) | ||||
6155 | << OutermostClass << Field; | ||||
6156 | Diag(Field->getEndLoc(), | ||||
6157 | diag::note_default_member_initializer_not_yet_parsed); | ||||
6158 | // Recover by marking the field invalid, unless we're in a SFINAE context. | ||||
6159 | if (!isSFINAEContext()) | ||||
6160 | Field->setInvalidDecl(); | ||||
6161 | return ExprError(); | ||||
6162 | } | ||||
6163 | |||||
6164 | Sema::VariadicCallType | ||||
6165 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||
6166 | Expr *Fn) { | ||||
6167 | if (Proto && Proto->isVariadic()) { | ||||
6168 | if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) | ||||
6169 | return VariadicConstructor; | ||||
6170 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||
6171 | return VariadicBlock; | ||||
6172 | else if (FDecl) { | ||||
6173 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
6174 | if (Method->isInstance()) | ||||
6175 | return VariadicMethod; | ||||
6176 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||
6177 | return VariadicMethod; | ||||
6178 | return VariadicFunction; | ||||
6179 | } | ||||
6180 | return VariadicDoesNotApply; | ||||
6181 | } | ||||
6182 | |||||
6183 | namespace { | ||||
6184 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||
6185 | public: | ||||
6186 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||
6187 | unsigned NumArgs, MemberExpr *ME) | ||||
6188 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||
6189 | FunctionName(FuncName) {} | ||||
6190 | |||||
6191 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
6192 | if (!candidate.getCorrectionSpecifier() || | ||||
6193 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||
6194 | return false; | ||||
6195 | } | ||||
6196 | |||||
6197 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||
6198 | } | ||||
6199 | |||||
6200 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
6201 | return std::make_unique<FunctionCallCCC>(*this); | ||||
6202 | } | ||||
6203 | |||||
6204 | private: | ||||
6205 | const IdentifierInfo *const FunctionName; | ||||
6206 | }; | ||||
6207 | } | ||||
6208 | |||||
6209 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||
6210 | FunctionDecl *FDecl, | ||||
6211 | ArrayRef<Expr *> Args) { | ||||
6212 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||
6213 | DeclarationName FuncName = FDecl->getDeclName(); | ||||
6214 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||
6215 | |||||
6216 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||
6217 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||
6218 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||
6219 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||
6220 | Sema::CTK_ErrorRecovery)) { | ||||
6221 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||
6222 | if (Corrected.isOverloaded()) { | ||||
6223 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||
6224 | OverloadCandidateSet::iterator Best; | ||||
6225 | for (NamedDecl *CD : Corrected) { | ||||
6226 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
6227 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||
6228 | OCS); | ||||
6229 | } | ||||
6230 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||
6231 | case OR_Success: | ||||
6232 | ND = Best->FoundDecl; | ||||
6233 | Corrected.setCorrectionDecl(ND); | ||||
6234 | break; | ||||
6235 | default: | ||||
6236 | break; | ||||
6237 | } | ||||
6238 | } | ||||
6239 | ND = ND->getUnderlyingDecl(); | ||||
6240 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||
6241 | return Corrected; | ||||
6242 | } | ||||
6243 | } | ||||
6244 | return TypoCorrection(); | ||||
6245 | } | ||||
6246 | |||||
6247 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||
6248 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||
6249 | /// function prototype Proto. Call is the call expression itself, and | ||||
6250 | /// Fn is the function expression. For a C++ member function, this | ||||
6251 | /// routine does not attempt to convert the object argument. Returns | ||||
6252 | /// true if the call is ill-formed. | ||||
6253 | bool | ||||
6254 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||
6255 | FunctionDecl *FDecl, | ||||
6256 | const FunctionProtoType *Proto, | ||||
6257 | ArrayRef<Expr *> Args, | ||||
6258 | SourceLocation RParenLoc, | ||||
6259 | bool IsExecConfig) { | ||||
6260 | // Bail out early if calling a builtin with custom typechecking. | ||||
6261 | if (FDecl) | ||||
6262 | if (unsigned ID = FDecl->getBuiltinID()) | ||||
6263 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||
6264 | return false; | ||||
6265 | |||||
6266 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||
6267 | // assignment, to the types of the corresponding parameter, ... | ||||
6268 | unsigned NumParams = Proto->getNumParams(); | ||||
6269 | bool Invalid = false; | ||||
6270 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||
6271 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||
6272 | ? 1 /* block */ | ||||
6273 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||
6274 | : 0 /* function */); | ||||
6275 | |||||
6276 | // If too few arguments are available (and we don't have default | ||||
6277 | // arguments for the remaining parameters), don't make the call. | ||||
6278 | if (Args.size() < NumParams) { | ||||
6279 | if (Args.size() < MinArgs) { | ||||
6280 | TypoCorrection TC; | ||||
6281 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
6282 | unsigned diag_id = | ||||
6283 | MinArgs == NumParams && !Proto->isVariadic() | ||||
6284 | ? diag::err_typecheck_call_too_few_args_suggest | ||||
6285 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||
6286 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||
6287 | << static_cast<unsigned>(Args.size()) | ||||
6288 | << TC.getCorrectionRange()); | ||||
6289 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||
6290 | Diag(RParenLoc, | ||||
6291 | MinArgs == NumParams && !Proto->isVariadic() | ||||
6292 | ? diag::err_typecheck_call_too_few_args_one | ||||
6293 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||
6294 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||
6295 | else | ||||
6296 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||
6297 | ? diag::err_typecheck_call_too_few_args | ||||
6298 | : diag::err_typecheck_call_too_few_args_at_least) | ||||
6299 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||
6300 | << Fn->getSourceRange(); | ||||
6301 | |||||
6302 | // Emit the location of the prototype. | ||||
6303 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
6304 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6305 | |||||
6306 | return true; | ||||
6307 | } | ||||
6308 | // We reserve space for the default arguments when we create | ||||
6309 | // the call expression, before calling ConvertArgumentsForCall. | ||||
6310 | assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "clang/lib/Sema/SemaExpr.cpp", 6311, __extension__ __PRETTY_FUNCTION__ )) | ||||
6311 | "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "clang/lib/Sema/SemaExpr.cpp", 6311, __extension__ __PRETTY_FUNCTION__ )); | ||||
6312 | } | ||||
6313 | |||||
6314 | // If too many are passed and not variadic, error on the extras and drop | ||||
6315 | // them. | ||||
6316 | if (Args.size() > NumParams) { | ||||
6317 | if (!Proto->isVariadic()) { | ||||
6318 | TypoCorrection TC; | ||||
6319 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
6320 | unsigned diag_id = | ||||
6321 | MinArgs == NumParams && !Proto->isVariadic() | ||||
6322 | ? diag::err_typecheck_call_too_many_args_suggest | ||||
6323 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||
6324 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||
6325 | << static_cast<unsigned>(Args.size()) | ||||
6326 | << TC.getCorrectionRange()); | ||||
6327 | } else if (NumParams == 1 && FDecl && | ||||
6328 | FDecl->getParamDecl(0)->getDeclName()) | ||||
6329 | Diag(Args[NumParams]->getBeginLoc(), | ||||
6330 | MinArgs == NumParams | ||||
6331 | ? diag::err_typecheck_call_too_many_args_one | ||||
6332 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||
6333 | << FnKind << FDecl->getParamDecl(0) | ||||
6334 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||
6335 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
6336 | Args.back()->getEndLoc()); | ||||
6337 | else | ||||
6338 | Diag(Args[NumParams]->getBeginLoc(), | ||||
6339 | MinArgs == NumParams | ||||
6340 | ? diag::err_typecheck_call_too_many_args | ||||
6341 | : diag::err_typecheck_call_too_many_args_at_most) | ||||
6342 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||
6343 | << Fn->getSourceRange() | ||||
6344 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
6345 | Args.back()->getEndLoc()); | ||||
6346 | |||||
6347 | // Emit the location of the prototype. | ||||
6348 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
6349 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6350 | |||||
6351 | // This deletes the extra arguments. | ||||
6352 | Call->shrinkNumArgs(NumParams); | ||||
6353 | return true; | ||||
6354 | } | ||||
6355 | } | ||||
6356 | SmallVector<Expr *, 8> AllArgs; | ||||
6357 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||
6358 | |||||
6359 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||
6360 | AllArgs, CallType); | ||||
6361 | if (Invalid) | ||||
6362 | return true; | ||||
6363 | unsigned TotalNumArgs = AllArgs.size(); | ||||
6364 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||
6365 | Call->setArg(i, AllArgs[i]); | ||||
6366 | |||||
6367 | Call->computeDependence(); | ||||
6368 | return false; | ||||
6369 | } | ||||
6370 | |||||
6371 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||
6372 | const FunctionProtoType *Proto, | ||||
6373 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||
6374 | SmallVectorImpl<Expr *> &AllArgs, | ||||
6375 | VariadicCallType CallType, bool AllowExplicit, | ||||
6376 | bool IsListInitialization) { | ||||
6377 | unsigned NumParams = Proto->getNumParams(); | ||||
6378 | bool Invalid = false; | ||||
6379 | size_t ArgIx = 0; | ||||
6380 | // Continue to check argument types (even if we have too few/many args). | ||||
6381 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||
6382 | QualType ProtoArgType = Proto->getParamType(i); | ||||
6383 | |||||
6384 | Expr *Arg; | ||||
6385 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||
6386 | if (ArgIx < Args.size()) { | ||||
6387 | Arg = Args[ArgIx++]; | ||||
6388 | |||||
6389 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||
6390 | diag::err_call_incomplete_argument, Arg)) | ||||
6391 | return true; | ||||
6392 | |||||
6393 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
6394 | bool CFAudited = false; | ||||
6395 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||
6396 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
6397 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
6398 | Arg = stripARCUnbridgedCast(Arg); | ||||
6399 | else if (getLangOpts().ObjCAutoRefCount && | ||||
6400 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
6401 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
6402 | CFAudited = true; | ||||
6403 | |||||
6404 | if (Proto->getExtParameterInfo(i).isNoEscape() && | ||||
6405 | ProtoArgType->isBlockPointerType()) | ||||
6406 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||
6407 | BE->getBlockDecl()->setDoesNotEscape(); | ||||
6408 | |||||
6409 | InitializedEntity Entity = | ||||
6410 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||
6411 | ProtoArgType) | ||||
6412 | : InitializedEntity::InitializeParameter( | ||||
6413 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||
6414 | |||||
6415 | // Remember that parameter belongs to a CF audited API. | ||||
6416 | if (CFAudited) | ||||
6417 | Entity.setParameterCFAudited(); | ||||
6418 | |||||
6419 | ExprResult ArgE = PerformCopyInitialization( | ||||
6420 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||
6421 | if (ArgE.isInvalid()) | ||||
6422 | return true; | ||||
6423 | |||||
6424 | Arg = ArgE.getAs<Expr>(); | ||||
6425 | } else { | ||||
6426 | assert(Param && "can't use default arguments without a known callee")(static_cast <bool> (Param && "can't use default arguments without a known callee" ) ? void (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "clang/lib/Sema/SemaExpr.cpp", 6426, __extension__ __PRETTY_FUNCTION__ )); | ||||
6427 | |||||
6428 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||
6429 | if (ArgExpr.isInvalid()) | ||||
6430 | return true; | ||||
6431 | |||||
6432 | Arg = ArgExpr.getAs<Expr>(); | ||||
6433 | } | ||||
6434 | |||||
6435 | // Check for array bounds violations for each argument to the call. This | ||||
6436 | // check only triggers warnings when the argument isn't a more complex Expr | ||||
6437 | // with its own checking, such as a BinaryOperator. | ||||
6438 | CheckArrayAccess(Arg); | ||||
6439 | |||||
6440 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||
6441 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||
6442 | |||||
6443 | AllArgs.push_back(Arg); | ||||
6444 | } | ||||
6445 | |||||
6446 | // If this is a variadic call, handle args passed through "...". | ||||
6447 | if (CallType != VariadicDoesNotApply) { | ||||
6448 | // Assume that extern "C" functions with variadic arguments that | ||||
6449 | // return __unknown_anytype aren't *really* variadic. | ||||
6450 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||
6451 | FDecl->isExternC()) { | ||||
6452 | for (Expr *A : Args.slice(ArgIx)) { | ||||
6453 | QualType paramType; // ignored | ||||
6454 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | ||||
6455 | Invalid |= arg.isInvalid(); | ||||
6456 | AllArgs.push_back(arg.get()); | ||||
6457 | } | ||||
6458 | |||||
6459 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | ||||
6460 | } else { | ||||
6461 | for (Expr *A : Args.slice(ArgIx)) { | ||||
6462 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | ||||
6463 | Invalid |= Arg.isInvalid(); | ||||
6464 | AllArgs.push_back(Arg.get()); | ||||
6465 | } | ||||
6466 | } | ||||
6467 | |||||
6468 | // Check for array bounds violations. | ||||
6469 | for (Expr *A : Args.slice(ArgIx)) | ||||
6470 | CheckArrayAccess(A); | ||||
6471 | } | ||||
6472 | return Invalid; | ||||
6473 | } | ||||
6474 | |||||
6475 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | ||||
6476 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | ||||
6477 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | ||||
6478 | TL = DTL.getOriginalLoc(); | ||||
6479 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | ||||
6480 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | ||||
6481 | << ATL.getLocalSourceRange(); | ||||
6482 | } | ||||
6483 | |||||
6484 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | ||||
6485 | /// array parameter, check that it is non-null, and that if it is formed by | ||||
6486 | /// array-to-pointer decay, the underlying array is sufficiently large. | ||||
6487 | /// | ||||
6488 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | ||||
6489 | /// array type derivation, then for each call to the function, the value of the | ||||
6490 | /// corresponding actual argument shall provide access to the first element of | ||||
6491 | /// an array with at least as many elements as specified by the size expression. | ||||
6492 | void | ||||
6493 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | ||||
6494 | ParmVarDecl *Param, | ||||
6495 | const Expr *ArgExpr) { | ||||
6496 | // Static array parameters are not supported in C++. | ||||
6497 | if (!Param || getLangOpts().CPlusPlus) | ||||
6498 | return; | ||||
6499 | |||||
6500 | QualType OrigTy = Param->getOriginalType(); | ||||
6501 | |||||
6502 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | ||||
6503 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | ||||
6504 | return; | ||||
6505 | |||||
6506 | if (ArgExpr->isNullPointerConstant(Context, | ||||
6507 | Expr::NPC_NeverValueDependent)) { | ||||
6508 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | ||||
6509 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6510 | return; | ||||
6511 | } | ||||
6512 | |||||
6513 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | ||||
6514 | if (!CAT) | ||||
6515 | return; | ||||
6516 | |||||
6517 | const ConstantArrayType *ArgCAT = | ||||
6518 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | ||||
6519 | if (!ArgCAT) | ||||
6520 | return; | ||||
6521 | |||||
6522 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | ||||
6523 | ArgCAT->getElementType())) { | ||||
6524 | if (ArgCAT->getSize().ult(CAT->getSize())) { | ||||
6525 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6526 | << ArgExpr->getSourceRange() | ||||
6527 | << (unsigned)ArgCAT->getSize().getZExtValue() | ||||
6528 | << (unsigned)CAT->getSize().getZExtValue() << 0; | ||||
6529 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6530 | } | ||||
6531 | return; | ||||
6532 | } | ||||
6533 | |||||
6534 | std::optional<CharUnits> ArgSize = | ||||
6535 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | ||||
6536 | std::optional<CharUnits> ParmSize = | ||||
6537 | getASTContext().getTypeSizeInCharsIfKnown(CAT); | ||||
6538 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | ||||
6539 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6540 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | ||||
6541 | << (unsigned)ParmSize->getQuantity() << 1; | ||||
6542 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6543 | } | ||||
6544 | } | ||||
6545 | |||||
6546 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
6547 | /// to have a function type. | ||||
6548 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | ||||
6549 | |||||
6550 | /// Is the given type a placeholder that we need to lower out | ||||
6551 | /// immediately during argument processing? | ||||
6552 | static bool isPlaceholderToRemoveAsArg(QualType type) { | ||||
6553 | // Placeholders are never sugared. | ||||
6554 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | ||||
6555 | if (!placeholder) return false; | ||||
6556 | |||||
6557 | switch (placeholder->getKind()) { | ||||
6558 | // Ignore all the non-placeholder types. | ||||
6559 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
6560 | case BuiltinType::Id: | ||||
6561 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
6562 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
6563 | case BuiltinType::Id: | ||||
6564 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
6565 | // In practice we'll never use this, since all SVE types are sugared | ||||
6566 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | ||||
6567 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
6568 | case BuiltinType::Id: | ||||
6569 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
6570 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
6571 | case BuiltinType::Id: | ||||
6572 | #include "clang/Basic/PPCTypes.def" | ||||
6573 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
6574 | #include "clang/Basic/RISCVVTypes.def" | ||||
6575 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
6576 | #include "clang/Basic/WebAssemblyReferenceTypes.def" | ||||
6577 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | ||||
6578 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | ||||
6579 | #include "clang/AST/BuiltinTypes.def" | ||||
6580 | return false; | ||||
6581 | |||||
6582 | // We cannot lower out overload sets; they might validly be resolved | ||||
6583 | // by the call machinery. | ||||
6584 | case BuiltinType::Overload: | ||||
6585 | return false; | ||||
6586 | |||||
6587 | // Unbridged casts in ARC can be handled in some call positions and | ||||
6588 | // should be left in place. | ||||
6589 | case BuiltinType::ARCUnbridgedCast: | ||||
6590 | return false; | ||||
6591 | |||||
6592 | // Pseudo-objects should be converted as soon as possible. | ||||
6593 | case BuiltinType::PseudoObject: | ||||
6594 | return true; | ||||
6595 | |||||
6596 | // The debugger mode could theoretically but currently does not try | ||||
6597 | // to resolve unknown-typed arguments based on known parameter types. | ||||
6598 | case BuiltinType::UnknownAny: | ||||
6599 | return true; | ||||
6600 | |||||
6601 | // These are always invalid as call arguments and should be reported. | ||||
6602 | case BuiltinType::BoundMember: | ||||
6603 | case BuiltinType::BuiltinFn: | ||||
6604 | case BuiltinType::IncompleteMatrixIdx: | ||||
6605 | case BuiltinType::OMPArraySection: | ||||
6606 | case BuiltinType::OMPArrayShaping: | ||||
6607 | case BuiltinType::OMPIterator: | ||||
6608 | return true; | ||||
6609 | |||||
6610 | } | ||||
6611 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp" , 6611); | ||||
6612 | } | ||||
6613 | |||||
6614 | /// Check an argument list for placeholders that we won't try to | ||||
6615 | /// handle later. | ||||
6616 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | ||||
6617 | // Apply this processing to all the arguments at once instead of | ||||
6618 | // dying at the first failure. | ||||
6619 | bool hasInvalid = false; | ||||
6620 | for (size_t i = 0, e = args.size(); i != e; i++) { | ||||
6621 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | ||||
6622 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | ||||
6623 | if (result.isInvalid()) hasInvalid = true; | ||||
6624 | else args[i] = result.get(); | ||||
6625 | } | ||||
6626 | } | ||||
6627 | return hasInvalid; | ||||
6628 | } | ||||
6629 | |||||
6630 | /// If a builtin function has a pointer argument with no explicit address | ||||
6631 | /// space, then it should be able to accept a pointer to any address | ||||
6632 | /// space as input. In order to do this, we need to replace the | ||||
6633 | /// standard builtin declaration with one that uses the same address space | ||||
6634 | /// as the call. | ||||
6635 | /// | ||||
6636 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | ||||
6637 | /// it does not contain any pointer arguments without | ||||
6638 | /// an address space qualifer. Otherwise the rewritten | ||||
6639 | /// FunctionDecl is returned. | ||||
6640 | /// TODO: Handle pointer return types. | ||||
6641 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | ||||
6642 | FunctionDecl *FDecl, | ||||
6643 | MultiExprArg ArgExprs) { | ||||
6644 | |||||
6645 | QualType DeclType = FDecl->getType(); | ||||
6646 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | ||||
6647 | |||||
6648 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | ||||
6649 | ArgExprs.size() < FT->getNumParams()) | ||||
6650 | return nullptr; | ||||
6651 | |||||
6652 | bool NeedsNewDecl = false; | ||||
6653 | unsigned i = 0; | ||||
6654 | SmallVector<QualType, 8> OverloadParams; | ||||
6655 | |||||
6656 | for (QualType ParamType : FT->param_types()) { | ||||
6657 | |||||
6658 | // Convert array arguments to pointer to simplify type lookup. | ||||
6659 | ExprResult ArgRes = | ||||
6660 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | ||||
6661 | if (ArgRes.isInvalid()) | ||||
6662 | return nullptr; | ||||
6663 | Expr *Arg = ArgRes.get(); | ||||
6664 | QualType ArgType = Arg->getType(); | ||||
6665 | if (!ParamType->isPointerType() || ParamType.hasAddressSpace() || | ||||
6666 | !ArgType->isPointerType() || | ||||
6667 | !ArgType->getPointeeType().hasAddressSpace() || | ||||
6668 | isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) { | ||||
6669 | OverloadParams.push_back(ParamType); | ||||
6670 | continue; | ||||
6671 | } | ||||
6672 | |||||
6673 | QualType PointeeType = ParamType->getPointeeType(); | ||||
6674 | if (PointeeType.hasAddressSpace()) | ||||
6675 | continue; | ||||
6676 | |||||
6677 | NeedsNewDecl = true; | ||||
6678 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | ||||
6679 | |||||
6680 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | ||||
6681 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | ||||
6682 | } | ||||
6683 | |||||
6684 | if (!NeedsNewDecl) | ||||
6685 | return nullptr; | ||||
6686 | |||||
6687 | FunctionProtoType::ExtProtoInfo EPI; | ||||
6688 | EPI.Variadic = FT->isVariadic(); | ||||
6689 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | ||||
6690 | OverloadParams, EPI); | ||||
6691 | DeclContext *Parent = FDecl->getParent(); | ||||
6692 | FunctionDecl *OverloadDecl = FunctionDecl::Create( | ||||
6693 | Context, Parent, FDecl->getLocation(), FDecl->getLocation(), | ||||
6694 | FDecl->getIdentifier(), OverloadTy, | ||||
6695 | /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), | ||||
6696 | false, | ||||
6697 | /*hasPrototype=*/true); | ||||
6698 | SmallVector<ParmVarDecl*, 16> Params; | ||||
6699 | FT = cast<FunctionProtoType>(OverloadTy); | ||||
6700 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
6701 | QualType ParamType = FT->getParamType(i); | ||||
6702 | ParmVarDecl *Parm = | ||||
6703 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | ||||
6704 | SourceLocation(), nullptr, ParamType, | ||||
6705 | /*TInfo=*/nullptr, SC_None, nullptr); | ||||
6706 | Parm->setScopeInfo(0, i); | ||||
6707 | Params.push_back(Parm); | ||||
6708 | } | ||||
6709 | OverloadDecl->setParams(Params); | ||||
6710 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | ||||
6711 | return OverloadDecl; | ||||
6712 | } | ||||
6713 | |||||
6714 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | ||||
6715 | FunctionDecl *Callee, | ||||
6716 | MultiExprArg ArgExprs) { | ||||
6717 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | ||||
6718 | // similar attributes) really don't like it when functions are called with an | ||||
6719 | // invalid number of args. | ||||
6720 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | ||||
6721 | /*PartialOverloading=*/false) && | ||||
6722 | !Callee->isVariadic()) | ||||
6723 | return; | ||||
6724 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | ||||
6725 | return; | ||||
6726 | |||||
6727 | if (const EnableIfAttr *Attr = | ||||
6728 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | ||||
6729 | S.Diag(Fn->getBeginLoc(), | ||||
6730 | isa<CXXMethodDecl>(Callee) | ||||
6731 | ? diag::err_ovl_no_viable_member_function_in_call | ||||
6732 | : diag::err_ovl_no_viable_function_in_call) | ||||
6733 | << Callee << Callee->getSourceRange(); | ||||
6734 | S.Diag(Callee->getLocation(), | ||||
6735 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | ||||
6736 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | ||||
6737 | return; | ||||
6738 | } | ||||
6739 | } | ||||
6740 | |||||
6741 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | ||||
6742 | const UnresolvedMemberExpr *const UME, Sema &S) { | ||||
6743 | |||||
6744 | const auto GetFunctionLevelDCIfCXXClass = | ||||
6745 | [](Sema &S) -> const CXXRecordDecl * { | ||||
6746 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | ||||
6747 | if (!DC || !DC->getParent()) | ||||
6748 | return nullptr; | ||||
6749 | |||||
6750 | // If the call to some member function was made from within a member | ||||
6751 | // function body 'M' return return 'M's parent. | ||||
6752 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
6753 | return MD->getParent()->getCanonicalDecl(); | ||||
6754 | // else the call was made from within a default member initializer of a | ||||
6755 | // class, so return the class. | ||||
6756 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
6757 | return RD->getCanonicalDecl(); | ||||
6758 | return nullptr; | ||||
6759 | }; | ||||
6760 | // If our DeclContext is neither a member function nor a class (in the | ||||
6761 | // case of a lambda in a default member initializer), we can't have an | ||||
6762 | // enclosing 'this'. | ||||
6763 | |||||
6764 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | ||||
6765 | if (!CurParentClass) | ||||
6766 | return false; | ||||
6767 | |||||
6768 | // The naming class for implicit member functions call is the class in which | ||||
6769 | // name lookup starts. | ||||
6770 | const CXXRecordDecl *const NamingClass = | ||||
6771 | UME->getNamingClass()->getCanonicalDecl(); | ||||
6772 | assert(NamingClass && "Must have naming class even for implicit access")(static_cast <bool> (NamingClass && "Must have naming class even for implicit access" ) ? void (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "clang/lib/Sema/SemaExpr.cpp", 6772, __extension__ __PRETTY_FUNCTION__ )); | ||||
6773 | |||||
6774 | // If the unresolved member functions were found in a 'naming class' that is | ||||
6775 | // related (either the same or derived from) to the class that contains the | ||||
6776 | // member function that itself contained the implicit member access. | ||||
6777 | |||||
6778 | return CurParentClass == NamingClass || | ||||
6779 | CurParentClass->isDerivedFrom(NamingClass); | ||||
6780 | } | ||||
6781 | |||||
6782 | static void | ||||
6783 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6784 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | ||||
6785 | |||||
6786 | if (!UME) | ||||
6787 | return; | ||||
6788 | |||||
6789 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | ||||
6790 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | ||||
6791 | // already been captured, or if this is an implicit member function call (if | ||||
6792 | // it isn't, an attempt to capture 'this' should already have been made). | ||||
6793 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | ||||
6794 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | ||||
6795 | return; | ||||
6796 | |||||
6797 | // Check if the naming class in which the unresolved members were found is | ||||
6798 | // related (same as or is a base of) to the enclosing class. | ||||
6799 | |||||
6800 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | ||||
6801 | return; | ||||
6802 | |||||
6803 | |||||
6804 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | ||||
6805 | // If the enclosing function is not dependent, then this lambda is | ||||
6806 | // capture ready, so if we can capture this, do so. | ||||
6807 | if (!EnclosingFunctionCtx->isDependentContext()) { | ||||
6808 | // If the current lambda and all enclosing lambdas can capture 'this' - | ||||
6809 | // then go ahead and capture 'this' (since our unresolved overload set | ||||
6810 | // contains at least one non-static member function). | ||||
6811 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | ||||
6812 | S.CheckCXXThisCapture(CallLoc); | ||||
6813 | } else if (S.CurContext->isDependentContext()) { | ||||
6814 | // ... since this is an implicit member reference, that might potentially | ||||
6815 | // involve a 'this' capture, mark 'this' for potential capture in | ||||
6816 | // enclosing lambdas. | ||||
6817 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | ||||
6818 | CurLSI->addPotentialThisCapture(CallLoc); | ||||
6819 | } | ||||
6820 | } | ||||
6821 | |||||
6822 | // Once a call is fully resolved, warn for unqualified calls to specific | ||||
6823 | // C++ standard functions, like move and forward. | ||||
6824 | static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { | ||||
6825 | // We are only checking unary move and forward so exit early here. | ||||
6826 | if (Call->getNumArgs() != 1) | ||||
6827 | return; | ||||
6828 | |||||
6829 | Expr *E = Call->getCallee()->IgnoreParenImpCasts(); | ||||
6830 | if (!E || isa<UnresolvedLookupExpr>(E)) | ||||
6831 | return; | ||||
6832 | DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); | ||||
6833 | if (!DRE || !DRE->getLocation().isValid()) | ||||
6834 | return; | ||||
6835 | |||||
6836 | if (DRE->getQualifier()) | ||||
6837 | return; | ||||
6838 | |||||
6839 | const FunctionDecl *FD = Call->getDirectCallee(); | ||||
6840 | if (!FD) | ||||
6841 | return; | ||||
6842 | |||||
6843 | // Only warn for some functions deemed more frequent or problematic. | ||||
6844 | unsigned BuiltinID = FD->getBuiltinID(); | ||||
6845 | if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) | ||||
6846 | return; | ||||
6847 | |||||
6848 | S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) | ||||
6849 | << FD->getQualifiedNameAsString() | ||||
6850 | << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); | ||||
6851 | } | ||||
6852 | |||||
6853 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6854 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6855 | Expr *ExecConfig) { | ||||
6856 | ExprResult Call = | ||||
6857 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6858 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); | ||||
6859 | if (Call.isInvalid()) | ||||
6860 | return Call; | ||||
6861 | |||||
6862 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | ||||
6863 | // language modes. | ||||
6864 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | ||||
6865 | if (ULE->hasExplicitTemplateArgs() && | ||||
6866 | ULE->decls_begin() == ULE->decls_end()) { | ||||
6867 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | ||||
6868 | ? diag::warn_cxx17_compat_adl_only_template_id | ||||
6869 | : diag::ext_adl_only_template_id) | ||||
6870 | << ULE->getName(); | ||||
6871 | } | ||||
6872 | } | ||||
6873 | |||||
6874 | if (LangOpts.OpenMP) | ||||
6875 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | ||||
6876 | ExecConfig); | ||||
6877 | if (LangOpts.CPlusPlus) { | ||||
6878 | CallExpr *CE = dyn_cast<CallExpr>(Call.get()); | ||||
6879 | if (CE) | ||||
6880 | DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); | ||||
6881 | } | ||||
6882 | return Call; | ||||
6883 | } | ||||
6884 | |||||
6885 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | ||||
6886 | /// This provides the location of the left/right parens and a list of comma | ||||
6887 | /// locations. | ||||
6888 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6889 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6890 | Expr *ExecConfig, bool IsExecConfig, | ||||
6891 | bool AllowRecovery) { | ||||
6892 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
6893 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | ||||
6894 | if (Result.isInvalid()) return ExprError(); | ||||
6895 | Fn = Result.get(); | ||||
6896 | |||||
6897 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
6898 | return ExprError(); | ||||
6899 | |||||
6900 | if (getLangOpts().CPlusPlus) { | ||||
6901 | // If this is a pseudo-destructor expression, build the call immediately. | ||||
6902 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | ||||
6903 | if (!ArgExprs.empty()) { | ||||
6904 | // Pseudo-destructor calls should not have any arguments. | ||||
6905 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | ||||
6906 | << FixItHint::CreateRemoval( | ||||
6907 | SourceRange(ArgExprs.front()->getBeginLoc(), | ||||
6908 | ArgExprs.back()->getEndLoc())); | ||||
6909 | } | ||||
6910 | |||||
6911 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | ||||
6912 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6913 | } | ||||
6914 | if (Fn->getType() == Context.PseudoObjectTy) { | ||||
6915 | ExprResult result = CheckPlaceholderExpr(Fn); | ||||
6916 | if (result.isInvalid()) return ExprError(); | ||||
6917 | Fn = result.get(); | ||||
6918 | } | ||||
6919 | |||||
6920 | // Determine whether this is a dependent call inside a C++ template, | ||||
6921 | // in which case we won't do any semantic analysis now. | ||||
6922 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | ||||
6923 | if (ExecConfig) { | ||||
6924 | return CUDAKernelCallExpr::Create(Context, Fn, | ||||
6925 | cast<CallExpr>(ExecConfig), ArgExprs, | ||||
6926 | Context.DependentTy, VK_PRValue, | ||||
6927 | RParenLoc, CurFPFeatureOverrides()); | ||||
6928 | } else { | ||||
6929 | |||||
6930 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6931 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | ||||
6932 | Fn->getBeginLoc()); | ||||
6933 | |||||
6934 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6935 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6936 | } | ||||
6937 | } | ||||
6938 | |||||
6939 | // Determine whether this is a call to an object (C++ [over.call.object]). | ||||
6940 | if (Fn->getType()->isRecordType()) | ||||
6941 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | ||||
6942 | RParenLoc); | ||||
6943 | |||||
6944 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6945 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6946 | if (result.isInvalid()) return ExprError(); | ||||
6947 | Fn = result.get(); | ||||
6948 | } | ||||
6949 | |||||
6950 | if (Fn->getType() == Context.BoundMemberTy) { | ||||
6951 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6952 | RParenLoc, ExecConfig, IsExecConfig, | ||||
6953 | AllowRecovery); | ||||
6954 | } | ||||
6955 | } | ||||
6956 | |||||
6957 | // Check for overloaded calls. This can happen even in C due to extensions. | ||||
6958 | if (Fn->getType() == Context.OverloadTy) { | ||||
6959 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | ||||
6960 | |||||
6961 | // We aren't supposed to apply this logic if there's an '&' involved. | ||||
6962 | if (!find.HasFormOfMemberPointer) { | ||||
6963 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | ||||
6964 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6965 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6966 | OverloadExpr *ovl = find.Expression; | ||||
6967 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | ||||
6968 | return BuildOverloadedCallExpr( | ||||
6969 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6970 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | ||||
6971 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6972 | RParenLoc, ExecConfig, IsExecConfig, | ||||
6973 | AllowRecovery); | ||||
6974 | } | ||||
6975 | } | ||||
6976 | |||||
6977 | // If we're directly calling a function, get the appropriate declaration. | ||||
6978 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6979 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6980 | if (result.isInvalid()) return ExprError(); | ||||
6981 | Fn = result.get(); | ||||
6982 | } | ||||
6983 | |||||
6984 | Expr *NakedFn = Fn->IgnoreParens(); | ||||
6985 | |||||
6986 | bool CallingNDeclIndirectly = false; | ||||
6987 | NamedDecl *NDecl = nullptr; | ||||
6988 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | ||||
6989 | if (UnOp->getOpcode() == UO_AddrOf) { | ||||
6990 | CallingNDeclIndirectly = true; | ||||
6991 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | ||||
6992 | } | ||||
6993 | } | ||||
6994 | |||||
6995 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | ||||
6996 | NDecl = DRE->getDecl(); | ||||
6997 | |||||
6998 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | ||||
6999 | if (FDecl && FDecl->getBuiltinID()) { | ||||
7000 | // Rewrite the function decl for this builtin by replacing parameters | ||||
7001 | // with no explicit address space with the address space of the arguments | ||||
7002 | // in ArgExprs. | ||||
7003 | if ((FDecl = | ||||
7004 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | ||||
7005 | NDecl = FDecl; | ||||
7006 | Fn = DeclRefExpr::Create( | ||||
7007 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | ||||
7008 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | ||||
7009 | nullptr, DRE->isNonOdrUse()); | ||||
7010 | } | ||||
7011 | } | ||||
7012 | } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn)) | ||||
7013 | NDecl = ME->getMemberDecl(); | ||||
7014 | |||||
7015 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | ||||
7016 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | ||||
7017 | FD, /*Complain=*/true, Fn->getBeginLoc())) | ||||
7018 | return ExprError(); | ||||
7019 | |||||
7020 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | ||||
7021 | |||||
7022 | // If this expression is a call to a builtin function in HIP device | ||||
7023 | // compilation, allow a pointer-type argument to default address space to be | ||||
7024 | // passed as a pointer-type parameter to a non-default address space. | ||||
7025 | // If Arg is declared in the default address space and Param is declared | ||||
7026 | // in a non-default address space, perform an implicit address space cast to | ||||
7027 | // the parameter type. | ||||
7028 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && | ||||
7029 | FD->getBuiltinID()) { | ||||
7030 | for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { | ||||
7031 | ParmVarDecl *Param = FD->getParamDecl(Idx); | ||||
7032 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || | ||||
7033 | !ArgExprs[Idx]->getType()->isPointerType()) | ||||
7034 | continue; | ||||
7035 | |||||
7036 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); | ||||
7037 | auto ArgTy = ArgExprs[Idx]->getType(); | ||||
7038 | auto ArgPtTy = ArgTy->getPointeeType(); | ||||
7039 | auto ArgAS = ArgPtTy.getAddressSpace(); | ||||
7040 | |||||
7041 | // Add address space cast if target address spaces are different | ||||
7042 | bool NeedImplicitASC = | ||||
7043 | ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. | ||||
7044 | ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS | ||||
7045 | // or from specific AS which has target AS matching that of Param. | ||||
7046 | getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); | ||||
7047 | if (!NeedImplicitASC) | ||||
7048 | continue; | ||||
7049 | |||||
7050 | // First, ensure that the Arg is an RValue. | ||||
7051 | if (ArgExprs[Idx]->isGLValue()) { | ||||
7052 | ArgExprs[Idx] = ImplicitCastExpr::Create( | ||||
7053 | Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], | ||||
7054 | nullptr, VK_PRValue, FPOptionsOverride()); | ||||
7055 | } | ||||
7056 | |||||
7057 | // Construct a new arg type with address space of Param | ||||
7058 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); | ||||
7059 | ArgPtQuals.setAddressSpace(ParamAS); | ||||
7060 | auto NewArgPtTy = | ||||
7061 | Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); | ||||
7062 | auto NewArgTy = | ||||
7063 | Context.getQualifiedType(Context.getPointerType(NewArgPtTy), | ||||
7064 | ArgTy.getQualifiers()); | ||||
7065 | |||||
7066 | // Finally perform an implicit address space cast | ||||
7067 | ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, | ||||
7068 | CK_AddressSpaceConversion) | ||||
7069 | .get(); | ||||
7070 | } | ||||
7071 | } | ||||
7072 | } | ||||
7073 | |||||
7074 | if (Context.isDependenceAllowed() && | ||||
7075 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
7076 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 7076, __extension__ __PRETTY_FUNCTION__)); | ||||
7077 | assert((Fn->containsErrors() ||(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 7080, __extension__ __PRETTY_FUNCTION__ )) | ||||
7078 | llvm::any_of(ArgExprs,(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 7080, __extension__ __PRETTY_FUNCTION__ )) | ||||
7079 | [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 7080, __extension__ __PRETTY_FUNCTION__ )) | ||||
7080 | "should only occur in error-recovery path.")(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 7080, __extension__ __PRETTY_FUNCTION__ )); | ||||
7081 | QualType ReturnType = | ||||
7082 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | ||||
7083 | ? cast<FunctionDecl>(NDecl)->getCallResultType() | ||||
7084 | : Context.DependentTy; | ||||
7085 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | ||||
7086 | Expr::getValueKindForType(ReturnType), RParenLoc, | ||||
7087 | CurFPFeatureOverrides()); | ||||
7088 | } | ||||
7089 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | ||||
7090 | ExecConfig, IsExecConfig); | ||||
7091 | } | ||||
7092 | |||||
7093 | /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id | ||||
7094 | // with the specified CallArgs | ||||
7095 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, | ||||
7096 | MultiExprArg CallArgs) { | ||||
7097 | StringRef Name = Context.BuiltinInfo.getName(Id); | ||||
7098 | LookupResult R(*this, &Context.Idents.get(Name), Loc, | ||||
7099 | Sema::LookupOrdinaryName); | ||||
7100 | LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); | ||||
7101 | |||||
7102 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); | ||||
7103 | assert(BuiltInDecl && "failed to find builtin declaration")(static_cast <bool> (BuiltInDecl && "failed to find builtin declaration" ) ? void (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\"" , "clang/lib/Sema/SemaExpr.cpp", 7103, __extension__ __PRETTY_FUNCTION__ )); | ||||
7104 | |||||
7105 | ExprResult DeclRef = | ||||
7106 | BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); | ||||
7107 | assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (DeclRef.isUsable() && "Builtin reference cannot fail" ) ? void (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\"" , "clang/lib/Sema/SemaExpr.cpp", 7107, __extension__ __PRETTY_FUNCTION__ )); | ||||
7108 | |||||
7109 | ExprResult Call = | ||||
7110 | BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); | ||||
7111 | |||||
7112 | assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to builtin cannot fail!" ) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\"" , "clang/lib/Sema/SemaExpr.cpp", 7112, __extension__ __PRETTY_FUNCTION__ )); | ||||
7113 | return Call.get(); | ||||
7114 | } | ||||
7115 | |||||
7116 | /// Parse a __builtin_astype expression. | ||||
7117 | /// | ||||
7118 | /// __builtin_astype( value, dst type ) | ||||
7119 | /// | ||||
7120 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | ||||
7121 | SourceLocation BuiltinLoc, | ||||
7122 | SourceLocation RParenLoc) { | ||||
7123 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | ||||
7124 | return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); | ||||
7125 | } | ||||
7126 | |||||
7127 | /// Create a new AsTypeExpr node (bitcast) from the arguments. | ||||
7128 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, | ||||
7129 | SourceLocation BuiltinLoc, | ||||
7130 | SourceLocation RParenLoc) { | ||||
7131 | ExprValueKind VK = VK_PRValue; | ||||
7132 | ExprObjectKind OK = OK_Ordinary; | ||||
7133 | QualType SrcTy = E->getType(); | ||||
7134 | if (!SrcTy->isDependentType() && | ||||
7135 | Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) | ||||
7136 | return ExprError( | ||||
7137 | Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) | ||||
7138 | << DestTy << SrcTy << E->getSourceRange()); | ||||
7139 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); | ||||
7140 | } | ||||
7141 | |||||
7142 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | ||||
7143 | /// provided arguments. | ||||
7144 | /// | ||||
7145 | /// __builtin_convertvector( value, dst type ) | ||||
7146 | /// | ||||
7147 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | ||||
7148 | SourceLocation BuiltinLoc, | ||||
7149 | SourceLocation RParenLoc) { | ||||
7150 | TypeSourceInfo *TInfo; | ||||
7151 | GetTypeFromParser(ParsedDestTy, &TInfo); | ||||
7152 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | ||||
7153 | } | ||||
7154 | |||||
7155 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | ||||
7156 | /// i.e. an expression not of \p OverloadTy. The expression should | ||||
7157 | /// unary-convert to an expression of function-pointer or | ||||
7158 | /// block-pointer type. | ||||
7159 | /// | ||||
7160 | /// \param NDecl the declaration being called, if available | ||||
7161 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | ||||
7162 | SourceLocation LParenLoc, | ||||
7163 | ArrayRef<Expr *> Args, | ||||
7164 | SourceLocation RParenLoc, Expr *Config, | ||||
7165 | bool IsExecConfig, ADLCallKind UsesADL) { | ||||
7166 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | ||||
7167 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | ||||
7168 | |||||
7169 | // Functions with 'interrupt' attribute cannot be called directly. | ||||
7170 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | ||||
7171 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | ||||
7172 | return ExprError(); | ||||
7173 | } | ||||
7174 | |||||
7175 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | ||||
7176 | // so there's some risk when calling out to non-interrupt handler functions | ||||
7177 | // that the callee might not preserve them. This is easy to diagnose here, | ||||
7178 | // but can be very challenging to debug. | ||||
7179 | // Likewise, X86 interrupt handlers may only call routines with attribute | ||||
7180 | // no_caller_saved_registers since there is no efficient way to | ||||
7181 | // save and restore the non-GPR state. | ||||
7182 | if (auto *Caller = getCurFunctionDecl()) { | ||||
7183 | if (Caller->hasAttr<ARMInterruptAttr>()) { | ||||
7184 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | ||||
7185 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { | ||||
7186 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | ||||
7187 | if (FDecl) | ||||
7188 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
7189 | } | ||||
7190 | } | ||||
7191 | if (Caller->hasAttr<AnyX86InterruptAttr>() && | ||||
7192 | ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { | ||||
7193 | Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); | ||||
7194 | if (FDecl) | ||||
7195 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
7196 | } | ||||
7197 | } | ||||
7198 | |||||
7199 | // Promote the function operand. | ||||
7200 | // We special-case function promotion here because we only allow promoting | ||||
7201 | // builtin functions to function pointers in the callee of a call. | ||||
7202 | ExprResult Result; | ||||
7203 | QualType ResultTy; | ||||
7204 | if (BuiltinID && | ||||
7205 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | ||||
7206 | // Extract the return type from the (builtin) function pointer type. | ||||
7207 | // FIXME Several builtins still have setType in | ||||
7208 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | ||||
7209 | // Builtins.def to ensure they are correct before removing setType calls. | ||||
7210 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | ||||
7211 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | ||||
7212 | ResultTy = FDecl->getCallResultType(); | ||||
7213 | } else { | ||||
7214 | Result = CallExprUnaryConversions(Fn); | ||||
7215 | ResultTy = Context.BoolTy; | ||||
7216 | } | ||||
7217 | if (Result.isInvalid()) | ||||
7218 | return ExprError(); | ||||
7219 | Fn = Result.get(); | ||||
7220 | |||||
7221 | // Check for a valid function type, but only if it is not a builtin which | ||||
7222 | // requires custom type checking. These will be handled by | ||||
7223 | // CheckBuiltinFunctionCall below just after creation of the call expression. | ||||
7224 | const FunctionType *FuncT = nullptr; | ||||
7225 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | ||||
7226 | retry: | ||||
7227 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | ||||
7228 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | ||||
7229 | // have type pointer to function". | ||||
7230 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | ||||
7231 | if (!FuncT) | ||||
7232 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
7233 | << Fn->getType() << Fn->getSourceRange()); | ||||
7234 | } else if (const BlockPointerType *BPT = | ||||
7235 | Fn->getType()->getAs<BlockPointerType>()) { | ||||
7236 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | ||||
7237 | } else { | ||||
7238 | // Handle calls to expressions of unknown-any type. | ||||
7239 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
7240 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | ||||
7241 | if (rewrite.isInvalid()) | ||||
7242 | return ExprError(); | ||||
7243 | Fn = rewrite.get(); | ||||
7244 | goto retry; | ||||
7245 | } | ||||
7246 | |||||
7247 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
7248 | << Fn->getType() << Fn->getSourceRange()); | ||||
7249 | } | ||||
7250 | } | ||||
7251 | |||||
7252 | // Get the number of parameters in the function prototype, if any. | ||||
7253 | // We will allocate space for max(Args.size(), NumParams) arguments | ||||
7254 | // in the call expression. | ||||
7255 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | ||||
7256 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; | ||||
7257 | |||||
7258 | CallExpr *TheCall; | ||||
7259 | if (Config) { | ||||
7260 | assert(UsesADL == ADLCallKind::NotADL &&(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "clang/lib/Sema/SemaExpr.cpp", 7261, __extension__ __PRETTY_FUNCTION__ )) | ||||
7261 | "CUDAKernelCallExpr should not use ADL")(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "clang/lib/Sema/SemaExpr.cpp", 7261, __extension__ __PRETTY_FUNCTION__ )); | ||||
7262 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | ||||
7263 | Args, ResultTy, VK_PRValue, RParenLoc, | ||||
7264 | CurFPFeatureOverrides(), NumParams); | ||||
7265 | } else { | ||||
7266 | TheCall = | ||||
7267 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | ||||
7268 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
7269 | } | ||||
7270 | |||||
7271 | if (!Context.isDependenceAllowed()) { | ||||
7272 | // Forget about the nulled arguments since typo correction | ||||
7273 | // do not handle them well. | ||||
7274 | TheCall->shrinkNumArgs(Args.size()); | ||||
7275 | // C cannot always handle TypoExpr nodes in builtin calls and direct | ||||
7276 | // function calls as their argument checking don't necessarily handle | ||||
7277 | // dependent types properly, so make sure any TypoExprs have been | ||||
7278 | // dealt with. | ||||
7279 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | ||||
7280 | if (!Result.isUsable()) return ExprError(); | ||||
7281 | CallExpr *TheOldCall = TheCall; | ||||
7282 | TheCall = dyn_cast<CallExpr>(Result.get()); | ||||
7283 | bool CorrectedTypos = TheCall != TheOldCall; | ||||
7284 | if (!TheCall) return Result; | ||||
7285 | Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | ||||
7286 | |||||
7287 | // A new call expression node was created if some typos were corrected. | ||||
7288 | // However it may not have been constructed with enough storage. In this | ||||
7289 | // case, rebuild the node with enough storage. The waste of space is | ||||
7290 | // immaterial since this only happens when some typos were corrected. | ||||
7291 | if (CorrectedTypos && Args.size() < NumParams) { | ||||
7292 | if (Config) | ||||
7293 | TheCall = CUDAKernelCallExpr::Create( | ||||
7294 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, | ||||
7295 | RParenLoc, CurFPFeatureOverrides(), NumParams); | ||||
7296 | else | ||||
7297 | TheCall = | ||||
7298 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | ||||
7299 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
7300 | } | ||||
7301 | // We can now handle the nulled arguments for the default arguments. | ||||
7302 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | ||||
7303 | } | ||||
7304 | |||||
7305 | // Bail out early if calling a builtin with custom type checking. | ||||
7306 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | ||||
7307 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
7308 | |||||
7309 | if (getLangOpts().CUDA) { | ||||
7310 | if (Config) { | ||||
7311 | // CUDA: Kernel calls must be to global functions | ||||
7312 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
7313 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | ||||
7314 | << FDecl << Fn->getSourceRange()); | ||||
7315 | |||||
7316 | // CUDA: Kernel function must have 'void' return type | ||||
7317 | if (!FuncT->getReturnType()->isVoidType() && | ||||
7318 | !FuncT->getReturnType()->getAs<AutoType>() && | ||||
7319 | !FuncT->getReturnType()->isInstantiationDependentType()) | ||||
7320 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | ||||
7321 | << Fn->getType() << Fn->getSourceRange()); | ||||
7322 | } else { | ||||
7323 | // CUDA: Calls to global functions must be configured | ||||
7324 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
7325 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | ||||
7326 | << FDecl << Fn->getSourceRange()); | ||||
7327 | } | ||||
7328 | } | ||||
7329 | |||||
7330 | // Check for a valid return type | ||||
7331 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | ||||
7332 | FDecl)) | ||||
7333 | return ExprError(); | ||||
7334 | |||||
7335 | // We know the result type of the call, set it. | ||||
7336 | TheCall->setType(FuncT->getCallResultType(Context)); | ||||
7337 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | ||||
7338 | |||||
7339 | if (Proto) { | ||||
7340 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | ||||
7341 | IsExecConfig)) | ||||
7342 | return ExprError(); | ||||
7343 | } else { | ||||
7344 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT ) && "Unknown FunctionType!") ? void (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "clang/lib/Sema/SemaExpr.cpp", 7344, __extension__ __PRETTY_FUNCTION__ )); | ||||
7345 | |||||
7346 | if (FDecl) { | ||||
7347 | // Check if we have too few/too many template arguments, based | ||||
7348 | // on our knowledge of the function definition. | ||||
7349 | const FunctionDecl *Def = nullptr; | ||||
7350 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | ||||
7351 | Proto = Def->getType()->getAs<FunctionProtoType>(); | ||||
7352 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | ||||
7353 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | ||||
7354 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | ||||
7355 | } | ||||
7356 | |||||
7357 | // If the function we're calling isn't a function prototype, but we have | ||||
7358 | // a function prototype from a prior declaratiom, use that prototype. | ||||
7359 | if (!FDecl->hasPrototype()) | ||||
7360 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | ||||
7361 | } | ||||
7362 | |||||
7363 | // If we still haven't found a prototype to use but there are arguments to | ||||
7364 | // the call, diagnose this as calling a function without a prototype. | ||||
7365 | // However, if we found a function declaration, check to see if | ||||
7366 | // -Wdeprecated-non-prototype was disabled where the function was declared. | ||||
7367 | // If so, we will silence the diagnostic here on the assumption that this | ||||
7368 | // interface is intentional and the user knows what they're doing. We will | ||||
7369 | // also silence the diagnostic if there is a function declaration but it | ||||
7370 | // was implicitly defined (the user already gets diagnostics about the | ||||
7371 | // creation of the implicit function declaration, so the additional warning | ||||
7372 | // is not helpful). | ||||
7373 | if (!Proto && !Args.empty() && | ||||
7374 | (!FDecl || (!FDecl->isImplicit() && | ||||
7375 | !Diags.isIgnored(diag::warn_strict_uses_without_prototype, | ||||
7376 | FDecl->getLocation())))) | ||||
7377 | Diag(LParenLoc, diag::warn_strict_uses_without_prototype) | ||||
7378 | << (FDecl != nullptr) << FDecl; | ||||
7379 | |||||
7380 | // Promote the arguments (C99 6.5.2.2p6). | ||||
7381 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
7382 | Expr *Arg = Args[i]; | ||||
7383 | |||||
7384 | if (Proto && i < Proto->getNumParams()) { | ||||
7385 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
7386 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | ||||
7387 | ExprResult ArgE = | ||||
7388 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | ||||
7389 | if (ArgE.isInvalid()) | ||||
7390 | return true; | ||||
7391 | |||||
7392 | Arg = ArgE.getAs<Expr>(); | ||||
7393 | |||||
7394 | } else { | ||||
7395 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | ||||
7396 | |||||
7397 | if (ArgE.isInvalid()) | ||||
7398 | return true; | ||||
7399 | |||||
7400 | Arg = ArgE.getAs<Expr>(); | ||||
7401 | } | ||||
7402 | |||||
7403 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | ||||
7404 | diag::err_call_incomplete_argument, Arg)) | ||||
7405 | return ExprError(); | ||||
7406 | |||||
7407 | TheCall->setArg(i, Arg); | ||||
7408 | } | ||||
7409 | TheCall->computeDependence(); | ||||
7410 | } | ||||
7411 | |||||
7412 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
7413 | if (!Method->isStatic()) | ||||
7414 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | ||||
7415 | << Fn->getSourceRange()); | ||||
7416 | |||||
7417 | // Check for sentinels | ||||
7418 | if (NDecl) | ||||
7419 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | ||||
7420 | |||||
7421 | // Warn for unions passing across security boundary (CMSE). | ||||
7422 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | ||||
7423 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
7424 | if (const auto *RT = | ||||
7425 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | ||||
7426 | if (RT->getDecl()->isOrContainsUnion()) | ||||
7427 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | ||||
7428 | << 0 << i; | ||||
7429 | } | ||||
7430 | } | ||||
7431 | } | ||||
7432 | |||||
7433 | // Do special checking on direct calls to functions. | ||||
7434 | if (FDecl) { | ||||
7435 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | ||||
7436 | return ExprError(); | ||||
7437 | |||||
7438 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | ||||
7439 | |||||
7440 | if (BuiltinID) | ||||
7441 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
7442 | } else if (NDecl) { | ||||
7443 | if (CheckPointerCall(NDecl, TheCall, Proto)) | ||||
7444 | return ExprError(); | ||||
7445 | } else { | ||||
7446 | if (CheckOtherCall(TheCall, Proto)) | ||||
7447 | return ExprError(); | ||||
7448 | } | ||||
7449 | |||||
7450 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | ||||
7451 | } | ||||
7452 | |||||
7453 | ExprResult | ||||
7454 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | ||||
7455 | SourceLocation RParenLoc, Expr *InitExpr) { | ||||
7456 | assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type" ) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 7456, __extension__ __PRETTY_FUNCTION__ )); | ||||
7457 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "clang/lib/Sema/SemaExpr.cpp", 7457, __extension__ __PRETTY_FUNCTION__ )); | ||||
7458 | |||||
7459 | TypeSourceInfo *TInfo; | ||||
7460 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | ||||
7461 | if (!TInfo) | ||||
7462 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | ||||
7463 | |||||
7464 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | ||||
7465 | } | ||||
7466 | |||||
7467 | ExprResult | ||||
7468 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | ||||
7469 | SourceLocation RParenLoc, Expr *LiteralExpr) { | ||||
7470 | QualType literalType = TInfo->getType(); | ||||
7471 | |||||
7472 | if (literalType->isArrayType()) { | ||||
7473 | if (RequireCompleteSizedType( | ||||
7474 | LParenLoc, Context.getBaseElementType(literalType), | ||||
7475 | diag::err_array_incomplete_or_sizeless_type, | ||||
7476 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
7477 | return ExprError(); | ||||
7478 | if (literalType->isVariableArrayType()) { | ||||
7479 | if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, | ||||
7480 | diag::err_variable_object_no_init)) { | ||||
7481 | return ExprError(); | ||||
7482 | } | ||||
7483 | } | ||||
7484 | } else if (!literalType->isDependentType() && | ||||
7485 | RequireCompleteType(LParenLoc, literalType, | ||||
7486 | diag::err_typecheck_decl_incomplete_type, | ||||
7487 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
7488 | return ExprError(); | ||||
7489 | |||||
7490 | InitializedEntity Entity | ||||
7491 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | ||||
7492 | InitializationKind Kind | ||||
7493 | = InitializationKind::CreateCStyleCast(LParenLoc, | ||||
7494 | SourceRange(LParenLoc, RParenLoc), | ||||
7495 | /*InitList=*/true); | ||||
7496 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | ||||
7497 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | ||||
7498 | &literalType); | ||||
7499 | if (Result.isInvalid()) | ||||
7500 | return ExprError(); | ||||
7501 | LiteralExpr = Result.get(); | ||||
7502 | |||||
7503 | bool isFileScope = !CurContext->isFunctionOrMethod(); | ||||
7504 | |||||
7505 | // In C, compound literals are l-values for some reason. | ||||
7506 | // For GCC compatibility, in C++, file-scope array compound literals with | ||||
7507 | // constant initializers are also l-values, and compound literals are | ||||
7508 | // otherwise prvalues. | ||||
7509 | // | ||||
7510 | // (GCC also treats C++ list-initialized file-scope array prvalues with | ||||
7511 | // constant initializers as l-values, but that's non-conforming, so we don't | ||||
7512 | // follow it there.) | ||||
7513 | // | ||||
7514 | // FIXME: It would be better to handle the lvalue cases as materializing and | ||||
7515 | // lifetime-extending a temporary object, but our materialized temporaries | ||||
7516 | // representation only supports lifetime extension from a variable, not "out | ||||
7517 | // of thin air". | ||||
7518 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | ||||
7519 | // is bound to the result of applying array-to-pointer decay to the compound | ||||
7520 | // literal. | ||||
7521 | // FIXME: GCC supports compound literals of reference type, which should | ||||
7522 | // obviously have a value kind derived from the kind of reference involved. | ||||
7523 | ExprValueKind VK = | ||||
7524 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | ||||
7525 | ? VK_PRValue | ||||
7526 | : VK_LValue; | ||||
7527 | |||||
7528 | if (isFileScope) | ||||
7529 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | ||||
7530 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | ||||
7531 | Expr *Init = ILE->getInit(i); | ||||
7532 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | ||||
7533 | } | ||||
7534 | |||||
7535 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | ||||
7536 | VK, LiteralExpr, isFileScope); | ||||
7537 | if (isFileScope) { | ||||
7538 | if (!LiteralExpr->isTypeDependent() && | ||||
7539 | !LiteralExpr->isValueDependent() && | ||||
7540 | !literalType->isDependentType()) // C99 6.5.2.5p3 | ||||
7541 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | ||||
7542 | return ExprError(); | ||||
7543 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | ||||
7544 | literalType.getAddressSpace() != LangAS::Default) { | ||||
7545 | // Embedded-C extensions to C99 6.5.2.5: | ||||
7546 | // "If the compound literal occurs inside the body of a function, the | ||||
7547 | // type name shall not be qualified by an address-space qualifier." | ||||
7548 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | ||||
7549 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | ||||
7550 | return ExprError(); | ||||
7551 | } | ||||
7552 | |||||
7553 | if (!isFileScope && !getLangOpts().CPlusPlus) { | ||||
7554 | // Compound literals that have automatic storage duration are destroyed at | ||||
7555 | // the end of the scope in C; in C++, they're just temporaries. | ||||
7556 | |||||
7557 | // Emit diagnostics if it is or contains a C union type that is non-trivial | ||||
7558 | // to destruct. | ||||
7559 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | ||||
7560 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
7561 | NTCUC_CompoundLiteral, NTCUK_Destruct); | ||||
7562 | |||||
7563 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | ||||
7564 | if (literalType.isDestructedType()) { | ||||
7565 | Cleanup.setExprNeedsCleanups(true); | ||||
7566 | ExprCleanupObjects.push_back(E); | ||||
7567 | getCurFunction()->setHasBranchProtectedScope(); | ||||
7568 | } | ||||
7569 | } | ||||
7570 | |||||
7571 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
7572 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
7573 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | ||||
7574 | E->getInitializer()->getExprLoc()); | ||||
7575 | |||||
7576 | return MaybeBindToTemporary(E); | ||||
7577 | } | ||||
7578 | |||||
7579 | ExprResult | ||||
7580 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7581 | SourceLocation RBraceLoc) { | ||||
7582 | // Only produce each kind of designated initialization diagnostic once. | ||||
7583 | SourceLocation FirstDesignator; | ||||
7584 | bool DiagnosedArrayDesignator = false; | ||||
7585 | bool DiagnosedNestedDesignator = false; | ||||
7586 | bool DiagnosedMixedDesignator = false; | ||||
7587 | |||||
7588 | // Check that any designated initializers are syntactically valid in the | ||||
7589 | // current language mode. | ||||
7590 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7591 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | ||||
7592 | if (FirstDesignator.isInvalid()) | ||||
7593 | FirstDesignator = DIE->getBeginLoc(); | ||||
7594 | |||||
7595 | if (!getLangOpts().CPlusPlus) | ||||
7596 | break; | ||||
7597 | |||||
7598 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | ||||
7599 | DiagnosedNestedDesignator = true; | ||||
7600 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | ||||
7601 | << DIE->getDesignatorsSourceRange(); | ||||
7602 | } | ||||
7603 | |||||
7604 | for (auto &Desig : DIE->designators()) { | ||||
7605 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | ||||
7606 | DiagnosedArrayDesignator = true; | ||||
7607 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | ||||
7608 | << Desig.getSourceRange(); | ||||
7609 | } | ||||
7610 | } | ||||
7611 | |||||
7612 | if (!DiagnosedMixedDesignator && | ||||
7613 | !isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7614 | DiagnosedMixedDesignator = true; | ||||
7615 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7616 | << DIE->getSourceRange(); | ||||
7617 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7618 | << InitArgList[0]->getSourceRange(); | ||||
7619 | } | ||||
7620 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | ||||
7621 | isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7622 | DiagnosedMixedDesignator = true; | ||||
7623 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | ||||
7624 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7625 | << DIE->getSourceRange(); | ||||
7626 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7627 | << InitArgList[I]->getSourceRange(); | ||||
7628 | } | ||||
7629 | } | ||||
7630 | |||||
7631 | if (FirstDesignator.isValid()) { | ||||
7632 | // Only diagnose designated initiaization as a C++20 extension if we didn't | ||||
7633 | // already diagnose use of (non-C++20) C99 designator syntax. | ||||
7634 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | ||||
7635 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | ||||
7636 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | ||||
7637 | ? diag::warn_cxx17_compat_designated_init | ||||
7638 | : diag::ext_cxx_designated_init); | ||||
7639 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | ||||
7640 | Diag(FirstDesignator, diag::ext_designated_init); | ||||
7641 | } | ||||
7642 | } | ||||
7643 | |||||
7644 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | ||||
7645 | } | ||||
7646 | |||||
7647 | ExprResult | ||||
7648 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7649 | SourceLocation RBraceLoc) { | ||||
7650 | // Semantic analysis for initializers is done by ActOnDeclarator() and | ||||
7651 | // CheckInitializer() - it requires knowledge of the object being initialized. | ||||
7652 | |||||
7653 | // Immediately handle non-overload placeholders. Overloads can be | ||||
7654 | // resolved contextually, but everything else here can't. | ||||
7655 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7656 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | ||||
7657 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | ||||
7658 | |||||
7659 | // Ignore failures; dropping the entire initializer list because | ||||
7660 | // of one failure would be terrible for indexing/etc. | ||||
7661 | if (result.isInvalid()) continue; | ||||
7662 | |||||
7663 | InitArgList[I] = result.get(); | ||||
7664 | } | ||||
7665 | } | ||||
7666 | |||||
7667 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | ||||
7668 | RBraceLoc); | ||||
7669 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | ||||
7670 | return E; | ||||
7671 | } | ||||
7672 | |||||
7673 | /// Do an explicit extend of the given block pointer if we're in ARC. | ||||
7674 | void Sema::maybeExtendBlockObject(ExprResult &E) { | ||||
7675 | assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType ()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 7675, __extension__ __PRETTY_FUNCTION__ )); | ||||
7676 | assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0 ) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp" , 7676, __extension__ __PRETTY_FUNCTION__)); | ||||
7677 | |||||
7678 | // Only do this in an r-value context. | ||||
7679 | if (!getLangOpts().ObjCAutoRefCount) return; | ||||
7680 | |||||
7681 | E = ImplicitCastExpr::Create( | ||||
7682 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | ||||
7683 | /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); | ||||
7684 | Cleanup.setExprNeedsCleanups(true); | ||||
7685 | } | ||||
7686 | |||||
7687 | /// Prepare a conversion of the given expression to an ObjC object | ||||
7688 | /// pointer type. | ||||
7689 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | ||||
7690 | QualType type = E.get()->getType(); | ||||
7691 | if (type->isObjCObjectPointerType()) { | ||||
7692 | return CK_BitCast; | ||||
7693 | } else if (type->isBlockPointerType()) { | ||||
7694 | maybeExtendBlockObject(E); | ||||
7695 | return CK_BlockPointerToObjCPointerCast; | ||||
7696 | } else { | ||||
7697 | assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void ( 0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp" , 7697, __extension__ __PRETTY_FUNCTION__)); | ||||
7698 | return CK_CPointerToObjCPointerCast; | ||||
7699 | } | ||||
7700 | } | ||||
7701 | |||||
7702 | /// Prepares for a scalar cast, performing all the necessary stages | ||||
7703 | /// except the final cast and returning the kind required. | ||||
7704 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | ||||
7705 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | ||||
7706 | // Also, callers should have filtered out the invalid cases with | ||||
7707 | // pointers. Everything else should be possible. | ||||
7708 | |||||
7709 | QualType SrcTy = Src.get()->getType(); | ||||
7710 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | ||||
7711 | return CK_NoOp; | ||||
7712 | |||||
7713 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | ||||
7714 | case Type::STK_MemberPointer: | ||||
7715 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7715); | ||||
7716 | |||||
7717 | case Type::STK_CPointer: | ||||
7718 | case Type::STK_BlockPointer: | ||||
7719 | case Type::STK_ObjCObjectPointer: | ||||
7720 | switch (DestTy->getScalarTypeKind()) { | ||||
7721 | case Type::STK_CPointer: { | ||||
7722 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | ||||
7723 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | ||||
7724 | if (SrcAS != DestAS) | ||||
7725 | return CK_AddressSpaceConversion; | ||||
7726 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | ||||
7727 | return CK_NoOp; | ||||
7728 | return CK_BitCast; | ||||
7729 | } | ||||
7730 | case Type::STK_BlockPointer: | ||||
7731 | return (SrcKind == Type::STK_BlockPointer | ||||
7732 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | ||||
7733 | case Type::STK_ObjCObjectPointer: | ||||
7734 | if (SrcKind == Type::STK_ObjCObjectPointer) | ||||
7735 | return CK_BitCast; | ||||
7736 | if (SrcKind == Type::STK_CPointer) | ||||
7737 | return CK_CPointerToObjCPointerCast; | ||||
7738 | maybeExtendBlockObject(Src); | ||||
7739 | return CK_BlockPointerToObjCPointerCast; | ||||
7740 | case Type::STK_Bool: | ||||
7741 | return CK_PointerToBoolean; | ||||
7742 | case Type::STK_Integral: | ||||
7743 | return CK_PointerToIntegral; | ||||
7744 | case Type::STK_Floating: | ||||
7745 | case Type::STK_FloatingComplex: | ||||
7746 | case Type::STK_IntegralComplex: | ||||
7747 | case Type::STK_MemberPointer: | ||||
7748 | case Type::STK_FixedPoint: | ||||
7749 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "clang/lib/Sema/SemaExpr.cpp", 7749); | ||||
7750 | } | ||||
7751 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7751); | ||||
7752 | |||||
7753 | case Type::STK_FixedPoint: | ||||
7754 | switch (DestTy->getScalarTypeKind()) { | ||||
7755 | case Type::STK_FixedPoint: | ||||
7756 | return CK_FixedPointCast; | ||||
7757 | case Type::STK_Bool: | ||||
7758 | return CK_FixedPointToBoolean; | ||||
7759 | case Type::STK_Integral: | ||||
7760 | return CK_FixedPointToIntegral; | ||||
7761 | case Type::STK_Floating: | ||||
7762 | return CK_FixedPointToFloating; | ||||
7763 | case Type::STK_IntegralComplex: | ||||
7764 | case Type::STK_FloatingComplex: | ||||
7765 | Diag(Src.get()->getExprLoc(), | ||||
7766 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7767 | << DestTy; | ||||
7768 | return CK_IntegralCast; | ||||
7769 | case Type::STK_CPointer: | ||||
7770 | case Type::STK_ObjCObjectPointer: | ||||
7771 | case Type::STK_BlockPointer: | ||||
7772 | case Type::STK_MemberPointer: | ||||
7773 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "clang/lib/Sema/SemaExpr.cpp", 7773); | ||||
7774 | } | ||||
7775 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7775); | ||||
7776 | |||||
7777 | case Type::STK_Bool: // casting from bool is like casting from an integer | ||||
7778 | case Type::STK_Integral: | ||||
7779 | switch (DestTy->getScalarTypeKind()) { | ||||
7780 | case Type::STK_CPointer: | ||||
7781 | case Type::STK_ObjCObjectPointer: | ||||
7782 | case Type::STK_BlockPointer: | ||||
7783 | if (Src.get()->isNullPointerConstant(Context, | ||||
7784 | Expr::NPC_ValueDependentIsNull)) | ||||
7785 | return CK_NullToPointer; | ||||
7786 | return CK_IntegralToPointer; | ||||
7787 | case Type::STK_Bool: | ||||
7788 | return CK_IntegralToBoolean; | ||||
7789 | case Type::STK_Integral: | ||||
7790 | return CK_IntegralCast; | ||||
7791 | case Type::STK_Floating: | ||||
7792 | return CK_IntegralToFloating; | ||||
7793 | case Type::STK_IntegralComplex: | ||||
7794 | Src = ImpCastExprToType(Src.get(), | ||||
7795 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7796 | CK_IntegralCast); | ||||
7797 | return CK_IntegralRealToComplex; | ||||
7798 | case Type::STK_FloatingComplex: | ||||
7799 | Src = ImpCastExprToType(Src.get(), | ||||
7800 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7801 | CK_IntegralToFloating); | ||||
7802 | return CK_FloatingRealToComplex; | ||||
7803 | case Type::STK_MemberPointer: | ||||
7804 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7804); | ||||
7805 | case Type::STK_FixedPoint: | ||||
7806 | return CK_IntegralToFixedPoint; | ||||
7807 | } | ||||
7808 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7808); | ||||
7809 | |||||
7810 | case Type::STK_Floating: | ||||
7811 | switch (DestTy->getScalarTypeKind()) { | ||||
7812 | case Type::STK_Floating: | ||||
7813 | return CK_FloatingCast; | ||||
7814 | case Type::STK_Bool: | ||||
7815 | return CK_FloatingToBoolean; | ||||
7816 | case Type::STK_Integral: | ||||
7817 | return CK_FloatingToIntegral; | ||||
7818 | case Type::STK_FloatingComplex: | ||||
7819 | Src = ImpCastExprToType(Src.get(), | ||||
7820 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7821 | CK_FloatingCast); | ||||
7822 | return CK_FloatingRealToComplex; | ||||
7823 | case Type::STK_IntegralComplex: | ||||
7824 | Src = ImpCastExprToType(Src.get(), | ||||
7825 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7826 | CK_FloatingToIntegral); | ||||
7827 | return CK_IntegralRealToComplex; | ||||
7828 | case Type::STK_CPointer: | ||||
7829 | case Type::STK_ObjCObjectPointer: | ||||
7830 | case Type::STK_BlockPointer: | ||||
7831 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7831); | ||||
7832 | case Type::STK_MemberPointer: | ||||
7833 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7833); | ||||
7834 | case Type::STK_FixedPoint: | ||||
7835 | return CK_FloatingToFixedPoint; | ||||
7836 | } | ||||
7837 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7837); | ||||
7838 | |||||
7839 | case Type::STK_FloatingComplex: | ||||
7840 | switch (DestTy->getScalarTypeKind()) { | ||||
7841 | case Type::STK_FloatingComplex: | ||||
7842 | return CK_FloatingComplexCast; | ||||
7843 | case Type::STK_IntegralComplex: | ||||
7844 | return CK_FloatingComplexToIntegralComplex; | ||||
7845 | case Type::STK_Floating: { | ||||
7846 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7847 | if (Context.hasSameType(ET, DestTy)) | ||||
7848 | return CK_FloatingComplexToReal; | ||||
7849 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | ||||
7850 | return CK_FloatingCast; | ||||
7851 | } | ||||
7852 | case Type::STK_Bool: | ||||
7853 | return CK_FloatingComplexToBoolean; | ||||
7854 | case Type::STK_Integral: | ||||
7855 | Src = ImpCastExprToType(Src.get(), | ||||
7856 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7857 | CK_FloatingComplexToReal); | ||||
7858 | return CK_FloatingToIntegral; | ||||
7859 | case Type::STK_CPointer: | ||||
7860 | case Type::STK_ObjCObjectPointer: | ||||
7861 | case Type::STK_BlockPointer: | ||||
7862 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7862); | ||||
7863 | case Type::STK_MemberPointer: | ||||
7864 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7864); | ||||
7865 | case Type::STK_FixedPoint: | ||||
7866 | Diag(Src.get()->getExprLoc(), | ||||
7867 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7868 | << SrcTy; | ||||
7869 | return CK_IntegralCast; | ||||
7870 | } | ||||
7871 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7871); | ||||
7872 | |||||
7873 | case Type::STK_IntegralComplex: | ||||
7874 | switch (DestTy->getScalarTypeKind()) { | ||||
7875 | case Type::STK_FloatingComplex: | ||||
7876 | return CK_IntegralComplexToFloatingComplex; | ||||
7877 | case Type::STK_IntegralComplex: | ||||
7878 | return CK_IntegralComplexCast; | ||||
7879 | case Type::STK_Integral: { | ||||
7880 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7881 | if (Context.hasSameType(ET, DestTy)) | ||||
7882 | return CK_IntegralComplexToReal; | ||||
7883 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | ||||
7884 | return CK_IntegralCast; | ||||
7885 | } | ||||
7886 | case Type::STK_Bool: | ||||
7887 | return CK_IntegralComplexToBoolean; | ||||
7888 | case Type::STK_Floating: | ||||
7889 | Src = ImpCastExprToType(Src.get(), | ||||
7890 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7891 | CK_IntegralComplexToReal); | ||||
7892 | return CK_IntegralToFloating; | ||||
7893 | case Type::STK_CPointer: | ||||
7894 | case Type::STK_ObjCObjectPointer: | ||||
7895 | case Type::STK_BlockPointer: | ||||
7896 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7896); | ||||
7897 | case Type::STK_MemberPointer: | ||||
7898 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7898); | ||||
7899 | case Type::STK_FixedPoint: | ||||
7900 | Diag(Src.get()->getExprLoc(), | ||||
7901 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7902 | << SrcTy; | ||||
7903 | return CK_IntegralCast; | ||||
7904 | } | ||||
7905 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7905); | ||||
7906 | } | ||||
7907 | |||||
7908 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp" , 7908); | ||||
7909 | } | ||||
7910 | |||||
7911 | static bool breakDownVectorType(QualType type, uint64_t &len, | ||||
7912 | QualType &eltType) { | ||||
7913 | // Vectors are simple. | ||||
7914 | if (const VectorType *vecType = type->getAs<VectorType>()) { | ||||
7915 | len = vecType->getNumElements(); | ||||
7916 | eltType = vecType->getElementType(); | ||||
7917 | assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void (0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp" , 7917, __extension__ __PRETTY_FUNCTION__)); | ||||
7918 | return true; | ||||
7919 | } | ||||
7920 | |||||
7921 | // We allow lax conversion to and from non-vector types, but only if | ||||
7922 | // they're real types (i.e. non-complex, non-pointer scalar types). | ||||
7923 | if (!type->isRealType()) return false; | ||||
7924 | |||||
7925 | len = 1; | ||||
7926 | eltType = type; | ||||
7927 | return true; | ||||
7928 | } | ||||
7929 | |||||
7930 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | ||||
7931 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | ||||
7932 | /// allowed? | ||||
7933 | /// | ||||
7934 | /// This will also return false if the two given types do not make sense from | ||||
7935 | /// the perspective of SVE bitcasts. | ||||
7936 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | ||||
7937 | assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy ->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7937, __extension__ __PRETTY_FUNCTION__ )); | ||||
7938 | |||||
7939 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | ||||
7940 | if (!FirstType->isSizelessBuiltinType()) | ||||
7941 | return false; | ||||
7942 | |||||
7943 | const auto *VecTy = SecondType->getAs<VectorType>(); | ||||
7944 | return VecTy && | ||||
7945 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | ||||
7946 | }; | ||||
7947 | |||||
7948 | return ValidScalableConversion(srcTy, destTy) || | ||||
7949 | ValidScalableConversion(destTy, srcTy); | ||||
7950 | } | ||||
7951 | |||||
7952 | /// Are the two types matrix types and do they have the same dimensions i.e. | ||||
7953 | /// do they have the same number of rows and the same number of columns? | ||||
7954 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { | ||||
7955 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) | ||||
7956 | return false; | ||||
7957 | |||||
7958 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); | ||||
7959 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); | ||||
7960 | |||||
7961 | return matSrcType->getNumRows() == matDestType->getNumRows() && | ||||
7962 | matSrcType->getNumColumns() == matDestType->getNumColumns(); | ||||
7963 | } | ||||
7964 | |||||
7965 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { | ||||
7966 | assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast <bool> (DestTy->isVectorType() || SrcTy ->isVectorType()) ? void (0) : __assert_fail ("DestTy->isVectorType() || SrcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7966, __extension__ __PRETTY_FUNCTION__ )); | ||||
7967 | |||||
7968 | uint64_t SrcLen, DestLen; | ||||
7969 | QualType SrcEltTy, DestEltTy; | ||||
7970 | if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) | ||||
7971 | return false; | ||||
7972 | if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) | ||||
7973 | return false; | ||||
7974 | |||||
7975 | // ASTContext::getTypeSize will return the size rounded up to a | ||||
7976 | // power of 2, so instead of using that, we need to use the raw | ||||
7977 | // element size multiplied by the element count. | ||||
7978 | uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); | ||||
7979 | uint64_t DestEltSize = Context.getTypeSize(DestEltTy); | ||||
7980 | |||||
7981 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); | ||||
7982 | } | ||||
7983 | |||||
7984 | // This returns true if at least one of the types is an altivec vector. | ||||
7985 | bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { | ||||
7986 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 7987, __extension__ __PRETTY_FUNCTION__ )) | ||||
7987 | "expected at least one type to be a vector here")(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 7987, __extension__ __PRETTY_FUNCTION__ )); | ||||
7988 | |||||
7989 | bool IsSrcTyAltivec = | ||||
7990 | SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() == | ||||
7991 | VectorType::AltiVecVector); | ||||
7992 | bool IsDestTyAltivec = DestTy->isVectorType() && | ||||
7993 | (DestTy->castAs<VectorType>()->getVectorKind() == | ||||
7994 | VectorType::AltiVecVector); | ||||
7995 | |||||
7996 | return (IsSrcTyAltivec || IsDestTyAltivec); | ||||
7997 | } | ||||
7998 | |||||
7999 | // This returns true if both vectors have the same element type. | ||||
8000 | bool Sema::areSameVectorElemTypes(QualType SrcTy, QualType DestTy) { | ||||
8001 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 8002, __extension__ __PRETTY_FUNCTION__ )) | ||||
8002 | "expected at least one type to be a vector here")(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 8002, __extension__ __PRETTY_FUNCTION__ )); | ||||
8003 | |||||
8004 | uint64_t SrcLen, DestLen; | ||||
8005 | QualType SrcEltTy, DestEltTy; | ||||
8006 | if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) | ||||
8007 | return false; | ||||
8008 | if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) | ||||
8009 | return false; | ||||
8010 | |||||
8011 | return (SrcEltTy == DestEltTy); | ||||
8012 | } | ||||
8013 | |||||
8014 | /// Are the two types lax-compatible vector types? That is, given | ||||
8015 | /// that one of them is a vector, do they have equal storage sizes, | ||||
8016 | /// where the storage size is the number of elements times the element | ||||
8017 | /// size? | ||||
8018 | /// | ||||
8019 | /// This will also return false if either of the types is neither a | ||||
8020 | /// vector nor a real type. | ||||
8021 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | ||||
8022 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 8022, __extension__ __PRETTY_FUNCTION__ )); | ||||
8023 | |||||
8024 | // Disallow lax conversions between scalars and ExtVectors (these | ||||
8025 | // conversions are allowed for other vector types because common headers | ||||
8026 | // depend on them). Most scalar OP ExtVector cases are handled by the | ||||
8027 | // splat path anyway, which does what we want (convert, not bitcast). | ||||
8028 | // What this rules out for ExtVectors is crazy things like char4*float. | ||||
8029 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | ||||
8030 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | ||||
8031 | |||||
8032 | return areVectorTypesSameSize(srcTy, destTy); | ||||
8033 | } | ||||
8034 | |||||
8035 | /// Is this a legal conversion between two types, one of which is | ||||
8036 | /// known to be a vector type? | ||||
8037 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | ||||
8038 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 8038, __extension__ __PRETTY_FUNCTION__ )); | ||||
8039 | |||||
8040 | switch (Context.getLangOpts().getLaxVectorConversions()) { | ||||
8041 | case LangOptions::LaxVectorConversionKind::None: | ||||
8042 | return false; | ||||
8043 | |||||
8044 | case LangOptions::LaxVectorConversionKind::Integer: | ||||
8045 | if (!srcTy->isIntegralOrEnumerationType()) { | ||||
8046 | auto *Vec = srcTy->getAs<VectorType>(); | ||||
8047 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
8048 | return false; | ||||
8049 | } | ||||
8050 | if (!destTy->isIntegralOrEnumerationType()) { | ||||
8051 | auto *Vec = destTy->getAs<VectorType>(); | ||||
8052 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
8053 | return false; | ||||
8054 | } | ||||
8055 | // OK, integer (vector) -> integer (vector) bitcast. | ||||
8056 | break; | ||||
8057 | |||||
8058 | case LangOptions::LaxVectorConversionKind::All: | ||||
8059 | break; | ||||
8060 | } | ||||
8061 | |||||
8062 | return areLaxCompatibleVectorTypes(srcTy, destTy); | ||||
8063 | } | ||||
8064 | |||||
8065 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, | ||||
8066 | CastKind &Kind) { | ||||
8067 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { | ||||
8068 | if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { | ||||
8069 | return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) | ||||
8070 | << DestTy << SrcTy << R; | ||||
8071 | } | ||||
8072 | } else if (SrcTy->isMatrixType()) { | ||||
8073 | return Diag(R.getBegin(), | ||||
8074 | diag::err_invalid_conversion_between_matrix_and_type) | ||||
8075 | << SrcTy << DestTy << R; | ||||
8076 | } else if (DestTy->isMatrixType()) { | ||||
8077 | return Diag(R.getBegin(), | ||||
8078 | diag::err_invalid_conversion_between_matrix_and_type) | ||||
8079 | << DestTy << SrcTy << R; | ||||
8080 | } | ||||
8081 | |||||
8082 | Kind = CK_MatrixCast; | ||||
8083 | return false; | ||||
8084 | } | ||||
8085 | |||||
8086 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | ||||
8087 | CastKind &Kind) { | ||||
8088 | assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast <bool> (VectorTy->isVectorType() && "Not a vector type!") ? void (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "clang/lib/Sema/SemaExpr.cpp", 8088, __extension__ __PRETTY_FUNCTION__ )); | ||||
8089 | |||||
8090 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | ||||
8091 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | ||||
8092 | return Diag(R.getBegin(), | ||||
8093 | Ty->isVectorType() ? | ||||
8094 | diag::err_invalid_conversion_between_vectors : | ||||
8095 | diag::err_invalid_conversion_between_vector_and_integer) | ||||
8096 | << VectorTy << Ty << R; | ||||
8097 | } else | ||||
8098 | return Diag(R.getBegin(), | ||||
8099 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
8100 | << VectorTy << Ty << R; | ||||
8101 | |||||
8102 | Kind = CK_BitCast; | ||||
8103 | return false; | ||||
8104 | } | ||||
8105 | |||||
8106 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | ||||
8107 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | ||||
8108 | |||||
8109 | if (DestElemTy == SplattedExpr->getType()) | ||||
8110 | return SplattedExpr; | ||||
8111 | |||||
8112 | assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaExpr.cpp", 8113, __extension__ __PRETTY_FUNCTION__ )) | ||||
8113 | DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaExpr.cpp", 8113, __extension__ __PRETTY_FUNCTION__ )); | ||||
8114 | |||||
8115 | CastKind CK; | ||||
8116 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | ||||
8117 | // OpenCL requires that we convert `true` boolean expressions to -1, but | ||||
8118 | // only when splatting vectors. | ||||
8119 | if (DestElemTy->isFloatingType()) { | ||||
8120 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | ||||
8121 | // in two steps: boolean to signed integral, then to floating. | ||||
8122 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | ||||
8123 | CK_BooleanToSignedIntegral); | ||||
8124 | SplattedExpr = CastExprRes.get(); | ||||
8125 | CK = CK_IntegralToFloating; | ||||
8126 | } else { | ||||
8127 | CK = CK_BooleanToSignedIntegral; | ||||
8128 | } | ||||
8129 | } else { | ||||
8130 | ExprResult CastExprRes = SplattedExpr; | ||||
8131 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | ||||
8132 | if (CastExprRes.isInvalid()) | ||||
8133 | return ExprError(); | ||||
8134 | SplattedExpr = CastExprRes.get(); | ||||
8135 | } | ||||
8136 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | ||||
8137 | } | ||||
8138 | |||||
8139 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | ||||
8140 | Expr *CastExpr, CastKind &Kind) { | ||||
8141 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast <bool> (DestTy->isExtVectorType() && "Not an extended vector type!") ? void (0) : __assert_fail ( "DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "clang/lib/Sema/SemaExpr.cpp", 8141, __extension__ __PRETTY_FUNCTION__ )); | ||||
8142 | |||||
8143 | QualType SrcTy = CastExpr->getType(); | ||||
8144 | |||||
8145 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | ||||
8146 | // an ExtVectorType. | ||||
8147 | // In OpenCL, casts between vectors of different types are not allowed. | ||||
8148 | // (See OpenCL 6.2). | ||||
8149 | if (SrcTy->isVectorType()) { | ||||
8150 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | ||||
8151 | (getLangOpts().OpenCL && | ||||
8152 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | ||||
8153 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | ||||
8154 | << DestTy << SrcTy << R; | ||||
8155 | return ExprError(); | ||||
8156 | } | ||||
8157 | Kind = CK_BitCast; | ||||
8158 | return CastExpr; | ||||
8159 | } | ||||
8160 | |||||
8161 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | ||||
8162 | // conversion will take place first from scalar to elt type, and then | ||||
8163 | // splat from elt type to vector. | ||||
8164 | if (SrcTy->isPointerType()) | ||||
8165 | return Diag(R.getBegin(), | ||||
8166 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
8167 | << DestTy << SrcTy << R; | ||||
8168 | |||||
8169 | Kind = CK_VectorSplat; | ||||
8170 | return prepareVectorSplat(DestTy, CastExpr); | ||||
8171 | } | ||||
8172 | |||||
8173 | ExprResult | ||||
8174 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | ||||
8175 | Declarator &D, ParsedType &Ty, | ||||
8176 | SourceLocation RParenLoc, Expr *CastExpr) { | ||||
8177 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "clang/lib/Sema/SemaExpr.cpp", 8178, __extension__ __PRETTY_FUNCTION__ )) | ||||
8178 | "ActOnCastExpr(): missing type or expr")(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "clang/lib/Sema/SemaExpr.cpp", 8178, __extension__ __PRETTY_FUNCTION__ )); | ||||
8179 | |||||
8180 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | ||||
8181 | if (D.isInvalidType()) | ||||
8182 | return ExprError(); | ||||
8183 | |||||
8184 | if (getLangOpts().CPlusPlus) { | ||||
8185 | // Check that there are no default arguments (C++ only). | ||||
8186 | CheckExtraCXXDefaultArguments(D); | ||||
8187 | } else { | ||||
8188 | // Make sure any TypoExprs have been dealt with. | ||||
8189 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | ||||
8190 | if (!Res.isUsable()) | ||||
8191 | return ExprError(); | ||||
8192 | CastExpr = Res.get(); | ||||
8193 | } | ||||
8194 | |||||
8195 | checkUnusedDeclAttributes(D); | ||||
8196 | |||||
8197 | QualType castType = castTInfo->getType(); | ||||
8198 | Ty = CreateParsedType(castType, castTInfo); | ||||
8199 | |||||
8200 | bool isVectorLiteral = false; | ||||
8201 | |||||
8202 | // Check for an altivec or OpenCL literal, | ||||
8203 | // i.e. all the elements are integer constants. | ||||
8204 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | ||||
8205 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | ||||
8206 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | ||||
8207 | && castType->isVectorType() && (PE || PLE)) { | ||||
8208 | if (PLE && PLE->getNumExprs() == 0) { | ||||
8209 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | ||||
8210 | return ExprError(); | ||||
8211 | } | ||||
8212 | if (PE || PLE->getNumExprs() == 1) { | ||||
8213 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | ||||
8214 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | ||||
8215 | isVectorLiteral = true; | ||||
8216 | } | ||||
8217 | else | ||||
8218 | isVectorLiteral = true; | ||||
8219 | } | ||||
8220 | |||||
8221 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | ||||
8222 | // then handle it as such. | ||||
8223 | if (isVectorLiteral) | ||||
8224 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | ||||
8225 | |||||
8226 | // If the Expr being casted is a ParenListExpr, handle it specially. | ||||
8227 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | ||||
8228 | // sequence of BinOp comma operators. | ||||
8229 | if (isa<ParenListExpr>(CastExpr)) { | ||||
8230 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | ||||
8231 | if (Result.isInvalid()) return ExprError(); | ||||
8232 | CastExpr = Result.get(); | ||||
8233 | } | ||||
8234 | |||||
8235 | if (getLangOpts().CPlusPlus && !castType->isVoidType()) | ||||
8236 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | ||||
8237 | |||||
8238 | CheckTollFreeBridgeCast(castType, CastExpr); | ||||
8239 | |||||
8240 | CheckObjCBridgeRelatedCast(castType, CastExpr); | ||||
8241 | |||||
8242 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | ||||
8243 | |||||
8244 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | ||||
8245 | } | ||||
8246 | |||||
8247 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | ||||
8248 | SourceLocation RParenLoc, Expr *E, | ||||
8249 | TypeSourceInfo *TInfo) { | ||||
8250 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "clang/lib/Sema/SemaExpr.cpp", 8251, __extension__ __PRETTY_FUNCTION__ )) | ||||
8251 | "Expected paren or paren list expression")(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "clang/lib/Sema/SemaExpr.cpp", 8251, __extension__ __PRETTY_FUNCTION__ )); | ||||
8252 | |||||
8253 | Expr **exprs; | ||||
8254 | unsigned numExprs; | ||||
8255 | Expr *subExpr; | ||||
8256 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | ||||
8257 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | ||||
8258 | LiteralLParenLoc = PE->getLParenLoc(); | ||||
8259 | LiteralRParenLoc = PE->getRParenLoc(); | ||||
8260 | exprs = PE->getExprs(); | ||||
8261 | numExprs = PE->getNumExprs(); | ||||
8262 | } else { // isa<ParenExpr> by assertion at function entrance | ||||
8263 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | ||||
8264 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | ||||
8265 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | ||||
8266 | exprs = &subExpr; | ||||
8267 | numExprs = 1; | ||||
8268 | } | ||||
8269 | |||||
8270 | QualType Ty = TInfo->getType(); | ||||
8271 | assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type" ) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "clang/lib/Sema/SemaExpr.cpp", 8271, __extension__ __PRETTY_FUNCTION__ )); | ||||
8272 | |||||
8273 | SmallVector<Expr *, 8> initExprs; | ||||
8274 | const VectorType *VTy = Ty->castAs<VectorType>(); | ||||
8275 | unsigned numElems = VTy->getNumElements(); | ||||
8276 | |||||
8277 | // '(...)' form of vector initialization in AltiVec: the number of | ||||
8278 | // initializers must be one or must match the size of the vector. | ||||
8279 | // If a single value is specified in the initializer then it will be | ||||
8280 | // replicated to all the components of the vector | ||||
8281 | if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, | ||||
8282 | VTy->getElementType())) | ||||
8283 | return ExprError(); | ||||
8284 | if (ShouldSplatAltivecScalarInCast(VTy)) { | ||||
8285 | // The number of initializers must be one or must match the size of the | ||||
8286 | // vector. If a single value is specified in the initializer then it will | ||||
8287 | // be replicated to all the components of the vector | ||||
8288 | if (numExprs == 1) { | ||||
8289 | QualType ElemTy = VTy->getElementType(); | ||||
8290 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
8291 | if (Literal.isInvalid()) | ||||
8292 | return ExprError(); | ||||
8293 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
8294 | PrepareScalarCast(Literal, ElemTy)); | ||||
8295 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
8296 | } | ||||
8297 | else if (numExprs < numElems) { | ||||
8298 | Diag(E->getExprLoc(), | ||||
8299 | diag::err_incorrect_number_of_vector_initializers); | ||||
8300 | return ExprError(); | ||||
8301 | } | ||||
8302 | else | ||||
8303 | initExprs.append(exprs, exprs + numExprs); | ||||
8304 | } | ||||
8305 | else { | ||||
8306 | // For OpenCL, when the number of initializers is a single value, | ||||
8307 | // it will be replicated to all components of the vector. | ||||
8308 | if (getLangOpts().OpenCL && | ||||
8309 | VTy->getVectorKind() == VectorType::GenericVector && | ||||
8310 | numExprs == 1) { | ||||
8311 | QualType ElemTy = VTy->getElementType(); | ||||
8312 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
8313 | if (Literal.isInvalid()) | ||||
8314 | return ExprError(); | ||||
8315 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
8316 | PrepareScalarCast(Literal, ElemTy)); | ||||
8317 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
8318 | } | ||||
8319 | |||||
8320 | initExprs.append(exprs, exprs + numExprs); | ||||
8321 | } | ||||
8322 | // FIXME: This means that pretty-printing the final AST will produce curly | ||||
8323 | // braces instead of the original commas. | ||||
8324 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | ||||
8325 | initExprs, LiteralRParenLoc); | ||||
8326 | initE->setType(Ty); | ||||
8327 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | ||||
8328 | } | ||||
8329 | |||||
8330 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | ||||
8331 | /// the ParenListExpr into a sequence of comma binary operators. | ||||
8332 | ExprResult | ||||
8333 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | ||||
8334 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | ||||
8335 | if (!E) | ||||
8336 | return OrigExpr; | ||||
8337 | |||||
8338 | ExprResult Result(E->getExpr(0)); | ||||
8339 | |||||
8340 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | ||||
8341 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | ||||
8342 | E->getExpr(i)); | ||||
8343 | |||||
8344 | if (Result.isInvalid()) return ExprError(); | ||||
8345 | |||||
8346 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | ||||
8347 | } | ||||
8348 | |||||
8349 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | ||||
8350 | SourceLocation R, | ||||
8351 | MultiExprArg Val) { | ||||
8352 | return ParenListExpr::Create(Context, L, Val, R); | ||||
8353 | } | ||||
8354 | |||||
8355 | /// Emit a specialized diagnostic when one expression is a null pointer | ||||
8356 | /// constant and the other is not a pointer. Returns true if a diagnostic is | ||||
8357 | /// emitted. | ||||
8358 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | ||||
8359 | SourceLocation QuestionLoc) { | ||||
8360 | Expr *NullExpr = LHSExpr; | ||||
8361 | Expr *NonPointerExpr = RHSExpr; | ||||
8362 | Expr::NullPointerConstantKind NullKind = | ||||
8363 | NullExpr->isNullPointerConstant(Context, | ||||
8364 | Expr::NPC_ValueDependentIsNotNull); | ||||
8365 | |||||
8366 | if (NullKind == Expr::NPCK_NotNull) { | ||||
8367 | NullExpr = RHSExpr; | ||||
8368 | NonPointerExpr = LHSExpr; | ||||
8369 | NullKind = | ||||
8370 | NullExpr->isNullPointerConstant(Context, | ||||
8371 | Expr::NPC_ValueDependentIsNotNull); | ||||
8372 | } | ||||
8373 | |||||
8374 | if (NullKind == Expr::NPCK_NotNull) | ||||
8375 | return false; | ||||
8376 | |||||
8377 | if (NullKind == Expr::NPCK_ZeroExpression) | ||||
8378 | return false; | ||||
8379 | |||||
8380 | if (NullKind == Expr::NPCK_ZeroLiteral) { | ||||
8381 | // In this case, check to make sure that we got here from a "NULL" | ||||
8382 | // string in the source code. | ||||
8383 | NullExpr = NullExpr->IgnoreParenImpCasts(); | ||||
8384 | SourceLocation loc = NullExpr->getExprLoc(); | ||||
8385 | if (!findMacroSpelling(loc, "NULL")) | ||||
8386 | return false; | ||||
8387 | } | ||||
8388 | |||||
8389 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | ||||
8390 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | ||||
8391 | << NonPointerExpr->getType() << DiagType | ||||
8392 | << NonPointerExpr->getSourceRange(); | ||||
8393 | return true; | ||||
8394 | } | ||||
8395 | |||||
8396 | /// Return false if the condition expression is valid, true otherwise. | ||||
8397 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | ||||
8398 | QualType CondTy = Cond->getType(); | ||||
8399 | |||||
8400 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | ||||
8401 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | ||||
8402 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8403 | << CondTy << Cond->getSourceRange(); | ||||
8404 | return true; | ||||
8405 | } | ||||
8406 | |||||
8407 | // C99 6.5.15p2 | ||||
8408 | if (CondTy->isScalarType()) return false; | ||||
8409 | |||||
8410 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | ||||
8411 | << CondTy << Cond->getSourceRange(); | ||||
8412 | return true; | ||||
8413 | } | ||||
8414 | |||||
8415 | /// Return false if the NullExpr can be promoted to PointerTy, | ||||
8416 | /// true otherwise. | ||||
8417 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | ||||
8418 | QualType PointerTy) { | ||||
8419 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | ||||
8420 | !NullExpr.get()->isNullPointerConstant(S.Context, | ||||
8421 | Expr::NPC_ValueDependentIsNull)) | ||||
8422 | return true; | ||||
8423 | |||||
8424 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | ||||
8425 | return false; | ||||
8426 | } | ||||
8427 | |||||
8428 | /// Checks compatibility between two pointers and return the resulting | ||||
8429 | /// type. | ||||
8430 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | ||||
8431 | ExprResult &RHS, | ||||
8432 | SourceLocation Loc) { | ||||
8433 | QualType LHSTy = LHS.get()->getType(); | ||||
8434 | QualType RHSTy = RHS.get()->getType(); | ||||
8435 | |||||
8436 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | ||||
8437 | // Two identical pointers types are always compatible. | ||||
8438 | return S.Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8439 | } | ||||
8440 | |||||
8441 | QualType lhptee, rhptee; | ||||
8442 | |||||
8443 | // Get the pointee types. | ||||
8444 | bool IsBlockPointer = false; | ||||
8445 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | ||||
8446 | lhptee = LHSBTy->getPointeeType(); | ||||
8447 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | ||||
8448 | IsBlockPointer = true; | ||||
8449 | } else { | ||||
8450 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8451 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8452 | } | ||||
8453 | |||||
8454 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | ||||
8455 | // differently qualified versions of compatible types, the result type is | ||||
8456 | // a pointer to an appropriately qualified version of the composite | ||||
8457 | // type. | ||||
8458 | |||||
8459 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | ||||
8460 | // clause doesn't make sense for our extensions. E.g. address space 2 should | ||||
8461 | // be incompatible with address space 3: they may live on different devices or | ||||
8462 | // anything. | ||||
8463 | Qualifiers lhQual = lhptee.getQualifiers(); | ||||
8464 | Qualifiers rhQual = rhptee.getQualifiers(); | ||||
8465 | |||||
8466 | LangAS ResultAddrSpace = LangAS::Default; | ||||
8467 | LangAS LAddrSpace = lhQual.getAddressSpace(); | ||||
8468 | LangAS RAddrSpace = rhQual.getAddressSpace(); | ||||
8469 | |||||
8470 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | ||||
8471 | // spaces is disallowed. | ||||
8472 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | ||||
8473 | ResultAddrSpace = LAddrSpace; | ||||
8474 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | ||||
8475 | ResultAddrSpace = RAddrSpace; | ||||
8476 | else { | ||||
8477 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
8478 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | ||||
8479 | << RHS.get()->getSourceRange(); | ||||
8480 | return QualType(); | ||||
8481 | } | ||||
8482 | |||||
8483 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | ||||
8484 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | ||||
8485 | lhQual.removeCVRQualifiers(); | ||||
8486 | rhQual.removeCVRQualifiers(); | ||||
8487 | |||||
8488 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | ||||
8489 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | ||||
8490 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | ||||
8491 | // qual types are compatible iff | ||||
8492 | // * corresponded types are compatible | ||||
8493 | // * CVR qualifiers are equal | ||||
8494 | // * address spaces are equal | ||||
8495 | // Thus for conditional operator we merge CVR and address space unqualified | ||||
8496 | // pointees and if there is a composite type we return a pointer to it with | ||||
8497 | // merged qualifiers. | ||||
8498 | LHSCastKind = | ||||
8499 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
8500 | RHSCastKind = | ||||
8501 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
8502 | lhQual.removeAddressSpace(); | ||||
8503 | rhQual.removeAddressSpace(); | ||||
8504 | |||||
8505 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | ||||
8506 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | ||||
8507 | |||||
8508 | QualType CompositeTy = S.Context.mergeTypes( | ||||
8509 | lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false, | ||||
8510 | /*BlockReturnType=*/false, /*IsConditionalOperator=*/true); | ||||
8511 | |||||
8512 | if (CompositeTy.isNull()) { | ||||
8513 | // In this situation, we assume void* type. No especially good | ||||
8514 | // reason, but this is what gcc does, and we do have to pick | ||||
8515 | // to get a consistent AST. | ||||
8516 | QualType incompatTy; | ||||
8517 | incompatTy = S.Context.getPointerType( | ||||
8518 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | ||||
8519 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | ||||
8520 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | ||||
8521 | |||||
8522 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | ||||
8523 | // for casts between types with incompatible address space qualifiers. | ||||
8524 | // For the following code the compiler produces casts between global and | ||||
8525 | // local address spaces of the corresponded innermost pointees: | ||||
8526 | // local int *global *a; | ||||
8527 | // global int *global *b; | ||||
8528 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | ||||
8529 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | ||||
8530 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8531 | << RHS.get()->getSourceRange(); | ||||
8532 | |||||
8533 | return incompatTy; | ||||
8534 | } | ||||
8535 | |||||
8536 | // The pointer types are compatible. | ||||
8537 | // In case of OpenCL ResultTy should have the address space qualifier | ||||
8538 | // which is a superset of address spaces of both the 2nd and the 3rd | ||||
8539 | // operands of the conditional operator. | ||||
8540 | QualType ResultTy = [&, ResultAddrSpace]() { | ||||
8541 | if (S.getLangOpts().OpenCL) { | ||||
8542 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | ||||
8543 | CompositeQuals.setAddressSpace(ResultAddrSpace); | ||||
8544 | return S.Context | ||||
8545 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | ||||
8546 | .withCVRQualifiers(MergedCVRQual); | ||||
8547 | } | ||||
8548 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | ||||
8549 | }(); | ||||
8550 | if (IsBlockPointer) | ||||
8551 | ResultTy = S.Context.getBlockPointerType(ResultTy); | ||||
8552 | else | ||||
8553 | ResultTy = S.Context.getPointerType(ResultTy); | ||||
8554 | |||||
8555 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | ||||
8556 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | ||||
8557 | return ResultTy; | ||||
8558 | } | ||||
8559 | |||||
8560 | /// Return the resulting type when the operands are both block pointers. | ||||
8561 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | ||||
8562 | ExprResult &LHS, | ||||
8563 | ExprResult &RHS, | ||||
8564 | SourceLocation Loc) { | ||||
8565 | QualType LHSTy = LHS.get()->getType(); | ||||
8566 | QualType RHSTy = RHS.get()->getType(); | ||||
8567 | |||||
8568 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | ||||
8569 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | ||||
8570 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | ||||
8571 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8572 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8573 | return destType; | ||||
8574 | } | ||||
8575 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | ||||
8576 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8577 | << RHS.get()->getSourceRange(); | ||||
8578 | return QualType(); | ||||
8579 | } | ||||
8580 | |||||
8581 | // We have 2 block pointer types. | ||||
8582 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
8583 | } | ||||
8584 | |||||
8585 | /// Return the resulting type when the operands are both pointers. | ||||
8586 | static QualType | ||||
8587 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | ||||
8588 | ExprResult &RHS, | ||||
8589 | SourceLocation Loc) { | ||||
8590 | // get the pointer types | ||||
8591 | QualType LHSTy = LHS.get()->getType(); | ||||
8592 | QualType RHSTy = RHS.get()->getType(); | ||||
8593 | |||||
8594 | // get the "pointed to" types | ||||
8595 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8596 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8597 | |||||
8598 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | ||||
8599 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | ||||
8600 | // Figure out necessary qualifiers (C99 6.5.15p6) | ||||
8601 | QualType destPointee | ||||
8602 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8603 | QualType destType = S.Context.getPointerType(destPointee); | ||||
8604 | // Add qualifiers if necessary. | ||||
8605 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8606 | // Promote to void*. | ||||
8607 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8608 | return destType; | ||||
8609 | } | ||||
8610 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | ||||
8611 | QualType destPointee | ||||
8612 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8613 | QualType destType = S.Context.getPointerType(destPointee); | ||||
8614 | // Add qualifiers if necessary. | ||||
8615 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8616 | // Promote to void*. | ||||
8617 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8618 | return destType; | ||||
8619 | } | ||||
8620 | |||||
8621 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
8622 | } | ||||
8623 | |||||
8624 | /// Return false if the first expression is not an integer and the second | ||||
8625 | /// expression is not a pointer, true otherwise. | ||||
8626 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | ||||
8627 | Expr* PointerExpr, SourceLocation Loc, | ||||
8628 | bool IsIntFirstExpr) { | ||||
8629 | if (!PointerExpr->getType()->isPointerType() || | ||||
8630 | !Int.get()->getType()->isIntegerType()) | ||||
8631 | return false; | ||||
8632 | |||||
8633 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | ||||
8634 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | ||||
8635 | |||||
8636 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | ||||
8637 | << Expr1->getType() << Expr2->getType() | ||||
8638 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | ||||
8639 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | ||||
8640 | CK_IntegralToPointer); | ||||
8641 | return true; | ||||
8642 | } | ||||
8643 | |||||
8644 | /// Simple conversion between integer and floating point types. | ||||
8645 | /// | ||||
8646 | /// Used when handling the OpenCL conditional operator where the | ||||
8647 | /// condition is a vector while the other operands are scalar. | ||||
8648 | /// | ||||
8649 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | ||||
8650 | /// types are either integer or floating type. Between the two | ||||
8651 | /// operands, the type with the higher rank is defined as the "result | ||||
8652 | /// type". The other operand needs to be promoted to the same type. No | ||||
8653 | /// other type promotion is allowed. We cannot use | ||||
8654 | /// UsualArithmeticConversions() for this purpose, since it always | ||||
8655 | /// promotes promotable types. | ||||
8656 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | ||||
8657 | ExprResult &RHS, | ||||
8658 | SourceLocation QuestionLoc) { | ||||
8659 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
8660 | if (LHS.isInvalid()) | ||||
8661 | return QualType(); | ||||
8662 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
8663 | if (RHS.isInvalid()) | ||||
8664 | return QualType(); | ||||
8665 | |||||
8666 | // For conversion purposes, we ignore any qualifiers. | ||||
8667 | // For example, "const float" and "float" are equivalent. | ||||
8668 | QualType LHSType = | ||||
8669 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
8670 | QualType RHSType = | ||||
8671 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
8672 | |||||
8673 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | ||||
8674 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8675 | << LHSType << LHS.get()->getSourceRange(); | ||||
8676 | return QualType(); | ||||
8677 | } | ||||
8678 | |||||
8679 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | ||||
8680 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8681 | << RHSType << RHS.get()->getSourceRange(); | ||||
8682 | return QualType(); | ||||
8683 | } | ||||
8684 | |||||
8685 | // If both types are identical, no conversion is needed. | ||||
8686 | if (LHSType == RHSType) | ||||
8687 | return LHSType; | ||||
8688 | |||||
8689 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
8690 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
8691 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
8692 | /*IsCompAssign = */ false); | ||||
8693 | |||||
8694 | // Finally, we have two differing integer types. | ||||
8695 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
8696 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | ||||
8697 | } | ||||
8698 | |||||
8699 | /// Convert scalar operands to a vector that matches the | ||||
8700 | /// condition in length. | ||||
8701 | /// | ||||
8702 | /// Used when handling the OpenCL conditional operator where the | ||||
8703 | /// condition is a vector while the other operands are scalar. | ||||
8704 | /// | ||||
8705 | /// We first compute the "result type" for the scalar operands | ||||
8706 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | ||||
8707 | /// into a vector of that type where the length matches the condition | ||||
8708 | /// vector type. s6.11.6 requires that the element types of the result | ||||
8709 | /// and the condition must have the same number of bits. | ||||
8710 | static QualType | ||||
8711 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
8712 | QualType CondTy, SourceLocation QuestionLoc) { | ||||
8713 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | ||||
8714 | if (ResTy.isNull()) return QualType(); | ||||
8715 | |||||
8716 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8717 | assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV" , "clang/lib/Sema/SemaExpr.cpp", 8717, __extension__ __PRETTY_FUNCTION__ )); | ||||
8718 | |||||
8719 | // Determine the vector result type | ||||
8720 | unsigned NumElements = CV->getNumElements(); | ||||
8721 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | ||||
8722 | |||||
8723 | // Ensure that all types have the same number of bits | ||||
8724 | if (S.Context.getTypeSize(CV->getElementType()) | ||||
8725 | != S.Context.getTypeSize(ResTy)) { | ||||
8726 | // Since VectorTy is created internally, it does not pretty print | ||||
8727 | // with an OpenCL name. Instead, we just print a description. | ||||
8728 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | ||||
8729 | SmallString<64> Str; | ||||
8730 | llvm::raw_svector_ostream OS(Str); | ||||
8731 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | ||||
8732 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8733 | << CondTy << OS.str(); | ||||
8734 | return QualType(); | ||||
8735 | } | ||||
8736 | |||||
8737 | // Convert operands to the vector result type | ||||
8738 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | ||||
8739 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | ||||
8740 | |||||
8741 | return VectorTy; | ||||
8742 | } | ||||
8743 | |||||
8744 | /// Return false if this is a valid OpenCL condition vector | ||||
8745 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | ||||
8746 | SourceLocation QuestionLoc) { | ||||
8747 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | ||||
8748 | // integral type. | ||||
8749 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | ||||
8750 | assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail ("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8750, __extension__ __PRETTY_FUNCTION__)); | ||||
8751 | QualType EleTy = CondTy->getElementType(); | ||||
8752 | if (EleTy->isIntegerType()) return false; | ||||
8753 | |||||
8754 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8755 | << Cond->getType() << Cond->getSourceRange(); | ||||
8756 | return true; | ||||
8757 | } | ||||
8758 | |||||
8759 | /// Return false if the vector condition type and the vector | ||||
8760 | /// result type are compatible. | ||||
8761 | /// | ||||
8762 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | ||||
8763 | /// number of elements, and their element types have the same number | ||||
8764 | /// of bits. | ||||
8765 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | ||||
8766 | SourceLocation QuestionLoc) { | ||||
8767 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8768 | const VectorType *RV = VecResTy->getAs<VectorType>(); | ||||
8769 | assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail ("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8769, __extension__ __PRETTY_FUNCTION__)); | ||||
8770 | |||||
8771 | if (CV->getNumElements() != RV->getNumElements()) { | ||||
8772 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | ||||
8773 | << CondTy << VecResTy; | ||||
8774 | return true; | ||||
8775 | } | ||||
8776 | |||||
8777 | QualType CVE = CV->getElementType(); | ||||
8778 | QualType RVE = RV->getElementType(); | ||||
8779 | |||||
8780 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | ||||
8781 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8782 | << CondTy << VecResTy; | ||||
8783 | return true; | ||||
8784 | } | ||||
8785 | |||||
8786 | return false; | ||||
8787 | } | ||||
8788 | |||||
8789 | /// Return the resulting type for the conditional operator in | ||||
8790 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | ||||
8791 | /// s6.3.i) when the condition is a vector type. | ||||
8792 | static QualType | ||||
8793 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | ||||
8794 | ExprResult &LHS, ExprResult &RHS, | ||||
8795 | SourceLocation QuestionLoc) { | ||||
8796 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | ||||
8797 | if (Cond.isInvalid()) | ||||
8798 | return QualType(); | ||||
8799 | QualType CondTy = Cond.get()->getType(); | ||||
8800 | |||||
8801 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | ||||
8802 | return QualType(); | ||||
8803 | |||||
8804 | // If either operand is a vector then find the vector type of the | ||||
8805 | // result as specified in OpenCL v1.1 s6.3.i. | ||||
8806 | if (LHS.get()->getType()->isVectorType() || | ||||
8807 | RHS.get()->getType()->isVectorType()) { | ||||
8808 | bool IsBoolVecLang = | ||||
8809 | !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; | ||||
8810 | QualType VecResTy = | ||||
8811 | S.CheckVectorOperands(LHS, RHS, QuestionLoc, | ||||
8812 | /*isCompAssign*/ false, | ||||
8813 | /*AllowBothBool*/ true, | ||||
8814 | /*AllowBoolConversions*/ false, | ||||
8815 | /*AllowBooleanOperation*/ IsBoolVecLang, | ||||
8816 | /*ReportInvalid*/ true); | ||||
8817 | if (VecResTy.isNull()) | ||||
8818 | return QualType(); | ||||
8819 | // The result type must match the condition type as specified in | ||||
8820 | // OpenCL v1.1 s6.11.6. | ||||
8821 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | ||||
8822 | return QualType(); | ||||
8823 | return VecResTy; | ||||
8824 | } | ||||
8825 | |||||
8826 | // Both operands are scalar. | ||||
8827 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | ||||
8828 | } | ||||
8829 | |||||
8830 | /// Return true if the Expr is block type | ||||
8831 | static bool checkBlockType(Sema &S, const Expr *E) { | ||||
8832 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
8833 | QualType Ty = CE->getCallee()->getType(); | ||||
8834 | if (Ty->isBlockPointerType()) { | ||||
8835 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | ||||
8836 | return true; | ||||
8837 | } | ||||
8838 | } | ||||
8839 | return false; | ||||
8840 | } | ||||
8841 | |||||
8842 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | ||||
8843 | /// In that case, LHS = cond. | ||||
8844 | /// C99 6.5.15 | ||||
8845 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | ||||
8846 | ExprResult &RHS, ExprValueKind &VK, | ||||
8847 | ExprObjectKind &OK, | ||||
8848 | SourceLocation QuestionLoc) { | ||||
8849 | |||||
8850 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | ||||
8851 | if (!LHSResult.isUsable()) return QualType(); | ||||
8852 | LHS = LHSResult; | ||||
8853 | |||||
8854 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | ||||
8855 | if (!RHSResult.isUsable()) return QualType(); | ||||
8856 | RHS = RHSResult; | ||||
8857 | |||||
8858 | // C++ is sufficiently different to merit its own checker. | ||||
8859 | if (getLangOpts().CPlusPlus) | ||||
8860 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | ||||
8861 | |||||
8862 | VK = VK_PRValue; | ||||
8863 | OK = OK_Ordinary; | ||||
8864 | |||||
8865 | if (Context.isDependenceAllowed() && | ||||
8866 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | ||||
8867 | RHS.get()->isTypeDependent())) { | ||||
8868 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 8868, __extension__ __PRETTY_FUNCTION__)); | ||||
8869 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8871, __extension__ __PRETTY_FUNCTION__ )) | ||||
8870 | RHS.get()->containsErrors()) &&(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8871, __extension__ __PRETTY_FUNCTION__ )) | ||||
8871 | "should only occur in error-recovery path.")(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8871, __extension__ __PRETTY_FUNCTION__ )); | ||||
8872 | return Context.DependentTy; | ||||
8873 | } | ||||
8874 | |||||
8875 | // The OpenCL operator with a vector condition is sufficiently | ||||
8876 | // different to merit its own checker. | ||||
8877 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | ||||
8878 | Cond.get()->getType()->isExtVectorType()) | ||||
8879 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | ||||
8880 | |||||
8881 | // First, check the condition. | ||||
8882 | Cond = UsualUnaryConversions(Cond.get()); | ||||
8883 | if (Cond.isInvalid()) | ||||
8884 | return QualType(); | ||||
8885 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | ||||
8886 | return QualType(); | ||||
8887 | |||||
8888 | // Now check the two expressions. | ||||
8889 | if (LHS.get()->getType()->isVectorType() || | ||||
8890 | RHS.get()->getType()->isVectorType()) | ||||
8891 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, | ||||
8892 | /*AllowBothBool*/ true, | ||||
8893 | /*AllowBoolConversions*/ false, | ||||
8894 | /*AllowBooleanOperation*/ false, | ||||
8895 | /*ReportInvalid*/ true); | ||||
8896 | |||||
8897 | QualType ResTy = | ||||
8898 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | ||||
8899 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8900 | return QualType(); | ||||
8901 | |||||
8902 | QualType LHSTy = LHS.get()->getType(); | ||||
8903 | QualType RHSTy = RHS.get()->getType(); | ||||
8904 | |||||
8905 | // Diagnose attempts to convert between __ibm128, __float128 and long double | ||||
8906 | // where such conversions currently can't be handled. | ||||
8907 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | ||||
8908 | Diag(QuestionLoc, | ||||
8909 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | ||||
8910 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8911 | return QualType(); | ||||
8912 | } | ||||
8913 | |||||
8914 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | ||||
8915 | // selection operator (?:). | ||||
8916 | if (getLangOpts().OpenCL && | ||||
8917 | ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { | ||||
8918 | return QualType(); | ||||
8919 | } | ||||
8920 | |||||
8921 | // If both operands have arithmetic type, do the usual arithmetic conversions | ||||
8922 | // to find a common type: C99 6.5.15p3,5. | ||||
8923 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | ||||
8924 | // Disallow invalid arithmetic conversions, such as those between bit- | ||||
8925 | // precise integers types of different sizes, or between a bit-precise | ||||
8926 | // integer and another type. | ||||
8927 | if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { | ||||
8928 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8929 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8930 | << RHS.get()->getSourceRange(); | ||||
8931 | return QualType(); | ||||
8932 | } | ||||
8933 | |||||
8934 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | ||||
8935 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | ||||
8936 | |||||
8937 | return ResTy; | ||||
8938 | } | ||||
8939 | |||||
8940 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | ||||
8941 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | ||||
8942 | return Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8943 | } | ||||
8944 | |||||
8945 | // If both operands are the same structure or union type, the result is that | ||||
8946 | // type. | ||||
8947 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | ||||
8948 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | ||||
8949 | if (LHSRT->getDecl() == RHSRT->getDecl()) | ||||
8950 | // "If both the operands have structure or union type, the result has | ||||
8951 | // that type." This implies that CV qualifiers are dropped. | ||||
8952 | return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(), | ||||
8953 | RHSTy.getUnqualifiedType()); | ||||
8954 | // FIXME: Type of conditional expression must be complete in C mode. | ||||
8955 | } | ||||
8956 | |||||
8957 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | ||||
8958 | // The following || allows only one side to be void (a GCC-ism). | ||||
8959 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | ||||
8960 | QualType ResTy; | ||||
8961 | if (LHSTy->isVoidType() && RHSTy->isVoidType()) { | ||||
8962 | ResTy = Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8963 | } else if (RHSTy->isVoidType()) { | ||||
8964 | ResTy = RHSTy; | ||||
8965 | Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
8966 | << RHS.get()->getSourceRange(); | ||||
8967 | } else { | ||||
8968 | ResTy = LHSTy; | ||||
8969 | Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
8970 | << LHS.get()->getSourceRange(); | ||||
8971 | } | ||||
8972 | LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid); | ||||
8973 | RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid); | ||||
8974 | return ResTy; | ||||
8975 | } | ||||
8976 | |||||
8977 | // C2x 6.5.15p7: | ||||
8978 | // ... if both the second and third operands have nullptr_t type, the | ||||
8979 | // result also has that type. | ||||
8980 | if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy)) | ||||
8981 | return ResTy; | ||||
8982 | |||||
8983 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | ||||
8984 | // the type of the other operand." | ||||
8985 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | ||||
8986 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | ||||
8987 | |||||
8988 | // All objective-c pointer type analysis is done here. | ||||
8989 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | ||||
8990 | QuestionLoc); | ||||
8991 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8992 | return QualType(); | ||||
8993 | if (!compositeType.isNull()) | ||||
8994 | return compositeType; | ||||
8995 | |||||
8996 | |||||
8997 | // Handle block pointer types. | ||||
8998 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | ||||
8999 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | ||||
9000 | QuestionLoc); | ||||
9001 | |||||
9002 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | ||||
9003 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | ||||
9004 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | ||||
9005 | QuestionLoc); | ||||
9006 | |||||
9007 | // GCC compatibility: soften pointer/integer mismatch. Note that | ||||
9008 | // null pointers have been filtered out by this point. | ||||
9009 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | ||||
9010 | /*IsIntFirstExpr=*/true)) | ||||
9011 | return RHSTy; | ||||
9012 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | ||||
9013 | /*IsIntFirstExpr=*/false)) | ||||
9014 | return LHSTy; | ||||
9015 | |||||
9016 | // Allow ?: operations in which both operands have the same | ||||
9017 | // built-in sizeless type. | ||||
9018 | if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) | ||||
9019 | return Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
9020 | |||||
9021 | // Emit a better diagnostic if one of the expressions is a null pointer | ||||
9022 | // constant and the other is not a pointer type. In this case, the user most | ||||
9023 | // likely forgot to take the address of the other expression. | ||||
9024 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | ||||
9025 | return QualType(); | ||||
9026 | |||||
9027 | // Otherwise, the operands are not compatible. | ||||
9028 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
9029 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
9030 | << RHS.get()->getSourceRange(); | ||||
9031 | return QualType(); | ||||
9032 | } | ||||
9033 | |||||
9034 | /// FindCompositeObjCPointerType - Helper method to find composite type of | ||||
9035 | /// two objective-c pointer types of the two input expressions. | ||||
9036 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | ||||
9037 | SourceLocation QuestionLoc) { | ||||
9038 | QualType LHSTy = LHS.get()->getType(); | ||||
9039 | QualType RHSTy = RHS.get()->getType(); | ||||
9040 | |||||
9041 | // Handle things like Class and struct objc_class*. Here we case the result | ||||
9042 | // to the pseudo-builtin, because that will be implicitly cast back to the | ||||
9043 | // redefinition type if an attempt is made to access its fields. | ||||
9044 | if (LHSTy->isObjCClassType() && | ||||
9045 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
9046 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
9047 | return LHSTy; | ||||
9048 | } | ||||
9049 | if (RHSTy->isObjCClassType() && | ||||
9050 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
9051 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
9052 | return RHSTy; | ||||
9053 | } | ||||
9054 | // And the same for struct objc_object* / id | ||||
9055 | if (LHSTy->isObjCIdType() && | ||||
9056 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
9057 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
9058 | return LHSTy; | ||||
9059 | } | ||||
9060 | if (RHSTy->isObjCIdType() && | ||||
9061 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
9062 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
9063 | return RHSTy; | ||||
9064 | } | ||||
9065 | // And the same for struct objc_selector* / SEL | ||||
9066 | if (Context.isObjCSelType(LHSTy) && | ||||
9067 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
9068 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | ||||
9069 | return LHSTy; | ||||
9070 | } | ||||
9071 | if (Context.isObjCSelType(RHSTy) && | ||||
9072 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
9073 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | ||||
9074 | return RHSTy; | ||||
9075 | } | ||||
9076 | // Check constraints for Objective-C object pointers types. | ||||
9077 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
9078 | |||||
9079 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | ||||
9080 | // Two identical object pointer types are always compatible. | ||||
9081 | return LHSTy; | ||||
9082 | } | ||||
9083 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | ||||
9084 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | ||||
9085 | QualType compositeType = LHSTy; | ||||
9086 | |||||
9087 | // If both operands are interfaces and either operand can be | ||||
9088 | // assigned to the other, use that type as the composite | ||||
9089 | // type. This allows | ||||
9090 | // xxx ? (A*) a : (B*) b | ||||
9091 | // where B is a subclass of A. | ||||
9092 | // | ||||
9093 | // Additionally, as for assignment, if either type is 'id' | ||||
9094 | // allow silent coercion. Finally, if the types are | ||||
9095 | // incompatible then make sure to use 'id' as the composite | ||||
9096 | // type so the result is acceptable for sending messages to. | ||||
9097 | |||||
9098 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | ||||
9099 | // It could return the composite type. | ||||
9100 | if (!(compositeType = | ||||
9101 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | ||||
9102 | // Nothing more to do. | ||||
9103 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | ||||
9104 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | ||||
9105 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | ||||
9106 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | ||||
9107 | } else if ((LHSOPT->isObjCQualifiedIdType() || | ||||
9108 | RHSOPT->isObjCQualifiedIdType()) && | ||||
9109 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | ||||
9110 | true)) { | ||||
9111 | // Need to handle "id<xx>" explicitly. | ||||
9112 | // GCC allows qualified id and any Objective-C type to devolve to | ||||
9113 | // id. Currently localizing to here until clear this should be | ||||
9114 | // part of ObjCQualifiedIdTypesAreCompatible. | ||||
9115 | compositeType = Context.getObjCIdType(); | ||||
9116 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | ||||
9117 | compositeType = Context.getObjCIdType(); | ||||
9118 | } else { | ||||
9119 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | ||||
9120 | << LHSTy << RHSTy | ||||
9121 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
9122 | QualType incompatTy = Context.getObjCIdType(); | ||||
9123 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | ||||
9124 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | ||||
9125 | return incompatTy; | ||||
9126 | } | ||||
9127 | // The object pointer types are compatible. | ||||
9128 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | ||||
9129 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | ||||
9130 | return compositeType; | ||||
9131 | } | ||||
9132 | // Check Objective-C object pointer types and 'void *' | ||||
9133 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
9134 | if (getLangOpts().ObjCAutoRefCount) { | ||||
9135 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
9136 | // so these types are not compatible. | ||||
9137 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
9138 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
9139 | LHS = RHS = true; | ||||
9140 | return QualType(); | ||||
9141 | } | ||||
9142 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
9143 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9144 | QualType destPointee | ||||
9145 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
9146 | QualType destType = Context.getPointerType(destPointee); | ||||
9147 | // Add qualifiers if necessary. | ||||
9148 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
9149 | // Promote to void*. | ||||
9150 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
9151 | return destType; | ||||
9152 | } | ||||
9153 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | ||||
9154 | if (getLangOpts().ObjCAutoRefCount) { | ||||
9155 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
9156 | // so these types are not compatible. | ||||
9157 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
9158 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
9159 | LHS = RHS = true; | ||||
9160 | return QualType(); | ||||
9161 | } | ||||
9162 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9163 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
9164 | QualType destPointee | ||||
9165 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
9166 | QualType destType = Context.getPointerType(destPointee); | ||||
9167 | // Add qualifiers if necessary. | ||||
9168 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
9169 | // Promote to void*. | ||||
9170 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
9171 | return destType; | ||||
9172 | } | ||||
9173 | return QualType(); | ||||
9174 | } | ||||
9175 | |||||
9176 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | ||||
9177 | /// ParenRange in parentheses. | ||||
9178 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | ||||
9179 | const PartialDiagnostic &Note, | ||||
9180 | SourceRange ParenRange) { | ||||
9181 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | ||||
9182 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | ||||
9183 | EndLoc.isValid()) { | ||||
9184 | Self.Diag(Loc, Note) | ||||
9185 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | ||||
9186 | << FixItHint::CreateInsertion(EndLoc, ")"); | ||||
9187 | } else { | ||||
9188 | // We can't display the parentheses, so just show the bare note. | ||||
9189 | Self.Diag(Loc, Note) << ParenRange; | ||||
9190 | } | ||||
9191 | } | ||||
9192 | |||||
9193 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | ||||
9194 | return BinaryOperator::isAdditiveOp(Opc) || | ||||
9195 | BinaryOperator::isMultiplicativeOp(Opc) || | ||||
9196 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | ||||
9197 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | ||||
9198 | // not any of the logical operators. Bitwise-xor is commonly used as a | ||||
9199 | // logical-xor because there is no logical-xor operator. The logical | ||||
9200 | // operators, including uses of xor, have a high false positive rate for | ||||
9201 | // precedence warnings. | ||||
9202 | } | ||||
9203 | |||||
9204 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | ||||
9205 | /// expression, either using a built-in or overloaded operator, | ||||
9206 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | ||||
9207 | /// expression. | ||||
9208 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | ||||
9209 | Expr **RHSExprs) { | ||||
9210 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | ||||
9211 | E = E->IgnoreImpCasts(); | ||||
9212 | E = E->IgnoreConversionOperatorSingleStep(); | ||||
9213 | E = E->IgnoreImpCasts(); | ||||
9214 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | ||||
9215 | E = MTE->getSubExpr(); | ||||
9216 | E = E->IgnoreImpCasts(); | ||||
9217 | } | ||||
9218 | |||||
9219 | // Built-in binary operator. | ||||
9220 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | ||||
9221 | if (IsArithmeticOp(OP->getOpcode())) { | ||||
9222 | *Opcode = OP->getOpcode(); | ||||
9223 | *RHSExprs = OP->getRHS(); | ||||
9224 | return true; | ||||
9225 | } | ||||
9226 | } | ||||
9227 | |||||
9228 | // Overloaded operator. | ||||
9229 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
9230 | if (Call->getNumArgs() != 2) | ||||
9231 | return false; | ||||
9232 | |||||
9233 | // Make sure this is really a binary operator that is safe to pass into | ||||
9234 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | ||||
9235 | OverloadedOperatorKind OO = Call->getOperator(); | ||||
9236 | if (OO < OO_Plus || OO > OO_Arrow || | ||||
9237 | OO == OO_PlusPlus || OO == OO_MinusMinus) | ||||
9238 | return false; | ||||
9239 | |||||
9240 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | ||||
9241 | if (IsArithmeticOp(OpKind)) { | ||||
9242 | *Opcode = OpKind; | ||||
9243 | *RHSExprs = Call->getArg(1); | ||||
9244 | return true; | ||||
9245 | } | ||||
9246 | } | ||||
9247 | |||||
9248 | return false; | ||||
9249 | } | ||||
9250 | |||||
9251 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | ||||
9252 | /// or is a logical expression such as (x==y) which has int type, but is | ||||
9253 | /// commonly interpreted as boolean. | ||||
9254 | static bool ExprLooksBoolean(Expr *E) { | ||||
9255 | E = E->IgnoreParenImpCasts(); | ||||
9256 | |||||
9257 | if (E->getType()->isBooleanType()) | ||||
9258 | return true; | ||||
9259 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | ||||
9260 | return OP->isComparisonOp() || OP->isLogicalOp(); | ||||
9261 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | ||||
9262 | return OP->getOpcode() == UO_LNot; | ||||
9263 | if (E->getType()->isPointerType()) | ||||
9264 | return true; | ||||
9265 | // FIXME: What about overloaded operator calls returning "unspecified boolean | ||||
9266 | // type"s (commonly pointer-to-members)? | ||||
9267 | |||||
9268 | return false; | ||||
9269 | } | ||||
9270 | |||||
9271 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | ||||
9272 | /// and binary operator are mixed in a way that suggests the programmer assumed | ||||
9273 | /// the conditional operator has higher precedence, for example: | ||||
9274 | /// "int x = a + someBinaryCondition ? 1 : 2". | ||||
9275 | static void DiagnoseConditionalPrecedence(Sema &Self, | ||||
9276 | SourceLocation OpLoc, | ||||
9277 | Expr *Condition, | ||||
9278 | Expr *LHSExpr, | ||||
9279 | Expr *RHSExpr) { | ||||
9280 | BinaryOperatorKind CondOpcode; | ||||
9281 | Expr *CondRHS; | ||||
9282 | |||||
9283 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | ||||
9284 | return; | ||||
9285 | if (!ExprLooksBoolean(CondRHS)) | ||||
9286 | return; | ||||
9287 | |||||
9288 | // The condition is an arithmetic binary expression, with a right- | ||||
9289 | // hand side that looks boolean, so warn. | ||||
9290 | |||||
9291 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | ||||
9292 | ? diag::warn_precedence_bitwise_conditional | ||||
9293 | : diag::warn_precedence_conditional; | ||||
9294 | |||||
9295 | Self.Diag(OpLoc, DiagID) | ||||
9296 | << Condition->getSourceRange() | ||||
9297 | << BinaryOperator::getOpcodeStr(CondOpcode); | ||||
9298 | |||||
9299 | SuggestParentheses( | ||||
9300 | Self, OpLoc, | ||||
9301 | Self.PDiag(diag::note_precedence_silence) | ||||
9302 | << BinaryOperator::getOpcodeStr(CondOpcode), | ||||
9303 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | ||||
9304 | |||||
9305 | SuggestParentheses(Self, OpLoc, | ||||
9306 | Self.PDiag(diag::note_precedence_conditional_first), | ||||
9307 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
9308 | } | ||||
9309 | |||||
9310 | /// Compute the nullability of a conditional expression. | ||||
9311 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | ||||
9312 | QualType LHSTy, QualType RHSTy, | ||||
9313 | ASTContext &Ctx) { | ||||
9314 | if (!ResTy->isAnyPointerType()) | ||||
9315 | return ResTy; | ||||
9316 | |||||
9317 | auto GetNullability = [](QualType Ty) { | ||||
9318 | std::optional<NullabilityKind> Kind = Ty->getNullability(); | ||||
9319 | if (Kind) { | ||||
9320 | // For our purposes, treat _Nullable_result as _Nullable. | ||||
9321 | if (*Kind == NullabilityKind::NullableResult) | ||||
9322 | return NullabilityKind::Nullable; | ||||
9323 | return *Kind; | ||||
9324 | } | ||||
9325 | return NullabilityKind::Unspecified; | ||||
9326 | }; | ||||
9327 | |||||
9328 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | ||||
9329 | NullabilityKind MergedKind; | ||||
9330 | |||||
9331 | // Compute nullability of a binary conditional expression. | ||||
9332 | if (IsBin) { | ||||
9333 | if (LHSKind == NullabilityKind::NonNull) | ||||
9334 | MergedKind = NullabilityKind::NonNull; | ||||
9335 | else | ||||
9336 | MergedKind = RHSKind; | ||||
9337 | // Compute nullability of a normal conditional expression. | ||||
9338 | } else { | ||||
9339 | if (LHSKind == NullabilityKind::Nullable || | ||||
9340 | RHSKind == NullabilityKind::Nullable) | ||||
9341 | MergedKind = NullabilityKind::Nullable; | ||||
9342 | else if (LHSKind == NullabilityKind::NonNull) | ||||
9343 | MergedKind = RHSKind; | ||||
9344 | else if (RHSKind == NullabilityKind::NonNull) | ||||
9345 | MergedKind = LHSKind; | ||||
9346 | else | ||||
9347 | MergedKind = NullabilityKind::Unspecified; | ||||
9348 | } | ||||
9349 | |||||
9350 | // Return if ResTy already has the correct nullability. | ||||
9351 | if (GetNullability(ResTy) == MergedKind) | ||||
9352 | return ResTy; | ||||
9353 | |||||
9354 | // Strip all nullability from ResTy. | ||||
9355 | while (ResTy->getNullability()) | ||||
9356 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | ||||
9357 | |||||
9358 | // Create a new AttributedType with the new nullability kind. | ||||
9359 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | ||||
9360 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | ||||
9361 | } | ||||
9362 | |||||
9363 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | ||||
9364 | /// in the case of a the GNU conditional expr extension. | ||||
9365 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | ||||
9366 | SourceLocation ColonLoc, | ||||
9367 | Expr *CondExpr, Expr *LHSExpr, | ||||
9368 | Expr *RHSExpr) { | ||||
9369 | if (!Context.isDependenceAllowed()) { | ||||
9370 | // C cannot handle TypoExpr nodes in the condition because it | ||||
9371 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
9372 | // been dealt with before checking the operands. | ||||
9373 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | ||||
9374 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | ||||
9375 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | ||||
9376 | |||||
9377 | if (!CondResult.isUsable()) | ||||
9378 | return ExprError(); | ||||
9379 | |||||
9380 | if (LHSExpr) { | ||||
9381 | if (!LHSResult.isUsable()) | ||||
9382 | return ExprError(); | ||||
9383 | } | ||||
9384 | |||||
9385 | if (!RHSResult.isUsable()) | ||||
9386 | return ExprError(); | ||||
9387 | |||||
9388 | CondExpr = CondResult.get(); | ||||
9389 | LHSExpr = LHSResult.get(); | ||||
9390 | RHSExpr = RHSResult.get(); | ||||
9391 | } | ||||
9392 | |||||
9393 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | ||||
9394 | // was the condition. | ||||
9395 | OpaqueValueExpr *opaqueValue = nullptr; | ||||
9396 | Expr *commonExpr = nullptr; | ||||
9397 | if (!LHSExpr) { | ||||
9398 | commonExpr = CondExpr; | ||||
9399 | // Lower out placeholder types first. This is important so that we don't | ||||
9400 | // try to capture a placeholder. This happens in few cases in C++; such | ||||
9401 | // as Objective-C++'s dictionary subscripting syntax. | ||||
9402 | if (commonExpr->hasPlaceholderType()) { | ||||
9403 | ExprResult result = CheckPlaceholderExpr(commonExpr); | ||||
9404 | if (!result.isUsable()) return ExprError(); | ||||
9405 | commonExpr = result.get(); | ||||
9406 | } | ||||
9407 | // We usually want to apply unary conversions *before* saving, except | ||||
9408 | // in the special case of a C++ l-value conditional. | ||||
9409 | if (!(getLangOpts().CPlusPlus | ||||
9410 | && !commonExpr->isTypeDependent() | ||||
9411 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | ||||
9412 | && commonExpr->isGLValue() | ||||
9413 | && commonExpr->isOrdinaryOrBitFieldObject() | ||||
9414 | && RHSExpr->isOrdinaryOrBitFieldObject() | ||||
9415 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | ||||
9416 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | ||||
9417 | if (commonRes.isInvalid()) | ||||
9418 | return ExprError(); | ||||
9419 | commonExpr = commonRes.get(); | ||||
9420 | } | ||||
9421 | |||||
9422 | // If the common expression is a class or array prvalue, materialize it | ||||
9423 | // so that we can safely refer to it multiple times. | ||||
9424 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || | ||||
9425 | commonExpr->getType()->isArrayType())) { | ||||
9426 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | ||||
9427 | if (MatExpr.isInvalid()) | ||||
9428 | return ExprError(); | ||||
9429 | commonExpr = MatExpr.get(); | ||||
9430 | } | ||||
9431 | |||||
9432 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | ||||
9433 | commonExpr->getType(), | ||||
9434 | commonExpr->getValueKind(), | ||||
9435 | commonExpr->getObjectKind(), | ||||
9436 | commonExpr); | ||||
9437 | LHSExpr = CondExpr = opaqueValue; | ||||
9438 | } | ||||
9439 | |||||
9440 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | ||||
9441 | ExprValueKind VK = VK_PRValue; | ||||
9442 | ExprObjectKind OK = OK_Ordinary; | ||||
9443 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | ||||
9444 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | ||||
9445 | VK, OK, QuestionLoc); | ||||
9446 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | ||||
9447 | RHS.isInvalid()) | ||||
9448 | return ExprError(); | ||||
9449 | |||||
9450 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | ||||
9451 | RHS.get()); | ||||
9452 | |||||
9453 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | ||||
9454 | |||||
9455 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | ||||
9456 | Context); | ||||
9457 | |||||
9458 | if (!commonExpr) | ||||
9459 | return new (Context) | ||||
9460 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | ||||
9461 | RHS.get(), result, VK, OK); | ||||
9462 | |||||
9463 | return new (Context) BinaryConditionalOperator( | ||||
9464 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | ||||
9465 | ColonLoc, result, VK, OK); | ||||
9466 | } | ||||
9467 | |||||
9468 | // Check if we have a conversion between incompatible cmse function pointer | ||||
9469 | // types, that is, a conversion between a function pointer with the | ||||
9470 | // cmse_nonsecure_call attribute and one without. | ||||
9471 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | ||||
9472 | QualType ToType) { | ||||
9473 | if (const auto *ToFn = | ||||
9474 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | ||||
9475 | if (const auto *FromFn = | ||||
9476 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | ||||
9477 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | ||||
9478 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | ||||
9479 | |||||
9480 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | ||||
9481 | } | ||||
9482 | } | ||||
9483 | return false; | ||||
9484 | } | ||||
9485 | |||||
9486 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | ||||
9487 | // being closely modeled after the C99 spec:-). The odd characteristic of this | ||||
9488 | // routine is it effectively iqnores the qualifiers on the top level pointee. | ||||
9489 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | ||||
9490 | // FIXME: add a couple examples in this comment. | ||||
9491 | static Sema::AssignConvertType | ||||
9492 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, | ||||
9493 | SourceLocation Loc) { | ||||
9494 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9494, __extension__ __PRETTY_FUNCTION__ )); | ||||
9495 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9495, __extension__ __PRETTY_FUNCTION__ )); | ||||
9496 | |||||
9497 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
9498 | const Type *lhptee, *rhptee; | ||||
9499 | Qualifiers lhq, rhq; | ||||
9500 | std::tie(lhptee, lhq) = | ||||
9501 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | ||||
9502 | std::tie(rhptee, rhq) = | ||||
9503 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | ||||
9504 | |||||
9505 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
9506 | |||||
9507 | // C99 6.5.16.1p1: This following citation is common to constraints | ||||
9508 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | ||||
9509 | // qualifiers of the type *pointed to* by the right; | ||||
9510 | |||||
9511 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | ||||
9512 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | ||||
9513 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | ||||
9514 | // Ignore lifetime for further calculation. | ||||
9515 | lhq.removeObjCLifetime(); | ||||
9516 | rhq.removeObjCLifetime(); | ||||
9517 | } | ||||
9518 | |||||
9519 | if (!lhq.compatiblyIncludes(rhq)) { | ||||
9520 | // Treat address-space mismatches as fatal. | ||||
9521 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | ||||
9522 | return Sema::IncompatiblePointerDiscardsQualifiers; | ||||
9523 | |||||
9524 | // It's okay to add or remove GC or lifetime qualifiers when converting to | ||||
9525 | // and from void*. | ||||
9526 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | ||||
9527 | .compatiblyIncludes( | ||||
9528 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | ||||
9529 | && (lhptee->isVoidType() || rhptee->isVoidType())) | ||||
9530 | ; // keep old | ||||
9531 | |||||
9532 | // Treat lifetime mismatches as fatal. | ||||
9533 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | ||||
9534 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | ||||
9535 | |||||
9536 | // For GCC/MS compatibility, other qualifier mismatches are treated | ||||
9537 | // as still compatible in C. | ||||
9538 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
9539 | } | ||||
9540 | |||||
9541 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | ||||
9542 | // incomplete type and the other is a pointer to a qualified or unqualified | ||||
9543 | // version of void... | ||||
9544 | if (lhptee->isVoidType()) { | ||||
9545 | if (rhptee->isIncompleteOrObjectType()) | ||||
9546 | return ConvTy; | ||||
9547 | |||||
9548 | // As an extension, we allow cast to/from void* to function pointer. | ||||
9549 | assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void (0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp" , 9549, __extension__ __PRETTY_FUNCTION__)); | ||||
9550 | return Sema::FunctionVoidPointer; | ||||
9551 | } | ||||
9552 | |||||
9553 | if (rhptee->isVoidType()) { | ||||
9554 | if (lhptee->isIncompleteOrObjectType()) | ||||
9555 | return ConvTy; | ||||
9556 | |||||
9557 | // As an extension, we allow cast to/from void* to function pointer. | ||||
9558 | assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void (0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp" , 9558, __extension__ __PRETTY_FUNCTION__)); | ||||
9559 | return Sema::FunctionVoidPointer; | ||||
9560 | } | ||||
9561 | |||||
9562 | if (!S.Diags.isIgnored( | ||||
9563 | diag::warn_typecheck_convert_incompatible_function_pointer_strict, | ||||
9564 | Loc) && | ||||
9565 | RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() && | ||||
9566 | !S.IsFunctionConversion(RHSType, LHSType, RHSType)) | ||||
9567 | return Sema::IncompatibleFunctionPointerStrict; | ||||
9568 | |||||
9569 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | ||||
9570 | // unqualified versions of compatible types, ... | ||||
9571 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | ||||
9572 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | ||||
9573 | // Check if the pointee types are compatible ignoring the sign. | ||||
9574 | // We explicitly check for char so that we catch "char" vs | ||||
9575 | // "unsigned char" on systems where "char" is unsigned. | ||||
9576 | if (lhptee->isCharType()) | ||||
9577 | ltrans = S.Context.UnsignedCharTy; | ||||
9578 | else if (lhptee->hasSignedIntegerRepresentation()) | ||||
9579 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | ||||
9580 | |||||
9581 | if (rhptee->isCharType()) | ||||
9582 | rtrans = S.Context.UnsignedCharTy; | ||||
9583 | else if (rhptee->hasSignedIntegerRepresentation()) | ||||
9584 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | ||||
9585 | |||||
9586 | if (ltrans == rtrans) { | ||||
9587 | // Types are compatible ignoring the sign. Qualifier incompatibility | ||||
9588 | // takes priority over sign incompatibility because the sign | ||||
9589 | // warning can be disabled. | ||||
9590 | if (ConvTy != Sema::Compatible) | ||||
9591 | return ConvTy; | ||||
9592 | |||||
9593 | return Sema::IncompatiblePointerSign; | ||||
9594 | } | ||||
9595 | |||||
9596 | // If we are a multi-level pointer, it's possible that our issue is simply | ||||
9597 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | ||||
9598 | // the eventual target type is the same and the pointers have the same | ||||
9599 | // level of indirection, this must be the issue. | ||||
9600 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | ||||
9601 | do { | ||||
9602 | std::tie(lhptee, lhq) = | ||||
9603 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | ||||
9604 | std::tie(rhptee, rhq) = | ||||
9605 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | ||||
9606 | |||||
9607 | // Inconsistent address spaces at this point is invalid, even if the | ||||
9608 | // address spaces would be compatible. | ||||
9609 | // FIXME: This doesn't catch address space mismatches for pointers of | ||||
9610 | // different nesting levels, like: | ||||
9611 | // __local int *** a; | ||||
9612 | // int ** b = a; | ||||
9613 | // It's not clear how to actually determine when such pointers are | ||||
9614 | // invalidly incompatible. | ||||
9615 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | ||||
9616 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | ||||
9617 | |||||
9618 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | ||||
9619 | |||||
9620 | if (lhptee == rhptee) | ||||
9621 | return Sema::IncompatibleNestedPointerQualifiers; | ||||
9622 | } | ||||
9623 | |||||
9624 | // General pointer incompatibility takes priority over qualifiers. | ||||
9625 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | ||||
9626 | return Sema::IncompatibleFunctionPointer; | ||||
9627 | return Sema::IncompatiblePointer; | ||||
9628 | } | ||||
9629 | if (!S.getLangOpts().CPlusPlus && | ||||
9630 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | ||||
9631 | return Sema::IncompatibleFunctionPointer; | ||||
9632 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | ||||
9633 | return Sema::IncompatibleFunctionPointer; | ||||
9634 | return ConvTy; | ||||
9635 | } | ||||
9636 | |||||
9637 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | ||||
9638 | /// block pointer types are compatible or whether a block and normal pointer | ||||
9639 | /// are compatible. It is more restrict than comparing two function pointer | ||||
9640 | // types. | ||||
9641 | static Sema::AssignConvertType | ||||
9642 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
9643 | QualType RHSType) { | ||||
9644 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9644, __extension__ __PRETTY_FUNCTION__ )); | ||||
9645 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9645, __extension__ __PRETTY_FUNCTION__ )); | ||||
9646 | |||||
9647 | QualType lhptee, rhptee; | ||||
9648 | |||||
9649 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
9650 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | ||||
9651 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | ||||
9652 | |||||
9653 | // In C++, the types have to match exactly. | ||||
9654 | if (S.getLangOpts().CPlusPlus) | ||||
9655 | return Sema::IncompatibleBlockPointer; | ||||
9656 | |||||
9657 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
9658 | |||||
9659 | // For blocks we enforce that qualifiers are identical. | ||||
9660 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | ||||
9661 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | ||||
9662 | if (S.getLangOpts().OpenCL) { | ||||
9663 | LQuals.removeAddressSpace(); | ||||
9664 | RQuals.removeAddressSpace(); | ||||
9665 | } | ||||
9666 | if (LQuals != RQuals) | ||||
9667 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
9668 | |||||
9669 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | ||||
9670 | // assignment. | ||||
9671 | // The current behavior is similar to C++ lambdas. A block might be | ||||
9672 | // assigned to a variable iff its return type and parameters are compatible | ||||
9673 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | ||||
9674 | // an assignment. Presumably it should behave in way that a function pointer | ||||
9675 | // assignment does in C, so for each parameter and return type: | ||||
9676 | // * CVR and address space of LHS should be a superset of CVR and address | ||||
9677 | // space of RHS. | ||||
9678 | // * unqualified types should be compatible. | ||||
9679 | if (S.getLangOpts().OpenCL) { | ||||
9680 | if (!S.Context.typesAreBlockPointerCompatible( | ||||
9681 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | ||||
9682 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | ||||
9683 | return Sema::IncompatibleBlockPointer; | ||||
9684 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | ||||
9685 | return Sema::IncompatibleBlockPointer; | ||||
9686 | |||||
9687 | return ConvTy; | ||||
9688 | } | ||||
9689 | |||||
9690 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | ||||
9691 | /// for assignment compatibility. | ||||
9692 | static Sema::AssignConvertType | ||||
9693 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
9694 | QualType RHSType) { | ||||
9695 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS was not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9695, __extension__ __PRETTY_FUNCTION__ )); | ||||
9696 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS was not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9696, __extension__ __PRETTY_FUNCTION__ )); | ||||
9697 | |||||
9698 | if (LHSType->isObjCBuiltinType()) { | ||||
9699 | // Class is not compatible with ObjC object pointers. | ||||
9700 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | ||||
9701 | !RHSType->isObjCQualifiedClassType()) | ||||
9702 | return Sema::IncompatiblePointer; | ||||
9703 | return Sema::Compatible; | ||||
9704 | } | ||||
9705 | if (RHSType->isObjCBuiltinType()) { | ||||
9706 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | ||||
9707 | !LHSType->isObjCQualifiedClassType()) | ||||
9708 | return Sema::IncompatiblePointer; | ||||
9709 | return Sema::Compatible; | ||||
9710 | } | ||||
9711 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9712 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9713 | |||||
9714 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | ||||
9715 | // make an exception for id<P> | ||||
9716 | !LHSType->isObjCQualifiedIdType()) | ||||
9717 | return Sema::CompatiblePointerDiscardsQualifiers; | ||||
9718 | |||||
9719 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | ||||
9720 | return Sema::Compatible; | ||||
9721 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | ||||
9722 | return Sema::IncompatibleObjCQualifiedId; | ||||
9723 | return Sema::IncompatiblePointer; | ||||
9724 | } | ||||
9725 | |||||
9726 | Sema::AssignConvertType | ||||
9727 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | ||||
9728 | QualType LHSType, QualType RHSType) { | ||||
9729 | // Fake up an opaque expression. We don't actually care about what | ||||
9730 | // cast operations are required, so if CheckAssignmentConstraints | ||||
9731 | // adds casts to this they'll be wasted, but fortunately that doesn't | ||||
9732 | // usually happen on valid code. | ||||
9733 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); | ||||
9734 | ExprResult RHSPtr = &RHSExpr; | ||||
9735 | CastKind K; | ||||
9736 | |||||
9737 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | ||||
9738 | } | ||||
9739 | |||||
9740 | /// This helper function returns true if QT is a vector type that has element | ||||
9741 | /// type ElementType. | ||||
9742 | static bool isVector(QualType QT, QualType ElementType) { | ||||
9743 | if (const VectorType *VT = QT->getAs<VectorType>()) | ||||
9744 | return VT->getElementType().getCanonicalType() == ElementType; | ||||
9745 | return false; | ||||
9746 | } | ||||
9747 | |||||
9748 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | ||||
9749 | /// has code to accommodate several GCC extensions when type checking | ||||
9750 | /// pointers. Here are some objectionable examples that GCC considers warnings: | ||||
9751 | /// | ||||
9752 | /// int a, *pint; | ||||
9753 | /// short *pshort; | ||||
9754 | /// struct foo *pfoo; | ||||
9755 | /// | ||||
9756 | /// pint = pshort; // warning: assignment from incompatible pointer type | ||||
9757 | /// a = pint; // warning: assignment makes integer from pointer without a cast | ||||
9758 | /// pint = a; // warning: assignment makes pointer from integer without a cast | ||||
9759 | /// pint = pfoo; // warning: assignment from incompatible pointer type | ||||
9760 | /// | ||||
9761 | /// As a result, the code for dealing with pointers is more complex than the | ||||
9762 | /// C99 spec dictates. | ||||
9763 | /// | ||||
9764 | /// Sets 'Kind' for any result kind except Incompatible. | ||||
9765 | Sema::AssignConvertType | ||||
9766 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | ||||
9767 | CastKind &Kind, bool ConvertRHS) { | ||||
9768 | QualType RHSType = RHS.get()->getType(); | ||||
9769 | QualType OrigLHSType = LHSType; | ||||
9770 | |||||
9771 | // Get canonical types. We're not formatting these types, just comparing | ||||
9772 | // them. | ||||
9773 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | ||||
9774 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | ||||
9775 | |||||
9776 | // Common case: no conversion required. | ||||
9777 | if (LHSType == RHSType) { | ||||
| |||||
9778 | Kind = CK_NoOp; | ||||
9779 | return Compatible; | ||||
9780 | } | ||||
9781 | |||||
9782 | // If the LHS has an __auto_type, there are no additional type constraints | ||||
9783 | // to be worried about. | ||||
9784 | if (const auto *AT
| ||||
9785 | if (AT->isGNUAutoType()) { | ||||
9786 | Kind = CK_NoOp; | ||||
9787 | return Compatible; | ||||
9788 | } | ||||
9789 | } | ||||
9790 | |||||
9791 | // If we have an atomic type, try a non-atomic assignment, then just add an | ||||
9792 | // atomic qualification step. | ||||
9793 | if (const AtomicType *AtomicTy
| ||||
9794 | Sema::AssignConvertType result = | ||||
9795 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | ||||
9796 | if (result != Compatible) | ||||
9797 | return result; | ||||
9798 | if (Kind != CK_NoOp && ConvertRHS) | ||||
9799 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | ||||
9800 | Kind = CK_NonAtomicToAtomic; | ||||
9801 | return Compatible; | ||||
9802 | } | ||||
9803 | |||||
9804 | // If the left-hand side is a reference type, then we are in a | ||||
9805 | // (rare!) case where we've allowed the use of references in C, | ||||
9806 | // e.g., as a parameter type in a built-in function. In this case, | ||||
9807 | // just make sure that the type referenced is compatible with the | ||||
9808 | // right-hand side type. The caller is responsible for adjusting | ||||
9809 | // LHSType so that the resulting expression does not have reference | ||||
9810 | // type. | ||||
9811 | if (const ReferenceType *LHSTypeRef
| ||||
9812 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | ||||
9813 | Kind = CK_LValueBitCast; | ||||
9814 | return Compatible; | ||||
9815 | } | ||||
9816 | return Incompatible; | ||||
9817 | } | ||||
9818 | |||||
9819 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | ||||
9820 | // to the same ExtVector type. | ||||
9821 | if (LHSType->isExtVectorType()) { | ||||
9822 | if (RHSType->isExtVectorType()) | ||||
9823 | return Incompatible; | ||||
9824 | if (RHSType->isArithmeticType()) { | ||||
9825 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | ||||
9826 | if (ConvertRHS) | ||||
9827 | RHS = prepareVectorSplat(LHSType, RHS.get()); | ||||
9828 | Kind = CK_VectorSplat; | ||||
9829 | return Compatible; | ||||
9830 | } | ||||
9831 | } | ||||
9832 | |||||
9833 | // Conversions to or from vector type. | ||||
9834 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | ||||
9835 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | ||||
9836 | // Allow assignments of an AltiVec vector type to an equivalent GCC | ||||
9837 | // vector type and vice versa | ||||
9838 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9839 | Kind = CK_BitCast; | ||||
9840 | return Compatible; | ||||
9841 | } | ||||
9842 | |||||
9843 | // If we are allowing lax vector conversions, and LHS and RHS are both | ||||
9844 | // vectors, the total size only needs to be the same. This is a bitcast; | ||||
9845 | // no bits are changed but the result type is different. | ||||
9846 | if (isLaxVectorConversion(RHSType, LHSType)) { | ||||
9847 | // The default for lax vector conversions with Altivec vectors will | ||||
9848 | // change, so if we are converting between vector types where | ||||
9849 | // at least one is an Altivec vector, emit a warning. | ||||
9850 | if (anyAltivecTypes(RHSType, LHSType) && | ||||
9851 | !areSameVectorElemTypes(RHSType, LHSType)) | ||||
9852 | Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) | ||||
9853 | << RHSType << LHSType; | ||||
9854 | Kind = CK_BitCast; | ||||
9855 | return IncompatibleVectors; | ||||
9856 | } | ||||
9857 | } | ||||
9858 | |||||
9859 | // When the RHS comes from another lax conversion (e.g. binops between | ||||
9860 | // scalars and vectors) the result is canonicalized as a vector. When the | ||||
9861 | // LHS is also a vector, the lax is allowed by the condition above. Handle | ||||
9862 | // the case where LHS is a scalar. | ||||
9863 | if (LHSType->isScalarType()) { | ||||
9864 | const VectorType *VecType = RHSType->getAs<VectorType>(); | ||||
9865 | if (VecType && VecType->getNumElements() == 1 && | ||||
9866 | isLaxVectorConversion(RHSType, LHSType)) { | ||||
9867 | if (VecType->getVectorKind() == VectorType::AltiVecVector) | ||||
9868 | Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) | ||||
9869 | << RHSType << LHSType; | ||||
9870 | ExprResult *VecExpr = &RHS; | ||||
9871 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | ||||
9872 | Kind = CK_BitCast; | ||||
9873 | return Compatible; | ||||
9874 | } | ||||
9875 | } | ||||
9876 | |||||
9877 | // Allow assignments between fixed-length and sizeless SVE vectors. | ||||
9878 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | ||||
9879 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | ||||
9880 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | ||||
9881 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | ||||
9882 | Kind = CK_BitCast; | ||||
9883 | return Compatible; | ||||
9884 | } | ||||
9885 | |||||
9886 | return Incompatible; | ||||
9887 | } | ||||
9888 | |||||
9889 | // Diagnose attempts to convert between __ibm128, __float128 and long double | ||||
9890 | // where such conversions currently can't be handled. | ||||
9891 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
9892 | return Incompatible; | ||||
9893 | |||||
9894 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | ||||
9895 | // discards the imaginary part. | ||||
9896 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | ||||
9897 | !LHSType->getAs<ComplexType>()) | ||||
9898 | return Incompatible; | ||||
9899 | |||||
9900 | // Arithmetic conversions. | ||||
9901 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | ||||
9902 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | ||||
9903 | if (ConvertRHS) | ||||
9904 | Kind = PrepareScalarCast(RHS, LHSType); | ||||
9905 | return Compatible; | ||||
9906 | } | ||||
9907 | |||||
9908 | // Conversions to normal pointers. | ||||
9909 | if (const PointerType *LHSPointer
| ||||
9910 | // U* -> T* | ||||
9911 | if (isa<PointerType>(RHSType)) { | ||||
9912 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9913 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | ||||
9914 | if (AddrSpaceL != AddrSpaceR) | ||||
9915 | Kind = CK_AddressSpaceConversion; | ||||
9916 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | ||||
9917 | Kind = CK_NoOp; | ||||
9918 | else | ||||
9919 | Kind = CK_BitCast; | ||||
9920 | return checkPointerTypesForAssignment(*this, LHSType, RHSType, | ||||
9921 | RHS.get()->getBeginLoc()); | ||||
9922 | } | ||||
9923 | |||||
9924 | // int -> T* | ||||
9925 | if (RHSType->isIntegerType()) { | ||||
9926 | Kind = CK_IntegralToPointer; // FIXME: null? | ||||
9927 | return IntToPointer; | ||||
9928 | } | ||||
9929 | |||||
9930 | // C pointers are not compatible with ObjC object pointers, | ||||
9931 | // with two exceptions: | ||||
9932 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9933 | // - conversions to void* | ||||
9934 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9935 | Kind = CK_BitCast; | ||||
9936 | return Compatible; | ||||
9937 | } | ||||
9938 | |||||
9939 | // - conversions from 'Class' to the redefinition type | ||||
9940 | if (RHSType->isObjCClassType() && | ||||
9941 | Context.hasSameType(LHSType, | ||||
9942 | Context.getObjCClassRedefinitionType())) { | ||||
9943 | Kind = CK_BitCast; | ||||
9944 | return Compatible; | ||||
9945 | } | ||||
9946 | |||||
9947 | Kind = CK_BitCast; | ||||
9948 | return IncompatiblePointer; | ||||
9949 | } | ||||
9950 | |||||
9951 | // U^ -> void* | ||||
9952 | if (RHSType->getAs<BlockPointerType>()) { | ||||
9953 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9954 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9955 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
| |||||
9956 | ->getPointeeType() | ||||
9957 | .getAddressSpace(); | ||||
9958 | Kind = | ||||
9959 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9960 | return Compatible; | ||||
9961 | } | ||||
9962 | } | ||||
9963 | |||||
9964 | return Incompatible; | ||||
9965 | } | ||||
9966 | |||||
9967 | // Conversions to block pointers. | ||||
9968 | if (isa<BlockPointerType>(LHSType)) { | ||||
9969 | // U^ -> T^ | ||||
9970 | if (RHSType->isBlockPointerType()) { | ||||
9971 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | ||||
9972 | ->getPointeeType() | ||||
9973 | .getAddressSpace(); | ||||
9974 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9975 | ->getPointeeType() | ||||
9976 | .getAddressSpace(); | ||||
9977 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9978 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9979 | } | ||||
9980 | |||||
9981 | // int or null -> T^ | ||||
9982 | if (RHSType->isIntegerType()) { | ||||
9983 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9984 | return IntToBlockPointer; | ||||
9985 | } | ||||
9986 | |||||
9987 | // id -> T^ | ||||
9988 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | ||||
9989 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9990 | return Compatible; | ||||
9991 | } | ||||
9992 | |||||
9993 | // void* -> T^ | ||||
9994 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | ||||
9995 | if (RHSPT->getPointeeType()->isVoidType()) { | ||||
9996 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9997 | return Compatible; | ||||
9998 | } | ||||
9999 | |||||
10000 | return Incompatible; | ||||
10001 | } | ||||
10002 | |||||
10003 | // Conversions to Objective-C pointers. | ||||
10004 | if (isa<ObjCObjectPointerType>(LHSType)) { | ||||
10005 | // A* -> B* | ||||
10006 | if (RHSType->isObjCObjectPointerType()) { | ||||
10007 | Kind = CK_BitCast; | ||||
10008 | Sema::AssignConvertType result = | ||||
10009 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
10010 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
10011 | result == Compatible && | ||||
10012 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | ||||
10013 | result = IncompatibleObjCWeakRef; | ||||
10014 | return result; | ||||
10015 | } | ||||
10016 | |||||
10017 | // int or null -> A* | ||||
10018 | if (RHSType->isIntegerType()) { | ||||
10019 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
10020 | return IntToPointer; | ||||
10021 | } | ||||
10022 | |||||
10023 | // In general, C pointers are not compatible with ObjC object pointers, | ||||
10024 | // with two exceptions: | ||||
10025 | if (isa<PointerType>(RHSType)) { | ||||
10026 | Kind = CK_CPointerToObjCPointerCast; | ||||
10027 | |||||
10028 | // - conversions from 'void*' | ||||
10029 | if (RHSType->isVoidPointerType()) { | ||||
10030 | return Compatible; | ||||
10031 | } | ||||
10032 | |||||
10033 | // - conversions to 'Class' from its redefinition type | ||||
10034 | if (LHSType->isObjCClassType() && | ||||
10035 | Context.hasSameType(RHSType, | ||||
10036 | Context.getObjCClassRedefinitionType())) { | ||||
10037 | return Compatible; | ||||
10038 | } | ||||
10039 | |||||
10040 | return IncompatiblePointer; | ||||
10041 | } | ||||
10042 | |||||
10043 | // Only under strict condition T^ is compatible with an Objective-C pointer. | ||||
10044 | if (RHSType->isBlockPointerType() && | ||||
10045 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
10046 | if (ConvertRHS) | ||||
10047 | maybeExtendBlockObject(RHS); | ||||
10048 | Kind = CK_BlockPointerToObjCPointerCast; | ||||
10049 | return Compatible; | ||||
10050 | } | ||||
10051 | |||||
10052 | return Incompatible; | ||||
10053 | } | ||||
10054 | |||||
10055 | // Conversions from pointers that are not covered by the above. | ||||
10056 | if (isa<PointerType>(RHSType)) { | ||||
10057 | // T* -> _Bool | ||||
10058 | if (LHSType == Context.BoolTy) { | ||||
10059 | Kind = CK_PointerToBoolean; | ||||
10060 | return Compatible; | ||||
10061 | } | ||||
10062 | |||||
10063 | // T* -> int | ||||
10064 | if (LHSType->isIntegerType()) { | ||||
10065 | Kind = CK_PointerToIntegral; | ||||
10066 | return PointerToInt; | ||||
10067 | } | ||||
10068 | |||||
10069 | return Incompatible; | ||||
10070 | } | ||||
10071 | |||||
10072 | // Conversions from Objective-C pointers that are not covered by the above. | ||||
10073 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
10074 | // T* -> _Bool | ||||
10075 | if (LHSType == Context.BoolTy) { | ||||
10076 | Kind = CK_PointerToBoolean; | ||||
10077 | return Compatible; | ||||
10078 | } | ||||
10079 | |||||
10080 | // T* -> int | ||||
10081 | if (LHSType->isIntegerType()) { | ||||
10082 | Kind = CK_PointerToIntegral; | ||||
10083 | return PointerToInt; | ||||
10084 | } | ||||
10085 | |||||
10086 | return Incompatible; | ||||
10087 | } | ||||
10088 | |||||
10089 | // struct A -> struct B | ||||
10090 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | ||||
10091 | if (Context.typesAreCompatible(LHSType, RHSType)) { | ||||
10092 | Kind = CK_NoOp; | ||||
10093 | return Compatible; | ||||
10094 | } | ||||
10095 | } | ||||
10096 | |||||
10097 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | ||||
10098 | Kind = CK_IntToOCLSampler; | ||||
10099 | return Compatible; | ||||
10100 | } | ||||
10101 | |||||
10102 | return Incompatible; | ||||
10103 | } | ||||
10104 | |||||
10105 | /// Constructs a transparent union from an expression that is | ||||
10106 | /// used to initialize the transparent union. | ||||
10107 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | ||||
10108 | ExprResult &EResult, QualType UnionType, | ||||
10109 | FieldDecl *Field) { | ||||
10110 | // Build an initializer list that designates the appropriate member | ||||
10111 | // of the transparent union. | ||||
10112 | Expr *E = EResult.get(); | ||||
10113 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | ||||
10114 | E, SourceLocation()); | ||||
10115 | Initializer->setType(UnionType); | ||||
10116 | Initializer->setInitializedFieldInUnion(Field); | ||||
10117 | |||||
10118 | // Build a compound literal constructing a value of the transparent | ||||
10119 | // union type from this initializer list. | ||||
10120 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | ||||
10121 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | ||||
10122 | VK_PRValue, Initializer, false); | ||||
10123 | } | ||||
10124 | |||||
10125 | Sema::AssignConvertType | ||||
10126 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | ||||
10127 | ExprResult &RHS) { | ||||
10128 | QualType RHSType = RHS.get()->getType(); | ||||
10129 | |||||
10130 | // If the ArgType is a Union type, we want to handle a potential | ||||
10131 | // transparent_union GCC extension. | ||||
10132 | const RecordType *UT = ArgType->getAsUnionType(); | ||||
10133 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | ||||
10134 | return Incompatible; | ||||
10135 | |||||
10136 | // The field to initialize within the transparent union. | ||||
10137 | RecordDecl *UD = UT->getDecl(); | ||||
10138 | FieldDecl *InitField = nullptr; | ||||
10139 | // It's compatible if the expression matches any of the fields. | ||||
10140 | for (auto *it : UD->fields()) { | ||||
10141 | if (it->getType()->isPointerType()) { | ||||
10142 | // If the transparent union contains a pointer type, we allow: | ||||
10143 | // 1) void pointer | ||||
10144 | // 2) null pointer constant | ||||
10145 | if (RHSType->isPointerType()) | ||||
10146 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | ||||
10147 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | ||||
10148 | InitField = it; | ||||
10149 | break; | ||||
10150 | } | ||||
10151 | |||||
10152 | if (RHS.get()->isNullPointerConstant(Context, | ||||
10153 | Expr::NPC_ValueDependentIsNull)) { | ||||
10154 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | ||||
10155 | CK_NullToPointer); | ||||
10156 | InitField = it; | ||||
10157 | break; | ||||
10158 | } | ||||
10159 | } | ||||
10160 | |||||
10161 | CastKind Kind; | ||||
10162 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | ||||
10163 | == Compatible) { | ||||
10164 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | ||||
10165 | InitField = it; | ||||
10166 | break; | ||||
10167 | } | ||||
10168 | } | ||||
10169 | |||||
10170 | if (!InitField) | ||||
10171 | return Incompatible; | ||||
10172 | |||||
10173 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | ||||
10174 | return Compatible; | ||||
10175 | } | ||||
10176 | |||||
10177 | Sema::AssignConvertType | ||||
10178 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | ||||
10179 | bool Diagnose, | ||||
10180 | bool DiagnoseCFAudited, | ||||
10181 | bool ConvertRHS) { | ||||
10182 | // We need to be able to tell the caller whether we diagnosed a problem, if | ||||
10183 | // they ask us to issue diagnostics. | ||||
10184 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast <bool> ((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed") ? void (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "clang/lib/Sema/SemaExpr.cpp", 10184, __extension__ __PRETTY_FUNCTION__ )); | ||||
10185 | |||||
10186 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | ||||
10187 | // we can't avoid *all* modifications at the moment, so we need some somewhere | ||||
10188 | // to put the updated value. | ||||
10189 | ExprResult LocalRHS = CallerRHS; | ||||
10190 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | ||||
10191 | |||||
10192 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | ||||
10193 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | ||||
10194 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||
10195 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
10196 | Diag(RHS.get()->getExprLoc(), | ||||
10197 | diag::warn_noderef_to_dereferenceable_pointer) | ||||
10198 | << RHS.get()->getSourceRange(); | ||||
10199 | } | ||||
10200 | } | ||||
10201 | } | ||||
10202 | |||||
10203 | if (getLangOpts().CPlusPlus) { | ||||
10204 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | ||||
10205 | // C++ 5.17p3: If the left operand is not of class type, the | ||||
10206 | // expression is implicitly converted (C++ 4) to the | ||||
10207 | // cv-unqualified type of the left operand. | ||||
10208 | QualType RHSType = RHS.get()->getType(); | ||||
10209 | if (Diagnose) { | ||||
10210 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
10211 | AA_Assigning); | ||||
10212 | } else { | ||||
10213 | ImplicitConversionSequence ICS = | ||||
10214 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
10215 | /*SuppressUserConversions=*/false, | ||||
10216 | AllowedExplicit::None, | ||||
10217 | /*InOverloadResolution=*/false, | ||||
10218 | /*CStyle=*/false, | ||||
10219 | /*AllowObjCWritebackConversion=*/false); | ||||
10220 | if (ICS.isFailure()) | ||||
10221 | return Incompatible; | ||||
10222 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
10223 | ICS, AA_Assigning); | ||||
10224 | } | ||||
10225 | if (RHS.isInvalid()) | ||||
10226 | return Incompatible; | ||||
10227 | Sema::AssignConvertType result = Compatible; | ||||
10228 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
10229 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | ||||
10230 | result = IncompatibleObjCWeakRef; | ||||
10231 | return result; | ||||
10232 | } | ||||
10233 | |||||
10234 | // FIXME: Currently, we fall through and treat C++ classes like C | ||||
10235 | // structures. | ||||
10236 | // FIXME: We also fall through for atomics; not sure what should | ||||
10237 | // happen there, though. | ||||
10238 | } else if (RHS.get()->getType() == Context.OverloadTy) { | ||||
10239 | // As a set of extensions to C, we support overloading on functions. These | ||||
10240 | // functions need to be resolved here. | ||||
10241 | DeclAccessPair DAP; | ||||
10242 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | ||||
10243 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | ||||
10244 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | ||||
10245 | else | ||||
10246 | return Incompatible; | ||||
10247 | } | ||||
10248 | |||||
10249 | // This check seems unnatural, however it is necessary to ensure the proper | ||||
10250 | // conversion of functions/arrays. If the conversion were done for all | ||||
10251 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | ||||
10252 | // expressions that suppress this implicit conversion (&, sizeof). This needs | ||||
10253 | // to happen before we check for null pointer conversions because C does not | ||||
10254 | // undergo the same implicit conversions as C++ does above (by the calls to | ||||
10255 | // TryImplicitConversion() and PerformImplicitConversion()) which insert the | ||||
10256 | // lvalue to rvalue cast before checking for null pointer constraints. This | ||||
10257 | // addresses code like: nullptr_t val; int *ptr; ptr = val; | ||||
10258 | // | ||||
10259 | // Suppress this for references: C++ 8.5.3p5. | ||||
10260 | if (!LHSType->isReferenceType()) { | ||||
10261 | // FIXME: We potentially allocate here even if ConvertRHS is false. | ||||
10262 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | ||||
10263 | if (RHS.isInvalid()) | ||||
10264 | return Incompatible; | ||||
10265 | } | ||||
10266 | |||||
10267 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | ||||
10268 | // a null pointer constant. | ||||
10269 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | ||||
10270 | LHSType->isBlockPointerType()) && | ||||
10271 | RHS.get()->isNullPointerConstant(Context, | ||||
10272 | Expr::NPC_ValueDependentIsNull)) { | ||||
10273 | if (Diagnose || ConvertRHS) { | ||||
10274 | CastKind Kind; | ||||
10275 | CXXCastPath Path; | ||||
10276 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | ||||
10277 | /*IgnoreBaseAccess=*/false, Diagnose); | ||||
10278 | if (ConvertRHS) | ||||
10279 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); | ||||
10280 | } | ||||
10281 | return Compatible; | ||||
10282 | } | ||||
10283 | |||||
10284 | // OpenCL queue_t type assignment. | ||||
10285 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | ||||
10286 | Context, Expr::NPC_ValueDependentIsNull)) { | ||||
10287 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
10288 | return Compatible; | ||||
10289 | } | ||||
10290 | |||||
10291 | CastKind Kind; | ||||
10292 | Sema::AssignConvertType result = | ||||
10293 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | ||||
10294 | |||||
10295 | // C99 6.5.16.1p2: The value of the right operand is converted to the | ||||
10296 | // type of the assignment expression. | ||||
10297 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | ||||
10298 | // so that we can use references in built-in functions even in C. | ||||
10299 | // The getNonReferenceType() call makes sure that the resulting expression | ||||
10300 | // does not have reference type. | ||||
10301 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | ||||
10302 | QualType Ty = LHSType.getNonLValueExprType(Context); | ||||
10303 | Expr *E = RHS.get(); | ||||
10304 | |||||
10305 | // Check for various Objective-C errors. If we are not reporting | ||||
10306 | // diagnostics and just checking for errors, e.g., during overload | ||||
10307 | // resolution, return Incompatible to indicate the failure. | ||||
10308 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
10309 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | ||||
10310 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | ||||
10311 | if (!Diagnose) | ||||
10312 | return Incompatible; | ||||
10313 | } | ||||
10314 | if (getLangOpts().ObjC && | ||||
10315 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | ||||
10316 | E->getType(), E, Diagnose) || | ||||
10317 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | ||||
10318 | if (!Diagnose) | ||||
10319 | return Incompatible; | ||||
10320 | // Replace the expression with a corrected version and continue so we | ||||
10321 | // can find further errors. | ||||
10322 | RHS = E; | ||||
10323 | return Compatible; | ||||
10324 | } | ||||
10325 | |||||
10326 | if (ConvertRHS) | ||||
10327 | RHS = ImpCastExprToType(E, Ty, Kind); | ||||
10328 | } | ||||
10329 | |||||
10330 | return result; | ||||
10331 | } | ||||
10332 | |||||
10333 | namespace { | ||||
10334 | /// The original operand to an operator, prior to the application of the usual | ||||
10335 | /// arithmetic conversions and converting the arguments of a builtin operator | ||||
10336 | /// candidate. | ||||
10337 | struct OriginalOperand { | ||||
10338 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | ||||
10339 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | ||||
10340 | Op = MTE->getSubExpr(); | ||||
10341 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | ||||
10342 | Op = BTE->getSubExpr(); | ||||
10343 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | ||||
10344 | Orig = ICE->getSubExprAsWritten(); | ||||
10345 | Conversion = ICE->getConversionFunction(); | ||||
10346 | } | ||||
10347 | } | ||||
10348 | |||||
10349 | QualType getType() const { return Orig->getType(); } | ||||
10350 | |||||
10351 | Expr *Orig; | ||||
10352 | NamedDecl *Conversion; | ||||
10353 | }; | ||||
10354 | } | ||||
10355 | |||||
10356 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | ||||
10357 | ExprResult &RHS) { | ||||
10358 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | ||||
10359 | |||||
10360 | Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
10361 | << OrigLHS.getType() << OrigRHS.getType() | ||||
10362 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10363 | |||||
10364 | // If a user-defined conversion was applied to either of the operands prior | ||||
10365 | // to applying the built-in operator rules, tell the user about it. | ||||
10366 | if (OrigLHS.Conversion) { | ||||
10367 | Diag(OrigLHS.Conversion->getLocation(), | ||||
10368 | diag::note_typecheck_invalid_operands_converted) | ||||
10369 | << 0 << LHS.get()->getType(); | ||||
10370 | } | ||||
10371 | if (OrigRHS.Conversion) { | ||||
10372 | Diag(OrigRHS.Conversion->getLocation(), | ||||
10373 | diag::note_typecheck_invalid_operands_converted) | ||||
10374 | << 1 << RHS.get()->getType(); | ||||
10375 | } | ||||
10376 | |||||
10377 | return QualType(); | ||||
10378 | } | ||||
10379 | |||||
10380 | // Diagnose cases where a scalar was implicitly converted to a vector and | ||||
10381 | // diagnose the underlying types. Otherwise, diagnose the error | ||||
10382 | // as invalid vector logical operands for non-C++ cases. | ||||
10383 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | ||||
10384 | ExprResult &RHS) { | ||||
10385 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | ||||
10386 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | ||||
10387 | |||||
10388 | bool LHSNatVec = LHSType->isVectorType(); | ||||
10389 | bool RHSNatVec = RHSType->isVectorType(); | ||||
10390 | |||||
10391 | if (!(LHSNatVec && RHSNatVec)) { | ||||
10392 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | ||||
10393 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | ||||
10394 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
10395 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | ||||
10396 | << Vector->getSourceRange(); | ||||
10397 | return QualType(); | ||||
10398 | } | ||||
10399 | |||||
10400 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
10401 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10402 | << RHS.get()->getSourceRange(); | ||||
10403 | |||||
10404 | return QualType(); | ||||
10405 | } | ||||
10406 | |||||
10407 | /// Try to convert a value of non-vector type to a vector type by converting | ||||
10408 | /// the type to the element type of the vector and then performing a splat. | ||||
10409 | /// If the language is OpenCL, we only use conversions that promote scalar | ||||
10410 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | ||||
10411 | /// for float->int. | ||||
10412 | /// | ||||
10413 | /// OpenCL V2.0 6.2.6.p2: | ||||
10414 | /// An error shall occur if any scalar operand type has greater rank | ||||
10415 | /// than the type of the vector element. | ||||
10416 | /// | ||||
10417 | /// \param scalar - if non-null, actually perform the conversions | ||||
10418 | /// \return true if the operation fails (but without diagnosing the failure) | ||||
10419 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | ||||
10420 | QualType scalarTy, | ||||
10421 | QualType vectorEltTy, | ||||
10422 | QualType vectorTy, | ||||
10423 | unsigned &DiagID) { | ||||
10424 | // The conversion to apply to the scalar before splatting it, | ||||
10425 | // if necessary. | ||||
10426 | CastKind scalarCast = CK_NoOp; | ||||
10427 | |||||
10428 | if (vectorEltTy->isIntegralType(S.Context)) { | ||||
10429 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | ||||
10430 | (scalarTy->isIntegerType() && | ||||
10431 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | ||||
10432 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
10433 | return true; | ||||
10434 | } | ||||
10435 | if (!scalarTy->isIntegralType(S.Context)) | ||||
10436 | return true; | ||||
10437 | scalarCast = CK_IntegralCast; | ||||
10438 | } else if (vectorEltTy->isRealFloatingType()) { | ||||
10439 | if (scalarTy->isRealFloatingType()) { | ||||
10440 | if (S.getLangOpts().OpenCL && | ||||
10441 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | ||||
10442 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
10443 | return true; | ||||
10444 | } | ||||
10445 | scalarCast = CK_FloatingCast; | ||||
10446 | } | ||||
10447 | else if (scalarTy->isIntegralType(S.Context)) | ||||
10448 | scalarCast = CK_IntegralToFloating; | ||||
10449 | else | ||||
10450 | return true; | ||||
10451 | } else { | ||||
10452 | return true; | ||||
10453 | } | ||||
10454 | |||||
10455 | // Adjust scalar if desired. | ||||
10456 | if (scalar) { | ||||
10457 | if (scalarCast != CK_NoOp) | ||||
10458 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | ||||
10459 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | ||||
10460 | } | ||||
10461 | return false; | ||||
10462 | } | ||||
10463 | |||||
10464 | /// Convert vector E to a vector with the same number of elements but different | ||||
10465 | /// element type. | ||||
10466 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | ||||
10467 | const auto *VecTy = E->getType()->getAs<VectorType>(); | ||||
10468 | assert(VecTy && "Expression E must be a vector")(static_cast <bool> (VecTy && "Expression E must be a vector" ) ? void (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "clang/lib/Sema/SemaExpr.cpp", 10468, __extension__ __PRETTY_FUNCTION__ )); | ||||
10469 | QualType NewVecTy = | ||||
10470 | VecTy->isExtVectorType() | ||||
10471 | ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) | ||||
10472 | : S.Context.getVectorType(ElementType, VecTy->getNumElements(), | ||||
10473 | VecTy->getVectorKind()); | ||||
10474 | |||||
10475 | // Look through the implicit cast. Return the subexpression if its type is | ||||
10476 | // NewVecTy. | ||||
10477 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
10478 | if (ICE->getSubExpr()->getType() == NewVecTy) | ||||
10479 | return ICE->getSubExpr(); | ||||
10480 | |||||
10481 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | ||||
10482 | return S.ImpCastExprToType(E, NewVecTy, Cast); | ||||
10483 | } | ||||
10484 | |||||
10485 | /// Test if a (constant) integer Int can be casted to another integer type | ||||
10486 | /// IntTy without losing precision. | ||||
10487 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | ||||
10488 | QualType OtherIntTy) { | ||||
10489 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
10490 | |||||
10491 | // Reject cases where the value of the Int is unknown as that would | ||||
10492 | // possibly cause truncation, but accept cases where the scalar can be | ||||
10493 | // demoted without loss of precision. | ||||
10494 | Expr::EvalResult EVResult; | ||||
10495 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
10496 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | ||||
10497 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | ||||
10498 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | ||||
10499 | |||||
10500 | if (CstInt) { | ||||
10501 | // If the scalar is constant and is of a higher order and has more active | ||||
10502 | // bits that the vector element type, reject it. | ||||
10503 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
10504 | unsigned NumBits = IntSigned | ||||
10505 | ? (Result.isNegative() ? Result.getSignificantBits() | ||||
10506 | : Result.getActiveBits()) | ||||
10507 | : Result.getActiveBits(); | ||||
10508 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | ||||
10509 | return true; | ||||
10510 | |||||
10511 | // If the signedness of the scalar type and the vector element type | ||||
10512 | // differs and the number of bits is greater than that of the vector | ||||
10513 | // element reject it. | ||||
10514 | return (IntSigned != OtherIntSigned && | ||||
10515 | NumBits > S.Context.getIntWidth(OtherIntTy)); | ||||
10516 | } | ||||
10517 | |||||
10518 | // Reject cases where the value of the scalar is not constant and it's | ||||
10519 | // order is greater than that of the vector element type. | ||||
10520 | return (Order < 0); | ||||
10521 | } | ||||
10522 | |||||
10523 | /// Test if a (constant) integer Int can be casted to floating point type | ||||
10524 | /// FloatTy without losing precision. | ||||
10525 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | ||||
10526 | QualType FloatTy) { | ||||
10527 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
10528 | |||||
10529 | // Determine if the integer constant can be expressed as a floating point | ||||
10530 | // number of the appropriate type. | ||||
10531 | Expr::EvalResult EVResult; | ||||
10532 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
10533 | |||||
10534 | uint64_t Bits = 0; | ||||
10535 | if (CstInt) { | ||||
10536 | // Reject constants that would be truncated if they were converted to | ||||
10537 | // the floating point type. Test by simple to/from conversion. | ||||
10538 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | ||||
10539 | // could be avoided if there was a convertFromAPInt method | ||||
10540 | // which could signal back if implicit truncation occurred. | ||||
10541 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
10542 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | ||||
10543 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | ||||
10544 | llvm::APFloat::rmTowardZero); | ||||
10545 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | ||||
10546 | !IntTy->hasSignedIntegerRepresentation()); | ||||
10547 | bool Ignored = false; | ||||
10548 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | ||||
10549 | &Ignored); | ||||
10550 | if (Result != ConvertBack) | ||||
10551 | return true; | ||||
10552 | } else { | ||||
10553 | // Reject types that cannot be fully encoded into the mantissa of | ||||
10554 | // the float. | ||||
10555 | Bits = S.Context.getTypeSize(IntTy); | ||||
10556 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | ||||
10557 | S.Context.getFloatTypeSemantics(FloatTy)); | ||||
10558 | if (Bits > FloatPrec) | ||||
10559 | return true; | ||||
10560 | } | ||||
10561 | |||||
10562 | return false; | ||||
10563 | } | ||||
10564 | |||||
10565 | /// Attempt to convert and splat Scalar into a vector whose types matches | ||||
10566 | /// Vector following GCC conversion rules. The rule is that implicit | ||||
10567 | /// conversion can occur when Scalar can be casted to match Vector's element | ||||
10568 | /// type without causing truncation of Scalar. | ||||
10569 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | ||||
10570 | ExprResult *Vector) { | ||||
10571 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | ||||
10572 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | ||||
10573 | QualType VectorEltTy; | ||||
10574 | |||||
10575 | if (const auto *VT = VectorTy->getAs<VectorType>()) { | ||||
10576 | assert(!isa<ExtVectorType>(VT) &&(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "clang/lib/Sema/SemaExpr.cpp", 10577, __extension__ __PRETTY_FUNCTION__ )) | ||||
10577 | "ExtVectorTypes should not be handled here!")(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "clang/lib/Sema/SemaExpr.cpp", 10577, __extension__ __PRETTY_FUNCTION__ )); | ||||
10578 | VectorEltTy = VT->getElementType(); | ||||
10579 | } else if (VectorTy->isVLSTBuiltinType()) { | ||||
10580 | VectorEltTy = | ||||
10581 | VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext()); | ||||
10582 | } else { | ||||
10583 | llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here")::llvm::llvm_unreachable_internal("Only Fixed-Length and SVE Vector types are handled here" , "clang/lib/Sema/SemaExpr.cpp", 10583); | ||||
10584 | } | ||||
10585 | |||||
10586 | // Reject cases where the vector element type or the scalar element type are | ||||
10587 | // not integral or floating point types. | ||||
10588 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | ||||
10589 | return true; | ||||
10590 | |||||
10591 | // The conversion to apply to the scalar before splatting it, | ||||
10592 | // if necessary. | ||||
10593 | CastKind ScalarCast = CK_NoOp; | ||||
10594 | |||||
10595 | // Accept cases where the vector elements are integers and the scalar is | ||||
10596 | // an integer. | ||||
10597 | // FIXME: Notionally if the scalar was a floating point value with a precise | ||||
10598 | // integral representation, we could cast it to an appropriate integer | ||||
10599 | // type and then perform the rest of the checks here. GCC will perform | ||||
10600 | // this conversion in some cases as determined by the input language. | ||||
10601 | // We should accept it on a language independent basis. | ||||
10602 | if (VectorEltTy->isIntegralType(S.Context) && | ||||
10603 | ScalarTy->isIntegralType(S.Context) && | ||||
10604 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | ||||
10605 | |||||
10606 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | ||||
10607 | return true; | ||||
10608 | |||||
10609 | ScalarCast = CK_IntegralCast; | ||||
10610 | } else if (VectorEltTy->isIntegralType(S.Context) && | ||||
10611 | ScalarTy->isRealFloatingType()) { | ||||
10612 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | ||||
10613 | ScalarCast = CK_FloatingToIntegral; | ||||
10614 | else | ||||
10615 | return true; | ||||
10616 | } else if (VectorEltTy->isRealFloatingType()) { | ||||
10617 | if (ScalarTy->isRealFloatingType()) { | ||||
10618 | |||||
10619 | // Reject cases where the scalar type is not a constant and has a higher | ||||
10620 | // Order than the vector element type. | ||||
10621 | llvm::APFloat Result(0.0); | ||||
10622 | |||||
10623 | // Determine whether this is a constant scalar. In the event that the | ||||
10624 | // value is dependent (and thus cannot be evaluated by the constant | ||||
10625 | // evaluator), skip the evaluation. This will then diagnose once the | ||||
10626 | // expression is instantiated. | ||||
10627 | bool CstScalar = Scalar->get()->isValueDependent() || | ||||
10628 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | ||||
10629 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | ||||
10630 | if (!CstScalar && Order < 0) | ||||
10631 | return true; | ||||
10632 | |||||
10633 | // If the scalar cannot be safely casted to the vector element type, | ||||
10634 | // reject it. | ||||
10635 | if (CstScalar) { | ||||
10636 | bool Truncated = false; | ||||
10637 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | ||||
10638 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | ||||
10639 | if (Truncated) | ||||
10640 | return true; | ||||
10641 | } | ||||
10642 | |||||
10643 | ScalarCast = CK_FloatingCast; | ||||
10644 | } else if (ScalarTy->isIntegralType(S.Context)) { | ||||
10645 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | ||||
10646 | return true; | ||||
10647 | |||||
10648 | ScalarCast = CK_IntegralToFloating; | ||||
10649 | } else | ||||
10650 | return true; | ||||
10651 | } else if (ScalarTy->isEnumeralType()) | ||||
10652 | return true; | ||||
10653 | |||||
10654 | // Adjust scalar if desired. | ||||
10655 | if (Scalar) { | ||||
10656 | if (ScalarCast != CK_NoOp) | ||||
10657 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | ||||
10658 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | ||||
10659 | } | ||||
10660 | return false; | ||||
10661 | } | ||||
10662 | |||||
10663 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10664 | SourceLocation Loc, bool IsCompAssign, | ||||
10665 | bool AllowBothBool, | ||||
10666 | bool AllowBoolConversions, | ||||
10667 | bool AllowBoolOperation, | ||||
10668 | bool ReportInvalid) { | ||||
10669 | if (!IsCompAssign) { | ||||
10670 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
10671 | if (LHS.isInvalid()) | ||||
10672 | return QualType(); | ||||
10673 | } | ||||
10674 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
10675 | if (RHS.isInvalid()) | ||||
10676 | return QualType(); | ||||
10677 | |||||
10678 | // For conversion purposes, we ignore any qualifiers. | ||||
10679 | // For example, "const float" and "float" are equivalent. | ||||
10680 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
10681 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
10682 | |||||
10683 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | ||||
10684 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | ||||
10685 | assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void ( 0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp" , 10685, __extension__ __PRETTY_FUNCTION__)); | ||||
10686 | |||||
10687 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | ||||
10688 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | ||||
10689 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); | ||||
10690 | |||||
10691 | // AltiVec-style "vector bool op vector bool" combinations are allowed | ||||
10692 | // for some operators but not others. | ||||
10693 | if (!AllowBothBool && | ||||
10694 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
10695 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10696 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); | ||||
10697 | |||||
10698 | // This operation may not be performed on boolean vectors. | ||||
10699 | if (!AllowBoolOperation && | ||||
10700 | (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) | ||||
10701 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); | ||||
10702 | |||||
10703 | // If the vector types are identical, return. | ||||
10704 | if (Context.hasSameType(LHSType, RHSType)) | ||||
10705 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
10706 | |||||
10707 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | ||||
10708 | if (LHSVecType && RHSVecType && | ||||
10709 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
10710 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10711 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
10712 | return LHSType; | ||||
10713 | } | ||||
10714 | |||||
10715 | if (!IsCompAssign) | ||||
10716 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
10717 | return RHSType; | ||||
10718 | } | ||||
10719 | |||||
10720 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | ||||
10721 | // can be mixed, with the result being the non-bool type. The non-bool | ||||
10722 | // operand must have integer element type. | ||||
10723 | if (AllowBoolConversions && LHSVecType && RHSVecType && | ||||
10724 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | ||||
10725 | (Context.getTypeSize(LHSVecType->getElementType()) == | ||||
10726 | Context.getTypeSize(RHSVecType->getElementType()))) { | ||||
10727 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
10728 | LHSVecType->getElementType()->isIntegerType() && | ||||
10729 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | ||||
10730 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
10731 | return LHSType; | ||||
10732 | } | ||||
10733 | if (!IsCompAssign && | ||||
10734 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
10735 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
10736 | RHSVecType->getElementType()->isIntegerType()) { | ||||
10737 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
10738 | return RHSType; | ||||
10739 | } | ||||
10740 | } | ||||
10741 | |||||
10742 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | ||||
10743 | // since the ambiguity can affect the ABI. | ||||
10744 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | ||||
10745 | const VectorType *VecType = SecondType->getAs<VectorType>(); | ||||
10746 | return FirstType->isSizelessBuiltinType() && VecType && | ||||
10747 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | ||||
10748 | VecType->getVectorKind() == | ||||
10749 | VectorType::SveFixedLengthPredicateVector); | ||||
10750 | }; | ||||
10751 | |||||
10752 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | ||||
10753 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | ||||
10754 | return QualType(); | ||||
10755 | } | ||||
10756 | |||||
10757 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | ||||
10758 | // since the ambiguity can affect the ABI. | ||||
10759 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | ||||
10760 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | ||||
10761 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | ||||
10762 | |||||
10763 | if (FirstVecType && SecondVecType) | ||||
10764 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | ||||
10765 | (SecondVecType->getVectorKind() == | ||||
10766 | VectorType::SveFixedLengthDataVector || | ||||
10767 | SecondVecType->getVectorKind() == | ||||
10768 | VectorType::SveFixedLengthPredicateVector); | ||||
10769 | |||||
10770 | return FirstType->isSizelessBuiltinType() && SecondVecType && | ||||
10771 | SecondVecType->getVectorKind() == VectorType::GenericVector; | ||||
10772 | }; | ||||
10773 | |||||
10774 | if (IsSveGnuConversion(LHSType, RHSType) || | ||||
10775 | IsSveGnuConversion(RHSType, LHSType)) { | ||||
10776 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | ||||
10777 | return QualType(); | ||||
10778 | } | ||||
10779 | |||||
10780 | // If there's a vector type and a scalar, try to convert the scalar to | ||||
10781 | // the vector element type and splat. | ||||
10782 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | ||||
10783 | if (!RHSVecType) { | ||||
10784 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10785 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | ||||
10786 | LHSVecType->getElementType(), LHSType, | ||||
10787 | DiagID)) | ||||
10788 | return LHSType; | ||||
10789 | } else { | ||||
10790 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
10791 | return LHSType; | ||||
10792 | } | ||||
10793 | } | ||||
10794 | if (!LHSVecType) { | ||||
10795 | if (isa<ExtVectorType>(RHSVecType)) { | ||||
10796 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | ||||
10797 | LHSType, RHSVecType->getElementType(), | ||||
10798 | RHSType, DiagID)) | ||||
10799 | return RHSType; | ||||
10800 | } else { | ||||
10801 | if (LHS.get()->isLValue() || | ||||
10802 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10803 | return RHSType; | ||||
10804 | } | ||||
10805 | } | ||||
10806 | |||||
10807 | // FIXME: The code below also handles conversion between vectors and | ||||
10808 | // non-scalars, we should break this down into fine grained specific checks | ||||
10809 | // and emit proper diagnostics. | ||||
10810 | QualType VecType = LHSVecType ? LHSType : RHSType; | ||||
10811 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | ||||
10812 | QualType OtherType = LHSVecType ? RHSType : LHSType; | ||||
10813 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | ||||
10814 | if (isLaxVectorConversion(OtherType, VecType)) { | ||||
10815 | if (anyAltivecTypes(RHSType, LHSType) && | ||||
10816 | !areSameVectorElemTypes(RHSType, LHSType)) | ||||
10817 | Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; | ||||
10818 | // If we're allowing lax vector conversions, only the total (data) size | ||||
10819 | // needs to be the same. For non compound assignment, if one of the types is | ||||
10820 | // scalar, the result is always the vector type. | ||||
10821 | if (!IsCompAssign) { | ||||
10822 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | ||||
10823 | return VecType; | ||||
10824 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | ||||
10825 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | ||||
10826 | // type. Note that this is already done by non-compound assignments in | ||||
10827 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | ||||
10828 | // <1 x T> -> T. The result is also a vector type. | ||||
10829 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | ||||
10830 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | ||||
10831 | ExprResult *RHSExpr = &RHS; | ||||
10832 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | ||||
10833 | return VecType; | ||||
10834 | } | ||||
10835 | } | ||||
10836 | |||||
10837 | // Okay, the expression is invalid. | ||||
10838 | |||||
10839 | // If there's a non-vector, non-real operand, diagnose that. | ||||
10840 | if ((!RHSVecType && !RHSType->isRealType()) || | ||||
10841 | (!LHSVecType && !LHSType->isRealType())) { | ||||
10842 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10843 | << LHSType << RHSType | ||||
10844 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10845 | return QualType(); | ||||
10846 | } | ||||
10847 | |||||
10848 | // OpenCL V1.1 6.2.6.p1: | ||||
10849 | // If the operands are of more than one vector type, then an error shall | ||||
10850 | // occur. Implicit conversions between vector types are not permitted, per | ||||
10851 | // section 6.2.1. | ||||
10852 | if (getLangOpts().OpenCL && | ||||
10853 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | ||||
10854 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | ||||
10855 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | ||||
10856 | << RHSType; | ||||
10857 | return QualType(); | ||||
10858 | } | ||||
10859 | |||||
10860 | |||||
10861 | // If there is a vector type that is not a ExtVector and a scalar, we reach | ||||
10862 | // this point if scalar could not be converted to the vector's element type | ||||
10863 | // without truncation. | ||||
10864 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | ||||
10865 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | ||||
10866 | QualType Scalar = LHSVecType ? RHSType : LHSType; | ||||
10867 | QualType Vector = LHSVecType ? LHSType : RHSType; | ||||
10868 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | ||||
10869 | Diag(Loc, | ||||
10870 | diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10871 | << ScalarOrVector << Scalar << Vector; | ||||
10872 | |||||
10873 | return QualType(); | ||||
10874 | } | ||||
10875 | |||||
10876 | // Otherwise, use the generic diagnostic. | ||||
10877 | Diag(Loc, DiagID) | ||||
10878 | << LHSType << RHSType | ||||
10879 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10880 | return QualType(); | ||||
10881 | } | ||||
10882 | |||||
10883 | QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10884 | SourceLocation Loc, | ||||
10885 | bool IsCompAssign, | ||||
10886 | ArithConvKind OperationKind) { | ||||
10887 | if (!IsCompAssign) { | ||||
10888 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
10889 | if (LHS.isInvalid()) | ||||
10890 | return QualType(); | ||||
10891 | } | ||||
10892 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
10893 | if (RHS.isInvalid()) | ||||
10894 | return QualType(); | ||||
10895 | |||||
10896 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
10897 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
10898 | |||||
10899 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); | ||||
10900 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); | ||||
10901 | |||||
10902 | unsigned DiagID = diag::err_typecheck_invalid_operands; | ||||
10903 | if ((OperationKind == ACK_Arithmetic) && | ||||
10904 | ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || | ||||
10905 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { | ||||
10906 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10907 | << RHS.get()->getSourceRange(); | ||||
10908 | return QualType(); | ||||
10909 | } | ||||
10910 | |||||
10911 | if (Context.hasSameType(LHSType, RHSType)) | ||||
10912 | return LHSType; | ||||
10913 | |||||
10914 | if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { | ||||
10915 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
10916 | return LHSType; | ||||
10917 | } | ||||
10918 | if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { | ||||
10919 | if (LHS.get()->isLValue() || | ||||
10920 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10921 | return RHSType; | ||||
10922 | } | ||||
10923 | |||||
10924 | if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) || | ||||
10925 | (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) { | ||||
10926 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10927 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10928 | << RHS.get()->getSourceRange(); | ||||
10929 | return QualType(); | ||||
10930 | } | ||||
10931 | |||||
10932 | if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && | ||||
10933 | Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != | ||||
10934 | Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) { | ||||
10935 | Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
10936 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10937 | << RHS.get()->getSourceRange(); | ||||
10938 | return QualType(); | ||||
10939 | } | ||||
10940 | |||||
10941 | if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) { | ||||
10942 | QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType; | ||||
10943 | QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType; | ||||
10944 | bool ScalarOrVector = | ||||
10945 | LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType(); | ||||
10946 | |||||
10947 | Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10948 | << ScalarOrVector << Scalar << Vector; | ||||
10949 | |||||
10950 | return QualType(); | ||||
10951 | } | ||||
10952 | |||||
10953 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10954 | << RHS.get()->getSourceRange(); | ||||
10955 | return QualType(); | ||||
10956 | } | ||||
10957 | |||||
10958 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | ||||
10959 | // expression. These are mainly cases where the null pointer is used as an | ||||
10960 | // integer instead of a pointer. | ||||
10961 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10962 | SourceLocation Loc, bool IsCompare) { | ||||
10963 | // The canonical way to check for a GNU null is with isNullPointerConstant, | ||||
10964 | // but we use a bit of a hack here for speed; this is a relatively | ||||
10965 | // hot path, and isNullPointerConstant is slow. | ||||
10966 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | ||||
10967 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | ||||
10968 | |||||
10969 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | ||||
10970 | |||||
10971 | // Avoid analyzing cases where the result will either be invalid (and | ||||
10972 | // diagnosed as such) or entirely valid and not something to warn about. | ||||
10973 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | ||||
10974 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | ||||
10975 | return; | ||||
10976 | |||||
10977 | // Comparison operations would not make sense with a null pointer no matter | ||||
10978 | // what the other expression is. | ||||
10979 | if (!IsCompare) { | ||||
10980 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | ||||
10981 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | ||||
10982 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | ||||
10983 | return; | ||||
10984 | } | ||||
10985 | |||||
10986 | // The rest of the operations only make sense with a null pointer | ||||
10987 | // if the other expression is a pointer. | ||||
10988 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | ||||
10989 | NonNullType->canDecayToPointerType()) | ||||
10990 | return; | ||||
10991 | |||||
10992 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | ||||
10993 | << LHSNull /* LHS is NULL */ << NonNullType | ||||
10994 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10995 | } | ||||
10996 | |||||
10997 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | ||||
10998 | SourceLocation Loc) { | ||||
10999 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | ||||
11000 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | ||||
11001 | if (!LUE || !RUE) | ||||
11002 | return; | ||||
11003 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | ||||
11004 | RUE->getKind() != UETT_SizeOf) | ||||
11005 | return; | ||||
11006 | |||||
11007 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | ||||
11008 | QualType LHSTy = LHSArg->getType(); | ||||
11009 | QualType RHSTy; | ||||
11010 | |||||
11011 | if (RUE->isArgumentType()) | ||||
11012 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | ||||
11013 | else | ||||
11014 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | ||||
11015 | |||||
11016 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | ||||
11017 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | ||||
11018 | return; | ||||
11019 | |||||
11020 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | ||||
11021 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
11022 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
11023 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | ||||
11024 | << LHSArgDecl; | ||||
11025 | } | ||||
11026 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | ||||
11027 | QualType ArrayElemTy = ArrayTy->getElementType(); | ||||
11028 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | ||||
11029 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | ||||
11030 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | ||||
11031 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | ||||
11032 | return; | ||||
11033 | S.Diag(Loc, diag::warn_division_sizeof_array) | ||||
11034 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | ||||
11035 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
11036 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
11037 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | ||||
11038 | << LHSArgDecl; | ||||
11039 | } | ||||
11040 | |||||
11041 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | ||||
11042 | } | ||||
11043 | } | ||||
11044 | |||||
11045 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | ||||
11046 | ExprResult &RHS, | ||||
11047 | SourceLocation Loc, bool IsDiv) { | ||||
11048 | // Check for division/remainder by zero. | ||||
11049 | Expr::EvalResult RHSValue; | ||||
11050 | if (!RHS.get()->isValueDependent() && | ||||
11051 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | ||||
11052 | RHSValue.Val.getInt() == 0) | ||||
11053 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11054 | S.PDiag(diag::warn_remainder_division_by_zero) | ||||
11055 | << IsDiv << RHS.get()->getSourceRange()); | ||||
11056 | } | ||||
11057 | |||||
11058 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11059 | SourceLocation Loc, | ||||
11060 | bool IsCompAssign, bool IsDiv) { | ||||
11061 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11062 | |||||
11063 | QualType LHSTy = LHS.get()->getType(); | ||||
11064 | QualType RHSTy = RHS.get()->getType(); | ||||
11065 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) | ||||
11066 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
11067 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
11068 | /*AllowBoolConversions*/ false, | ||||
11069 | /*AllowBooleanOperation*/ false, | ||||
11070 | /*ReportInvalid*/ true); | ||||
11071 | if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) | ||||
11072 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
11073 | ACK_Arithmetic); | ||||
11074 | if (!IsDiv && | ||||
11075 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) | ||||
11076 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | ||||
11077 | // For division, only matrix-by-scalar is supported. Other combinations with | ||||
11078 | // matrix types are invalid. | ||||
11079 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) | ||||
11080 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
11081 | |||||
11082 | QualType compType = UsualArithmeticConversions( | ||||
11083 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
11084 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11085 | return QualType(); | ||||
11086 | |||||
11087 | |||||
11088 | if (compType.isNull() || !compType->isArithmeticType()) | ||||
11089 | return InvalidOperands(Loc, LHS, RHS); | ||||
11090 | if (IsDiv) { | ||||
11091 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | ||||
11092 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | ||||
11093 | } | ||||
11094 | return compType; | ||||
11095 | } | ||||
11096 | |||||
11097 | QualType Sema::CheckRemainderOperands( | ||||
11098 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | ||||
11099 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11100 | |||||
11101 | if (LHS.get()->getType()->isVectorType() || | ||||
11102 | RHS.get()->getType()->isVectorType()) { | ||||
11103 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
11104 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
11105 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
11106 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
11107 | /*AllowBoolConversions*/ false, | ||||
11108 | /*AllowBooleanOperation*/ false, | ||||
11109 | /*ReportInvalid*/ true); | ||||
11110 | return InvalidOperands(Loc, LHS, RHS); | ||||
11111 | } | ||||
11112 | |||||
11113 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11114 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
11115 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
11116 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
11117 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
11118 | ACK_Arithmetic); | ||||
11119 | |||||
11120 | return InvalidOperands(Loc, LHS, RHS); | ||||
11121 | } | ||||
11122 | |||||
11123 | QualType compType = UsualArithmeticConversions( | ||||
11124 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
11125 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11126 | return QualType(); | ||||
11127 | |||||
11128 | if (compType.isNull() || !compType->isIntegerType()) | ||||
11129 | return InvalidOperands(Loc, LHS, RHS); | ||||
11130 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | ||||
11131 | return compType; | ||||
11132 | } | ||||
11133 | |||||
11134 | /// Diagnose invalid arithmetic on two void pointers. | ||||
11135 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | ||||
11136 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11137 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
11138 | ? diag::err_typecheck_pointer_arith_void_type | ||||
11139 | : diag::ext_gnu_void_ptr) | ||||
11140 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | ||||
11141 | << RHSExpr->getSourceRange(); | ||||
11142 | } | ||||
11143 | |||||
11144 | /// Diagnose invalid arithmetic on a void pointer. | ||||
11145 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | ||||
11146 | Expr *Pointer) { | ||||
11147 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
11148 | ? diag::err_typecheck_pointer_arith_void_type | ||||
11149 | : diag::ext_gnu_void_ptr) | ||||
11150 | << 0 /* one pointer */ << Pointer->getSourceRange(); | ||||
11151 | } | ||||
11152 | |||||
11153 | /// Diagnose invalid arithmetic on a null pointer. | ||||
11154 | /// | ||||
11155 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | ||||
11156 | /// idiom, which we recognize as a GNU extension. | ||||
11157 | /// | ||||
11158 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | ||||
11159 | Expr *Pointer, bool IsGNUIdiom) { | ||||
11160 | if (IsGNUIdiom) | ||||
11161 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | ||||
11162 | << Pointer->getSourceRange(); | ||||
11163 | else | ||||
11164 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | ||||
11165 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||
11166 | } | ||||
11167 | |||||
11168 | /// Diagnose invalid subraction on a null pointer. | ||||
11169 | /// | ||||
11170 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, | ||||
11171 | Expr *Pointer, bool BothNull) { | ||||
11172 | // Null - null is valid in C++ [expr.add]p7 | ||||
11173 | if (BothNull && S.getLangOpts().CPlusPlus) | ||||
11174 | return; | ||||
11175 | |||||
11176 | // Is this s a macro from a system header? | ||||
11177 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) | ||||
11178 | return; | ||||
11179 | |||||
11180 | S.DiagRuntimeBehavior(Loc, Pointer, | ||||
11181 | S.PDiag(diag::warn_pointer_sub_null_ptr) | ||||
11182 | << S.getLangOpts().CPlusPlus | ||||
11183 | << Pointer->getSourceRange()); | ||||
11184 | } | ||||
11185 | |||||
11186 | /// Diagnose invalid arithmetic on two function pointers. | ||||
11187 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | ||||
11188 | Expr *LHS, Expr *RHS) { | ||||
11189 | assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11189, __extension__ __PRETTY_FUNCTION__ )); | ||||
11190 | assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11190, __extension__ __PRETTY_FUNCTION__ )); | ||||
11191 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
11192 | ? diag::err_typecheck_pointer_arith_function_type | ||||
11193 | : diag::ext_gnu_ptr_func_arith) | ||||
11194 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | ||||
11195 | // We only show the second type if it differs from the first. | ||||
11196 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | ||||
11197 | RHS->getType()) | ||||
11198 | << RHS->getType()->getPointeeType() | ||||
11199 | << LHS->getSourceRange() << RHS->getSourceRange(); | ||||
11200 | } | ||||
11201 | |||||
11202 | /// Diagnose invalid arithmetic on a function pointer. | ||||
11203 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | ||||
11204 | Expr *Pointer) { | ||||
11205 | assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11205, __extension__ __PRETTY_FUNCTION__ )); | ||||
11206 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
11207 | ? diag::err_typecheck_pointer_arith_function_type | ||||
11208 | : diag::ext_gnu_ptr_func_arith) | ||||
11209 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | ||||
11210 | << 0 /* one pointer, so only one type */ | ||||
11211 | << Pointer->getSourceRange(); | ||||
11212 | } | ||||
11213 | |||||
11214 | /// Emit error if Operand is incomplete pointer type | ||||
11215 | /// | ||||
11216 | /// \returns True if pointer has incomplete type | ||||
11217 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | ||||
11218 | Expr *Operand) { | ||||
11219 | QualType ResType = Operand->getType(); | ||||
11220 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
11221 | ResType = ResAtomicType->getValueType(); | ||||
11222 | |||||
11223 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() && !ResType->isDependentType()) ? void (0) : __assert_fail ( "ResType->isAnyPointerType() && !ResType->isDependentType()" , "clang/lib/Sema/SemaExpr.cpp", 11223, __extension__ __PRETTY_FUNCTION__ )); | ||||
11224 | QualType PointeeTy = ResType->getPointeeType(); | ||||
11225 | return S.RequireCompleteSizedType( | ||||
11226 | Loc, PointeeTy, | ||||
11227 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | ||||
11228 | Operand->getSourceRange()); | ||||
11229 | } | ||||
11230 | |||||
11231 | /// Check the validity of an arithmetic pointer operand. | ||||
11232 | /// | ||||
11233 | /// If the operand has pointer type, this code will check for pointer types | ||||
11234 | /// which are invalid in arithmetic operations. These will be diagnosed | ||||
11235 | /// appropriately, including whether or not the use is supported as an | ||||
11236 | /// extension. | ||||
11237 | /// | ||||
11238 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
11239 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | ||||
11240 | Expr *Operand) { | ||||
11241 | QualType ResType = Operand->getType(); | ||||
11242 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
11243 | ResType = ResAtomicType->getValueType(); | ||||
11244 | |||||
11245 | if (!ResType->isAnyPointerType()) return true; | ||||
11246 | |||||
11247 | QualType PointeeTy = ResType->getPointeeType(); | ||||
11248 | if (PointeeTy->isVoidType()) { | ||||
11249 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | ||||
11250 | return !S.getLangOpts().CPlusPlus; | ||||
11251 | } | ||||
11252 | if (PointeeTy->isFunctionType()) { | ||||
11253 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | ||||
11254 | return !S.getLangOpts().CPlusPlus; | ||||
11255 | } | ||||
11256 | |||||
11257 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | ||||
11258 | |||||
11259 | return true; | ||||
11260 | } | ||||
11261 | |||||
11262 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | ||||
11263 | /// operands. | ||||
11264 | /// | ||||
11265 | /// This routine will diagnose any invalid arithmetic on pointer operands much | ||||
11266 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | ||||
11267 | /// for emitting a single diagnostic even for operations where both LHS and RHS | ||||
11268 | /// are (potentially problematic) pointers. | ||||
11269 | /// | ||||
11270 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
11271 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | ||||
11272 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11273 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | ||||
11274 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | ||||
11275 | if (!isLHSPointer && !isRHSPointer) return true; | ||||
11276 | |||||
11277 | QualType LHSPointeeTy, RHSPointeeTy; | ||||
11278 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | ||||
11279 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | ||||
11280 | |||||
11281 | // if both are pointers check if operation is valid wrt address spaces | ||||
11282 | if (isLHSPointer && isRHSPointer) { | ||||
11283 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | ||||
11284 | S.Diag(Loc, | ||||
11285 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
11286 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | ||||
11287 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | ||||
11288 | return false; | ||||
11289 | } | ||||
11290 | } | ||||
11291 | |||||
11292 | // Check for arithmetic on pointers to incomplete types. | ||||
11293 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | ||||
11294 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | ||||
11295 | if (isLHSVoidPtr || isRHSVoidPtr) { | ||||
11296 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | ||||
11297 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | ||||
11298 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | ||||
11299 | |||||
11300 | return !S.getLangOpts().CPlusPlus; | ||||
11301 | } | ||||
11302 | |||||
11303 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | ||||
11304 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | ||||
11305 | if (isLHSFuncPtr || isRHSFuncPtr) { | ||||
11306 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | ||||
11307 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | ||||
11308 | RHSExpr); | ||||
11309 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | ||||
11310 | |||||
11311 | return !S.getLangOpts().CPlusPlus; | ||||
11312 | } | ||||
11313 | |||||
11314 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | ||||
11315 | return false; | ||||
11316 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | ||||
11317 | return false; | ||||
11318 | |||||
11319 | return true; | ||||
11320 | } | ||||
11321 | |||||
11322 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | ||||
11323 | /// literal. | ||||
11324 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | ||||
11325 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11326 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
11327 | Expr* IndexExpr = RHSExpr; | ||||
11328 | if (!StrExpr) { | ||||
11329 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
11330 | IndexExpr = LHSExpr; | ||||
11331 | } | ||||
11332 | |||||
11333 | bool IsStringPlusInt = StrExpr && | ||||
11334 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | ||||
11335 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | ||||
11336 | return; | ||||
11337 | |||||
11338 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
11339 | Self.Diag(OpLoc, diag::warn_string_plus_int) | ||||
11340 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | ||||
11341 | |||||
11342 | // Only print a fixit for "str" + int, not for int + "str". | ||||
11343 | if (IndexExpr == RHSExpr) { | ||||
11344 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
11345 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
11346 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
11347 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
11348 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
11349 | } else | ||||
11350 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
11351 | } | ||||
11352 | |||||
11353 | /// Emit a warning when adding a char literal to a string. | ||||
11354 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | ||||
11355 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11356 | const Expr *StringRefExpr = LHSExpr; | ||||
11357 | const CharacterLiteral *CharExpr = | ||||
11358 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
11359 | |||||
11360 | if (!CharExpr) { | ||||
11361 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
11362 | StringRefExpr = RHSExpr; | ||||
11363 | } | ||||
11364 | |||||
11365 | if (!CharExpr || !StringRefExpr) | ||||
11366 | return; | ||||
11367 | |||||
11368 | const QualType StringType = StringRefExpr->getType(); | ||||
11369 | |||||
11370 | // Return if not a PointerType. | ||||
11371 | if (!StringType->isAnyPointerType()) | ||||
11372 | return; | ||||
11373 | |||||
11374 | // Return if not a CharacterType. | ||||
11375 | if (!StringType->getPointeeType()->isAnyCharacterType()) | ||||
11376 | return; | ||||
11377 | |||||
11378 | ASTContext &Ctx = Self.getASTContext(); | ||||
11379 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
11380 | |||||
11381 | const QualType CharType = CharExpr->getType(); | ||||
11382 | if (!CharType->isAnyCharacterType() && | ||||
11383 | CharType->isIntegerType() && | ||||
11384 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | ||||
11385 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
11386 | << DiagRange << Ctx.CharTy; | ||||
11387 | } else { | ||||
11388 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
11389 | << DiagRange << CharExpr->getType(); | ||||
11390 | } | ||||
11391 | |||||
11392 | // Only print a fixit for str + char, not for char + str. | ||||
11393 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | ||||
11394 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
11395 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
11396 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
11397 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
11398 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
11399 | } else { | ||||
11400 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
11401 | } | ||||
11402 | } | ||||
11403 | |||||
11404 | /// Emit error when two pointers are incompatible. | ||||
11405 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | ||||
11406 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11407 | assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11407, __extension__ __PRETTY_FUNCTION__ )); | ||||
11408 | assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11408, __extension__ __PRETTY_FUNCTION__ )); | ||||
11409 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | ||||
11410 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | ||||
11411 | << RHSExpr->getSourceRange(); | ||||
11412 | } | ||||
11413 | |||||
11414 | // C99 6.5.6 | ||||
11415 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11416 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11417 | QualType* CompLHSTy) { | ||||
11418 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11419 | |||||
11420 | if (LHS.get()->getType()->isVectorType() || | ||||
11421 | RHS.get()->getType()->isVectorType()) { | ||||
11422 | QualType compType = | ||||
11423 | CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, | ||||
11424 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
11425 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
11426 | /*AllowBooleanOperation*/ false, | ||||
11427 | /*ReportInvalid*/ true); | ||||
11428 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11429 | return compType; | ||||
11430 | } | ||||
11431 | |||||
11432 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11433 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
11434 | QualType compType = | ||||
11435 | CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); | ||||
11436 | if (CompLHSTy) | ||||
11437 | *CompLHSTy = compType; | ||||
11438 | return compType; | ||||
11439 | } | ||||
11440 | |||||
11441 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
11442 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
11443 | QualType compType = | ||||
11444 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
11445 | if (CompLHSTy) | ||||
11446 | *CompLHSTy = compType; | ||||
11447 | return compType; | ||||
11448 | } | ||||
11449 | |||||
11450 | QualType compType = UsualArithmeticConversions( | ||||
11451 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
11452 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11453 | return QualType(); | ||||
11454 | |||||
11455 | // Diagnose "string literal" '+' int and string '+' "char literal". | ||||
11456 | if (Opc == BO_Add) { | ||||
11457 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | ||||
11458 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | ||||
11459 | } | ||||
11460 | |||||
11461 | // handle the common case first (both operands are arithmetic). | ||||
11462 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
11463 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11464 | return compType; | ||||
11465 | } | ||||
11466 | |||||
11467 | // Type-checking. Ultimately the pointer's going to be in PExp; | ||||
11468 | // note that we bias towards the LHS being the pointer. | ||||
11469 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | ||||
11470 | |||||
11471 | bool isObjCPointer; | ||||
11472 | if (PExp->getType()->isPointerType()) { | ||||
11473 | isObjCPointer = false; | ||||
11474 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
11475 | isObjCPointer = true; | ||||
11476 | } else { | ||||
11477 | std::swap(PExp, IExp); | ||||
11478 | if (PExp->getType()->isPointerType()) { | ||||
11479 | isObjCPointer = false; | ||||
11480 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
11481 | isObjCPointer = true; | ||||
11482 | } else { | ||||
11483 | return InvalidOperands(Loc, LHS, RHS); | ||||
11484 | } | ||||
11485 | } | ||||
11486 | assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11486, __extension__ __PRETTY_FUNCTION__ )); | ||||
11487 | |||||
11488 | if (!IExp->getType()->isIntegerType()) | ||||
11489 | return InvalidOperands(Loc, LHS, RHS); | ||||
11490 | |||||
11491 | // Adding to a null pointer results in undefined behavior. | ||||
11492 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | ||||
11493 | Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||
11494 | // In C++ adding zero to a null pointer is defined. | ||||
11495 | Expr::EvalResult KnownVal; | ||||
11496 | if (!getLangOpts().CPlusPlus || | ||||
11497 | (!IExp->isValueDependent() && | ||||
11498 | (!IExp->EvaluateAsInt(KnownVal, Context) || | ||||
11499 | KnownVal.Val.getInt() != 0))) { | ||||
11500 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | ||||
11501 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | ||||
11502 | Context, BO_Add, PExp, IExp); | ||||
11503 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | ||||
11504 | } | ||||
11505 | } | ||||
11506 | |||||
11507 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | ||||
11508 | return QualType(); | ||||
11509 | |||||
11510 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | ||||
11511 | return QualType(); | ||||
11512 | |||||
11513 | // Check array bounds for pointer arithemtic | ||||
11514 | CheckArrayAccess(PExp, IExp); | ||||
11515 | |||||
11516 | if (CompLHSTy) { | ||||
11517 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | ||||
11518 | if (LHSTy.isNull()) { | ||||
11519 | LHSTy = LHS.get()->getType(); | ||||
11520 | if (Context.isPromotableIntegerType(LHSTy)) | ||||
11521 | LHSTy = Context.getPromotedIntegerType(LHSTy); | ||||
11522 | } | ||||
11523 | *CompLHSTy = LHSTy; | ||||
11524 | } | ||||
11525 | |||||
11526 | return PExp->getType(); | ||||
11527 | } | ||||
11528 | |||||
11529 | // C99 6.5.6 | ||||
11530 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11531 | SourceLocation Loc, | ||||
11532 | QualType* CompLHSTy) { | ||||
11533 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11534 | |||||
11535 | if (LHS.get()->getType()->isVectorType() || | ||||
11536 | RHS.get()->getType()->isVectorType()) { | ||||
11537 | QualType compType = | ||||
11538 | CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, | ||||
11539 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
11540 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
11541 | /*AllowBooleanOperation*/ false, | ||||
11542 | /*ReportInvalid*/ true); | ||||
11543 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11544 | return compType; | ||||
11545 | } | ||||
11546 | |||||
11547 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11548 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
11549 | QualType compType = | ||||
11550 | CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); | ||||
11551 | if (CompLHSTy) | ||||
11552 | *CompLHSTy = compType; | ||||
11553 | return compType; | ||||
11554 | } | ||||
11555 | |||||
11556 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
11557 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
11558 | QualType compType = | ||||
11559 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
11560 | if (CompLHSTy) | ||||
11561 | *CompLHSTy = compType; | ||||
11562 | return compType; | ||||
11563 | } | ||||
11564 | |||||
11565 | QualType compType = UsualArithmeticConversions( | ||||
11566 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
11567 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11568 | return QualType(); | ||||
11569 | |||||
11570 | // Enforce type constraints: C99 6.5.6p3. | ||||
11571 | |||||
11572 | // Handle the common case first (both operands are arithmetic). | ||||
11573 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
11574 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11575 | return compType; | ||||
11576 | } | ||||
11577 | |||||
11578 | // Either ptr - int or ptr - ptr. | ||||
11579 | if (LHS.get()->getType()->isAnyPointerType()) { | ||||
11580 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | ||||
11581 | |||||
11582 | // Diagnose bad cases where we step over interface counts. | ||||
11583 | if (LHS.get()->getType()->isObjCObjectPointerType() && | ||||
11584 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | ||||
11585 | return QualType(); | ||||
11586 | |||||
11587 | // The result type of a pointer-int computation is the pointer type. | ||||
11588 | if (RHS.get()->getType()->isIntegerType()) { | ||||
11589 | // Subtracting from a null pointer should produce a warning. | ||||
11590 | // The last argument to the diagnose call says this doesn't match the | ||||
11591 | // GNU int-to-pointer idiom. | ||||
11592 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | ||||
11593 | Expr::NPC_ValueDependentIsNotNull)) { | ||||
11594 | // In C++ adding zero to a null pointer is defined. | ||||
11595 | Expr::EvalResult KnownVal; | ||||
11596 | if (!getLangOpts().CPlusPlus || | ||||
11597 | (!RHS.get()->isValueDependent() && | ||||
11598 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | ||||
11599 | KnownVal.Val.getInt() != 0))) { | ||||
11600 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | ||||
11601 | } | ||||
11602 | } | ||||
11603 | |||||
11604 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | ||||
11605 | return QualType(); | ||||
11606 | |||||
11607 | // Check array bounds for pointer arithemtic | ||||
11608 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | ||||
11609 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | ||||
11610 | |||||
11611 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
11612 | return LHS.get()->getType(); | ||||
11613 | } | ||||
11614 | |||||
11615 | // Handle pointer-pointer subtractions. | ||||
11616 | if (const PointerType *RHSPTy | ||||
11617 | = RHS.get()->getType()->getAs<PointerType>()) { | ||||
11618 | QualType rpointee = RHSPTy->getPointeeType(); | ||||
11619 | |||||
11620 | if (getLangOpts().CPlusPlus) { | ||||
11621 | // Pointee types must be the same: C++ [expr.add] | ||||
11622 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | ||||
11623 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
11624 | } | ||||
11625 | } else { | ||||
11626 | // Pointee types must be compatible C99 6.5.6p3 | ||||
11627 | if (!Context.typesAreCompatible( | ||||
11628 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | ||||
11629 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | ||||
11630 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
11631 | return QualType(); | ||||
11632 | } | ||||
11633 | } | ||||
11634 | |||||
11635 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | ||||
11636 | LHS.get(), RHS.get())) | ||||
11637 | return QualType(); | ||||
11638 | |||||
11639 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( | ||||
11640 | Context, Expr::NPC_ValueDependentIsNotNull); | ||||
11641 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( | ||||
11642 | Context, Expr::NPC_ValueDependentIsNotNull); | ||||
11643 | |||||
11644 | // Subtracting nullptr or from nullptr is suspect | ||||
11645 | if (LHSIsNullPtr) | ||||
11646 | diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); | ||||
11647 | if (RHSIsNullPtr) | ||||
11648 | diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); | ||||
11649 | |||||
11650 | // The pointee type may have zero size. As an extension, a structure or | ||||
11651 | // union may have zero size or an array may have zero length. In this | ||||
11652 | // case subtraction does not make sense. | ||||
11653 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | ||||
11654 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | ||||
11655 | if (ElementSize.isZero()) { | ||||
11656 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | ||||
11657 | << rpointee.getUnqualifiedType() | ||||
11658 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11659 | } | ||||
11660 | } | ||||
11661 | |||||
11662 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
11663 | return Context.getPointerDiffType(); | ||||
11664 | } | ||||
11665 | } | ||||
11666 | |||||
11667 | return InvalidOperands(Loc, LHS, RHS); | ||||
11668 | } | ||||
11669 | |||||
11670 | static bool isScopedEnumerationType(QualType T) { | ||||
11671 | if (const EnumType *ET = T->getAs<EnumType>()) | ||||
11672 | return ET->getDecl()->isScoped(); | ||||
11673 | return false; | ||||
11674 | } | ||||
11675 | |||||
11676 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | ||||
11677 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11678 | QualType LHSType) { | ||||
11679 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | ||||
11680 | // so skip remaining warnings as we don't want to modify values within Sema. | ||||
11681 | if (S.getLangOpts().OpenCL) | ||||
11682 | return; | ||||
11683 | |||||
11684 | // Check right/shifter operand | ||||
11685 | Expr::EvalResult RHSResult; | ||||
11686 | if (RHS.get()->isValueDependent() || | ||||
11687 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | ||||
11688 | return; | ||||
11689 | llvm::APSInt Right = RHSResult.Val.getInt(); | ||||
11690 | |||||
11691 | if (Right.isNegative()) { | ||||
11692 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11693 | S.PDiag(diag::warn_shift_negative) | ||||
11694 | << RHS.get()->getSourceRange()); | ||||
11695 | return; | ||||
11696 | } | ||||
11697 | |||||
11698 | QualType LHSExprType = LHS.get()->getType(); | ||||
11699 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | ||||
11700 | if (LHSExprType->isBitIntType()) | ||||
11701 | LeftSize = S.Context.getIntWidth(LHSExprType); | ||||
11702 | else if (LHSExprType->isFixedPointType()) { | ||||
11703 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | ||||
11704 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | ||||
11705 | } | ||||
11706 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | ||||
11707 | if (Right.uge(LeftBits)) { | ||||
11708 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11709 | S.PDiag(diag::warn_shift_gt_typewidth) | ||||
11710 | << RHS.get()->getSourceRange()); | ||||
11711 | return; | ||||
11712 | } | ||||
11713 | |||||
11714 | // FIXME: We probably need to handle fixed point types specially here. | ||||
11715 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | ||||
11716 | return; | ||||
11717 | |||||
11718 | // When left shifting an ICE which is signed, we can check for overflow which | ||||
11719 | // according to C++ standards prior to C++2a has undefined behavior | ||||
11720 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | ||||
11721 | // more than the maximum value representable in the result type, so never | ||||
11722 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | ||||
11723 | // expression is still probably a bug.) | ||||
11724 | Expr::EvalResult LHSResult; | ||||
11725 | if (LHS.get()->isValueDependent() || | ||||
11726 | LHSType->hasUnsignedIntegerRepresentation() || | ||||
11727 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | ||||
11728 | return; | ||||
11729 | llvm::APSInt Left = LHSResult.Val.getInt(); | ||||
11730 | |||||
11731 | // Don't warn if signed overflow is defined, then all the rest of the | ||||
11732 | // diagnostics will not be triggered because the behavior is defined. | ||||
11733 | // Also don't warn in C++20 mode (and newer), as signed left shifts | ||||
11734 | // always wrap and never overflow. | ||||
11735 | if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) | ||||
11736 | return; | ||||
11737 | |||||
11738 | // If LHS does not have a non-negative value then, the | ||||
11739 | // behavior is undefined before C++2a. Warn about it. | ||||
11740 | if (Left.isNegative()) { | ||||
11741 | S.DiagRuntimeBehavior(Loc, LHS.get(), | ||||
11742 | S.PDiag(diag::warn_shift_lhs_negative) | ||||
11743 | << LHS.get()->getSourceRange()); | ||||
11744 | return; | ||||
11745 | } | ||||
11746 | |||||
11747 | llvm::APInt ResultBits = | ||||
11748 | static_cast<llvm::APInt &>(Right) + Left.getSignificantBits(); | ||||
11749 | if (LeftBits.uge(ResultBits)) | ||||
11750 | return; | ||||
11751 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | ||||
11752 | Result = Result.shl(Right); | ||||
11753 | |||||
11754 | // Print the bit representation of the signed integer as an unsigned | ||||
11755 | // hexadecimal number. | ||||
11756 | SmallString<40> HexResult; | ||||
11757 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | ||||
11758 | |||||
11759 | // If we are only missing a sign bit, this is less likely to result in actual | ||||
11760 | // bugs -- if the result is cast back to an unsigned type, it will have the | ||||
11761 | // expected value. Thus we place this behind a different warning that can be | ||||
11762 | // turned off separately if needed. | ||||
11763 | if (LeftBits == ResultBits - 1) { | ||||
11764 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | ||||
11765 | << HexResult << LHSType | ||||
11766 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11767 | return; | ||||
11768 | } | ||||
11769 | |||||
11770 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | ||||
11771 | << HexResult.str() << Result.getSignificantBits() << LHSType | ||||
11772 | << Left.getBitWidth() << LHS.get()->getSourceRange() | ||||
11773 | << RHS.get()->getSourceRange(); | ||||
11774 | } | ||||
11775 | |||||
11776 | /// Return the resulting type when a vector is shifted | ||||
11777 | /// by a scalar or vector shift amount. | ||||
11778 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
11779 | SourceLocation Loc, bool IsCompAssign) { | ||||
11780 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | ||||
11781 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | ||||
11782 | !LHS.get()->getType()->isVectorType()) { | ||||
11783 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | ||||
11784 | << RHS.get()->getType() << LHS.get()->getType() | ||||
11785 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11786 | return QualType(); | ||||
11787 | } | ||||
11788 | |||||
11789 | if (!IsCompAssign) { | ||||
11790 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
11791 | if (LHS.isInvalid()) return QualType(); | ||||
11792 | } | ||||
11793 | |||||
11794 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
11795 | if (RHS.isInvalid()) return QualType(); | ||||
11796 | |||||
11797 | QualType LHSType = LHS.get()->getType(); | ||||
11798 | // Note that LHS might be a scalar because the routine calls not only in | ||||
11799 | // OpenCL case. | ||||
11800 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | ||||
11801 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | ||||
11802 | |||||
11803 | // Note that RHS might not be a vector. | ||||
11804 | QualType RHSType = RHS.get()->getType(); | ||||
11805 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | ||||
11806 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | ||||
11807 | |||||
11808 | // Do not allow shifts for boolean vectors. | ||||
11809 | if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || | ||||
11810 | (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { | ||||
11811 | S.Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
11812 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11813 | << LHS.get()->getSourceRange(); | ||||
11814 | return QualType(); | ||||
11815 | } | ||||
11816 | |||||
11817 | // The operands need to be integers. | ||||
11818 | if (!LHSEleType->isIntegerType()) { | ||||
11819 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11820 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
11821 | return QualType(); | ||||
11822 | } | ||||
11823 | |||||
11824 | if (!RHSEleType->isIntegerType()) { | ||||
11825 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11826 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
11827 | return QualType(); | ||||
11828 | } | ||||
11829 | |||||
11830 | if (!LHSVecTy) { | ||||
11831 | assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail ("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11831, __extension__ __PRETTY_FUNCTION__)); | ||||
11832 | if (IsCompAssign) | ||||
11833 | return RHSType; | ||||
11834 | if (LHSEleType != RHSEleType) { | ||||
11835 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | ||||
11836 | LHSEleType = RHSEleType; | ||||
11837 | } | ||||
11838 | QualType VecTy = | ||||
11839 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | ||||
11840 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | ||||
11841 | LHSType = VecTy; | ||||
11842 | } else if (RHSVecTy) { | ||||
11843 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | ||||
11844 | // are applied component-wise. So if RHS is a vector, then ensure | ||||
11845 | // that the number of elements is the same as LHS... | ||||
11846 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | ||||
11847 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
11848 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11849 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11850 | return QualType(); | ||||
11851 | } | ||||
11852 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | ||||
11853 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | ||||
11854 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | ||||
11855 | if (LHSBT != RHSBT && | ||||
11856 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | ||||
11857 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | ||||
11858 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11859 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11860 | } | ||||
11861 | } | ||||
11862 | } else { | ||||
11863 | // ...else expand RHS to match the number of elements in LHS. | ||||
11864 | QualType VecTy = | ||||
11865 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | ||||
11866 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
11867 | } | ||||
11868 | |||||
11869 | return LHSType; | ||||
11870 | } | ||||
11871 | |||||
11872 | static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, | ||||
11873 | ExprResult &RHS, SourceLocation Loc, | ||||
11874 | bool IsCompAssign) { | ||||
11875 | if (!IsCompAssign) { | ||||
11876 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
11877 | if (LHS.isInvalid()) | ||||
11878 | return QualType(); | ||||
11879 | } | ||||
11880 | |||||
11881 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
11882 | if (RHS.isInvalid()) | ||||
11883 | return QualType(); | ||||
11884 | |||||
11885 | QualType LHSType = LHS.get()->getType(); | ||||
11886 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); | ||||
11887 | QualType LHSEleType = LHSType->isVLSTBuiltinType() | ||||
11888 | ? LHSBuiltinTy->getSveEltType(S.getASTContext()) | ||||
11889 | : LHSType; | ||||
11890 | |||||
11891 | // Note that RHS might not be a vector | ||||
11892 | QualType RHSType = RHS.get()->getType(); | ||||
11893 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); | ||||
11894 | QualType RHSEleType = RHSType->isVLSTBuiltinType() | ||||
11895 | ? RHSBuiltinTy->getSveEltType(S.getASTContext()) | ||||
11896 | : RHSType; | ||||
11897 | |||||
11898 | if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || | ||||
11899 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { | ||||
11900 | S.Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
11901 | << LHSType << RHSType << LHS.get()->getSourceRange(); | ||||
11902 | return QualType(); | ||||
11903 | } | ||||
11904 | |||||
11905 | if (!LHSEleType->isIntegerType()) { | ||||
11906 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11907 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
11908 | return QualType(); | ||||
11909 | } | ||||
11910 | |||||
11911 | if (!RHSEleType->isIntegerType()) { | ||||
11912 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11913 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
11914 | return QualType(); | ||||
11915 | } | ||||
11916 | |||||
11917 | if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && | ||||
11918 | (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != | ||||
11919 | S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { | ||||
11920 | S.Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
11921 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11922 | << RHS.get()->getSourceRange(); | ||||
11923 | return QualType(); | ||||
11924 | } | ||||
11925 | |||||
11926 | if (!LHSType->isVLSTBuiltinType()) { | ||||
11927 | assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ? void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()", "clang/lib/Sema/SemaExpr.cpp", 11927, __extension__ __PRETTY_FUNCTION__ )); | ||||
11928 | if (IsCompAssign) | ||||
11929 | return RHSType; | ||||
11930 | if (LHSEleType != RHSEleType) { | ||||
11931 | LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); | ||||
11932 | LHSEleType = RHSEleType; | ||||
11933 | } | ||||
11934 | const llvm::ElementCount VecSize = | ||||
11935 | S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; | ||||
11936 | QualType VecTy = | ||||
11937 | S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); | ||||
11938 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); | ||||
11939 | LHSType = VecTy; | ||||
11940 | } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { | ||||
11941 | if (S.Context.getTypeSize(RHSBuiltinTy) != | ||||
11942 | S.Context.getTypeSize(LHSBuiltinTy)) { | ||||
11943 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
11944 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11945 | << RHS.get()->getSourceRange(); | ||||
11946 | return QualType(); | ||||
11947 | } | ||||
11948 | } else { | ||||
11949 | const llvm::ElementCount VecSize = | ||||
11950 | S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; | ||||
11951 | if (LHSEleType != RHSEleType) { | ||||
11952 | RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); | ||||
11953 | RHSEleType = LHSEleType; | ||||
11954 | } | ||||
11955 | QualType VecTy = | ||||
11956 | S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); | ||||
11957 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
11958 | } | ||||
11959 | |||||
11960 | return LHSType; | ||||
11961 | } | ||||
11962 | |||||
11963 | // C99 6.5.7 | ||||
11964 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11965 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11966 | bool IsCompAssign) { | ||||
11967 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11968 | |||||
11969 | // Vector shifts promote their scalar inputs to vector type. | ||||
11970 | if (LHS.get()->getType()->isVectorType() || | ||||
11971 | RHS.get()->getType()->isVectorType()) { | ||||
11972 | if (LangOpts.ZVector) { | ||||
11973 | // The shift operators for the z vector extensions work basically | ||||
11974 | // like general shifts, except that neither the LHS nor the RHS is | ||||
11975 | // allowed to be a "vector bool". | ||||
11976 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | ||||
11977 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
11978 | return InvalidOperands(Loc, LHS, RHS); | ||||
11979 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | ||||
11980 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
11981 | return InvalidOperands(Loc, LHS, RHS); | ||||
11982 | } | ||||
11983 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
11984 | } | ||||
11985 | |||||
11986 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11987 | RHS.get()->getType()->isVLSTBuiltinType()) | ||||
11988 | return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
11989 | |||||
11990 | // Shifts don't perform usual arithmetic conversions, they just do integer | ||||
11991 | // promotions on each operand. C99 6.5.7p3 | ||||
11992 | |||||
11993 | // For the LHS, do usual unary conversions, but then reset them away | ||||
11994 | // if this is a compound assignment. | ||||
11995 | ExprResult OldLHS = LHS; | ||||
11996 | LHS = UsualUnaryConversions(LHS.get()); | ||||
11997 | if (LHS.isInvalid()) | ||||
11998 | return QualType(); | ||||
11999 | QualType LHSType = LHS.get()->getType(); | ||||
12000 | if (IsCompAssign) LHS = OldLHS; | ||||
12001 | |||||
12002 | // The RHS is simpler. | ||||
12003 | RHS = UsualUnaryConversions(RHS.get()); | ||||
12004 | if (RHS.isInvalid()) | ||||
12005 | return QualType(); | ||||
12006 | QualType RHSType = RHS.get()->getType(); | ||||
12007 | |||||
12008 | // C99 6.5.7p2: Each of the operands shall have integer type. | ||||
12009 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | ||||
12010 | if ((!LHSType->isFixedPointOrIntegerType() && | ||||
12011 | !LHSType->hasIntegerRepresentation()) || | ||||
12012 | !RHSType->hasIntegerRepresentation()) | ||||
12013 | return InvalidOperands(Loc, LHS, RHS); | ||||
12014 | |||||
12015 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | ||||
12016 | // hasIntegerRepresentation() above instead of this. | ||||
12017 | if (isScopedEnumerationType(LHSType) || | ||||
12018 | isScopedEnumerationType(RHSType)) { | ||||
12019 | return InvalidOperands(Loc, LHS, RHS); | ||||
12020 | } | ||||
12021 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | ||||
12022 | |||||
12023 | // "The type of the result is that of the promoted left operand." | ||||
12024 | return LHSType; | ||||
12025 | } | ||||
12026 | |||||
12027 | /// Diagnose bad pointer comparisons. | ||||
12028 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | ||||
12029 | ExprResult &LHS, ExprResult &RHS, | ||||
12030 | bool IsError) { | ||||
12031 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | ||||
12032 | : diag::ext_typecheck_comparison_of_distinct_pointers) | ||||
12033 | << LHS.get()->getType() << RHS.get()->getType() | ||||
12034 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
12035 | } | ||||
12036 | |||||
12037 | /// Returns false if the pointers are converted to a composite type, | ||||
12038 | /// true otherwise. | ||||
12039 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | ||||
12040 | ExprResult &LHS, ExprResult &RHS) { | ||||
12041 | // C++ [expr.rel]p2: | ||||
12042 | // [...] Pointer conversions (4.10) and qualification | ||||
12043 | // conversions (4.4) are performed on pointer operands (or on | ||||
12044 | // a pointer operand and a null pointer constant) to bring | ||||
12045 | // them to their composite pointer type. [...] | ||||
12046 | // | ||||
12047 | // C++ [expr.eq]p1 uses the same notion for (in)equality | ||||
12048 | // comparisons of pointers. | ||||
12049 | |||||
12050 | QualType LHSType = LHS.get()->getType(); | ||||
12051 | QualType RHSType = RHS.get()->getType(); | ||||
12052 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 12053, __extension__ __PRETTY_FUNCTION__ )) | ||||
12053 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 12053, __extension__ __PRETTY_FUNCTION__ )); | ||||
12054 | |||||
12055 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | ||||
12056 | if (T.isNull()) { | ||||
12057 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | ||||
12058 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | ||||
12059 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | ||||
12060 | else | ||||
12061 | S.InvalidOperands(Loc, LHS, RHS); | ||||
12062 | return true; | ||||
12063 | } | ||||
12064 | |||||
12065 | return false; | ||||
12066 | } | ||||
12067 | |||||
12068 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | ||||
12069 | ExprResult &LHS, | ||||
12070 | ExprResult &RHS, | ||||
12071 | bool IsError) { | ||||
12072 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | ||||
12073 | : diag::ext_typecheck_comparison_of_fptr_to_void) | ||||
12074 | << LHS.get()->getType() << RHS.get()->getType() | ||||
12075 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
12076 | } | ||||
12077 | |||||
12078 | static bool isObjCObjectLiteral(ExprResult &E) { | ||||
12079 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | ||||
12080 | case Stmt::ObjCArrayLiteralClass: | ||||
12081 | case Stmt::ObjCDictionaryLiteralClass: | ||||
12082 | case Stmt::ObjCStringLiteralClass: | ||||
12083 | case Stmt::ObjCBoxedExprClass: | ||||
12084 | return true; | ||||
12085 | default: | ||||
12086 | // Note that ObjCBoolLiteral is NOT an object literal! | ||||
12087 | return false; | ||||
12088 | } | ||||
12089 | } | ||||
12090 | |||||
12091 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | ||||
12092 | const ObjCObjectPointerType *Type = | ||||
12093 | LHS->getType()->getAs<ObjCObjectPointerType>(); | ||||
12094 | |||||
12095 | // If this is not actually an Objective-C object, bail out. | ||||
12096 | if (!Type) | ||||
12097 | return false; | ||||
12098 | |||||
12099 | // Get the LHS object's interface type. | ||||
12100 | QualType InterfaceType = Type->getPointeeType(); | ||||
12101 | |||||
12102 | // If the RHS isn't an Objective-C object, bail out. | ||||
12103 | if (!RHS->getType()->isObjCObjectPointerType()) | ||||
12104 | return false; | ||||
12105 | |||||
12106 | // Try to find the -isEqual: method. | ||||
12107 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | ||||
12108 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | ||||
12109 | InterfaceType, | ||||
12110 | /*IsInstance=*/true); | ||||
12111 | if (!Method) { | ||||
12112 | if (Type->isObjCIdType()) { | ||||
12113 | // For 'id', just check the global pool. | ||||
12114 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | ||||
12115 | /*receiverId=*/true); | ||||
12116 | } else { | ||||
12117 | // Check protocols. | ||||
12118 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | ||||
12119 | /*IsInstance=*/true); | ||||
12120 | } | ||||
12121 | } | ||||
12122 | |||||
12123 | if (!Method) | ||||
12124 | return false; | ||||
12125 | |||||
12126 | QualType T = Method->parameters()[0]->getType(); | ||||
12127 | if (!T->isObjCObjectPointerType()) | ||||
12128 | return false; | ||||
12129 | |||||
12130 | QualType R = Method->getReturnType(); | ||||
12131 | if (!R->isScalarType()) | ||||
12132 | return false; | ||||
12133 | |||||
12134 | return true; | ||||
12135 | } | ||||
12136 | |||||
12137 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | ||||
12138 | FromE = FromE->IgnoreParenImpCasts(); | ||||
12139 | switch (FromE->getStmtClass()) { | ||||
12140 | default: | ||||
12141 | break; | ||||
12142 | case Stmt::ObjCStringLiteralClass: | ||||
12143 | // "string literal" | ||||
12144 | return LK_String; | ||||
12145 | case Stmt::ObjCArrayLiteralClass: | ||||
12146 | // "array literal" | ||||
12147 | return LK_Array; | ||||
12148 | case Stmt::ObjCDictionaryLiteralClass: | ||||
12149 | // "dictionary literal" | ||||
12150 | return LK_Dictionary; | ||||
12151 | case Stmt::BlockExprClass: | ||||
12152 | return LK_Block; | ||||
12153 | case Stmt::ObjCBoxedExprClass: { | ||||
12154 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | ||||
12155 | switch (Inner->getStmtClass()) { | ||||
12156 | case Stmt::IntegerLiteralClass: | ||||
12157 | case Stmt::FloatingLiteralClass: | ||||
12158 | case Stmt::CharacterLiteralClass: | ||||
12159 | case Stmt::ObjCBoolLiteralExprClass: | ||||
12160 | case Stmt::CXXBoolLiteralExprClass: | ||||
12161 | // "numeric literal" | ||||
12162 | return LK_Numeric; | ||||
12163 | case Stmt::ImplicitCastExprClass: { | ||||
12164 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | ||||
12165 | // Boolean literals can be represented by implicit casts. | ||||
12166 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | ||||
12167 | return LK_Numeric; | ||||
12168 | break; | ||||
12169 | } | ||||
12170 | default: | ||||
12171 | break; | ||||
12172 | } | ||||
12173 | return LK_Boxed; | ||||
12174 | } | ||||
12175 | } | ||||
12176 | return LK_None; | ||||
12177 | } | ||||
12178 | |||||
12179 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | ||||
12180 | ExprResult &LHS, ExprResult &RHS, | ||||
12181 | BinaryOperator::Opcode Opc){ | ||||
12182 | Expr *Literal; | ||||
12183 | Expr *Other; | ||||
12184 | if (isObjCObjectLiteral(LHS)) { | ||||
12185 | Literal = LHS.get(); | ||||
12186 | Other = RHS.get(); | ||||
12187 | } else { | ||||
12188 | Literal = RHS.get(); | ||||
12189 | Other = LHS.get(); | ||||
12190 | } | ||||
12191 | |||||
12192 | // Don't warn on comparisons against nil. | ||||
12193 | Other = Other->IgnoreParenCasts(); | ||||
12194 | if (Other->isNullPointerConstant(S.getASTContext(), | ||||
12195 | Expr::NPC_ValueDependentIsNotNull)) | ||||
12196 | return; | ||||
12197 | |||||
12198 | // This should be kept in sync with warn_objc_literal_comparison. | ||||
12199 | // LK_String should always be after the other literals, since it has its own | ||||
12200 | // warning flag. | ||||
12201 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | ||||
12202 | assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void (0) : __assert_fail ("LiteralKind != Sema::LK_Block", "clang/lib/Sema/SemaExpr.cpp" , 12202, __extension__ __PRETTY_FUNCTION__)); | ||||
12203 | if (LiteralKind == Sema::LK_None) { | ||||
12204 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "clang/lib/Sema/SemaExpr.cpp", 12204); | ||||
12205 | } | ||||
12206 | |||||
12207 | if (LiteralKind == Sema::LK_String) | ||||
12208 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | ||||
12209 | << Literal->getSourceRange(); | ||||
12210 | else | ||||
12211 | S.Diag(Loc, diag::warn_objc_literal_comparison) | ||||
12212 | << LiteralKind << Literal->getSourceRange(); | ||||
12213 | |||||
12214 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
12215 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | ||||
12216 | SourceLocation Start = LHS.get()->getBeginLoc(); | ||||
12217 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
12218 | CharSourceRange OpRange = | ||||
12219 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
12220 | |||||
12221 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | ||||
12222 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | ||||
12223 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | ||||
12224 | << FixItHint::CreateInsertion(End, "]"); | ||||
12225 | } | ||||
12226 | } | ||||
12227 | |||||
12228 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | ||||
12229 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | ||||
12230 | ExprResult &RHS, SourceLocation Loc, | ||||
12231 | BinaryOperatorKind Opc) { | ||||
12232 | // Check that left hand side is !something. | ||||
12233 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | ||||
12234 | if (!UO || UO->getOpcode() != UO_LNot) return; | ||||
12235 | |||||
12236 | // Only check if the right hand side is non-bool arithmetic type. | ||||
12237 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | ||||
12238 | |||||
12239 | // Make sure that the something in !something is not bool. | ||||
12240 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | ||||
12241 | if (SubExpr->isKnownToHaveBooleanValue()) return; | ||||
12242 | |||||
12243 | // Emit warning. | ||||
12244 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | ||||
12245 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | ||||
12246 | << Loc << IsBitwiseOp; | ||||
12247 | |||||
12248 | // First note suggest !(x < y) | ||||
12249 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | ||||
12250 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | ||||
12251 | FirstClose = S.getLocForEndOfToken(FirstClose); | ||||
12252 | if (FirstClose.isInvalid()) | ||||
12253 | FirstOpen = SourceLocation(); | ||||
12254 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | ||||
12255 | << IsBitwiseOp | ||||
12256 | << FixItHint::CreateInsertion(FirstOpen, "(") | ||||
12257 | << FixItHint::CreateInsertion(FirstClose, ")"); | ||||
12258 | |||||
12259 | // Second note suggests (!x) < y | ||||
12260 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | ||||
12261 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | ||||
12262 | SecondClose = S.getLocForEndOfToken(SecondClose); | ||||
12263 | if (SecondClose.isInvalid()) | ||||
12264 | SecondOpen = SourceLocation(); | ||||
12265 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | ||||
12266 | << FixItHint::CreateInsertion(SecondOpen, "(") | ||||
12267 | << FixItHint::CreateInsertion(SecondClose, ")"); | ||||
12268 | } | ||||
12269 | |||||
12270 | // Returns true if E refers to a non-weak array. | ||||
12271 | static bool checkForArray(const Expr *E) { | ||||
12272 | const ValueDecl *D = nullptr; | ||||
12273 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | ||||
12274 | D = DR->getDecl(); | ||||
12275 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | ||||
12276 | if (Mem->isImplicitAccess()) | ||||
12277 | D = Mem->getMemberDecl(); | ||||
12278 | } | ||||
12279 | if (!D) | ||||
12280 | return false; | ||||
12281 | return D->getType()->isArrayType() && !D->isWeak(); | ||||
12282 | } | ||||
12283 | |||||
12284 | /// Diagnose some forms of syntactically-obvious tautological comparison. | ||||
12285 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | ||||
12286 | Expr *LHS, Expr *RHS, | ||||
12287 | BinaryOperatorKind Opc) { | ||||
12288 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | ||||
12289 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | ||||
12290 | |||||
12291 | QualType LHSType = LHS->getType(); | ||||
12292 | QualType RHSType = RHS->getType(); | ||||
12293 | if (LHSType->hasFloatingRepresentation() || | ||||
12294 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | ||||
12295 | S.inTemplateInstantiation()) | ||||
12296 | return; | ||||
12297 | |||||
12298 | // Comparisons between two array types are ill-formed for operator<=>, so | ||||
12299 | // we shouldn't emit any additional warnings about it. | ||||
12300 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | ||||
12301 | return; | ||||
12302 | |||||
12303 | // For non-floating point types, check for self-comparisons of the form | ||||
12304 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12305 | // often indicate logic errors in the program. | ||||
12306 | // | ||||
12307 | // NOTE: Don't warn about comparison expressions resulting from macro | ||||
12308 | // expansion. Also don't warn about comparisons which are only self | ||||
12309 | // comparisons within a template instantiation. The warnings should catch | ||||
12310 | // obvious cases in the definition of the template anyways. The idea is to | ||||
12311 | // warn when the typed comparison operator will always evaluate to the same | ||||
12312 | // result. | ||||
12313 | |||||
12314 | // Used for indexing into %select in warn_comparison_always | ||||
12315 | enum { | ||||
12316 | AlwaysConstant, | ||||
12317 | AlwaysTrue, | ||||
12318 | AlwaysFalse, | ||||
12319 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | ||||
12320 | }; | ||||
12321 | |||||
12322 | // C++2a [depr.array.comp]: | ||||
12323 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | ||||
12324 | // operands of array type are deprecated. | ||||
12325 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | ||||
12326 | RHSStripped->getType()->isArrayType()) { | ||||
12327 | S.Diag(Loc, diag::warn_depr_array_comparison) | ||||
12328 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
12329 | << LHSStripped->getType() << RHSStripped->getType(); | ||||
12330 | // Carry on to produce the tautological comparison warning, if this | ||||
12331 | // expression is potentially-evaluated, we can resolve the array to a | ||||
12332 | // non-weak declaration, and so on. | ||||
12333 | } | ||||
12334 | |||||
12335 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | ||||
12336 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | ||||
12337 | unsigned Result; | ||||
12338 | switch (Opc) { | ||||
12339 | case BO_EQ: | ||||
12340 | case BO_LE: | ||||
12341 | case BO_GE: | ||||
12342 | Result = AlwaysTrue; | ||||
12343 | break; | ||||
12344 | case BO_NE: | ||||
12345 | case BO_LT: | ||||
12346 | case BO_GT: | ||||
12347 | Result = AlwaysFalse; | ||||
12348 | break; | ||||
12349 | case BO_Cmp: | ||||
12350 | Result = AlwaysEqual; | ||||
12351 | break; | ||||
12352 | default: | ||||
12353 | Result = AlwaysConstant; | ||||
12354 | break; | ||||
12355 | } | ||||
12356 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
12357 | S.PDiag(diag::warn_comparison_always) | ||||
12358 | << 0 /*self-comparison*/ | ||||
12359 | << Result); | ||||
12360 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | ||||
12361 | // What is it always going to evaluate to? | ||||
12362 | unsigned Result; | ||||
12363 | switch (Opc) { | ||||
12364 | case BO_EQ: // e.g. array1 == array2 | ||||
12365 | Result = AlwaysFalse; | ||||
12366 | break; | ||||
12367 | case BO_NE: // e.g. array1 != array2 | ||||
12368 | Result = AlwaysTrue; | ||||
12369 | break; | ||||
12370 | default: // e.g. array1 <= array2 | ||||
12371 | // The best we can say is 'a constant' | ||||
12372 | Result = AlwaysConstant; | ||||
12373 | break; | ||||
12374 | } | ||||
12375 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
12376 | S.PDiag(diag::warn_comparison_always) | ||||
12377 | << 1 /*array comparison*/ | ||||
12378 | << Result); | ||||
12379 | } | ||||
12380 | } | ||||
12381 | |||||
12382 | if (isa<CastExpr>(LHSStripped)) | ||||
12383 | LHSStripped = LHSStripped->IgnoreParenCasts(); | ||||
12384 | if (isa<CastExpr>(RHSStripped)) | ||||
12385 | RHSStripped = RHSStripped->IgnoreParenCasts(); | ||||
12386 | |||||
12387 | // Warn about comparisons against a string constant (unless the other | ||||
12388 | // operand is null); the user probably wants string comparison function. | ||||
12389 | Expr *LiteralString = nullptr; | ||||
12390 | Expr *LiteralStringStripped = nullptr; | ||||
12391 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | ||||
12392 | !RHSStripped->isNullPointerConstant(S.Context, | ||||
12393 | Expr::NPC_ValueDependentIsNull)) { | ||||
12394 | LiteralString = LHS; | ||||
12395 | LiteralStringStripped = LHSStripped; | ||||
12396 | } else if ((isa<StringLiteral>(RHSStripped) || | ||||
12397 | isa<ObjCEncodeExpr>(RHSStripped)) && | ||||
12398 | !LHSStripped->isNullPointerConstant(S.Context, | ||||
12399 | Expr::NPC_ValueDependentIsNull)) { | ||||
12400 | LiteralString = RHS; | ||||
12401 | LiteralStringStripped = RHSStripped; | ||||
12402 | } | ||||
12403 | |||||
12404 | if (LiteralString) { | ||||
12405 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
12406 | S.PDiag(diag::warn_stringcompare) | ||||
12407 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | ||||
12408 | << LiteralString->getSourceRange()); | ||||
12409 | } | ||||
12410 | } | ||||
12411 | |||||
12412 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | ||||
12413 | switch (CK) { | ||||
12414 | default: { | ||||
12415 | #ifndef NDEBUG | ||||
12416 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | ||||
12417 | << "\n"; | ||||
12418 | #endif | ||||
12419 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp" , 12419); | ||||
12420 | } | ||||
12421 | case CK_UserDefinedConversion: | ||||
12422 | return ICK_Identity; | ||||
12423 | case CK_LValueToRValue: | ||||
12424 | return ICK_Lvalue_To_Rvalue; | ||||
12425 | case CK_ArrayToPointerDecay: | ||||
12426 | return ICK_Array_To_Pointer; | ||||
12427 | case CK_FunctionToPointerDecay: | ||||
12428 | return ICK_Function_To_Pointer; | ||||
12429 | case CK_IntegralCast: | ||||
12430 | return ICK_Integral_Conversion; | ||||
12431 | case CK_FloatingCast: | ||||
12432 | return ICK_Floating_Conversion; | ||||
12433 | case CK_IntegralToFloating: | ||||
12434 | case CK_FloatingToIntegral: | ||||
12435 | return ICK_Floating_Integral; | ||||
12436 | case CK_IntegralComplexCast: | ||||
12437 | case CK_FloatingComplexCast: | ||||
12438 | case CK_FloatingComplexToIntegralComplex: | ||||
12439 | case CK_IntegralComplexToFloatingComplex: | ||||
12440 | return ICK_Complex_Conversion; | ||||
12441 | case CK_FloatingComplexToReal: | ||||
12442 | case CK_FloatingRealToComplex: | ||||
12443 | case CK_IntegralComplexToReal: | ||||
12444 | case CK_IntegralRealToComplex: | ||||
12445 | return ICK_Complex_Real; | ||||
12446 | } | ||||
12447 | } | ||||
12448 | |||||
12449 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | ||||
12450 | QualType FromType, | ||||
12451 | SourceLocation Loc) { | ||||
12452 | // Check for a narrowing implicit conversion. | ||||
12453 | StandardConversionSequence SCS; | ||||
12454 | SCS.setAsIdentityConversion(); | ||||
12455 | SCS.setToType(0, FromType); | ||||
12456 | SCS.setToType(1, ToType); | ||||
12457 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
12458 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | ||||
12459 | |||||
12460 | APValue PreNarrowingValue; | ||||
12461 | QualType PreNarrowingType; | ||||
12462 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | ||||
12463 | PreNarrowingType, | ||||
12464 | /*IgnoreFloatToIntegralConversion*/ true)) { | ||||
12465 | case NK_Dependent_Narrowing: | ||||
12466 | // Implicit conversion to a narrower type, but the expression is | ||||
12467 | // value-dependent so we can't tell whether it's actually narrowing. | ||||
12468 | case NK_Not_Narrowing: | ||||
12469 | return false; | ||||
12470 | |||||
12471 | case NK_Constant_Narrowing: | ||||
12472 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
12473 | // expression. | ||||
12474 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
12475 | << /*Constant*/ 1 | ||||
12476 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | ||||
12477 | return true; | ||||
12478 | |||||
12479 | case NK_Variable_Narrowing: | ||||
12480 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
12481 | // expression. | ||||
12482 | case NK_Type_Narrowing: | ||||
12483 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
12484 | << /*Constant*/ 0 << FromType << ToType; | ||||
12485 | // TODO: It's not a constant expression, but what if the user intended it | ||||
12486 | // to be? Can we produce notes to help them figure out why it isn't? | ||||
12487 | return true; | ||||
12488 | } | ||||
12489 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "clang/lib/Sema/SemaExpr.cpp", 12489); | ||||
12490 | } | ||||
12491 | |||||
12492 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | ||||
12493 | ExprResult &LHS, | ||||
12494 | ExprResult &RHS, | ||||
12495 | SourceLocation Loc) { | ||||
12496 | QualType LHSType = LHS.get()->getType(); | ||||
12497 | QualType RHSType = RHS.get()->getType(); | ||||
12498 | // Dig out the original argument type and expression before implicit casts | ||||
12499 | // were applied. These are the types/expressions we need to check the | ||||
12500 | // [expr.spaceship] requirements against. | ||||
12501 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | ||||
12502 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | ||||
12503 | QualType LHSStrippedType = LHSStripped.get()->getType(); | ||||
12504 | QualType RHSStrippedType = RHSStripped.get()->getType(); | ||||
12505 | |||||
12506 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | ||||
12507 | // other is not, the program is ill-formed. | ||||
12508 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | ||||
12509 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
12510 | return QualType(); | ||||
12511 | } | ||||
12512 | |||||
12513 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | ||||
12514 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | ||||
12515 | RHSStrippedType->isEnumeralType(); | ||||
12516 | if (NumEnumArgs == 1) { | ||||
12517 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | ||||
12518 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | ||||
12519 | if (OtherTy->hasFloatingRepresentation()) { | ||||
12520 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
12521 | return QualType(); | ||||
12522 | } | ||||
12523 | } | ||||
12524 | if (NumEnumArgs == 2) { | ||||
12525 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | ||||
12526 | // type E, the operator yields the result of converting the operands | ||||
12527 | // to the underlying type of E and applying <=> to the converted operands. | ||||
12528 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | ||||
12529 | S.InvalidOperands(Loc, LHS, RHS); | ||||
12530 | return QualType(); | ||||
12531 | } | ||||
12532 | QualType IntType = | ||||
12533 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | ||||
12534 | assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void (0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp" , 12534, __extension__ __PRETTY_FUNCTION__)); | ||||
12535 | |||||
12536 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | ||||
12537 | // promote the boolean type, and all other promotable integer types, to | ||||
12538 | // avoid this. | ||||
12539 | if (S.Context.isPromotableIntegerType(IntType)) | ||||
12540 | IntType = S.Context.getPromotedIntegerType(IntType); | ||||
12541 | |||||
12542 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | ||||
12543 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | ||||
12544 | LHSType = RHSType = IntType; | ||||
12545 | } | ||||
12546 | |||||
12547 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | ||||
12548 | // usual arithmetic conversions are applied to the operands. | ||||
12549 | QualType Type = | ||||
12550 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
12551 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
12552 | return QualType(); | ||||
12553 | if (Type.isNull()) | ||||
12554 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12555 | |||||
12556 | std::optional<ComparisonCategoryType> CCT = | ||||
12557 | getComparisonCategoryForBuiltinCmp(Type); | ||||
12558 | if (!CCT) | ||||
12559 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12560 | |||||
12561 | bool HasNarrowing = checkThreeWayNarrowingConversion( | ||||
12562 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | ||||
12563 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | ||||
12564 | RHS.get()->getBeginLoc()); | ||||
12565 | if (HasNarrowing) | ||||
12566 | return QualType(); | ||||
12567 | |||||
12568 | assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast <bool> (!Type.isNull() && "composite type for <=> has not been set" ) ? void (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "clang/lib/Sema/SemaExpr.cpp", 12568, __extension__ __PRETTY_FUNCTION__ )); | ||||
12569 | |||||
12570 | return S.CheckComparisonCategoryType( | ||||
12571 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | ||||
12572 | } | ||||
12573 | |||||
12574 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | ||||
12575 | ExprResult &RHS, | ||||
12576 | SourceLocation Loc, | ||||
12577 | BinaryOperatorKind Opc) { | ||||
12578 | if (Opc == BO_Cmp) | ||||
12579 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | ||||
12580 | |||||
12581 | // C99 6.5.8p3 / C99 6.5.9p4 | ||||
12582 | QualType Type = | ||||
12583 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
12584 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
12585 | return QualType(); | ||||
12586 | if (Type.isNull()) | ||||
12587 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12588 | assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type ->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "clang/lib/Sema/SemaExpr.cpp", 12588, __extension__ __PRETTY_FUNCTION__ )); | ||||
12589 | |||||
12590 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | ||||
12591 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12592 | |||||
12593 | // Check for comparisons of floating point operands using != and ==. | ||||
12594 | if (Type->hasFloatingRepresentation()) | ||||
12595 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); | ||||
12596 | |||||
12597 | // The result of comparisons is 'bool' in C++, 'int' in C. | ||||
12598 | return S.Context.getLogicalOperationType(); | ||||
12599 | } | ||||
12600 | |||||
12601 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | ||||
12602 | if (!NullE.get()->getType()->isAnyPointerType()) | ||||
12603 | return; | ||||
12604 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | ||||
12605 | if (!E.get()->getType()->isAnyPointerType() && | ||||
12606 | E.get()->isNullPointerConstant(Context, | ||||
12607 | Expr::NPC_ValueDependentIsNotNull) == | ||||
12608 | Expr::NPCK_ZeroExpression) { | ||||
12609 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | ||||
12610 | if (CL->getValue() == 0) | ||||
12611 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
12612 | << NullValue | ||||
12613 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
12614 | NullValue ? "NULL" : "(void *)0"); | ||||
12615 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | ||||
12616 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | ||||
12617 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | ||||
12618 | if (T == Context.CharTy) | ||||
12619 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
12620 | << NullValue | ||||
12621 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
12622 | NullValue ? "NULL" : "(void *)0"); | ||||
12623 | } | ||||
12624 | } | ||||
12625 | } | ||||
12626 | |||||
12627 | // C99 6.5.8, C++ [expr.rel] | ||||
12628 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12629 | SourceLocation Loc, | ||||
12630 | BinaryOperatorKind Opc) { | ||||
12631 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | ||||
12632 | bool IsThreeWay = Opc == BO_Cmp; | ||||
12633 | bool IsOrdered = IsRelational || IsThreeWay; | ||||
12634 | auto IsAnyPointerType = [](ExprResult E) { | ||||
12635 | QualType Ty = E.get()->getType(); | ||||
12636 | return Ty->isPointerType() || Ty->isMemberPointerType(); | ||||
12637 | }; | ||||
12638 | |||||
12639 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | ||||
12640 | // type, array-to-pointer, ..., conversions are performed on both operands to | ||||
12641 | // bring them to their composite type. | ||||
12642 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | ||||
12643 | // any type-related checks. | ||||
12644 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | ||||
12645 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12646 | if (LHS.isInvalid()) | ||||
12647 | return QualType(); | ||||
12648 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12649 | if (RHS.isInvalid()) | ||||
12650 | return QualType(); | ||||
12651 | } else { | ||||
12652 | LHS = DefaultLvalueConversion(LHS.get()); | ||||
12653 | if (LHS.isInvalid()) | ||||
12654 | return QualType(); | ||||
12655 | RHS = DefaultLvalueConversion(RHS.get()); | ||||
12656 | if (RHS.isInvalid()) | ||||
12657 | return QualType(); | ||||
12658 | } | ||||
12659 | |||||
12660 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | ||||
12661 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | ||||
12662 | CheckPtrComparisonWithNullChar(LHS, RHS); | ||||
12663 | CheckPtrComparisonWithNullChar(RHS, LHS); | ||||
12664 | } | ||||
12665 | |||||
12666 | // Handle vector comparisons separately. | ||||
12667 | if (LHS.get()->getType()->isVectorType() || | ||||
12668 | RHS.get()->getType()->isVectorType()) | ||||
12669 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
12670 | |||||
12671 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
12672 | RHS.get()->getType()->isVLSTBuiltinType()) | ||||
12673 | return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
12674 | |||||
12675 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
12676 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12677 | |||||
12678 | QualType LHSType = LHS.get()->getType(); | ||||
12679 | QualType RHSType = RHS.get()->getType(); | ||||
12680 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | ||||
12681 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | ||||
12682 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | ||||
12683 | |||||
12684 | const Expr::NullPointerConstantKind LHSNullKind = | ||||
12685 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
12686 | const Expr::NullPointerConstantKind RHSNullKind = | ||||
12687 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
12688 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | ||||
12689 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | ||||
12690 | |||||
12691 | auto computeResultTy = [&]() { | ||||
12692 | if (Opc != BO_Cmp) | ||||
12693 | return Context.getLogicalOperationType(); | ||||
12694 | assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0 ) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 12694, __extension__ __PRETTY_FUNCTION__)); | ||||
12695 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast <bool> (Context.hasSameType(LHS.get()-> getType(), RHS.get()->getType())) ? void (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "clang/lib/Sema/SemaExpr.cpp", 12695, __extension__ __PRETTY_FUNCTION__ )); | ||||
12696 | |||||
12697 | QualType CompositeTy = LHS.get()->getType(); | ||||
12698 | assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType() ) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()" , "clang/lib/Sema/SemaExpr.cpp", 12698, __extension__ __PRETTY_FUNCTION__ )); | ||||
12699 | |||||
12700 | std::optional<ComparisonCategoryType> CCT = | ||||
12701 | getComparisonCategoryForBuiltinCmp(CompositeTy); | ||||
12702 | if (!CCT) | ||||
12703 | return InvalidOperands(Loc, LHS, RHS); | ||||
12704 | |||||
12705 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | ||||
12706 | // P0946R0: Comparisons between a null pointer constant and an object | ||||
12707 | // pointer result in std::strong_equality, which is ill-formed under | ||||
12708 | // P1959R0. | ||||
12709 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | ||||
12710 | << (LHSIsNull ? LHS.get()->getSourceRange() | ||||
12711 | : RHS.get()->getSourceRange()); | ||||
12712 | return QualType(); | ||||
12713 | } | ||||
12714 | |||||
12715 | return CheckComparisonCategoryType( | ||||
12716 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | ||||
12717 | }; | ||||
12718 | |||||
12719 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | ||||
12720 | bool IsEquality = Opc == BO_EQ; | ||||
12721 | if (RHSIsNull) | ||||
12722 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | ||||
12723 | RHS.get()->getSourceRange()); | ||||
12724 | else | ||||
12725 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | ||||
12726 | LHS.get()->getSourceRange()); | ||||
12727 | } | ||||
12728 | |||||
12729 | if (IsOrdered && LHSType->isFunctionPointerType() && | ||||
12730 | RHSType->isFunctionPointerType()) { | ||||
12731 | // Valid unless a relational comparison of function pointers | ||||
12732 | bool IsError = Opc == BO_Cmp; | ||||
12733 | auto DiagID = | ||||
12734 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers | ||||
12735 | : getLangOpts().CPlusPlus | ||||
12736 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers | ||||
12737 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; | ||||
12738 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12739 | << RHS.get()->getSourceRange(); | ||||
12740 | if (IsError) | ||||
12741 | return QualType(); | ||||
12742 | } | ||||
12743 | |||||
12744 | if ((LHSType->isIntegerType() && !LHSIsNull) || | ||||
12745 | (RHSType->isIntegerType() && !RHSIsNull)) { | ||||
12746 | // Skip normal pointer conversion checks in this case; we have better | ||||
12747 | // diagnostics for this below. | ||||
12748 | } else if (getLangOpts().CPlusPlus) { | ||||
12749 | // Equality comparison of a function pointer to a void pointer is invalid, | ||||
12750 | // but we allow it as an extension. | ||||
12751 | // FIXME: If we really want to allow this, should it be part of composite | ||||
12752 | // pointer type computation so it works in conditionals too? | ||||
12753 | if (!IsOrdered && | ||||
12754 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | ||||
12755 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | ||||
12756 | // This is a gcc extension compatibility comparison. | ||||
12757 | // In a SFINAE context, we treat this as a hard error to maintain | ||||
12758 | // conformance with the C++ standard. | ||||
12759 | diagnoseFunctionPointerToVoidComparison( | ||||
12760 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | ||||
12761 | |||||
12762 | if (isSFINAEContext()) | ||||
12763 | return QualType(); | ||||
12764 | |||||
12765 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12766 | return computeResultTy(); | ||||
12767 | } | ||||
12768 | |||||
12769 | // C++ [expr.eq]p2: | ||||
12770 | // If at least one operand is a pointer [...] bring them to their | ||||
12771 | // composite pointer type. | ||||
12772 | // C++ [expr.spaceship]p6 | ||||
12773 | // If at least one of the operands is of pointer type, [...] bring them | ||||
12774 | // to their composite pointer type. | ||||
12775 | // C++ [expr.rel]p2: | ||||
12776 | // If both operands are pointers, [...] bring them to their composite | ||||
12777 | // pointer type. | ||||
12778 | // For <=>, the only valid non-pointer types are arrays and functions, and | ||||
12779 | // we already decayed those, so this is really the same as the relational | ||||
12780 | // comparison rule. | ||||
12781 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | ||||
12782 | (IsOrdered ? 2 : 1) && | ||||
12783 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | ||||
12784 | RHSType->isObjCObjectPointerType()))) { | ||||
12785 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
12786 | return QualType(); | ||||
12787 | return computeResultTy(); | ||||
12788 | } | ||||
12789 | } else if (LHSType->isPointerType() && | ||||
12790 | RHSType->isPointerType()) { // C99 6.5.8p2 | ||||
12791 | // All of the following pointer-related warnings are GCC extensions, except | ||||
12792 | // when handling null pointer constants. | ||||
12793 | QualType LCanPointeeTy = | ||||
12794 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
12795 | QualType RCanPointeeTy = | ||||
12796 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
12797 | |||||
12798 | // C99 6.5.9p2 and C99 6.5.8p2 | ||||
12799 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | ||||
12800 | RCanPointeeTy.getUnqualifiedType())) { | ||||
12801 | if (IsRelational) { | ||||
12802 | // Pointers both need to point to complete or incomplete types | ||||
12803 | if ((LCanPointeeTy->isIncompleteType() != | ||||
12804 | RCanPointeeTy->isIncompleteType()) && | ||||
12805 | !getLangOpts().C11) { | ||||
12806 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | ||||
12807 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | ||||
12808 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | ||||
12809 | << RCanPointeeTy->isIncompleteType(); | ||||
12810 | } | ||||
12811 | } | ||||
12812 | } else if (!IsRelational && | ||||
12813 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | ||||
12814 | // Valid unless comparison between non-null pointer and function pointer | ||||
12815 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | ||||
12816 | && !LHSIsNull && !RHSIsNull) | ||||
12817 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | ||||
12818 | /*isError*/false); | ||||
12819 | } else { | ||||
12820 | // Invalid | ||||
12821 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | ||||
12822 | } | ||||
12823 | if (LCanPointeeTy != RCanPointeeTy) { | ||||
12824 | // Treat NULL constant as a special case in OpenCL. | ||||
12825 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | ||||
12826 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | ||||
12827 | Diag(Loc, | ||||
12828 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
12829 | << LHSType << RHSType << 0 /* comparison */ | ||||
12830 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
12831 | } | ||||
12832 | } | ||||
12833 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | ||||
12834 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | ||||
12835 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | ||||
12836 | : CK_BitCast; | ||||
12837 | if (LHSIsNull && !RHSIsNull) | ||||
12838 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | ||||
12839 | else | ||||
12840 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | ||||
12841 | } | ||||
12842 | return computeResultTy(); | ||||
12843 | } | ||||
12844 | |||||
12845 | |||||
12846 | // C++ [expr.eq]p4: | ||||
12847 | // Two operands of type std::nullptr_t or one operand of type | ||||
12848 | // std::nullptr_t and the other a null pointer constant compare | ||||
12849 | // equal. | ||||
12850 | // C2x 6.5.9p5: | ||||
12851 | // If both operands have type nullptr_t or one operand has type nullptr_t | ||||
12852 | // and the other is a null pointer constant, they compare equal. | ||||
12853 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | ||||
12854 | if (LHSType->isNullPtrType()) { | ||||
12855 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12856 | return computeResultTy(); | ||||
12857 | } | ||||
12858 | if (RHSType->isNullPtrType()) { | ||||
12859 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12860 | return computeResultTy(); | ||||
12861 | } | ||||
12862 | } | ||||
12863 | |||||
12864 | if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) { | ||||
12865 | // C2x 6.5.9p6: | ||||
12866 | // Otherwise, at least one operand is a pointer. If one is a pointer and | ||||
12867 | // the other is a null pointer constant, the null pointer constant is | ||||
12868 | // converted to the type of the pointer. | ||||
12869 | if (LHSIsNull && RHSType->isPointerType()) { | ||||
12870 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12871 | return computeResultTy(); | ||||
12872 | } | ||||
12873 | if (RHSIsNull && LHSType->isPointerType()) { | ||||
12874 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12875 | return computeResultTy(); | ||||
12876 | } | ||||
12877 | } | ||||
12878 | |||||
12879 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | ||||
12880 | // These aren't covered by the composite pointer type rules. | ||||
12881 | if (!IsOrdered && RHSType->isNullPtrType() && | ||||
12882 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | ||||
12883 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12884 | return computeResultTy(); | ||||
12885 | } | ||||
12886 | if (!IsOrdered && LHSType->isNullPtrType() && | ||||
12887 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | ||||
12888 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12889 | return computeResultTy(); | ||||
12890 | } | ||||
12891 | |||||
12892 | if (getLangOpts().CPlusPlus) { | ||||
12893 | if (IsRelational && | ||||
12894 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | ||||
12895 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | ||||
12896 | // HACK: Relational comparison of nullptr_t against a pointer type is | ||||
12897 | // invalid per DR583, but we allow it within std::less<> and friends, | ||||
12898 | // since otherwise common uses of it break. | ||||
12899 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | ||||
12900 | // friends to have std::nullptr_t overload candidates. | ||||
12901 | DeclContext *DC = CurContext; | ||||
12902 | if (isa<FunctionDecl>(DC)) | ||||
12903 | DC = DC->getParent(); | ||||
12904 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | ||||
12905 | if (CTSD->isInStdNamespace() && | ||||
12906 | llvm::StringSwitch<bool>(CTSD->getName()) | ||||
12907 | .Cases("less", "less_equal", "greater", "greater_equal", true) | ||||
12908 | .Default(false)) { | ||||
12909 | if (RHSType->isNullPtrType()) | ||||
12910 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12911 | else | ||||
12912 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12913 | return computeResultTy(); | ||||
12914 | } | ||||
12915 | } | ||||
12916 | } | ||||
12917 | |||||
12918 | // C++ [expr.eq]p2: | ||||
12919 | // If at least one operand is a pointer to member, [...] bring them to | ||||
12920 | // their composite pointer type. | ||||
12921 | if (!IsOrdered && | ||||
12922 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | ||||
12923 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
12924 | return QualType(); | ||||
12925 | else | ||||
12926 | return computeResultTy(); | ||||
12927 | } | ||||
12928 | } | ||||
12929 | |||||
12930 | // Handle block pointer types. | ||||
12931 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
12932 | RHSType->isBlockPointerType()) { | ||||
12933 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
12934 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
12935 | |||||
12936 | if (!LHSIsNull && !RHSIsNull && | ||||
12937 | !Context.typesAreCompatible(lpointee, rpointee)) { | ||||
12938 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
12939 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12940 | << RHS.get()->getSourceRange(); | ||||
12941 | } | ||||
12942 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12943 | return computeResultTy(); | ||||
12944 | } | ||||
12945 | |||||
12946 | // Allow block pointers to be compared with null pointer constants. | ||||
12947 | if (!IsOrdered | ||||
12948 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | ||||
12949 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | ||||
12950 | if (!LHSIsNull && !RHSIsNull) { | ||||
12951 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | ||||
12952 | ->getPointeeType()->isVoidType()) | ||||
12953 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | ||||
12954 | ->getPointeeType()->isVoidType()))) | ||||
12955 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
12956 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12957 | << RHS.get()->getSourceRange(); | ||||
12958 | } | ||||
12959 | if (LHSIsNull && !RHSIsNull) | ||||
12960 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12961 | RHSType->isPointerType() ? CK_BitCast | ||||
12962 | : CK_AnyPointerToBlockPointerCast); | ||||
12963 | else | ||||
12964 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12965 | LHSType->isPointerType() ? CK_BitCast | ||||
12966 | : CK_AnyPointerToBlockPointerCast); | ||||
12967 | return computeResultTy(); | ||||
12968 | } | ||||
12969 | |||||
12970 | if (LHSType->isObjCObjectPointerType() || | ||||
12971 | RHSType->isObjCObjectPointerType()) { | ||||
12972 | const PointerType *LPT = LHSType->getAs<PointerType>(); | ||||
12973 | const PointerType *RPT = RHSType->getAs<PointerType>(); | ||||
12974 | if (LPT || RPT) { | ||||
12975 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | ||||
12976 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | ||||
12977 | |||||
12978 | if (!LPtrToVoid && !RPtrToVoid && | ||||
12979 | !Context.typesAreCompatible(LHSType, RHSType)) { | ||||
12980 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
12981 | /*isError*/false); | ||||
12982 | } | ||||
12983 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | ||||
12984 | // the RHS, but we have test coverage for this behavior. | ||||
12985 | // FIXME: Consider using convertPointersToCompositeType in C++. | ||||
12986 | if (LHSIsNull && !RHSIsNull) { | ||||
12987 | Expr *E = LHS.get(); | ||||
12988 | if (getLangOpts().ObjCAutoRefCount) | ||||
12989 | CheckObjCConversion(SourceRange(), RHSType, E, | ||||
12990 | CCK_ImplicitConversion); | ||||
12991 | LHS = ImpCastExprToType(E, RHSType, | ||||
12992 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
12993 | } | ||||
12994 | else { | ||||
12995 | Expr *E = RHS.get(); | ||||
12996 | if (getLangOpts().ObjCAutoRefCount) | ||||
12997 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | ||||
12998 | /*Diagnose=*/true, | ||||
12999 | /*DiagnoseCFAudited=*/false, Opc); | ||||
13000 | RHS = ImpCastExprToType(E, LHSType, | ||||
13001 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
13002 | } | ||||
13003 | return computeResultTy(); | ||||
13004 | } | ||||
13005 | if (LHSType->isObjCObjectPointerType() && | ||||
13006 | RHSType->isObjCObjectPointerType()) { | ||||
13007 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | ||||
13008 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
13009 | /*isError*/false); | ||||
13010 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | ||||
13011 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | ||||
13012 | |||||
13013 | if (LHSIsNull && !RHSIsNull) | ||||
13014 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
13015 | else | ||||
13016 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
13017 | return computeResultTy(); | ||||
13018 | } | ||||
13019 | |||||
13020 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
13021 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
13022 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
13023 | CK_BlockPointerToObjCPointerCast); | ||||
13024 | return computeResultTy(); | ||||
13025 | } else if (!IsOrdered && | ||||
13026 | LHSType->isBlockCompatibleObjCPointerType(Context) && | ||||
13027 | RHSType->isBlockPointerType()) { | ||||
13028 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
13029 | CK_BlockPointerToObjCPointerCast); | ||||
13030 | return computeResultTy(); | ||||
13031 | } | ||||
13032 | } | ||||
13033 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | ||||
13034 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | ||||
13035 | unsigned DiagID = 0; | ||||
13036 | bool isError = false; | ||||
13037 | if (LangOpts.DebuggerSupport) { | ||||
13038 | // Under a debugger, allow the comparison of pointers to integers, | ||||
13039 | // since users tend to want to compare addresses. | ||||
13040 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | ||||
13041 | (RHSIsNull && RHSType->isIntegerType())) { | ||||
13042 | if (IsOrdered) { | ||||
13043 | isError = getLangOpts().CPlusPlus; | ||||
13044 | DiagID = | ||||
13045 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | ||||
13046 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | ||||
13047 | } | ||||
13048 | } else if (getLangOpts().CPlusPlus) { | ||||
13049 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | ||||
13050 | isError = true; | ||||
13051 | } else if (IsOrdered) | ||||
13052 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | ||||
13053 | else | ||||
13054 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | ||||
13055 | |||||
13056 | if (DiagID) { | ||||
13057 | Diag(Loc, DiagID) | ||||
13058 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
13059 | << RHS.get()->getSourceRange(); | ||||
13060 | if (isError) | ||||
13061 | return QualType(); | ||||
13062 | } | ||||
13063 | |||||
13064 | if (LHSType->isIntegerType()) | ||||
13065 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
13066 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
13067 | else | ||||
13068 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
13069 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
13070 | return computeResultTy(); | ||||
13071 | } | ||||
13072 | |||||
13073 | // Handle block pointers. | ||||
13074 | if (!IsOrdered && RHSIsNull | ||||
13075 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | ||||
13076 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
13077 | return computeResultTy(); | ||||
13078 | } | ||||
13079 | if (!IsOrdered && LHSIsNull | ||||
13080 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | ||||
13081 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
13082 | return computeResultTy(); | ||||
13083 | } | ||||
13084 | |||||
13085 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { | ||||
13086 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | ||||
13087 | return computeResultTy(); | ||||
13088 | } | ||||
13089 | |||||
13090 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | ||||
13091 | return computeResultTy(); | ||||
13092 | } | ||||
13093 | |||||
13094 | if (LHSIsNull && RHSType->isQueueT()) { | ||||
13095 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
13096 | return computeResultTy(); | ||||
13097 | } | ||||
13098 | |||||
13099 | if (LHSType->isQueueT() && RHSIsNull) { | ||||
13100 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
13101 | return computeResultTy(); | ||||
13102 | } | ||||
13103 | } | ||||
13104 | |||||
13105 | return InvalidOperands(Loc, LHS, RHS); | ||||
13106 | } | ||||
13107 | |||||
13108 | // Return a signed ext_vector_type that is of identical size and number of | ||||
13109 | // elements. For floating point vectors, return an integer type of identical | ||||
13110 | // size and number of elements. In the non ext_vector_type case, search from | ||||
13111 | // the largest type to the smallest type to avoid cases where long long == long, | ||||
13112 | // where long gets picked over long long. | ||||
13113 | QualType Sema::GetSignedVectorType(QualType V) { | ||||
13114 | const VectorType *VTy = V->castAs<VectorType>(); | ||||
13115 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | ||||
13116 | |||||
13117 | if (isa<ExtVectorType>(VTy)) { | ||||
13118 | if (VTy->isExtVectorBoolType()) | ||||
13119 | return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); | ||||
13120 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | ||||
13121 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | ||||
13122 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
13123 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | ||||
13124 | if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
13125 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | ||||
13126 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) | ||||
13127 | return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); | ||||
13128 | if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
13129 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | ||||
13130 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 13131, __extension__ __PRETTY_FUNCTION__ )) | ||||
13131 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 13131, __extension__ __PRETTY_FUNCTION__ )); | ||||
13132 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | ||||
13133 | } | ||||
13134 | |||||
13135 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) | ||||
13136 | return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), | ||||
13137 | VectorType::GenericVector); | ||||
13138 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | ||||
13139 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | ||||
13140 | VectorType::GenericVector); | ||||
13141 | if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
13142 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | ||||
13143 | VectorType::GenericVector); | ||||
13144 | if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
13145 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | ||||
13146 | VectorType::GenericVector); | ||||
13147 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
13148 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | ||||
13149 | VectorType::GenericVector); | ||||
13150 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 13151, __extension__ __PRETTY_FUNCTION__ )) | ||||
13151 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 13151, __extension__ __PRETTY_FUNCTION__ )); | ||||
13152 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | ||||
13153 | VectorType::GenericVector); | ||||
13154 | } | ||||
13155 | |||||
13156 | QualType Sema::GetSignedSizelessVectorType(QualType V) { | ||||
13157 | const BuiltinType *VTy = V->castAs<BuiltinType>(); | ||||
13158 | assert(VTy->isSizelessBuiltinType() && "expected sizeless type")(static_cast <bool> (VTy->isSizelessBuiltinType() && "expected sizeless type") ? void (0) : __assert_fail ("VTy->isSizelessBuiltinType() && \"expected sizeless type\"" , "clang/lib/Sema/SemaExpr.cpp", 13158, __extension__ __PRETTY_FUNCTION__ )); | ||||
13159 | |||||
13160 | const QualType ETy = V->getSveEltType(Context); | ||||
13161 | const auto TypeSize = Context.getTypeSize(ETy); | ||||
13162 | |||||
13163 | const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); | ||||
13164 | const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; | ||||
13165 | return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); | ||||
13166 | } | ||||
13167 | |||||
13168 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | ||||
13169 | /// operates on extended vector types. Instead of producing an IntTy result, | ||||
13170 | /// like a scalar comparison, a vector comparison produces a vector of integer | ||||
13171 | /// types. | ||||
13172 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13173 | SourceLocation Loc, | ||||
13174 | BinaryOperatorKind Opc) { | ||||
13175 | if (Opc == BO_Cmp) { | ||||
13176 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
13177 | return QualType(); | ||||
13178 | } | ||||
13179 | |||||
13180 | // Check to make sure we're operating on vectors of the same type and width, | ||||
13181 | // Allowing one side to be a scalar of element type. | ||||
13182 | QualType vType = | ||||
13183 | CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, | ||||
13184 | /*AllowBothBool*/ true, | ||||
13185 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
13186 | /*AllowBooleanOperation*/ true, | ||||
13187 | /*ReportInvalid*/ true); | ||||
13188 | if (vType.isNull()) | ||||
13189 | return vType; | ||||
13190 | |||||
13191 | QualType LHSType = LHS.get()->getType(); | ||||
13192 | |||||
13193 | // Determine the return type of a vector compare. By default clang will return | ||||
13194 | // a scalar for all vector compares except vector bool and vector pixel. | ||||
13195 | // With the gcc compiler we will always return a vector type and with the xl | ||||
13196 | // compiler we will always return a scalar type. This switch allows choosing | ||||
13197 | // which behavior is prefered. | ||||
13198 | if (getLangOpts().AltiVec) { | ||||
13199 | switch (getLangOpts().getAltivecSrcCompat()) { | ||||
13200 | case LangOptions::AltivecSrcCompatKind::Mixed: | ||||
13201 | // If AltiVec, the comparison results in a numeric type, i.e. | ||||
13202 | // bool for C++, int for C | ||||
13203 | if (vType->castAs<VectorType>()->getVectorKind() == | ||||
13204 | VectorType::AltiVecVector) | ||||
13205 | return Context.getLogicalOperationType(); | ||||
13206 | else | ||||
13207 | Diag(Loc, diag::warn_deprecated_altivec_src_compat); | ||||
13208 | break; | ||||
13209 | case LangOptions::AltivecSrcCompatKind::GCC: | ||||
13210 | // For GCC we always return the vector type. | ||||
13211 | break; | ||||
13212 | case LangOptions::AltivecSrcCompatKind::XL: | ||||
13213 | return Context.getLogicalOperationType(); | ||||
13214 | break; | ||||
13215 | } | ||||
13216 | } | ||||
13217 | |||||
13218 | // For non-floating point types, check for self-comparisons of the form | ||||
13219 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
13220 | // often indicate logic errors in the program. | ||||
13221 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
13222 | |||||
13223 | // Check for comparisons of floating point operands using != and ==. | ||||
13224 | if (LHSType->hasFloatingRepresentation()) { | ||||
13225 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "clang/lib/Sema/SemaExpr.cpp", 13225, __extension__ __PRETTY_FUNCTION__ )); | ||||
13226 | CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); | ||||
13227 | } | ||||
13228 | |||||
13229 | // Return a signed type for the vector. | ||||
13230 | return GetSignedVectorType(vType); | ||||
13231 | } | ||||
13232 | |||||
13233 | QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, | ||||
13234 | ExprResult &RHS, | ||||
13235 | SourceLocation Loc, | ||||
13236 | BinaryOperatorKind Opc) { | ||||
13237 | if (Opc == BO_Cmp) { | ||||
13238 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
13239 | return QualType(); | ||||
13240 | } | ||||
13241 | |||||
13242 | // Check to make sure we're operating on vectors of the same type and width, | ||||
13243 | // Allowing one side to be a scalar of element type. | ||||
13244 | QualType vType = CheckSizelessVectorOperands( | ||||
13245 | LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); | ||||
13246 | |||||
13247 | if (vType.isNull()) | ||||
13248 | return vType; | ||||
13249 | |||||
13250 | QualType LHSType = LHS.get()->getType(); | ||||
13251 | |||||
13252 | // For non-floating point types, check for self-comparisons of the form | ||||
13253 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
13254 | // often indicate logic errors in the program. | ||||
13255 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
13256 | |||||
13257 | // Check for comparisons of floating point operands using != and ==. | ||||
13258 | if (LHSType->hasFloatingRepresentation()) { | ||||
13259 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "clang/lib/Sema/SemaExpr.cpp", 13259, __extension__ __PRETTY_FUNCTION__ )); | ||||
13260 | CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); | ||||
13261 | } | ||||
13262 | |||||
13263 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); | ||||
13264 | const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); | ||||
13265 | |||||
13266 | if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && | ||||
13267 | RHSBuiltinTy->isSVEBool()) | ||||
13268 | return LHSType; | ||||
13269 | |||||
13270 | // Return a signed type for the vector. | ||||
13271 | return GetSignedSizelessVectorType(vType); | ||||
13272 | } | ||||
13273 | |||||
13274 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | ||||
13275 | const ExprResult &XorRHS, | ||||
13276 | const SourceLocation Loc) { | ||||
13277 | // Do not diagnose macros. | ||||
13278 | if (Loc.isMacroID()) | ||||
13279 | return; | ||||
13280 | |||||
13281 | // Do not diagnose if both LHS and RHS are macros. | ||||
13282 | if (XorLHS.get()->getExprLoc().isMacroID() && | ||||
13283 | XorRHS.get()->getExprLoc().isMacroID()) | ||||
13284 | return; | ||||
13285 | |||||
13286 | bool Negative = false; | ||||
13287 | bool ExplicitPlus = false; | ||||
13288 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | ||||
13289 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | ||||
13290 | |||||
13291 | if (!LHSInt) | ||||
13292 | return; | ||||
13293 | if (!RHSInt) { | ||||
13294 | // Check negative literals. | ||||
13295 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | ||||
13296 | UnaryOperatorKind Opc = UO->getOpcode(); | ||||
13297 | if (Opc != UO_Minus && Opc != UO_Plus) | ||||
13298 | return; | ||||
13299 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | ||||
13300 | if (!RHSInt) | ||||
13301 | return; | ||||
13302 | Negative = (Opc == UO_Minus); | ||||
13303 | ExplicitPlus = !Negative; | ||||
13304 | } else { | ||||
13305 | return; | ||||
13306 | } | ||||
13307 | } | ||||
13308 | |||||
13309 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | ||||
13310 | llvm::APInt RightSideValue = RHSInt->getValue(); | ||||
13311 | if (LeftSideValue != 2 && LeftSideValue != 10) | ||||
13312 | return; | ||||
13313 | |||||
13314 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | ||||
13315 | return; | ||||
13316 | |||||
13317 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | ||||
13318 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | ||||
13319 | llvm::StringRef ExprStr = | ||||
13320 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | ||||
13321 | |||||
13322 | CharSourceRange XorRange = | ||||
13323 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
13324 | llvm::StringRef XorStr = | ||||
13325 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | ||||
13326 | // Do not diagnose if xor keyword/macro is used. | ||||
13327 | if (XorStr == "xor") | ||||
13328 | return; | ||||
13329 | |||||
13330 | std::string LHSStr = std::string(Lexer::getSourceText( | ||||
13331 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | ||||
13332 | S.getSourceManager(), S.getLangOpts())); | ||||
13333 | std::string RHSStr = std::string(Lexer::getSourceText( | ||||
13334 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | ||||
13335 | S.getSourceManager(), S.getLangOpts())); | ||||
13336 | |||||
13337 | if (Negative) { | ||||
13338 | RightSideValue = -RightSideValue; | ||||
13339 | RHSStr = "-" + RHSStr; | ||||
13340 | } else if (ExplicitPlus) { | ||||
13341 | RHSStr = "+" + RHSStr; | ||||
13342 | } | ||||
13343 | |||||
13344 | StringRef LHSStrRef = LHSStr; | ||||
13345 | StringRef RHSStrRef = RHSStr; | ||||
13346 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | ||||
13347 | // literals. | ||||
13348 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | ||||
13349 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | ||||
13350 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | ||||
13351 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | ||||
13352 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | ||||
13353 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | ||||
13354 | LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) | ||||
13355 | return; | ||||
13356 | |||||
13357 | bool SuggestXor = | ||||
13358 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | ||||
13359 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | ||||
13360 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | ||||
13361 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | ||||
13362 | std::string SuggestedExpr = "1 << " + RHSStr; | ||||
13363 | bool Overflow = false; | ||||
13364 | llvm::APInt One = (LeftSideValue - 1); | ||||
13365 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | ||||
13366 | if (Overflow) { | ||||
13367 | if (RightSideIntValue < 64) | ||||
13368 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
13369 | << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) | ||||
13370 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | ||||
13371 | else if (RightSideIntValue == 64) | ||||
13372 | S.Diag(Loc, diag::warn_xor_used_as_pow) | ||||
13373 | << ExprStr << toString(XorValue, 10, true); | ||||
13374 | else | ||||
13375 | return; | ||||
13376 | } else { | ||||
13377 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | ||||
13378 | << ExprStr << toString(XorValue, 10, true) << SuggestedExpr | ||||
13379 | << toString(PowValue, 10, true) | ||||
13380 | << FixItHint::CreateReplacement( | ||||
13381 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | ||||
13382 | } | ||||
13383 | |||||
13384 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | ||||
13385 | << ("0x2 ^ " + RHSStr) << SuggestXor; | ||||
13386 | } else if (LeftSideValue == 10) { | ||||
13387 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | ||||
13388 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
13389 | << ExprStr << toString(XorValue, 10, true) << SuggestedValue | ||||
13390 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | ||||
13391 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | ||||
13392 | << ("0xA ^ " + RHSStr) << SuggestXor; | ||||
13393 | } | ||||
13394 | } | ||||
13395 | |||||
13396 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13397 | SourceLocation Loc) { | ||||
13398 | // Ensure that either both operands are of the same vector type, or | ||||
13399 | // one operand is of a vector type and the other is of its element type. | ||||
13400 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | ||||
13401 | /*AllowBothBool*/ true, | ||||
13402 | /*AllowBoolConversions*/ false, | ||||
13403 | /*AllowBooleanOperation*/ false, | ||||
13404 | /*ReportInvalid*/ false); | ||||
13405 | if (vType.isNull()) | ||||
13406 | return InvalidOperands(Loc, LHS, RHS); | ||||
13407 | if (getLangOpts().OpenCL && | ||||
13408 | getLangOpts().getOpenCLCompatibleVersion() < 120 && | ||||
13409 | vType->hasFloatingRepresentation()) | ||||
13410 | return InvalidOperands(Loc, LHS, RHS); | ||||
13411 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | ||||
13412 | // usage of the logical operators && and || with vectors in C. This | ||||
13413 | // check could be notionally dropped. | ||||
13414 | if (!getLangOpts().CPlusPlus && | ||||
13415 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | ||||
13416 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | ||||
13417 | |||||
13418 | return GetSignedVectorType(LHS.get()->getType()); | ||||
13419 | } | ||||
13420 | |||||
13421 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13422 | SourceLocation Loc, | ||||
13423 | bool IsCompAssign) { | ||||
13424 | if (!IsCompAssign) { | ||||
13425 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
13426 | if (LHS.isInvalid()) | ||||
13427 | return QualType(); | ||||
13428 | } | ||||
13429 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13430 | if (RHS.isInvalid()) | ||||
13431 | return QualType(); | ||||
13432 | |||||
13433 | // For conversion purposes, we ignore any qualifiers. | ||||
13434 | // For example, "const float" and "float" are equivalent. | ||||
13435 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
13436 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
13437 | |||||
13438 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | ||||
13439 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | ||||
13440 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "clang/lib/Sema/SemaExpr.cpp", 13440, __extension__ __PRETTY_FUNCTION__ )); | ||||
13441 | |||||
13442 | if (Context.hasSameType(LHSType, RHSType)) | ||||
13443 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
13444 | |||||
13445 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | ||||
13446 | // case we have to return InvalidOperands. | ||||
13447 | ExprResult OriginalLHS = LHS; | ||||
13448 | ExprResult OriginalRHS = RHS; | ||||
13449 | if (LHSMatType && !RHSMatType) { | ||||
13450 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | ||||
13451 | if (!RHS.isInvalid()) | ||||
13452 | return LHSType; | ||||
13453 | |||||
13454 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
13455 | } | ||||
13456 | |||||
13457 | if (!LHSMatType && RHSMatType) { | ||||
13458 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | ||||
13459 | if (!LHS.isInvalid()) | ||||
13460 | return RHSType; | ||||
13461 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
13462 | } | ||||
13463 | |||||
13464 | return InvalidOperands(Loc, LHS, RHS); | ||||
13465 | } | ||||
13466 | |||||
13467 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13468 | SourceLocation Loc, | ||||
13469 | bool IsCompAssign) { | ||||
13470 | if (!IsCompAssign) { | ||||
13471 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
13472 | if (LHS.isInvalid()) | ||||
13473 | return QualType(); | ||||
13474 | } | ||||
13475 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13476 | if (RHS.isInvalid()) | ||||
13477 | return QualType(); | ||||
13478 | |||||
13479 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
13480 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
13481 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "clang/lib/Sema/SemaExpr.cpp", 13481, __extension__ __PRETTY_FUNCTION__ )); | ||||
13482 | |||||
13483 | if (LHSMatType && RHSMatType) { | ||||
13484 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | ||||
13485 | return InvalidOperands(Loc, LHS, RHS); | ||||
13486 | |||||
13487 | if (Context.hasSameType(LHSMatType, RHSMatType)) | ||||
13488 | return Context.getCommonSugaredType( | ||||
13489 | LHS.get()->getType().getUnqualifiedType(), | ||||
13490 | RHS.get()->getType().getUnqualifiedType()); | ||||
13491 | |||||
13492 | QualType LHSELTy = LHSMatType->getElementType(), | ||||
13493 | RHSELTy = RHSMatType->getElementType(); | ||||
13494 | if (!Context.hasSameType(LHSELTy, RHSELTy)) | ||||
13495 | return InvalidOperands(Loc, LHS, RHS); | ||||
13496 | |||||
13497 | return Context.getConstantMatrixType( | ||||
13498 | Context.getCommonSugaredType(LHSELTy, RHSELTy), | ||||
13499 | LHSMatType->getNumRows(), RHSMatType->getNumColumns()); | ||||
13500 | } | ||||
13501 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
13502 | } | ||||
13503 | |||||
13504 | static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { | ||||
13505 | switch (Opc) { | ||||
13506 | default: | ||||
13507 | return false; | ||||
13508 | case BO_And: | ||||
13509 | case BO_AndAssign: | ||||
13510 | case BO_Or: | ||||
13511 | case BO_OrAssign: | ||||
13512 | case BO_Xor: | ||||
13513 | case BO_XorAssign: | ||||
13514 | return true; | ||||
13515 | } | ||||
13516 | } | ||||
13517 | |||||
13518 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13519 | SourceLocation Loc, | ||||
13520 | BinaryOperatorKind Opc) { | ||||
13521 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
13522 | |||||
13523 | bool IsCompAssign = | ||||
13524 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | ||||
13525 | |||||
13526 | bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); | ||||
13527 | |||||
13528 | if (LHS.get()->getType()->isVectorType() || | ||||
13529 | RHS.get()->getType()->isVectorType()) { | ||||
13530 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
13531 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
13532 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
13533 | /*AllowBothBool*/ true, | ||||
13534 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
13535 | /*AllowBooleanOperation*/ LegalBoolVecOperator, | ||||
13536 | /*ReportInvalid*/ true); | ||||
13537 | return InvalidOperands(Loc, LHS, RHS); | ||||
13538 | } | ||||
13539 | |||||
13540 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
13541 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
13542 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
13543 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
13544 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
13545 | ACK_BitwiseOp); | ||||
13546 | return InvalidOperands(Loc, LHS, RHS); | ||||
13547 | } | ||||
13548 | |||||
13549 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
13550 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
13551 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
13552 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
13553 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
13554 | ACK_BitwiseOp); | ||||
13555 | return InvalidOperands(Loc, LHS, RHS); | ||||
13556 | } | ||||
13557 | |||||
13558 | if (Opc == BO_And) | ||||
13559 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
13560 | |||||
13561 | if (LHS.get()->getType()->hasFloatingRepresentation() || | ||||
13562 | RHS.get()->getType()->hasFloatingRepresentation()) | ||||
13563 | return InvalidOperands(Loc, LHS, RHS); | ||||
13564 | |||||
13565 | ExprResult LHSResult = LHS, RHSResult = RHS; | ||||
13566 | QualType compType = UsualArithmeticConversions( | ||||
13567 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | ||||
13568 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | ||||
13569 | return QualType(); | ||||
13570 | LHS = LHSResult.get(); | ||||
13571 | RHS = RHSResult.get(); | ||||
13572 | |||||
13573 | if (Opc == BO_Xor) | ||||
13574 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | ||||
13575 | |||||
13576 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | ||||
13577 | return compType; | ||||
13578 | return InvalidOperands(Loc, LHS, RHS); | ||||
13579 | } | ||||
13580 | |||||
13581 | // C99 6.5.[13,14] | ||||
13582 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13583 | SourceLocation Loc, | ||||
13584 | BinaryOperatorKind Opc) { | ||||
13585 | // Check vector operands differently. | ||||
13586 | if (LHS.get()->getType()->isVectorType() || | ||||
13587 | RHS.get()->getType()->isVectorType()) | ||||
13588 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | ||||
13589 | |||||
13590 | bool EnumConstantInBoolContext = false; | ||||
13591 | for (const ExprResult &HS : {LHS, RHS}) { | ||||
13592 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | ||||
13593 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | ||||
13594 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | ||||
13595 | EnumConstantInBoolContext = true; | ||||
13596 | } | ||||
13597 | } | ||||
13598 | |||||
13599 | if (EnumConstantInBoolContext) | ||||
13600 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | ||||
13601 | |||||
13602 | // Diagnose cases where the user write a logical and/or but probably meant a | ||||
13603 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | ||||
13604 | // is a constant. | ||||
13605 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | ||||
13606 | !LHS.get()->getType()->isBooleanType() && | ||||
13607 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | ||||
13608 | // Don't warn in macros or template instantiations. | ||||
13609 | !Loc.isMacroID() && !inTemplateInstantiation()) { | ||||
13610 | // If the RHS can be constant folded, and if it constant folds to something | ||||
13611 | // that isn't 0 or 1 (which indicate a potential logical operation that | ||||
13612 | // happened to fold to true/false) then warn. | ||||
13613 | // Parens on the RHS are ignored. | ||||
13614 | Expr::EvalResult EVResult; | ||||
13615 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | ||||
13616 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
13617 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | ||||
13618 | !RHS.get()->getExprLoc().isMacroID()) || | ||||
13619 | (Result != 0 && Result != 1)) { | ||||
13620 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | ||||
13621 | << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); | ||||
13622 | // Suggest replacing the logical operator with the bitwise version | ||||
13623 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | ||||
13624 | << (Opc == BO_LAnd ? "&" : "|") | ||||
13625 | << FixItHint::CreateReplacement( | ||||
13626 | SourceRange(Loc, getLocForEndOfToken(Loc)), | ||||
13627 | Opc == BO_LAnd ? "&" : "|"); | ||||
13628 | if (Opc == BO_LAnd) | ||||
13629 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | ||||
13630 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | ||||
13631 | << FixItHint::CreateRemoval( | ||||
13632 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | ||||
13633 | RHS.get()->getEndLoc())); | ||||
13634 | } | ||||
13635 | } | ||||
13636 | } | ||||
13637 | |||||
13638 | if (!Context.getLangOpts().CPlusPlus) { | ||||
13639 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | ||||
13640 | // not operate on the built-in scalar and vector float types. | ||||
13641 | if (Context.getLangOpts().OpenCL && | ||||
13642 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
13643 | if (LHS.get()->getType()->isFloatingType() || | ||||
13644 | RHS.get()->getType()->isFloatingType()) | ||||
13645 | return InvalidOperands(Loc, LHS, RHS); | ||||
13646 | } | ||||
13647 | |||||
13648 | LHS = UsualUnaryConversions(LHS.get()); | ||||
13649 | if (LHS.isInvalid()) | ||||
13650 | return QualType(); | ||||
13651 | |||||
13652 | RHS = UsualUnaryConversions(RHS.get()); | ||||
13653 | if (RHS.isInvalid()) | ||||
13654 | return QualType(); | ||||
13655 | |||||
13656 | if (!LHS.get()->getType()->isScalarType() || | ||||
13657 | !RHS.get()->getType()->isScalarType()) | ||||
13658 | return InvalidOperands(Loc, LHS, RHS); | ||||
13659 | |||||
13660 | return Context.IntTy; | ||||
13661 | } | ||||
13662 | |||||
13663 | // The following is safe because we only use this method for | ||||
13664 | // non-overloadable operands. | ||||
13665 | |||||
13666 | // C++ [expr.log.and]p1 | ||||
13667 | // C++ [expr.log.or]p1 | ||||
13668 | // The operands are both contextually converted to type bool. | ||||
13669 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | ||||
13670 | if (LHSRes.isInvalid()) | ||||
13671 | return InvalidOperands(Loc, LHS, RHS); | ||||
13672 | LHS = LHSRes; | ||||
13673 | |||||
13674 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | ||||
13675 | if (RHSRes.isInvalid()) | ||||
13676 | return InvalidOperands(Loc, LHS, RHS); | ||||
13677 | RHS = RHSRes; | ||||
13678 | |||||
13679 | // C++ [expr.log.and]p2 | ||||
13680 | // C++ [expr.log.or]p2 | ||||
13681 | // The result is a bool. | ||||
13682 | return Context.BoolTy; | ||||
13683 | } | ||||
13684 | |||||
13685 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | ||||
13686 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
13687 | if (!ME) return false; | ||||
13688 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | ||||
13689 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | ||||
13690 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | ||||
13691 | if (!Base) return false; | ||||
13692 | return Base->getMethodDecl() != nullptr; | ||||
13693 | } | ||||
13694 | |||||
13695 | /// Is the given expression (which must be 'const') a reference to a | ||||
13696 | /// variable which was originally non-const, but which has become | ||||
13697 | /// 'const' due to being captured within a block? | ||||
13698 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | ||||
13699 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | ||||
13700 | assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E-> getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "clang/lib/Sema/SemaExpr.cpp", 13700, __extension__ __PRETTY_FUNCTION__ )); | ||||
13701 | E = E->IgnoreParens(); | ||||
13702 | |||||
13703 | // Must be a reference to a declaration from an enclosing scope. | ||||
13704 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
13705 | if (!DRE) return NCCK_None; | ||||
13706 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | ||||
13707 | |||||
13708 | // The declaration must be a variable which is not declared 'const'. | ||||
13709 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
13710 | if (!var) return NCCK_None; | ||||
13711 | if (var->getType().isConstQualified()) return NCCK_None; | ||||
13712 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast <bool> (var->hasLocalStorage() && "capture added 'const' to non-local?") ? void (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "clang/lib/Sema/SemaExpr.cpp", 13712, __extension__ __PRETTY_FUNCTION__ )); | ||||
13713 | |||||
13714 | // Decide whether the first capture was for a block or a lambda. | ||||
13715 | DeclContext *DC = S.CurContext, *Prev = nullptr; | ||||
13716 | // Decide whether the first capture was for a block or a lambda. | ||||
13717 | while (DC) { | ||||
13718 | // For init-capture, it is possible that the variable belongs to the | ||||
13719 | // template pattern of the current context. | ||||
13720 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | ||||
13721 | if (var->isInitCapture() && | ||||
13722 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | ||||
13723 | break; | ||||
13724 | if (DC == var->getDeclContext()) | ||||
13725 | break; | ||||
13726 | Prev = DC; | ||||
13727 | DC = DC->getParent(); | ||||
13728 | } | ||||
13729 | // Unless we have an init-capture, we've gone one step too far. | ||||
13730 | if (!var->isInitCapture()) | ||||
13731 | DC = Prev; | ||||
13732 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | ||||
13733 | } | ||||
13734 | |||||
13735 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | ||||
13736 | Ty = Ty.getNonReferenceType(); | ||||
13737 | if (IsDereference && Ty->isPointerType()) | ||||
13738 | Ty = Ty->getPointeeType(); | ||||
13739 | return !Ty.isConstQualified(); | ||||
13740 | } | ||||
13741 | |||||
13742 | // Update err_typecheck_assign_const and note_typecheck_assign_const | ||||
13743 | // when this enum is changed. | ||||
13744 | enum { | ||||
13745 | ConstFunction, | ||||
13746 | ConstVariable, | ||||
13747 | ConstMember, | ||||
13748 | ConstMethod, | ||||
13749 | NestedConstMember, | ||||
13750 | ConstUnknown, // Keep as last element | ||||
13751 | }; | ||||
13752 | |||||
13753 | /// Emit the "read-only variable not assignable" error and print notes to give | ||||
13754 | /// more information about why the variable is not assignable, such as pointing | ||||
13755 | /// to the declaration of a const variable, showing that a method is const, or | ||||
13756 | /// that the function is returning a const reference. | ||||
13757 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | ||||
13758 | SourceLocation Loc) { | ||||
13759 | SourceRange ExprRange = E->getSourceRange(); | ||||
13760 | |||||
13761 | // Only emit one error on the first const found. All other consts will emit | ||||
13762 | // a note to the error. | ||||
13763 | bool DiagnosticEmitted = false; | ||||
13764 | |||||
13765 | // Track if the current expression is the result of a dereference, and if the | ||||
13766 | // next checked expression is the result of a dereference. | ||||
13767 | bool IsDereference = false; | ||||
13768 | bool NextIsDereference = false; | ||||
13769 | |||||
13770 | // Loop to process MemberExpr chains. | ||||
13771 | while (true) { | ||||
13772 | IsDereference = NextIsDereference; | ||||
13773 | |||||
13774 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | ||||
13775 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
13776 | NextIsDereference = ME->isArrow(); | ||||
13777 | const ValueDecl *VD = ME->getMemberDecl(); | ||||
13778 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | ||||
13779 | // Mutable fields can be modified even if the class is const. | ||||
13780 | if (Field->isMutable()) { | ||||
13781 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted." ) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "clang/lib/Sema/SemaExpr.cpp", 13781, __extension__ __PRETTY_FUNCTION__ )); | ||||
13782 | break; | ||||
13783 | } | ||||
13784 | |||||
13785 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | ||||
13786 | if (!DiagnosticEmitted) { | ||||
13787 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13788 | << ExprRange << ConstMember << false /*static*/ << Field | ||||
13789 | << Field->getType(); | ||||
13790 | DiagnosticEmitted = true; | ||||
13791 | } | ||||
13792 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
13793 | << ConstMember << false /*static*/ << Field << Field->getType() | ||||
13794 | << Field->getSourceRange(); | ||||
13795 | } | ||||
13796 | E = ME->getBase(); | ||||
13797 | continue; | ||||
13798 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | ||||
13799 | if (VDecl->getType().isConstQualified()) { | ||||
13800 | if (!DiagnosticEmitted) { | ||||
13801 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13802 | << ExprRange << ConstMember << true /*static*/ << VDecl | ||||
13803 | << VDecl->getType(); | ||||
13804 | DiagnosticEmitted = true; | ||||
13805 | } | ||||
13806 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
13807 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | ||||
13808 | << VDecl->getSourceRange(); | ||||
13809 | } | ||||
13810 | // Static fields do not inherit constness from parents. | ||||
13811 | break; | ||||
13812 | } | ||||
13813 | break; // End MemberExpr | ||||
13814 | } else if (const ArraySubscriptExpr *ASE = | ||||
13815 | dyn_cast<ArraySubscriptExpr>(E)) { | ||||
13816 | E = ASE->getBase()->IgnoreParenImpCasts(); | ||||
13817 | continue; | ||||
13818 | } else if (const ExtVectorElementExpr *EVE = | ||||
13819 | dyn_cast<ExtVectorElementExpr>(E)) { | ||||
13820 | E = EVE->getBase()->IgnoreParenImpCasts(); | ||||
13821 | continue; | ||||
13822 | } | ||||
13823 | break; | ||||
13824 | } | ||||
13825 | |||||
13826 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
13827 | // Function calls | ||||
13828 | const FunctionDecl *FD = CE->getDirectCallee(); | ||||
13829 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | ||||
13830 | if (!DiagnosticEmitted) { | ||||
13831 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
13832 | << ConstFunction << FD; | ||||
13833 | DiagnosticEmitted = true; | ||||
13834 | } | ||||
13835 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | ||||
13836 | diag::note_typecheck_assign_const) | ||||
13837 | << ConstFunction << FD << FD->getReturnType() | ||||
13838 | << FD->getReturnTypeSourceRange(); | ||||
13839 | } | ||||
13840 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
13841 | // Point to variable declaration. | ||||
13842 | if (const ValueDecl *VD = DRE->getDecl()) { | ||||
13843 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | ||||
13844 | if (!DiagnosticEmitted) { | ||||
13845 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13846 | << ExprRange << ConstVariable << VD << VD->getType(); | ||||
13847 | DiagnosticEmitted = true; | ||||
13848 | } | ||||
13849 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
13850 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | ||||
13851 | } | ||||
13852 | } | ||||
13853 | } else if (isa<CXXThisExpr>(E)) { | ||||
13854 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | ||||
13855 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | ||||
13856 | if (MD->isConst()) { | ||||
13857 | if (!DiagnosticEmitted) { | ||||
13858 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
13859 | << ConstMethod << MD; | ||||
13860 | DiagnosticEmitted = true; | ||||
13861 | } | ||||
13862 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | ||||
13863 | << ConstMethod << MD << MD->getSourceRange(); | ||||
13864 | } | ||||
13865 | } | ||||
13866 | } | ||||
13867 | } | ||||
13868 | |||||
13869 | if (DiagnosticEmitted) | ||||
13870 | return; | ||||
13871 | |||||
13872 | // Can't determine a more specific message, so display the generic error. | ||||
13873 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | ||||
13874 | } | ||||
13875 | |||||
13876 | enum OriginalExprKind { | ||||
13877 | OEK_Variable, | ||||
13878 | OEK_Member, | ||||
13879 | OEK_LValue | ||||
13880 | }; | ||||
13881 | |||||
13882 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | ||||
13883 | const RecordType *Ty, | ||||
13884 | SourceLocation Loc, SourceRange Range, | ||||
13885 | OriginalExprKind OEK, | ||||
13886 | bool &DiagnosticEmitted) { | ||||
13887 | std::vector<const RecordType *> RecordTypeList; | ||||
13888 | RecordTypeList.push_back(Ty); | ||||
13889 | unsigned NextToCheckIndex = 0; | ||||
13890 | // We walk the record hierarchy breadth-first to ensure that we print | ||||
13891 | // diagnostics in field nesting order. | ||||
13892 | while (RecordTypeList.size() > NextToCheckIndex) { | ||||
13893 | bool IsNested = NextToCheckIndex > 0; | ||||
13894 | for (const FieldDecl *Field : | ||||
13895 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | ||||
13896 | // First, check every field for constness. | ||||
13897 | QualType FieldTy = Field->getType(); | ||||
13898 | if (FieldTy.isConstQualified()) { | ||||
13899 | if (!DiagnosticEmitted) { | ||||
13900 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13901 | << Range << NestedConstMember << OEK << VD | ||||
13902 | << IsNested << Field; | ||||
13903 | DiagnosticEmitted = true; | ||||
13904 | } | ||||
13905 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | ||||
13906 | << NestedConstMember << IsNested << Field | ||||
13907 | << FieldTy << Field->getSourceRange(); | ||||
13908 | } | ||||
13909 | |||||
13910 | // Then we append it to the list to check next in order. | ||||
13911 | FieldTy = FieldTy.getCanonicalType(); | ||||
13912 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | ||||
13913 | if (!llvm::is_contained(RecordTypeList, FieldRecTy)) | ||||
13914 | RecordTypeList.push_back(FieldRecTy); | ||||
13915 | } | ||||
13916 | } | ||||
13917 | ++NextToCheckIndex; | ||||
13918 | } | ||||
13919 | } | ||||
13920 | |||||
13921 | /// Emit an error for the case where a record we are trying to assign to has a | ||||
13922 | /// const-qualified field somewhere in its hierarchy. | ||||
13923 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | ||||
13924 | SourceLocation Loc) { | ||||
13925 | QualType Ty = E->getType(); | ||||
13926 | assert(Ty->isRecordType() && "lvalue was not record?")(static_cast <bool> (Ty->isRecordType() && "lvalue was not record?" ) ? void (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "clang/lib/Sema/SemaExpr.cpp", 13926, __extension__ __PRETTY_FUNCTION__ )); | ||||
13927 | SourceRange Range = E->getSourceRange(); | ||||
13928 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | ||||
13929 | bool DiagEmitted = false; | ||||
13930 | |||||
13931 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
13932 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | ||||
13933 | Range, OEK_Member, DiagEmitted); | ||||
13934 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
13935 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | ||||
13936 | Range, OEK_Variable, DiagEmitted); | ||||
13937 | else | ||||
13938 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | ||||
13939 | Range, OEK_LValue, DiagEmitted); | ||||
13940 | if (!DiagEmitted) | ||||
13941 | DiagnoseConstAssignment(S, E, Loc); | ||||
13942 | } | ||||
13943 | |||||
13944 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | ||||
13945 | /// emit an error and return true. If so, return false. | ||||
13946 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | ||||
13947 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "clang/lib/Sema/SemaExpr.cpp", 13947, __extension__ __PRETTY_FUNCTION__ )); | ||||
13948 | |||||
13949 | S.CheckShadowingDeclModification(E, Loc); | ||||
13950 | |||||
13951 | SourceLocation OrigLoc = Loc; | ||||
13952 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | ||||
13953 | &Loc); | ||||
13954 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | ||||
13955 | IsLV = Expr::MLV_InvalidMessageExpression; | ||||
13956 | if (IsLV == Expr::MLV_Valid) | ||||
13957 | return false; | ||||
13958 | |||||
13959 | unsigned DiagID = 0; | ||||
13960 | bool NeedType = false; | ||||
13961 | switch (IsLV) { // C99 6.5.16p2 | ||||
13962 | case Expr::MLV_ConstQualified: | ||||
13963 | // Use a specialized diagnostic when we're assigning to an object | ||||
13964 | // from an enclosing function or block. | ||||
13965 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | ||||
13966 | if (NCCK == NCCK_Block) | ||||
13967 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | ||||
13968 | else | ||||
13969 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | ||||
13970 | break; | ||||
13971 | } | ||||
13972 | |||||
13973 | // In ARC, use some specialized diagnostics for occasions where we | ||||
13974 | // infer 'const'. These are always pseudo-strong variables. | ||||
13975 | if (S.getLangOpts().ObjCAutoRefCount) { | ||||
13976 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | ||||
13977 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | ||||
13978 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | ||||
13979 | |||||
13980 | // Use the normal diagnostic if it's pseudo-__strong but the | ||||
13981 | // user actually wrote 'const'. | ||||
13982 | if (var->isARCPseudoStrong() && | ||||
13983 | (!var->getTypeSourceInfo() || | ||||
13984 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | ||||
13985 | // There are three pseudo-strong cases: | ||||
13986 | // - self | ||||
13987 | ObjCMethodDecl *method = S.getCurMethodDecl(); | ||||
13988 | if (method && var == method->getSelfDecl()) { | ||||
13989 | DiagID = method->isClassMethod() | ||||
13990 | ? diag::err_typecheck_arc_assign_self_class_method | ||||
13991 | : diag::err_typecheck_arc_assign_self; | ||||
13992 | |||||
13993 | // - Objective-C externally_retained attribute. | ||||
13994 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | ||||
13995 | isa<ParmVarDecl>(var)) { | ||||
13996 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | ||||
13997 | |||||
13998 | // - fast enumeration variables | ||||
13999 | } else { | ||||
14000 | DiagID = diag::err_typecheck_arr_assign_enumeration; | ||||
14001 | } | ||||
14002 | |||||
14003 | SourceRange Assign; | ||||
14004 | if (Loc != OrigLoc) | ||||
14005 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
14006 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
14007 | // We need to preserve the AST regardless, so migration tool | ||||
14008 | // can do its job. | ||||
14009 | return false; | ||||
14010 | } | ||||
14011 | } | ||||
14012 | } | ||||
14013 | |||||
14014 | // If none of the special cases above are triggered, then this is a | ||||
14015 | // simple const assignment. | ||||
14016 | if (DiagID == 0) { | ||||
14017 | DiagnoseConstAssignment(S, E, Loc); | ||||
14018 | return true; | ||||
14019 | } | ||||
14020 | |||||
14021 | break; | ||||
14022 | case Expr::MLV_ConstAddrSpace: | ||||
14023 | DiagnoseConstAssignment(S, E, Loc); | ||||
14024 | return true; | ||||
14025 | case Expr::MLV_ConstQualifiedField: | ||||
14026 | DiagnoseRecursiveConstFields(S, E, Loc); | ||||
14027 | return true; | ||||
14028 | case Expr::MLV_ArrayType: | ||||
14029 | case Expr::MLV_ArrayTemporary: | ||||
14030 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | ||||
14031 | NeedType = true; | ||||
14032 | break; | ||||
14033 | case Expr::MLV_NotObjectType: | ||||
14034 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | ||||
14035 | NeedType = true; | ||||
14036 | break; | ||||
14037 | case Expr::MLV_LValueCast: | ||||
14038 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | ||||
14039 | break; | ||||
14040 | case Expr::MLV_Valid: | ||||
14041 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "clang/lib/Sema/SemaExpr.cpp", 14041); | ||||
14042 | case Expr::MLV_InvalidExpression: | ||||
14043 | case Expr::MLV_MemberFunction: | ||||
14044 | case Expr::MLV_ClassTemporary: | ||||
14045 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | ||||
14046 | break; | ||||
14047 | case Expr::MLV_IncompleteType: | ||||
14048 | case Expr::MLV_IncompleteVoidType: | ||||
14049 | return S.RequireCompleteType(Loc, E->getType(), | ||||
14050 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | ||||
14051 | case Expr::MLV_DuplicateVectorComponents: | ||||
14052 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | ||||
14053 | break; | ||||
14054 | case Expr::MLV_NoSetterProperty: | ||||
14055 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "clang/lib/Sema/SemaExpr.cpp", 14055); | ||||
14056 | case Expr::MLV_InvalidMessageExpression: | ||||
14057 | DiagID = diag::err_readonly_message_assignment; | ||||
14058 | break; | ||||
14059 | case Expr::MLV_SubObjCPropertySetting: | ||||
14060 | DiagID = diag::err_no_subobject_property_setting; | ||||
14061 | break; | ||||
14062 | } | ||||
14063 | |||||
14064 | SourceRange Assign; | ||||
14065 | if (Loc != OrigLoc) | ||||
14066 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
14067 | if (NeedType) | ||||
14068 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | ||||
14069 | else | ||||
14070 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
14071 | return true; | ||||
14072 | } | ||||
14073 | |||||
14074 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | ||||
14075 | SourceLocation Loc, | ||||
14076 | Sema &Sema) { | ||||
14077 | if (Sema.inTemplateInstantiation()) | ||||
14078 | return; | ||||
14079 | if (Sema.isUnevaluatedContext()) | ||||
14080 | return; | ||||
14081 | if (Loc.isInvalid() || Loc.isMacroID()) | ||||
14082 | return; | ||||
14083 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | ||||
14084 | return; | ||||
14085 | |||||
14086 | // C / C++ fields | ||||
14087 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | ||||
14088 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | ||||
14089 | if (ML && MR) { | ||||
14090 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | ||||
14091 | return; | ||||
14092 | const ValueDecl *LHSDecl = | ||||
14093 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | ||||
14094 | const ValueDecl *RHSDecl = | ||||
14095 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | ||||
14096 | if (LHSDecl != RHSDecl) | ||||
14097 | return; | ||||
14098 | if (LHSDecl->getType().isVolatileQualified()) | ||||
14099 | return; | ||||
14100 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
14101 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
14102 | return; | ||||
14103 | |||||
14104 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | ||||
14105 | } | ||||
14106 | |||||
14107 | // Objective-C instance variables | ||||
14108 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | ||||
14109 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | ||||
14110 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | ||||
14111 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | ||||
14112 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | ||||
14113 | if (RL && RR && RL->getDecl() == RR->getDecl()) | ||||
14114 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | ||||
14115 | } | ||||
14116 | } | ||||
14117 | |||||
14118 | // C99 6.5.16.1 | ||||
14119 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | ||||
14120 | SourceLocation Loc, | ||||
14121 | QualType CompoundType, | ||||
14122 | BinaryOperatorKind Opc) { | ||||
14123 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "clang/lib/Sema/SemaExpr.cpp", 14123, __extension__ __PRETTY_FUNCTION__ )); | ||||
14124 | |||||
14125 | // Verify that LHS is a modifiable lvalue, and emit error if not. | ||||
14126 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | ||||
14127 | return QualType(); | ||||
14128 | |||||
14129 | QualType LHSType = LHSExpr->getType(); | ||||
14130 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | ||||
14131 | CompoundType; | ||||
14132 | // OpenCL v1.2 s6.1.1.1 p2: | ||||
14133 | // The half data type can only be used to declare a pointer to a buffer that | ||||
14134 | // contains half values | ||||
14135 | if (getLangOpts().OpenCL && | ||||
14136 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
14137 | LHSType->isHalfType()) { | ||||
14138 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | ||||
14139 | << LHSType.getUnqualifiedType(); | ||||
14140 | return QualType(); | ||||
14141 | } | ||||
14142 | |||||
14143 | AssignConvertType ConvTy; | ||||
14144 | if (CompoundType.isNull()) { | ||||
14145 | Expr *RHSCheck = RHS.get(); | ||||
14146 | |||||
14147 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | ||||
14148 | |||||
14149 | QualType LHSTy(LHSType); | ||||
14150 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | ||||
14151 | if (RHS.isInvalid()) | ||||
14152 | return QualType(); | ||||
14153 | // Special case of NSObject attributes on c-style pointer types. | ||||
14154 | if (ConvTy == IncompatiblePointer && | ||||
14155 | ((Context.isObjCNSObjectType(LHSType) && | ||||
14156 | RHSType->isObjCObjectPointerType()) || | ||||
14157 | (Context.isObjCNSObjectType(RHSType) && | ||||
14158 | LHSType->isObjCObjectPointerType()))) | ||||
14159 | ConvTy = Compatible; | ||||
14160 | |||||
14161 | if (ConvTy == Compatible && | ||||
14162 | LHSType->isObjCObjectType()) | ||||
14163 | Diag(Loc, diag::err_objc_object_assignment) | ||||
14164 | << LHSType; | ||||
14165 | |||||
14166 | // If the RHS is a unary plus or minus, check to see if they = and + are | ||||
14167 | // right next to each other. If so, the user may have typo'd "x =+ 4" | ||||
14168 | // instead of "x += 4". | ||||
14169 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | ||||
14170 | RHSCheck = ICE->getSubExpr(); | ||||
14171 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | ||||
14172 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | ||||
14173 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | ||||
14174 | // Only if the two operators are exactly adjacent. | ||||
14175 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | ||||
14176 | // And there is a space or other character before the subexpr of the | ||||
14177 | // unary +/-. We don't want to warn on "x=-1". | ||||
14178 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | ||||
14179 | UO->getSubExpr()->getBeginLoc().isFileID()) { | ||||
14180 | Diag(Loc, diag::warn_not_compound_assign) | ||||
14181 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | ||||
14182 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | ||||
14183 | } | ||||
14184 | } | ||||
14185 | |||||
14186 | if (ConvTy == Compatible) { | ||||
14187 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | ||||
14188 | // Warn about retain cycles where a block captures the LHS, but | ||||
14189 | // not if the LHS is a simple variable into which the block is | ||||
14190 | // being stored...unless that variable can be captured by reference! | ||||
14191 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | ||||
14192 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | ||||
14193 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | ||||
14194 | checkRetainCycles(LHSExpr, RHS.get()); | ||||
14195 | } | ||||
14196 | |||||
14197 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | ||||
14198 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | ||||
14199 | // It is safe to assign a weak reference into a strong variable. | ||||
14200 | // Although this code can still have problems: | ||||
14201 | // id x = self.weakProp; | ||||
14202 | // id y = self.weakProp; | ||||
14203 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||
14204 | // paths through the function. This should be revisited if | ||||
14205 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||
14206 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | ||||
14207 | // variable, which will be valid for the current autorelease scope. | ||||
14208 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||
14209 | RHS.get()->getBeginLoc())) | ||||
14210 | getCurFunction()->markSafeWeakUse(RHS.get()); | ||||
14211 | |||||
14212 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | ||||
14213 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | ||||
14214 | } | ||||
14215 | } | ||||
14216 | } else { | ||||
14217 | // Compound assignment "x += y" | ||||
14218 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | ||||
14219 | } | ||||
14220 | |||||
14221 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | ||||
14222 | RHS.get(), AA_Assigning)) | ||||
14223 | return QualType(); | ||||
14224 | |||||
14225 | CheckForNullPointerDereference(*this, LHSExpr); | ||||
14226 | |||||
14227 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | ||||
14228 | if (CompoundType.isNull()) { | ||||
14229 | // C++2a [expr.ass]p5: | ||||
14230 | // A simple-assignment whose left operand is of a volatile-qualified | ||||
14231 | // type is deprecated unless the assignment is either a discarded-value | ||||
14232 | // expression or an unevaluated operand | ||||
14233 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | ||||
14234 | } | ||||
14235 | } | ||||
14236 | |||||
14237 | // C11 6.5.16p3: The type of an assignment expression is the type of the | ||||
14238 | // left operand would have after lvalue conversion. | ||||
14239 | // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has | ||||
14240 | // qualified type, the value has the unqualified version of the type of the | ||||
14241 | // lvalue; additionally, if the lvalue has atomic type, the value has the | ||||
14242 | // non-atomic version of the type of the lvalue. | ||||
14243 | // C++ 5.17p1: the type of the assignment expression is that of its left | ||||
14244 | // operand. | ||||
14245 | return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); | ||||
14246 | } | ||||
14247 | |||||
14248 | // Scenarios to ignore if expression E is: | ||||
14249 | // 1. an explicit cast expression into void | ||||
14250 | // 2. a function call expression that returns void | ||||
14251 | static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { | ||||
14252 | E = E->IgnoreParens(); | ||||
14253 | |||||
14254 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | ||||
14255 | if (CE->getCastKind() == CK_ToVoid) { | ||||
14256 | return true; | ||||
14257 | } | ||||
14258 | |||||
14259 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | ||||
14260 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | ||||
14261 | CE->getSubExpr()->getType()->isDependentType()) { | ||||
14262 | return true; | ||||
14263 | } | ||||
14264 | } | ||||
14265 | |||||
14266 | if (const auto *CE = dyn_cast<CallExpr>(E)) | ||||
14267 | return CE->getCallReturnType(Context)->isVoidType(); | ||||
14268 | return false; | ||||
14269 | } | ||||
14270 | |||||
14271 | // Look for instances where it is likely the comma operator is confused with | ||||
14272 | // another operator. There is an explicit list of acceptable expressions for | ||||
14273 | // the left hand side of the comma operator, otherwise emit a warning. | ||||
14274 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | ||||
14275 | // No warnings in macros | ||||
14276 | if (Loc.isMacroID()) | ||||
14277 | return; | ||||
14278 | |||||
14279 | // Don't warn in template instantiations. | ||||
14280 | if (inTemplateInstantiation()) | ||||
14281 | return; | ||||
14282 | |||||
14283 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | ||||
14284 | // instead, skip more than needed, then call back into here with the | ||||
14285 | // CommaVisitor in SemaStmt.cpp. | ||||
14286 | // The listed locations are the initialization and increment portions | ||||
14287 | // of a for loop. The additional checks are on the condition of | ||||
14288 | // if statements, do/while loops, and for loops. | ||||
14289 | // Differences in scope flags for C89 mode requires the extra logic. | ||||
14290 | const unsigned ForIncrementFlags = | ||||
14291 | getLangOpts().C99 || getLangOpts().CPlusPlus | ||||
14292 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | ||||
14293 | : Scope::ContinueScope | Scope::BreakScope; | ||||
14294 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | ||||
14295 | const unsigned ScopeFlags = getCurScope()->getFlags(); | ||||
14296 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | ||||
14297 | (ScopeFlags & ForInitFlags) == ForInitFlags) | ||||
14298 | return; | ||||
14299 | |||||
14300 | // If there are multiple comma operators used together, get the RHS of the | ||||
14301 | // of the comma operator as the LHS. | ||||
14302 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | ||||
14303 | if (BO->getOpcode() != BO_Comma) | ||||
14304 | break; | ||||
14305 | LHS = BO->getRHS(); | ||||
14306 | } | ||||
14307 | |||||
14308 | // Only allow some expressions on LHS to not warn. | ||||
14309 | if (IgnoreCommaOperand(LHS, Context)) | ||||
14310 | return; | ||||
14311 | |||||
14312 | Diag(Loc, diag::warn_comma_operator); | ||||
14313 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | ||||
14314 | << LHS->getSourceRange() | ||||
14315 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | ||||
14316 | LangOpts.CPlusPlus ? "static_cast<void>(" | ||||
14317 | : "(void)(") | ||||
14318 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | ||||
14319 | ")"); | ||||
14320 | } | ||||
14321 | |||||
14322 | // C99 6.5.17 | ||||
14323 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
14324 | SourceLocation Loc) { | ||||
14325 | LHS = S.CheckPlaceholderExpr(LHS.get()); | ||||
14326 | RHS = S.CheckPlaceholderExpr(RHS.get()); | ||||
14327 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
14328 | return QualType(); | ||||
14329 | |||||
14330 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | ||||
14331 | // operands, but not unary promotions. | ||||
14332 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | ||||
14333 | |||||
14334 | // So we treat the LHS as a ignored value, and in C++ we allow the | ||||
14335 | // containing site to determine what should be done with the RHS. | ||||
14336 | LHS = S.IgnoredValueConversions(LHS.get()); | ||||
14337 | if (LHS.isInvalid()) | ||||
14338 | return QualType(); | ||||
14339 | |||||
14340 | S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); | ||||
14341 | |||||
14342 | if (!S.getLangOpts().CPlusPlus) { | ||||
14343 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
14344 | if (RHS.isInvalid()) | ||||
14345 | return QualType(); | ||||
14346 | if (!RHS.get()->getType()->isVoidType()) | ||||
14347 | S.RequireCompleteType(Loc, RHS.get()->getType(), | ||||
14348 | diag::err_incomplete_type); | ||||
14349 | } | ||||
14350 | |||||
14351 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | ||||
14352 | S.DiagnoseCommaOperator(LHS.get(), Loc); | ||||
14353 | |||||
14354 | return RHS.get()->getType(); | ||||
14355 | } | ||||
14356 | |||||
14357 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | ||||
14358 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | ||||
14359 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | ||||
14360 | ExprValueKind &VK, | ||||
14361 | ExprObjectKind &OK, | ||||
14362 | SourceLocation OpLoc, | ||||
14363 | bool IsInc, bool IsPrefix) { | ||||
14364 | if (Op->isTypeDependent()) | ||||
14365 | return S.Context.DependentTy; | ||||
14366 | |||||
14367 | QualType ResType = Op->getType(); | ||||
14368 | // Atomic types can be used for increment / decrement where the non-atomic | ||||
14369 | // versions can, so ignore the _Atomic() specifier for the purpose of | ||||
14370 | // checking. | ||||
14371 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
14372 | ResType = ResAtomicType->getValueType(); | ||||
14373 | |||||
14374 | assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast <bool> (!ResType.isNull() && "no type for increment/decrement expression" ) ? void (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "clang/lib/Sema/SemaExpr.cpp", 14374, __extension__ __PRETTY_FUNCTION__ )); | ||||
14375 | |||||
14376 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | ||||
14377 | // Decrement of bool is not allowed. | ||||
14378 | if (!IsInc) { | ||||
14379 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | ||||
14380 | return QualType(); | ||||
14381 | } | ||||
14382 | // Increment of bool sets it to true, but is deprecated. | ||||
14383 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | ||||
14384 | : diag::warn_increment_bool) | ||||
14385 | << Op->getSourceRange(); | ||||
14386 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | ||||
14387 | // Error on enum increments and decrements in C++ mode | ||||
14388 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | ||||
14389 | return QualType(); | ||||
14390 | } else if (ResType->isRealType()) { | ||||
14391 | // OK! | ||||
14392 | } else if (ResType->isPointerType()) { | ||||
14393 | // C99 6.5.2.4p2, 6.5.6p2 | ||||
14394 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | ||||
14395 | return QualType(); | ||||
14396 | } else if (ResType->isObjCObjectPointerType()) { | ||||
14397 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | ||||
14398 | // Otherwise, we just need a complete type. | ||||
14399 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | ||||
14400 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | ||||
14401 | return QualType(); | ||||
14402 | } else if (ResType->isAnyComplexType()) { | ||||
14403 | // C99 does not support ++/-- on complex types, we allow as an extension. | ||||
14404 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | ||||
14405 | << ResType << Op->getSourceRange(); | ||||
14406 | } else if (ResType->isPlaceholderType()) { | ||||
14407 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
14408 | if (PR.isInvalid()) return QualType(); | ||||
14409 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | ||||
14410 | IsInc, IsPrefix); | ||||
14411 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | ||||
14412 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | ||||
14413 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | ||||
14414 | (ResType->castAs<VectorType>()->getVectorKind() != | ||||
14415 | VectorType::AltiVecBool)) { | ||||
14416 | // The z vector extensions allow ++ and -- for non-bool vectors. | ||||
14417 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | ||||
14418 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | ||||
14419 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | ||||
14420 | } else { | ||||
14421 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | ||||
14422 | << ResType << int(IsInc) << Op->getSourceRange(); | ||||
14423 | return QualType(); | ||||
14424 | } | ||||
14425 | // At this point, we know we have a real, complex or pointer type. | ||||
14426 | // Now make sure the operand is a modifiable lvalue. | ||||
14427 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | ||||
14428 | return QualType(); | ||||
14429 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | ||||
14430 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | ||||
14431 | // An operand with volatile-qualified type is deprecated | ||||
14432 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | ||||
14433 | << IsInc << ResType; | ||||
14434 | } | ||||
14435 | // In C++, a prefix increment is the same type as the operand. Otherwise | ||||
14436 | // (in C or with postfix), the increment is the unqualified type of the | ||||
14437 | // operand. | ||||
14438 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | ||||
14439 | VK = VK_LValue; | ||||
14440 | OK = Op->getObjectKind(); | ||||
14441 | return ResType; | ||||
14442 | } else { | ||||
14443 | VK = VK_PRValue; | ||||
14444 | return ResType.getUnqualifiedType(); | ||||
14445 | } | ||||
14446 | } | ||||
14447 | |||||
14448 | |||||
14449 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | ||||
14450 | /// This routine allows us to typecheck complex/recursive expressions | ||||
14451 | /// where the declaration is needed for type checking. We only need to | ||||
14452 | /// handle cases when the expression references a function designator | ||||
14453 | /// or is an lvalue. Here are some examples: | ||||
14454 | /// - &(x) => x | ||||
14455 | /// - &*****f => f for f a function designator. | ||||
14456 | /// - &s.xx => s | ||||
14457 | /// - &s.zz[1].yy -> s, if zz is an array | ||||
14458 | /// - *(x + 1) -> x, if x is an array | ||||
14459 | /// - &"123"[2] -> 0 | ||||
14460 | /// - & __real__ x -> x | ||||
14461 | /// | ||||
14462 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | ||||
14463 | /// members. | ||||
14464 | static ValueDecl *getPrimaryDecl(Expr *E) { | ||||
14465 | switch (E->getStmtClass()) { | ||||
14466 | case Stmt::DeclRefExprClass: | ||||
14467 | return cast<DeclRefExpr>(E)->getDecl(); | ||||
14468 | case Stmt::MemberExprClass: | ||||
14469 | // If this is an arrow operator, the address is an offset from | ||||
14470 | // the base's value, so the object the base refers to is | ||||
14471 | // irrelevant. | ||||
14472 | if (cast<MemberExpr>(E)->isArrow()) | ||||
14473 | return nullptr; | ||||
14474 | // Otherwise, the expression refers to a part of the base | ||||
14475 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | ||||
14476 | case Stmt::ArraySubscriptExprClass: { | ||||
14477 | // FIXME: This code shouldn't be necessary! We should catch the implicit | ||||
14478 | // promotion of register arrays earlier. | ||||
14479 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | ||||
14480 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | ||||
14481 | if (ICE->getSubExpr()->getType()->isArrayType()) | ||||
14482 | return getPrimaryDecl(ICE->getSubExpr()); | ||||
14483 | } | ||||
14484 | return nullptr; | ||||
14485 | } | ||||
14486 | case Stmt::UnaryOperatorClass: { | ||||
14487 | UnaryOperator *UO = cast<UnaryOperator>(E); | ||||
14488 | |||||
14489 | switch(UO->getOpcode()) { | ||||
14490 | case UO_Real: | ||||
14491 | case UO_Imag: | ||||
14492 | case UO_Extension: | ||||
14493 | return getPrimaryDecl(UO->getSubExpr()); | ||||
14494 | default: | ||||
14495 | return nullptr; | ||||
14496 | } | ||||
14497 | } | ||||
14498 | case Stmt::ParenExprClass: | ||||
14499 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | ||||
14500 | case Stmt::ImplicitCastExprClass: | ||||
14501 | // If the result of an implicit cast is an l-value, we care about | ||||
14502 | // the sub-expression; otherwise, the result here doesn't matter. | ||||
14503 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | ||||
14504 | case Stmt::CXXUuidofExprClass: | ||||
14505 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | ||||
14506 | default: | ||||
14507 | return nullptr; | ||||
14508 | } | ||||
14509 | } | ||||
14510 | |||||
14511 | namespace { | ||||
14512 | enum { | ||||
14513 | AO_Bit_Field = 0, | ||||
14514 | AO_Vector_Element = 1, | ||||
14515 | AO_Property_Expansion = 2, | ||||
14516 | AO_Register_Variable = 3, | ||||
14517 | AO_Matrix_Element = 4, | ||||
14518 | AO_No_Error = 5 | ||||
14519 | }; | ||||
14520 | } | ||||
14521 | /// Diagnose invalid operand for address of operations. | ||||
14522 | /// | ||||
14523 | /// \param Type The type of operand which cannot have its address taken. | ||||
14524 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | ||||
14525 | Expr *E, unsigned Type) { | ||||
14526 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | ||||
14527 | } | ||||
14528 | |||||
14529 | /// CheckAddressOfOperand - The operand of & must be either a function | ||||
14530 | /// designator or an lvalue designating an object. If it is an lvalue, the | ||||
14531 | /// object cannot be declared with storage class register or be a bit field. | ||||
14532 | /// Note: The usual conversions are *not* applied to the operand of the & | ||||
14533 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | ||||
14534 | /// In C++, the operand might be an overloaded function name, in which case | ||||
14535 | /// we allow the '&' but retain the overloaded-function type. | ||||
14536 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | ||||
14537 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | ||||
14538 | if (PTy->getKind() == BuiltinType::Overload) { | ||||
14539 | Expr *E = OrigOp.get()->IgnoreParens(); | ||||
14540 | if (!isa<OverloadExpr>(E)) { | ||||
14541 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode () == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "clang/lib/Sema/SemaExpr.cpp", 14541, __extension__ __PRETTY_FUNCTION__ )); | ||||
14542 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | ||||
14543 | << OrigOp.get()->getSourceRange(); | ||||
14544 | return QualType(); | ||||
14545 | } | ||||
14546 | |||||
14547 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | ||||
14548 | if (isa<UnresolvedMemberExpr>(Ovl)) | ||||
14549 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | ||||
14550 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
14551 | << OrigOp.get()->getSourceRange(); | ||||
14552 | return QualType(); | ||||
14553 | } | ||||
14554 | |||||
14555 | return Context.OverloadTy; | ||||
14556 | } | ||||
14557 | |||||
14558 | if (PTy->getKind() == BuiltinType::UnknownAny) | ||||
14559 | return Context.UnknownAnyTy; | ||||
14560 | |||||
14561 | if (PTy->getKind() == BuiltinType::BoundMember) { | ||||
14562 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
14563 | << OrigOp.get()->getSourceRange(); | ||||
14564 | return QualType(); | ||||
14565 | } | ||||
14566 | |||||
14567 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | ||||
14568 | if (OrigOp.isInvalid()) return QualType(); | ||||
14569 | } | ||||
14570 | |||||
14571 | if (OrigOp.get()->isTypeDependent()) | ||||
14572 | return Context.DependentTy; | ||||
14573 | |||||
14574 | assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType ()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()" , "clang/lib/Sema/SemaExpr.cpp", 14574, __extension__ __PRETTY_FUNCTION__ )); | ||||
14575 | |||||
14576 | // Make sure to ignore parentheses in subsequent checks | ||||
14577 | Expr *op = OrigOp.get()->IgnoreParens(); | ||||
14578 | |||||
14579 | // In OpenCL captures for blocks called as lambda functions | ||||
14580 | // are located in the private address space. Blocks used in | ||||
14581 | // enqueue_kernel can be located in a different address space | ||||
14582 | // depending on a vendor implementation. Thus preventing | ||||
14583 | // taking an address of the capture to avoid invalid AS casts. | ||||
14584 | if (LangOpts.OpenCL) { | ||||
14585 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | ||||
14586 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | ||||
14587 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | ||||
14588 | return QualType(); | ||||
14589 | } | ||||
14590 | } | ||||
14591 | |||||
14592 | if (getLangOpts().C99) { | ||||
14593 | // Implement C99-only parts of addressof rules. | ||||
14594 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | ||||
14595 | if (uOp->getOpcode() == UO_Deref) | ||||
14596 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | ||||
14597 | // (assuming the deref expression is valid). | ||||
14598 | return uOp->getSubExpr()->getType(); | ||||
14599 | } | ||||
14600 | // Technically, there should be a check for array subscript | ||||
14601 | // expressions here, but the result of one is always an lvalue anyway. | ||||
14602 | } | ||||
14603 | ValueDecl *dcl = getPrimaryDecl(op); | ||||
14604 | |||||
14605 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | ||||
14606 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
14607 | op->getBeginLoc())) | ||||
14608 | return QualType(); | ||||
14609 | |||||
14610 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | ||||
14611 | unsigned AddressOfError = AO_No_Error; | ||||
14612 | |||||
14613 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | ||||
14614 | bool sfinae = (bool)isSFINAEContext(); | ||||
14615 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | ||||
14616 | : diag::ext_typecheck_addrof_temporary) | ||||
14617 | << op->getType() << op->getSourceRange(); | ||||
14618 | if (sfinae) | ||||
14619 | return QualType(); | ||||
14620 | // Materialize the temporary as an lvalue so that we can take its address. | ||||
14621 | OrigOp = op = | ||||
14622 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | ||||
14623 | } else if (isa<ObjCSelectorExpr>(op)) { | ||||
14624 | return Context.getPointerType(op->getType()); | ||||
14625 | } else if (lval == Expr::LV_MemberFunction) { | ||||
14626 | // If it's an instance method, make a member pointer. | ||||
14627 | // The expression must have exactly the form &A::foo. | ||||
14628 | |||||
14629 | // If the underlying expression isn't a decl ref, give up. | ||||
14630 | if (!isa<DeclRefExpr>(op)) { | ||||
14631 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
14632 | << OrigOp.get()->getSourceRange(); | ||||
14633 | return QualType(); | ||||
14634 | } | ||||
14635 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | ||||
14636 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | ||||
14637 | |||||
14638 | // The id-expression was parenthesized. | ||||
14639 | if (OrigOp.get() != DRE) { | ||||
14640 | Diag(OpLoc, diag::err_parens_pointer_member_function) | ||||
14641 | << OrigOp.get()->getSourceRange(); | ||||
14642 | |||||
14643 | // The method was named without a qualifier. | ||||
14644 | } else if (!DRE->getQualifier()) { | ||||
14645 | if (MD->getParent()->getName().empty()) | ||||
14646 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
14647 | << op->getSourceRange(); | ||||
14648 | else { | ||||
14649 | SmallString<32> Str; | ||||
14650 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | ||||
14651 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
14652 | << op->getSourceRange() | ||||
14653 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | ||||
14654 | } | ||||
14655 | } | ||||
14656 | |||||
14657 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | ||||
14658 | if (isa<CXXDestructorDecl>(MD)) | ||||
14659 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | ||||
14660 | |||||
14661 | QualType MPTy = Context.getMemberPointerType( | ||||
14662 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | ||||
14663 | // Under the MS ABI, lock down the inheritance model now. | ||||
14664 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
14665 | (void)isCompleteType(OpLoc, MPTy); | ||||
14666 | return MPTy; | ||||
14667 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | ||||
14668 | // C99 6.5.3.2p1 | ||||
14669 | // The operand must be either an l-value or a function designator | ||||
14670 | if (!op->getType()->isFunctionType()) { | ||||
14671 | // Use a special diagnostic for loads from property references. | ||||
14672 | if (isa<PseudoObjectExpr>(op)) { | ||||
14673 | AddressOfError = AO_Property_Expansion; | ||||
14674 | } else { | ||||
14675 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | ||||
14676 | << op->getType() << op->getSourceRange(); | ||||
14677 | return QualType(); | ||||
14678 | } | ||||
14679 | } | ||||
14680 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | ||||
14681 | // The operand cannot be a bit-field | ||||
14682 | AddressOfError = AO_Bit_Field; | ||||
14683 | } else if (op->getObjectKind() == OK_VectorComponent) { | ||||
14684 | // The operand cannot be an element of a vector | ||||
14685 | AddressOfError = AO_Vector_Element; | ||||
14686 | } else if (op->getObjectKind() == OK_MatrixComponent) { | ||||
14687 | // The operand cannot be an element of a matrix. | ||||
14688 | AddressOfError = AO_Matrix_Element; | ||||
14689 | } else if (dcl) { // C99 6.5.3.2p1 | ||||
14690 | // We have an lvalue with a decl. Make sure the decl is not declared | ||||
14691 | // with the register storage-class specifier. | ||||
14692 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | ||||
14693 | // in C++ it is not error to take address of a register | ||||
14694 | // variable (c++03 7.1.1P3) | ||||
14695 | if (vd->getStorageClass() == SC_Register && | ||||
14696 | !getLangOpts().CPlusPlus) { | ||||
14697 | AddressOfError = AO_Register_Variable; | ||||
14698 | } | ||||
14699 | } else if (isa<MSPropertyDecl>(dcl)) { | ||||
14700 | AddressOfError = AO_Property_Expansion; | ||||
14701 | } else if (isa<FunctionTemplateDecl>(dcl)) { | ||||
14702 | return Context.OverloadTy; | ||||
14703 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | ||||
14704 | // Okay: we can take the address of a field. | ||||
14705 | // Could be a pointer to member, though, if there is an explicit | ||||
14706 | // scope qualifier for the class. | ||||
14707 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | ||||
14708 | DeclContext *Ctx = dcl->getDeclContext(); | ||||
14709 | if (Ctx && Ctx->isRecord()) { | ||||
14710 | if (dcl->getType()->isReferenceType()) { | ||||
14711 | Diag(OpLoc, | ||||
14712 | diag::err_cannot_form_pointer_to_member_of_reference_type) | ||||
14713 | << dcl->getDeclName() << dcl->getType(); | ||||
14714 | return QualType(); | ||||
14715 | } | ||||
14716 | |||||
14717 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | ||||
14718 | Ctx = Ctx->getParent(); | ||||
14719 | |||||
14720 | QualType MPTy = Context.getMemberPointerType( | ||||
14721 | op->getType(), | ||||
14722 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | ||||
14723 | // Under the MS ABI, lock down the inheritance model now. | ||||
14724 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
14725 | (void)isCompleteType(OpLoc, MPTy); | ||||
14726 | return MPTy; | ||||
14727 | } | ||||
14728 | } | ||||
14729 | } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, | ||||
14730 | MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) | ||||
14731 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "clang/lib/Sema/SemaExpr.cpp", 14731); | ||||
14732 | } | ||||
14733 | |||||
14734 | if (AddressOfError != AO_No_Error) { | ||||
14735 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | ||||
14736 | return QualType(); | ||||
14737 | } | ||||
14738 | |||||
14739 | if (lval == Expr::LV_IncompleteVoidType) { | ||||
14740 | // Taking the address of a void variable is technically illegal, but we | ||||
14741 | // allow it in cases which are otherwise valid. | ||||
14742 | // Example: "extern void x; void* y = &x;". | ||||
14743 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | ||||
14744 | } | ||||
14745 | |||||
14746 | // If the operand has type "type", the result has type "pointer to type". | ||||
14747 | if (op->getType()->isObjCObjectType()) | ||||
14748 | return Context.getObjCObjectPointerType(op->getType()); | ||||
14749 | |||||
14750 | if (Context.getTargetInfo().getTriple().isWasm() && | ||||
14751 | op->getType()->isWebAssemblyReferenceType()) { | ||||
14752 | Diag(OpLoc, diag::err_wasm_ca_reference) | ||||
14753 | << 1 << OrigOp.get()->getSourceRange(); | ||||
14754 | return QualType(); | ||||
14755 | } | ||||
14756 | |||||
14757 | CheckAddressOfPackedMember(op); | ||||
14758 | |||||
14759 | return Context.getPointerType(op->getType()); | ||||
14760 | } | ||||
14761 | |||||
14762 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | ||||
14763 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | ||||
14764 | if (!DRE) | ||||
14765 | return; | ||||
14766 | const Decl *D = DRE->getDecl(); | ||||
14767 | if (!D) | ||||
14768 | return; | ||||
14769 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | ||||
14770 | if (!Param) | ||||
14771 | return; | ||||
14772 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | ||||
14773 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | ||||
14774 | return; | ||||
14775 | if (FunctionScopeInfo *FD = S.getCurFunction()) | ||||
14776 | FD->ModifiedNonNullParams.insert(Param); | ||||
14777 | } | ||||
14778 | |||||
14779 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | ||||
14780 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | ||||
14781 | SourceLocation OpLoc, | ||||
14782 | bool IsAfterAmp = false) { | ||||
14783 | if (Op->isTypeDependent()) | ||||
14784 | return S.Context.DependentTy; | ||||
14785 | |||||
14786 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | ||||
14787 | if (ConvResult.isInvalid()) | ||||
14788 | return QualType(); | ||||
14789 | Op = ConvResult.get(); | ||||
14790 | QualType OpTy = Op->getType(); | ||||
14791 | QualType Result; | ||||
14792 | |||||
14793 | if (isa<CXXReinterpretCastExpr>(Op)) { | ||||
14794 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | ||||
14795 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | ||||
14796 | Op->getSourceRange()); | ||||
14797 | } | ||||
14798 | |||||
14799 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | ||||
14800 | { | ||||
14801 | Result = PT->getPointeeType(); | ||||
14802 | } | ||||
14803 | else if (const ObjCObjectPointerType *OPT = | ||||
14804 | OpTy->getAs<ObjCObjectPointerType>()) | ||||
14805 | Result = OPT->getPointeeType(); | ||||
14806 | else { | ||||
14807 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
14808 | if (PR.isInvalid()) return QualType(); | ||||
14809 | if (PR.get() != Op) | ||||
14810 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | ||||
14811 | } | ||||
14812 | |||||
14813 | if (Result.isNull()) { | ||||
14814 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | ||||
14815 | << OpTy << Op->getSourceRange(); | ||||
14816 | return QualType(); | ||||
14817 | } | ||||
14818 | |||||
14819 | if (Result->isVoidType()) { | ||||
14820 | // C++ [expr.unary.op]p1: | ||||
14821 | // [...] the expression to which [the unary * operator] is applied shall | ||||
14822 | // be a pointer to an object type, or a pointer to a function type | ||||
14823 | LangOptions LO = S.getLangOpts(); | ||||
14824 | if (LO.CPlusPlus) | ||||
14825 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp) | ||||
14826 | << OpTy << Op->getSourceRange(); | ||||
14827 | else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext()) | ||||
14828 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | ||||
14829 | << OpTy << Op->getSourceRange(); | ||||
14830 | } | ||||
14831 | |||||
14832 | // Dereferences are usually l-values... | ||||
14833 | VK = VK_LValue; | ||||
14834 | |||||
14835 | // ...except that certain expressions are never l-values in C. | ||||
14836 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | ||||
14837 | VK = VK_PRValue; | ||||
14838 | |||||
14839 | return Result; | ||||
14840 | } | ||||
14841 | |||||
14842 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | ||||
14843 | BinaryOperatorKind Opc; | ||||
14844 | switch (Kind) { | ||||
14845 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp" , 14845); | ||||
14846 | case tok::periodstar: Opc = BO_PtrMemD; break; | ||||
14847 | case tok::arrowstar: Opc = BO_PtrMemI; break; | ||||
14848 | case tok::star: Opc = BO_Mul; break; | ||||
14849 | case tok::slash: Opc = BO_Div; break; | ||||
14850 | case tok::percent: Opc = BO_Rem; break; | ||||
14851 | case tok::plus: Opc = BO_Add; break; | ||||
14852 | case tok::minus: Opc = BO_Sub; break; | ||||
14853 | case tok::lessless: Opc = BO_Shl; break; | ||||
14854 | case tok::greatergreater: Opc = BO_Shr; break; | ||||
14855 | case tok::lessequal: Opc = BO_LE; break; | ||||
14856 | case tok::less: Opc = BO_LT; break; | ||||
14857 | case tok::greaterequal: Opc = BO_GE; break; | ||||
14858 | case tok::greater: Opc = BO_GT; break; | ||||
14859 | case tok::exclaimequal: Opc = BO_NE; break; | ||||
14860 | case tok::equalequal: Opc = BO_EQ; break; | ||||
14861 | case tok::spaceship: Opc = BO_Cmp; break; | ||||
14862 | case tok::amp: Opc = BO_And; break; | ||||
14863 | case tok::caret: Opc = BO_Xor; break; | ||||
14864 | case tok::pipe: Opc = BO_Or; break; | ||||
14865 | case tok::ampamp: Opc = BO_LAnd; break; | ||||
14866 | case tok::pipepipe: Opc = BO_LOr; break; | ||||
14867 | case tok::equal: Opc = BO_Assign; break; | ||||
14868 | case tok::starequal: Opc = BO_MulAssign; break; | ||||
14869 | case tok::slashequal: Opc = BO_DivAssign; break; | ||||
14870 | case tok::percentequal: Opc = BO_RemAssign; break; | ||||
14871 | case tok::plusequal: Opc = BO_AddAssign; break; | ||||
14872 | case tok::minusequal: Opc = BO_SubAssign; break; | ||||
14873 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | ||||
14874 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | ||||
14875 | case tok::ampequal: Opc = BO_AndAssign; break; | ||||
14876 | case tok::caretequal: Opc = BO_XorAssign; break; | ||||
14877 | case tok::pipeequal: Opc = BO_OrAssign; break; | ||||
14878 | case tok::comma: Opc = BO_Comma; break; | ||||
14879 | } | ||||
14880 | return Opc; | ||||
14881 | } | ||||
14882 | |||||
14883 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | ||||
14884 | tok::TokenKind Kind) { | ||||
14885 | UnaryOperatorKind Opc; | ||||
14886 | switch (Kind) { | ||||
14887 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp" , 14887); | ||||
14888 | case tok::plusplus: Opc = UO_PreInc; break; | ||||
14889 | case tok::minusminus: Opc = UO_PreDec; break; | ||||
14890 | case tok::amp: Opc = UO_AddrOf; break; | ||||
14891 | case tok::star: Opc = UO_Deref; break; | ||||
14892 | case tok::plus: Opc = UO_Plus; break; | ||||
14893 | case tok::minus: Opc = UO_Minus; break; | ||||
14894 | case tok::tilde: Opc = UO_Not; break; | ||||
14895 | case tok::exclaim: Opc = UO_LNot; break; | ||||
14896 | case tok::kw___real: Opc = UO_Real; break; | ||||
14897 | case tok::kw___imag: Opc = UO_Imag; break; | ||||
14898 | case tok::kw___extension__: Opc = UO_Extension; break; | ||||
14899 | } | ||||
14900 | return Opc; | ||||
14901 | } | ||||
14902 | |||||
14903 | const FieldDecl * | ||||
14904 | Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { | ||||
14905 | // Explore the case for adding 'this->' to the LHS of a self assignment, very | ||||
14906 | // common for setters. | ||||
14907 | // struct A { | ||||
14908 | // int X; | ||||
14909 | // -void setX(int X) { X = X; } | ||||
14910 | // +void setX(int X) { this->X = X; } | ||||
14911 | // }; | ||||
14912 | |||||
14913 | // Only consider parameters for self assignment fixes. | ||||
14914 | if (!isa<ParmVarDecl>(SelfAssigned)) | ||||
14915 | return nullptr; | ||||
14916 | const auto *Method = | ||||
14917 | dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true)); | ||||
14918 | if (!Method) | ||||
14919 | return nullptr; | ||||
14920 | |||||
14921 | const CXXRecordDecl *Parent = Method->getParent(); | ||||
14922 | // In theory this is fixable if the lambda explicitly captures this, but | ||||
14923 | // that's added complexity that's rarely going to be used. | ||||
14924 | if (Parent->isLambda()) | ||||
14925 | return nullptr; | ||||
14926 | |||||
14927 | // FIXME: Use an actual Lookup operation instead of just traversing fields | ||||
14928 | // in order to get base class fields. | ||||
14929 | auto Field = | ||||
14930 | llvm::find_if(Parent->fields(), | ||||
14931 | [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { | ||||
14932 | return F->getDeclName() == Name; | ||||
14933 | }); | ||||
14934 | return (Field != Parent->field_end()) ? *Field : nullptr; | ||||
14935 | } | ||||
14936 | |||||
14937 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | ||||
14938 | /// This warning suppressed in the event of macro expansions. | ||||
14939 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | ||||
14940 | SourceLocation OpLoc, bool IsBuiltin) { | ||||
14941 | if (S.inTemplateInstantiation()) | ||||
14942 | return; | ||||
14943 | if (S.isUnevaluatedContext()) | ||||
14944 | return; | ||||
14945 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | ||||
14946 | return; | ||||
14947 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | ||||
14948 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | ||||
14949 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | ||||
14950 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | ||||
14951 | if (!LHSDeclRef || !RHSDeclRef || | ||||
14952 | LHSDeclRef->getLocation().isMacroID() || | ||||
14953 | RHSDeclRef->getLocation().isMacroID()) | ||||
14954 | return; | ||||
14955 | const ValueDecl *LHSDecl = | ||||
14956 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
14957 | const ValueDecl *RHSDecl = | ||||
14958 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
14959 | if (LHSDecl != RHSDecl) | ||||
14960 | return; | ||||
14961 | if (LHSDecl->getType().isVolatileQualified()) | ||||
14962 | return; | ||||
14963 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
14964 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
14965 | return; | ||||
14966 | |||||
14967 | auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | ||||
14968 | : diag::warn_self_assignment_overloaded) | ||||
14969 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | ||||
14970 | << RHSExpr->getSourceRange(); | ||||
14971 | if (const FieldDecl *SelfAssignField = | ||||
14972 | S.getSelfAssignmentClassMemberCandidate(RHSDecl)) | ||||
14973 | Diag << 1 << SelfAssignField | ||||
14974 | << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); | ||||
14975 | else | ||||
14976 | Diag << 0; | ||||
14977 | } | ||||
14978 | |||||
14979 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | ||||
14980 | /// is usually indicative of introspection within the Objective-C pointer. | ||||
14981 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | ||||
14982 | SourceLocation OpLoc) { | ||||
14983 | if (!S.getLangOpts().ObjC) | ||||
14984 | return; | ||||
14985 | |||||
14986 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | ||||
14987 | const Expr *LHS = L.get(); | ||||
14988 | const Expr *RHS = R.get(); | ||||
14989 | |||||
14990 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
14991 | ObjCPointerExpr = LHS; | ||||
14992 | OtherExpr = RHS; | ||||
14993 | } | ||||
14994 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
14995 | ObjCPointerExpr = RHS; | ||||
14996 | OtherExpr = LHS; | ||||
14997 | } | ||||
14998 | |||||
14999 | // This warning is deliberately made very specific to reduce false | ||||
15000 | // positives with logic that uses '&' for hashing. This logic mainly | ||||
15001 | // looks for code trying to introspect into tagged pointers, which | ||||
15002 | // code should generally never do. | ||||
15003 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | ||||
15004 | unsigned Diag = diag::warn_objc_pointer_masking; | ||||
15005 | // Determine if we are introspecting the result of performSelectorXXX. | ||||
15006 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | ||||
15007 | // Special case messages to -performSelector and friends, which | ||||
15008 | // can return non-pointer values boxed in a pointer value. | ||||
15009 | // Some clients may wish to silence warnings in this subcase. | ||||
15010 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | ||||
15011 | Selector S = ME->getSelector(); | ||||
15012 | StringRef SelArg0 = S.getNameForSlot(0); | ||||
15013 | if (SelArg0.startswith("performSelector")) | ||||
15014 | Diag = diag::warn_objc_pointer_masking_performSelector; | ||||
15015 | } | ||||
15016 | |||||
15017 | S.Diag(OpLoc, Diag) | ||||
15018 | << ObjCPointerExpr->getSourceRange(); | ||||
15019 | } | ||||
15020 | } | ||||
15021 | |||||
15022 | static NamedDecl *getDeclFromExpr(Expr *E) { | ||||
15023 | if (!E) | ||||
15024 | return nullptr; | ||||
15025 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
15026 | return DRE->getDecl(); | ||||
15027 | if (auto *ME = dyn_cast<MemberExpr>(E)) | ||||
15028 | return ME->getMemberDecl(); | ||||
15029 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | ||||
15030 | return IRE->getDecl(); | ||||
15031 | return nullptr; | ||||
15032 | } | ||||
15033 | |||||
15034 | // This helper function promotes a binary operator's operands (which are of a | ||||
15035 | // half vector type) to a vector of floats and then truncates the result to | ||||
15036 | // a vector of either half or short. | ||||
15037 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | ||||
15038 | BinaryOperatorKind Opc, QualType ResultTy, | ||||
15039 | ExprValueKind VK, ExprObjectKind OK, | ||||
15040 | bool IsCompAssign, SourceLocation OpLoc, | ||||
15041 | FPOptionsOverride FPFeatures) { | ||||
15042 | auto &Context = S.getASTContext(); | ||||
15043 | assert((isVector(ResultTy, Context.HalfTy) ||(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 15045, __extension__ __PRETTY_FUNCTION__ )) | ||||
15044 | isVector(ResultTy, Context.ShortTy)) &&(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 15045, __extension__ __PRETTY_FUNCTION__ )) | ||||
15045 | "Result must be a vector of half or short")(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 15045, __extension__ __PRETTY_FUNCTION__ )); | ||||
15046 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 15048, __extension__ __PRETTY_FUNCTION__ )) | ||||
15047 | isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 15048, __extension__ __PRETTY_FUNCTION__ )) | ||||
15048 | "both operands expected to be a half vector")(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 15048, __extension__ __PRETTY_FUNCTION__ )); | ||||
15049 | |||||
15050 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | ||||
15051 | QualType BinOpResTy = RHS.get()->getType(); | ||||
15052 | |||||
15053 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | ||||
15054 | // change BinOpResTy to a vector of ints. | ||||
15055 | if (isVector(ResultTy, Context.ShortTy)) | ||||
15056 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | ||||
15057 | |||||
15058 | if (IsCompAssign) | ||||
15059 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
15060 | ResultTy, VK, OK, OpLoc, FPFeatures, | ||||
15061 | BinOpResTy, BinOpResTy); | ||||
15062 | |||||
15063 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | ||||
15064 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
15065 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | ||||
15066 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | ||||
15067 | } | ||||
15068 | |||||
15069 | static std::pair<ExprResult, ExprResult> | ||||
15070 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | ||||
15071 | Expr *RHSExpr) { | ||||
15072 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
15073 | if (!S.Context.isDependenceAllowed()) { | ||||
15074 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
15075 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
15076 | // been dealt with before checking the operands. | ||||
15077 | LHS = S.CorrectDelayedTyposInExpr(LHS); | ||||
15078 | RHS = S.CorrectDelayedTyposInExpr( | ||||
15079 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | ||||
15080 | [Opc, LHS](Expr *E) { | ||||
15081 | if (Opc != BO_Assign) | ||||
15082 | return ExprResult(E); | ||||
15083 | // Avoid correcting the RHS to the same Expr as the LHS. | ||||
15084 | Decl *D = getDeclFromExpr(E); | ||||
15085 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | ||||
15086 | }); | ||||
15087 | } | ||||
15088 | return std::make_pair(LHS, RHS); | ||||
15089 | } | ||||
15090 | |||||
15091 | /// Returns true if conversion between vectors of halfs and vectors of floats | ||||
15092 | /// is needed. | ||||
15093 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | ||||
15094 | Expr *E0, Expr *E1 = nullptr) { | ||||
15095 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | ||||
15096 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | ||||
15097 | return false; | ||||
15098 | |||||
15099 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | ||||
15100 | QualType Ty = E->IgnoreImplicit()->getType(); | ||||
15101 | |||||
15102 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | ||||
15103 | // to vectors of floats. Although the element type of the vectors is __fp16, | ||||
15104 | // the vectors shouldn't be treated as storage-only types. See the | ||||
15105 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | ||||
15106 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | ||||
15107 | if (VT->getVectorKind() == VectorType::NeonVector) | ||||
15108 | return false; | ||||
15109 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | ||||
15110 | } | ||||
15111 | return false; | ||||
15112 | }; | ||||
15113 | |||||
15114 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | ||||
15115 | } | ||||
15116 | |||||
15117 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | ||||
15118 | /// operator @p Opc at location @c TokLoc. This routine only supports | ||||
15119 | /// built-in operations; ActOnBinOp handles overloaded operators. | ||||
15120 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | ||||
15121 | BinaryOperatorKind Opc, | ||||
15122 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15123 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | ||||
15124 | // The syntax only allows initializer lists on the RHS of assignment, | ||||
15125 | // so we don't need to worry about accepting invalid code for | ||||
15126 | // non-assignment operators. | ||||
15127 | // C++11 5.17p9: | ||||
15128 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | ||||
15129 | // of x = {} is x = T(). | ||||
15130 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
15131 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
15132 | InitializedEntity Entity = | ||||
15133 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | ||||
15134 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | ||||
15135 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | ||||
15136 | if (Init.isInvalid()) | ||||
15137 | return Init; | ||||
15138 | RHSExpr = Init.get(); | ||||
15139 | } | ||||
15140 | |||||
15141 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
15142 | QualType ResultTy; // Result type of the binary operator. | ||||
15143 | // The following two variables are used for compound assignment operators | ||||
15144 | QualType CompLHSTy; // Type of LHS after promotions for computation | ||||
15145 | QualType CompResultTy; // Type of computation result | ||||
15146 | ExprValueKind VK = VK_PRValue; | ||||
15147 | ExprObjectKind OK = OK_Ordinary; | ||||
15148 | bool ConvertHalfVec = false; | ||||
15149 | |||||
15150 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
15151 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
15152 | return ExprError(); | ||||
15153 | |||||
15154 | if (getLangOpts().OpenCL) { | ||||
15155 | QualType LHSTy = LHSExpr->getType(); | ||||
15156 | QualType RHSTy = RHSExpr->getType(); | ||||
15157 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | ||||
15158 | // the ATOMIC_VAR_INIT macro. | ||||
15159 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | ||||
15160 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
15161 | if (BO_Assign == Opc) | ||||
15162 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | ||||
15163 | else | ||||
15164 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
15165 | return ExprError(); | ||||
15166 | } | ||||
15167 | |||||
15168 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
15169 | // only with a builtin functions and therefore should be disallowed here. | ||||
15170 | if (LHSTy->isImageType() || RHSTy->isImageType() || | ||||
15171 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | ||||
15172 | LHSTy->isPipeType() || RHSTy->isPipeType() || | ||||
15173 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | ||||
15174 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
15175 | return ExprError(); | ||||
15176 | } | ||||
15177 | } | ||||
15178 | |||||
15179 | checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); | ||||
15180 | checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); | ||||
15181 | |||||
15182 | switch (Opc) { | ||||
15183 | case BO_Assign: | ||||
15184 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc); | ||||
15185 | if (getLangOpts().CPlusPlus && | ||||
15186 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | ||||
15187 | VK = LHS.get()->getValueKind(); | ||||
15188 | OK = LHS.get()->getObjectKind(); | ||||
15189 | } | ||||
15190 | if (!ResultTy.isNull()) { | ||||
15191 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
15192 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | ||||
15193 | |||||
15194 | // Avoid copying a block to the heap if the block is assigned to a local | ||||
15195 | // auto variable that is declared in the same scope as the block. This | ||||
15196 | // optimization is unsafe if the local variable is declared in an outer | ||||
15197 | // scope. For example: | ||||
15198 | // | ||||
15199 | // BlockTy b; | ||||
15200 | // { | ||||
15201 | // b = ^{...}; | ||||
15202 | // } | ||||
15203 | // // It is unsafe to invoke the block here if it wasn't copied to the | ||||
15204 | // // heap. | ||||
15205 | // b(); | ||||
15206 | |||||
15207 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | ||||
15208 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | ||||
15209 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | ||||
15210 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | ||||
15211 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||
15212 | |||||
15213 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
15214 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | ||||
15215 | NTCUC_Assignment, NTCUK_Copy); | ||||
15216 | } | ||||
15217 | RecordModifiableNonNullParam(*this, LHS.get()); | ||||
15218 | break; | ||||
15219 | case BO_PtrMemD: | ||||
15220 | case BO_PtrMemI: | ||||
15221 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | ||||
15222 | Opc == BO_PtrMemI); | ||||
15223 | break; | ||||
15224 | case BO_Mul: | ||||
15225 | case BO_Div: | ||||
15226 | ConvertHalfVec = true; | ||||
15227 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | ||||
15228 | Opc == BO_Div); | ||||
15229 | break; | ||||
15230 | case BO_Rem: | ||||
15231 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | ||||
15232 | break; | ||||
15233 | case BO_Add: | ||||
15234 | ConvertHalfVec = true; | ||||
15235 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | ||||
15236 | break; | ||||
15237 | case BO_Sub: | ||||
15238 | ConvertHalfVec = true; | ||||
15239 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | ||||
15240 | break; | ||||
15241 | case BO_Shl: | ||||
15242 | case BO_Shr: | ||||
15243 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | ||||
15244 | break; | ||||
15245 | case BO_LE: | ||||
15246 | case BO_LT: | ||||
15247 | case BO_GE: | ||||
15248 | case BO_GT: | ||||
15249 | ConvertHalfVec = true; | ||||
15250 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
15251 | break; | ||||
15252 | case BO_EQ: | ||||
15253 | case BO_NE: | ||||
15254 | ConvertHalfVec = true; | ||||
15255 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
15256 | break; | ||||
15257 | case BO_Cmp: | ||||
15258 | ConvertHalfVec = true; | ||||
15259 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
15260 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast <bool> (ResultTy.isNull() || ResultTy-> getAsCXXRecordDecl()) ? void (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "clang/lib/Sema/SemaExpr.cpp", 15260, __extension__ __PRETTY_FUNCTION__ )); | ||||
15261 | break; | ||||
15262 | case BO_And: | ||||
15263 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | ||||
15264 | [[fallthrough]]; | ||||
15265 | case BO_Xor: | ||||
15266 | case BO_Or: | ||||
15267 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
15268 | break; | ||||
15269 | case BO_LAnd: | ||||
15270 | case BO_LOr: | ||||
15271 | ConvertHalfVec = true; | ||||
15272 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | ||||
15273 | break; | ||||
15274 | case BO_MulAssign: | ||||
15275 | case BO_DivAssign: | ||||
15276 | ConvertHalfVec = true; | ||||
15277 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | ||||
15278 | Opc == BO_DivAssign); | ||||
15279 | CompLHSTy = CompResultTy; | ||||
15280 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15281 | ResultTy = | ||||
15282 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15283 | break; | ||||
15284 | case BO_RemAssign: | ||||
15285 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | ||||
15286 | CompLHSTy = CompResultTy; | ||||
15287 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15288 | ResultTy = | ||||
15289 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15290 | break; | ||||
15291 | case BO_AddAssign: | ||||
15292 | ConvertHalfVec = true; | ||||
15293 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | ||||
15294 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15295 | ResultTy = | ||||
15296 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15297 | break; | ||||
15298 | case BO_SubAssign: | ||||
15299 | ConvertHalfVec = true; | ||||
15300 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | ||||
15301 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15302 | ResultTy = | ||||
15303 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15304 | break; | ||||
15305 | case BO_ShlAssign: | ||||
15306 | case BO_ShrAssign: | ||||
15307 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | ||||
15308 | CompLHSTy = CompResultTy; | ||||
15309 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15310 | ResultTy = | ||||
15311 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15312 | break; | ||||
15313 | case BO_AndAssign: | ||||
15314 | case BO_OrAssign: // fallthrough | ||||
15315 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
15316 | [[fallthrough]]; | ||||
15317 | case BO_XorAssign: | ||||
15318 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
15319 | CompLHSTy = CompResultTy; | ||||
15320 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15321 | ResultTy = | ||||
15322 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15323 | break; | ||||
15324 | case BO_Comma: | ||||
15325 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | ||||
15326 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | ||||
15327 | VK = RHS.get()->getValueKind(); | ||||
15328 | OK = RHS.get()->getObjectKind(); | ||||
15329 | } | ||||
15330 | break; | ||||
15331 | } | ||||
15332 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | ||||
15333 | return ExprError(); | ||||
15334 | |||||
15335 | // Some of the binary operations require promoting operands of half vector to | ||||
15336 | // float vectors and truncating the result back to half vector. For now, we do | ||||
15337 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | ||||
15338 | // arm64). | ||||
15339 | assert((static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 15342, __extension__ __PRETTY_FUNCTION__ )) | ||||
15340 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 15342, __extension__ __PRETTY_FUNCTION__ )) | ||||
15341 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 15342, __extension__ __PRETTY_FUNCTION__ )) | ||||
15342 | "both sides are half vectors or neither sides are")(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "clang/lib/Sema/SemaExpr.cpp", 15342, __extension__ __PRETTY_FUNCTION__ )); | ||||
15343 | ConvertHalfVec = | ||||
15344 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | ||||
15345 | |||||
15346 | // Check for array bounds violations for both sides of the BinaryOperator | ||||
15347 | CheckArrayAccess(LHS.get()); | ||||
15348 | CheckArrayAccess(RHS.get()); | ||||
15349 | |||||
15350 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | ||||
15351 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | ||||
15352 | &Context.Idents.get("object_setClass"), | ||||
15353 | SourceLocation(), LookupOrdinaryName); | ||||
15354 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | ||||
15355 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
15356 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | ||||
15357 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | ||||
15358 | "object_setClass(") | ||||
15359 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | ||||
15360 | ",") | ||||
15361 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
15362 | } | ||||
15363 | else | ||||
15364 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | ||||
15365 | } | ||||
15366 | else if (const ObjCIvarRefExpr *OIRE = | ||||
15367 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | ||||
15368 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | ||||
15369 | |||||
15370 | // Opc is not a compound assignment if CompResultTy is null. | ||||
15371 | if (CompResultTy.isNull()) { | ||||
15372 | if (ConvertHalfVec) | ||||
15373 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | ||||
15374 | OpLoc, CurFPFeatureOverrides()); | ||||
15375 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | ||||
15376 | VK, OK, OpLoc, CurFPFeatureOverrides()); | ||||
15377 | } | ||||
15378 | |||||
15379 | // Handle compound assignments. | ||||
15380 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | ||||
15381 | OK_ObjCProperty) { | ||||
15382 | VK = VK_LValue; | ||||
15383 | OK = LHS.get()->getObjectKind(); | ||||
15384 | } | ||||
15385 | |||||
15386 | // The LHS is not converted to the result type for fixed-point compound | ||||
15387 | // assignment as the common type is computed on demand. Reset the CompLHSTy | ||||
15388 | // to the LHS type we would have gotten after unary conversions. | ||||
15389 | if (CompResultTy->isFixedPointType()) | ||||
15390 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | ||||
15391 | |||||
15392 | if (ConvertHalfVec) | ||||
15393 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | ||||
15394 | OpLoc, CurFPFeatureOverrides()); | ||||
15395 | |||||
15396 | return CompoundAssignOperator::Create( | ||||
15397 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | ||||
15398 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | ||||
15399 | } | ||||
15400 | |||||
15401 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | ||||
15402 | /// operators are mixed in a way that suggests that the programmer forgot that | ||||
15403 | /// comparison operators have higher precedence. The most typical example of | ||||
15404 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | ||||
15405 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
15406 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
15407 | Expr *RHSExpr) { | ||||
15408 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | ||||
15409 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | ||||
15410 | |||||
15411 | // Check that one of the sides is a comparison operator and the other isn't. | ||||
15412 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | ||||
15413 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | ||||
15414 | if (isLeftComp == isRightComp) | ||||
15415 | return; | ||||
15416 | |||||
15417 | // Bitwise operations are sometimes used as eager logical ops. | ||||
15418 | // Don't diagnose this. | ||||
15419 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | ||||
15420 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | ||||
15421 | if (isLeftBitwise || isRightBitwise) | ||||
15422 | return; | ||||
15423 | |||||
15424 | SourceRange DiagRange = isLeftComp | ||||
15425 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | ||||
15426 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | ||||
15427 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | ||||
15428 | SourceRange ParensRange = | ||||
15429 | isLeftComp | ||||
15430 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | ||||
15431 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | ||||
15432 | |||||
15433 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | ||||
15434 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | ||||
15435 | SuggestParentheses(Self, OpLoc, | ||||
15436 | Self.PDiag(diag::note_precedence_silence) << OpStr, | ||||
15437 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | ||||
15438 | SuggestParentheses(Self, OpLoc, | ||||
15439 | Self.PDiag(diag::note_precedence_bitwise_first) | ||||
15440 | << BinaryOperator::getOpcodeStr(Opc), | ||||
15441 | ParensRange); | ||||
15442 | } | ||||
15443 | |||||
15444 | /// It accepts a '&&' expr that is inside a '||' one. | ||||
15445 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | ||||
15446 | /// in parentheses. | ||||
15447 | static void | ||||
15448 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | ||||
15449 | BinaryOperator *Bop) { | ||||
15450 | assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void (0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "clang/lib/Sema/SemaExpr.cpp" , 15450, __extension__ __PRETTY_FUNCTION__)); | ||||
15451 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | ||||
15452 | << Bop->getSourceRange() << OpLoc; | ||||
15453 | SuggestParentheses(Self, Bop->getOperatorLoc(), | ||||
15454 | Self.PDiag(diag::note_precedence_silence) | ||||
15455 | << Bop->getOpcodeStr(), | ||||
15456 | Bop->getSourceRange()); | ||||
15457 | } | ||||
15458 | |||||
15459 | /// Look for '&&' in the left hand of a '||' expr. | ||||
15460 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | ||||
15461 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15462 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | ||||
15463 | if (Bop->getOpcode() == BO_LAnd) { | ||||
15464 | // If it's "string_literal && a || b" don't warn since the precedence | ||||
15465 | // doesn't matter. | ||||
15466 | if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts())) | ||||
15467 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
15468 | } else if (Bop->getOpcode() == BO_LOr) { | ||||
15469 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | ||||
15470 | // If it's "a || b && string_literal || c" we didn't warn earlier for | ||||
15471 | // "a || b && string_literal", but warn now. | ||||
15472 | if (RBop->getOpcode() == BO_LAnd && | ||||
15473 | isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts())) | ||||
15474 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | ||||
15475 | } | ||||
15476 | } | ||||
15477 | } | ||||
15478 | } | ||||
15479 | |||||
15480 | /// Look for '&&' in the right hand of a '||' expr. | ||||
15481 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | ||||
15482 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15483 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | ||||
15484 | if (Bop->getOpcode() == BO_LAnd) { | ||||
15485 | // If it's "a || b && string_literal" don't warn since the precedence | ||||
15486 | // doesn't matter. | ||||
15487 | if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts())) | ||||
15488 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
15489 | } | ||||
15490 | } | ||||
15491 | } | ||||
15492 | |||||
15493 | /// Look for bitwise op in the left or right hand of a bitwise op with | ||||
15494 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | ||||
15495 | /// the '&' expression in parentheses. | ||||
15496 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | ||||
15497 | SourceLocation OpLoc, Expr *SubExpr) { | ||||
15498 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
15499 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | ||||
15500 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | ||||
15501 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | ||||
15502 | << Bop->getSourceRange() << OpLoc; | ||||
15503 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
15504 | S.PDiag(diag::note_precedence_silence) | ||||
15505 | << Bop->getOpcodeStr(), | ||||
15506 | Bop->getSourceRange()); | ||||
15507 | } | ||||
15508 | } | ||||
15509 | } | ||||
15510 | |||||
15511 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | ||||
15512 | Expr *SubExpr, StringRef Shift) { | ||||
15513 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
15514 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | ||||
15515 | StringRef Op = Bop->getOpcodeStr(); | ||||
15516 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | ||||
15517 | << Bop->getSourceRange() << OpLoc << Shift << Op; | ||||
15518 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
15519 | S.PDiag(diag::note_precedence_silence) << Op, | ||||
15520 | Bop->getSourceRange()); | ||||
15521 | } | ||||
15522 | } | ||||
15523 | } | ||||
15524 | |||||
15525 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | ||||
15526 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15527 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | ||||
15528 | if (!OCE) | ||||
15529 | return; | ||||
15530 | |||||
15531 | FunctionDecl *FD = OCE->getDirectCallee(); | ||||
15532 | if (!FD || !FD->isOverloadedOperator()) | ||||
15533 | return; | ||||
15534 | |||||
15535 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | ||||
15536 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | ||||
15537 | return; | ||||
15538 | |||||
15539 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | ||||
15540 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | ||||
15541 | << (Kind == OO_LessLess); | ||||
15542 | SuggestParentheses(S, OCE->getOperatorLoc(), | ||||
15543 | S.PDiag(diag::note_precedence_silence) | ||||
15544 | << (Kind == OO_LessLess ? "<<" : ">>"), | ||||
15545 | OCE->getSourceRange()); | ||||
15546 | SuggestParentheses( | ||||
15547 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | ||||
15548 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
15549 | } | ||||
15550 | |||||
15551 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | ||||
15552 | /// precedence. | ||||
15553 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
15554 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
15555 | Expr *RHSExpr){ | ||||
15556 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | ||||
15557 | if (BinaryOperator::isBitwiseOp(Opc)) | ||||
15558 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | ||||
15559 | |||||
15560 | // Diagnose "arg1 & arg2 | arg3" | ||||
15561 | if ((Opc == BO_Or || Opc == BO_Xor) && | ||||
15562 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
15563 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | ||||
15564 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | ||||
15565 | } | ||||
15566 | |||||
15567 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | ||||
15568 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | ||||
15569 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
15570 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
15571 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
15572 | } | ||||
15573 | |||||
15574 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | ||||
15575 | || Opc == BO_Shr) { | ||||
15576 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | ||||
15577 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | ||||
15578 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | ||||
15579 | } | ||||
15580 | |||||
15581 | // Warn on overloaded shift operators and comparisons, such as: | ||||
15582 | // cout << 5 == 4; | ||||
15583 | if (BinaryOperator::isComparisonOp(Opc)) | ||||
15584 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | ||||
15585 | } | ||||
15586 | |||||
15587 | // Binary Operators. 'Tok' is the token for the operator. | ||||
15588 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | ||||
15589 | tok::TokenKind Kind, | ||||
15590 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15591 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | ||||
15592 | assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression" ) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "clang/lib/Sema/SemaExpr.cpp", 15592, __extension__ __PRETTY_FUNCTION__ )); | ||||
15593 | assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression" ) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "clang/lib/Sema/SemaExpr.cpp", 15593, __extension__ __PRETTY_FUNCTION__ )); | ||||
15594 | |||||
15595 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | ||||
15596 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | ||||
15597 | |||||
15598 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | ||||
15599 | } | ||||
15600 | |||||
15601 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | ||||
15602 | UnresolvedSetImpl &Functions) { | ||||
15603 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | ||||
15604 | if (OverOp != OO_None && OverOp != OO_Equal) | ||||
15605 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
15606 | |||||
15607 | // In C++20 onwards, we may have a second operator to look up. | ||||
15608 | if (getLangOpts().CPlusPlus20) { | ||||
15609 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | ||||
15610 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | ||||
15611 | } | ||||
15612 | } | ||||
15613 | |||||
15614 | /// Build an overloaded binary operator expression in the given scope. | ||||
15615 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | ||||
15616 | BinaryOperatorKind Opc, | ||||
15617 | Expr *LHS, Expr *RHS) { | ||||
15618 | switch (Opc) { | ||||
15619 | case BO_Assign: | ||||
15620 | case BO_DivAssign: | ||||
15621 | case BO_RemAssign: | ||||
15622 | case BO_SubAssign: | ||||
15623 | case BO_AndAssign: | ||||
15624 | case BO_OrAssign: | ||||
15625 | case BO_XorAssign: | ||||
15626 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | ||||
15627 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | ||||
15628 | break; | ||||
15629 | default: | ||||
15630 | break; | ||||
15631 | } | ||||
15632 | |||||
15633 | // Find all of the overloaded operators visible from this point. | ||||
15634 | UnresolvedSet<16> Functions; | ||||
15635 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | ||||
15636 | |||||
15637 | // Build the (potentially-overloaded, potentially-dependent) | ||||
15638 | // binary operation. | ||||
15639 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | ||||
15640 | } | ||||
15641 | |||||
15642 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | ||||
15643 | BinaryOperatorKind Opc, | ||||
15644 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15645 | ExprResult LHS, RHS; | ||||
15646 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
15647 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
15648 | return ExprError(); | ||||
15649 | LHSExpr = LHS.get(); | ||||
15650 | RHSExpr = RHS.get(); | ||||
15651 | |||||
15652 | // We want to end up calling one of checkPseudoObjectAssignment | ||||
15653 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | ||||
15654 | // both expressions are overloadable or either is type-dependent), | ||||
15655 | // or CreateBuiltinBinOp (in any other case). We also want to get | ||||
15656 | // any placeholder types out of the way. | ||||
15657 | |||||
15658 | // Handle pseudo-objects in the LHS. | ||||
15659 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | ||||
15660 | // Assignments with a pseudo-object l-value need special analysis. | ||||
15661 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
15662 | BinaryOperator::isAssignmentOp(Opc)) | ||||
15663 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15664 | |||||
15665 | // Don't resolve overloads if the other type is overloadable. | ||||
15666 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | ||||
15667 | // We can't actually test that if we still have a placeholder, | ||||
15668 | // though. Fortunately, none of the exceptions we see in that | ||||
15669 | // code below are valid when the LHS is an overload set. Note | ||||
15670 | // that an overload set can be dependently-typed, but it never | ||||
15671 | // instantiates to having an overloadable type. | ||||
15672 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
15673 | if (resolvedRHS.isInvalid()) return ExprError(); | ||||
15674 | RHSExpr = resolvedRHS.get(); | ||||
15675 | |||||
15676 | if (RHSExpr->isTypeDependent() || | ||||
15677 | RHSExpr->getType()->isOverloadableType()) | ||||
15678 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15679 | } | ||||
15680 | |||||
15681 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | ||||
15682 | // template, diagnose the missing 'template' keyword instead of diagnosing | ||||
15683 | // an invalid use of a bound member function. | ||||
15684 | // | ||||
15685 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | ||||
15686 | // to C++1z [over.over]/1.4, but we already checked for that case above. | ||||
15687 | if (Opc == BO_LT && inTemplateInstantiation() && | ||||
15688 | (pty->getKind() == BuiltinType::BoundMember || | ||||
15689 | pty->getKind() == BuiltinType::Overload)) { | ||||
15690 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | ||||
15691 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | ||||
15692 | llvm::any_of(OE->decls(), [](NamedDecl *ND) { | ||||
15693 | return isa<FunctionTemplateDecl>(ND); | ||||
15694 | })) { | ||||
15695 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | ||||
15696 | : OE->getNameLoc(), | ||||
15697 | diag::err_template_kw_missing) | ||||
15698 | << OE->getName().getAsString() << ""; | ||||
15699 | return ExprError(); | ||||
15700 | } | ||||
15701 | } | ||||
15702 | |||||
15703 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | ||||
15704 | if (LHS.isInvalid()) return ExprError(); | ||||
15705 | LHSExpr = LHS.get(); | ||||
15706 | } | ||||
15707 | |||||
15708 | // Handle pseudo-objects in the RHS. | ||||
15709 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | ||||
15710 | // An overload in the RHS can potentially be resolved by the type | ||||
15711 | // being assigned to. | ||||
15712 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | ||||
15713 | if (getLangOpts().CPlusPlus && | ||||
15714 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | ||||
15715 | LHSExpr->getType()->isOverloadableType())) | ||||
15716 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15717 | |||||
15718 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15719 | } | ||||
15720 | |||||
15721 | // Don't resolve overloads if the other type is overloadable. | ||||
15722 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | ||||
15723 | LHSExpr->getType()->isOverloadableType()) | ||||
15724 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15725 | |||||
15726 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
15727 | if (!resolvedRHS.isUsable()) return ExprError(); | ||||
15728 | RHSExpr = resolvedRHS.get(); | ||||
15729 | } | ||||
15730 | |||||
15731 | if (getLangOpts().CPlusPlus) { | ||||
15732 | // If either expression is type-dependent, always build an | ||||
15733 | // overloaded op. | ||||
15734 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | ||||
15735 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15736 | |||||
15737 | // Otherwise, build an overloaded op if either expression has an | ||||
15738 | // overloadable type. | ||||
15739 | if (LHSExpr->getType()->isOverloadableType() || | ||||
15740 | RHSExpr->getType()->isOverloadableType()) | ||||
15741 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15742 | } | ||||
15743 | |||||
15744 | if (getLangOpts().RecoveryAST && | ||||
15745 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | ||||
15746 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 15746, __extension__ __PRETTY_FUNCTION__)); | ||||
15747 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 15748, __extension__ __PRETTY_FUNCTION__ )) | ||||
15748 | "Should only occur in error-recovery path.")(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 15748, __extension__ __PRETTY_FUNCTION__ )); | ||||
15749 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | ||||
15750 | // C [6.15.16] p3: | ||||
15751 | // An assignment expression has the value of the left operand after the | ||||
15752 | // assignment, but is not an lvalue. | ||||
15753 | return CompoundAssignOperator::Create( | ||||
15754 | Context, LHSExpr, RHSExpr, Opc, | ||||
15755 | LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, | ||||
15756 | OpLoc, CurFPFeatureOverrides()); | ||||
15757 | QualType ResultType; | ||||
15758 | switch (Opc) { | ||||
15759 | case BO_Assign: | ||||
15760 | ResultType = LHSExpr->getType().getUnqualifiedType(); | ||||
15761 | break; | ||||
15762 | case BO_LT: | ||||
15763 | case BO_GT: | ||||
15764 | case BO_LE: | ||||
15765 | case BO_GE: | ||||
15766 | case BO_EQ: | ||||
15767 | case BO_NE: | ||||
15768 | case BO_LAnd: | ||||
15769 | case BO_LOr: | ||||
15770 | // These operators have a fixed result type regardless of operands. | ||||
15771 | ResultType = Context.IntTy; | ||||
15772 | break; | ||||
15773 | case BO_Comma: | ||||
15774 | ResultType = RHSExpr->getType(); | ||||
15775 | break; | ||||
15776 | default: | ||||
15777 | ResultType = Context.DependentTy; | ||||
15778 | break; | ||||
15779 | } | ||||
15780 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | ||||
15781 | VK_PRValue, OK_Ordinary, OpLoc, | ||||
15782 | CurFPFeatureOverrides()); | ||||
15783 | } | ||||
15784 | |||||
15785 | // Build a built-in binary operation. | ||||
15786 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15787 | } | ||||
15788 | |||||
15789 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | ||||
15790 | if (T.isNull() || T->isDependentType()) | ||||
15791 | return false; | ||||
15792 | |||||
15793 | if (!Ctx.isPromotableIntegerType(T)) | ||||
15794 | return true; | ||||
15795 | |||||
15796 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | ||||
15797 | } | ||||
15798 | |||||
15799 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | ||||
15800 | UnaryOperatorKind Opc, Expr *InputExpr, | ||||
15801 | bool IsAfterAmp) { | ||||
15802 | ExprResult Input = InputExpr; | ||||
15803 | ExprValueKind VK = VK_PRValue; | ||||
15804 | ExprObjectKind OK = OK_Ordinary; | ||||
15805 | QualType resultType; | ||||
15806 | bool CanOverflow = false; | ||||
15807 | |||||
15808 | bool ConvertHalfVec = false; | ||||
15809 | if (getLangOpts().OpenCL) { | ||||
15810 | QualType Ty = InputExpr->getType(); | ||||
15811 | // The only legal unary operation for atomics is '&'. | ||||
15812 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | ||||
15813 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
15814 | // only with a builtin functions and therefore should be disallowed here. | ||||
15815 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | ||||
15816 | || Ty->isBlockPointerType())) { | ||||
15817 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15818 | << InputExpr->getType() | ||||
15819 | << Input.get()->getSourceRange()); | ||||
15820 | } | ||||
15821 | } | ||||
15822 | |||||
15823 | if (getLangOpts().HLSL && OpLoc.isValid()) { | ||||
15824 | if (Opc == UO_AddrOf) | ||||
15825 | return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); | ||||
15826 | if (Opc == UO_Deref) | ||||
15827 | return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); | ||||
15828 | } | ||||
15829 | |||||
15830 | switch (Opc) { | ||||
15831 | case UO_PreInc: | ||||
15832 | case UO_PreDec: | ||||
15833 | case UO_PostInc: | ||||
15834 | case UO_PostDec: | ||||
15835 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | ||||
15836 | OpLoc, | ||||
15837 | Opc == UO_PreInc || | ||||
15838 | Opc == UO_PostInc, | ||||
15839 | Opc == UO_PreInc || | ||||
15840 | Opc == UO_PreDec); | ||||
15841 | CanOverflow = isOverflowingIntegerType(Context, resultType); | ||||
15842 | break; | ||||
15843 | case UO_AddrOf: | ||||
15844 | resultType = CheckAddressOfOperand(Input, OpLoc); | ||||
15845 | CheckAddressOfNoDeref(InputExpr); | ||||
15846 | RecordModifiableNonNullParam(*this, InputExpr); | ||||
15847 | break; | ||||
15848 | case UO_Deref: { | ||||
15849 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
15850 | if (Input.isInvalid()) return ExprError(); | ||||
15851 | resultType = | ||||
15852 | CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp); | ||||
15853 | break; | ||||
15854 | } | ||||
15855 | case UO_Plus: | ||||
15856 | case UO_Minus: | ||||
15857 | CanOverflow = Opc == UO_Minus && | ||||
15858 | isOverflowingIntegerType(Context, Input.get()->getType()); | ||||
15859 | Input = UsualUnaryConversions(Input.get()); | ||||
15860 | if (Input.isInvalid()) return ExprError(); | ||||
15861 | // Unary plus and minus require promoting an operand of half vector to a | ||||
15862 | // float vector and truncating the result back to a half vector. For now, we | ||||
15863 | // do this only when HalfArgsAndReturns is set (that is, when the target is | ||||
15864 | // arm or arm64). | ||||
15865 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | ||||
15866 | |||||
15867 | // If the operand is a half vector, promote it to a float vector. | ||||
15868 | if (ConvertHalfVec) | ||||
15869 | Input = convertVector(Input.get(), Context.FloatTy, *this); | ||||
15870 | resultType = Input.get()->getType(); | ||||
15871 | if (resultType->isDependentType()) | ||||
15872 | break; | ||||
15873 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | ||||
15874 | break; | ||||
15875 | else if (resultType->isVectorType() && | ||||
15876 | // The z vector extensions don't allow + or - with bool vectors. | ||||
15877 | (!Context.getLangOpts().ZVector || | ||||
15878 | resultType->castAs<VectorType>()->getVectorKind() != | ||||
15879 | VectorType::AltiVecBool)) | ||||
15880 | break; | ||||
15881 | else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and - | ||||
15882 | break; | ||||
15883 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | ||||
15884 | Opc == UO_Plus && | ||||
15885 | resultType->isPointerType()) | ||||
15886 | break; | ||||
15887 | |||||
15888 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15889 | << resultType << Input.get()->getSourceRange()); | ||||
15890 | |||||
15891 | case UO_Not: // bitwise complement | ||||
15892 | Input = UsualUnaryConversions(Input.get()); | ||||
15893 | if (Input.isInvalid()) | ||||
15894 | return ExprError(); | ||||
15895 | resultType = Input.get()->getType(); | ||||
15896 | if (resultType->isDependentType()) | ||||
15897 | break; | ||||
15898 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | ||||
15899 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | ||||
15900 | // C99 does not support '~' for complex conjugation. | ||||
15901 | Diag(OpLoc, diag::ext_integer_complement_complex) | ||||
15902 | << resultType << Input.get()->getSourceRange(); | ||||
15903 | else if (resultType->hasIntegerRepresentation()) | ||||
15904 | break; | ||||
15905 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | ||||
15906 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | ||||
15907 | // on vector float types. | ||||
15908 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
15909 | if (!T->isIntegerType()) | ||||
15910 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15911 | << resultType << Input.get()->getSourceRange()); | ||||
15912 | } else { | ||||
15913 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15914 | << resultType << Input.get()->getSourceRange()); | ||||
15915 | } | ||||
15916 | break; | ||||
15917 | |||||
15918 | case UO_LNot: // logical negation | ||||
15919 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | ||||
15920 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
15921 | if (Input.isInvalid()) return ExprError(); | ||||
15922 | resultType = Input.get()->getType(); | ||||
15923 | |||||
15924 | // Though we still have to promote half FP to float... | ||||
15925 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | ||||
15926 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | ||||
15927 | resultType = Context.FloatTy; | ||||
15928 | } | ||||
15929 | |||||
15930 | if (resultType->isDependentType()) | ||||
15931 | break; | ||||
15932 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | ||||
15933 | // C99 6.5.3.3p1: ok, fallthrough; | ||||
15934 | if (Context.getLangOpts().CPlusPlus) { | ||||
15935 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | ||||
15936 | // operand contextually converted to bool. | ||||
15937 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | ||||
15938 | ScalarTypeToBooleanCastKind(resultType)); | ||||
15939 | } else if (Context.getLangOpts().OpenCL && | ||||
15940 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
15941 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
15942 | // operate on scalar float types. | ||||
15943 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | ||||
15944 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15945 | << resultType << Input.get()->getSourceRange()); | ||||
15946 | } | ||||
15947 | } else if (resultType->isExtVectorType()) { | ||||
15948 | if (Context.getLangOpts().OpenCL && | ||||
15949 | Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { | ||||
15950 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
15951 | // operate on vector float types. | ||||
15952 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
15953 | if (!T->isIntegerType()) | ||||
15954 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15955 | << resultType << Input.get()->getSourceRange()); | ||||
15956 | } | ||||
15957 | // Vector logical not returns the signed variant of the operand type. | ||||
15958 | resultType = GetSignedVectorType(resultType); | ||||
15959 | break; | ||||
15960 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | ||||
15961 | const VectorType *VTy = resultType->castAs<VectorType>(); | ||||
15962 | if (VTy->getVectorKind() != VectorType::GenericVector) | ||||
15963 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15964 | << resultType << Input.get()->getSourceRange()); | ||||
15965 | |||||
15966 | // Vector logical not returns the signed variant of the operand type. | ||||
15967 | resultType = GetSignedVectorType(resultType); | ||||
15968 | break; | ||||
15969 | } else { | ||||
15970 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15971 | << resultType << Input.get()->getSourceRange()); | ||||
15972 | } | ||||
15973 | |||||
15974 | // LNot always has type int. C99 6.5.3.3p5. | ||||
15975 | // In C++, it's bool. C++ 5.3.1p8 | ||||
15976 | resultType = Context.getLogicalOperationType(); | ||||
15977 | break; | ||||
15978 | case UO_Real: | ||||
15979 | case UO_Imag: | ||||
15980 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | ||||
15981 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | ||||
15982 | // complex l-values to ordinary l-values and all other values to r-values. | ||||
15983 | if (Input.isInvalid()) return ExprError(); | ||||
15984 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | ||||
15985 | if (Input.get()->isGLValue() && | ||||
15986 | Input.get()->getObjectKind() == OK_Ordinary) | ||||
15987 | VK = Input.get()->getValueKind(); | ||||
15988 | } else if (!getLangOpts().CPlusPlus) { | ||||
15989 | // In C, a volatile scalar is read by __imag. In C++, it is not. | ||||
15990 | Input = DefaultLvalueConversion(Input.get()); | ||||
15991 | } | ||||
15992 | break; | ||||
15993 | case UO_Extension: | ||||
15994 | resultType = Input.get()->getType(); | ||||
15995 | VK = Input.get()->getValueKind(); | ||||
15996 | OK = Input.get()->getObjectKind(); | ||||
15997 | break; | ||||
15998 | case UO_Coawait: | ||||
15999 | // It's unnecessary to represent the pass-through operator co_await in the | ||||
16000 | // AST; just return the input expression instead. | ||||
16001 | assert(!Input.get()->getType()->isDependentType() &&(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 16003, __extension__ __PRETTY_FUNCTION__ )) | ||||
16002 | "the co_await expression must be non-dependant before "(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 16003, __extension__ __PRETTY_FUNCTION__ )) | ||||
16003 | "building operator co_await")(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 16003, __extension__ __PRETTY_FUNCTION__ )); | ||||
16004 | return Input; | ||||
16005 | } | ||||
16006 | if (resultType.isNull() || Input.isInvalid()) | ||||
16007 | return ExprError(); | ||||
16008 | |||||
16009 | // Check for array bounds violations in the operand of the UnaryOperator, | ||||
16010 | // except for the '*' and '&' operators that have to be handled specially | ||||
16011 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | ||||
16012 | // that are explicitly defined as valid by the standard). | ||||
16013 | if (Opc != UO_AddrOf && Opc != UO_Deref) | ||||
16014 | CheckArrayAccess(Input.get()); | ||||
16015 | |||||
16016 | auto *UO = | ||||
16017 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | ||||
16018 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | ||||
16019 | |||||
16020 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | ||||
16021 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | ||||
16022 | !isUnevaluatedContext()) | ||||
16023 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | ||||
16024 | |||||
16025 | // Convert the result back to a half vector. | ||||
16026 | if (ConvertHalfVec) | ||||
16027 | return convertVector(UO, Context.HalfTy, *this); | ||||
16028 | return UO; | ||||
16029 | } | ||||
16030 | |||||
16031 | /// Determine whether the given expression is a qualified member | ||||
16032 | /// access expression, of a form that could be turned into a pointer to member | ||||
16033 | /// with the address-of operator. | ||||
16034 | bool Sema::isQualifiedMemberAccess(Expr *E) { | ||||
16035 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
16036 | if (!DRE->getQualifier()) | ||||
16037 | return false; | ||||
16038 | |||||
16039 | ValueDecl *VD = DRE->getDecl(); | ||||
16040 | if (!VD->isCXXClassMember()) | ||||
16041 | return false; | ||||
16042 | |||||
16043 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | ||||
16044 | return true; | ||||
16045 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | ||||
16046 | return Method->isInstance(); | ||||
16047 | |||||
16048 | return false; | ||||
16049 | } | ||||
16050 | |||||
16051 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | ||||
16052 | if (!ULE->getQualifier()) | ||||
16053 | return false; | ||||
16054 | |||||
16055 | for (NamedDecl *D : ULE->decls()) { | ||||
16056 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | ||||
16057 | if (Method->isInstance()) | ||||
16058 | return true; | ||||
16059 | } else { | ||||
16060 | // Overload set does not contain methods. | ||||
16061 | break; | ||||
16062 | } | ||||
16063 | } | ||||
16064 | |||||
16065 | return false; | ||||
16066 | } | ||||
16067 | |||||
16068 | return false; | ||||
16069 | } | ||||
16070 | |||||
16071 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
16072 | UnaryOperatorKind Opc, Expr *Input, | ||||
16073 | bool IsAfterAmp) { | ||||
16074 | // First things first: handle placeholders so that the | ||||
16075 | // overloaded-operator check considers the right type. | ||||
16076 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | ||||
16077 | // Increment and decrement of pseudo-object references. | ||||
16078 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
16079 | UnaryOperator::isIncrementDecrementOp(Opc)) | ||||
16080 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | ||||
16081 | |||||
16082 | // extension is always a builtin operator. | ||||
16083 | if (Opc == UO_Extension) | ||||
16084 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
16085 | |||||
16086 | // & gets special logic for several kinds of placeholder. | ||||
16087 | // The builtin code knows what to do. | ||||
16088 | if (Opc == UO_AddrOf && | ||||
16089 | (pty->getKind() == BuiltinType::Overload || | ||||
16090 | pty->getKind() == BuiltinType::UnknownAny || | ||||
16091 | pty->getKind() == BuiltinType::BoundMember)) | ||||
16092 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
16093 | |||||
16094 | // Anything else needs to be handled now. | ||||
16095 | ExprResult Result = CheckPlaceholderExpr(Input); | ||||
16096 | if (Result.isInvalid()) return ExprError(); | ||||
16097 | Input = Result.get(); | ||||
16098 | } | ||||
16099 | |||||
16100 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | ||||
16101 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | ||||
16102 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | ||||
16103 | // Find all of the overloaded operators visible from this point. | ||||
16104 | UnresolvedSet<16> Functions; | ||||
16105 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | ||||
16106 | if (S && OverOp != OO_None) | ||||
16107 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
16108 | |||||
16109 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | ||||
16110 | } | ||||
16111 | |||||
16112 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp); | ||||
16113 | } | ||||
16114 | |||||
16115 | // Unary Operators. 'Tok' is the token for the operator. | ||||
16116 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, | ||||
16117 | Expr *Input, bool IsAfterAmp) { | ||||
16118 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input, | ||||
16119 | IsAfterAmp); | ||||
16120 | } | ||||
16121 | |||||
16122 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | ||||
16123 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | ||||
16124 | LabelDecl *TheDecl) { | ||||
16125 | TheDecl->markUsed(Context); | ||||
16126 | // Create the AST node. The address of a label always has type 'void*'. | ||||
16127 | auto *Res = new (Context) AddrLabelExpr( | ||||
16128 | OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy)); | ||||
16129 | |||||
16130 | if (getCurFunction()) | ||||
16131 | getCurFunction()->AddrLabels.push_back(Res); | ||||
16132 | |||||
16133 | return Res; | ||||
16134 | } | ||||
16135 | |||||
16136 | void Sema::ActOnStartStmtExpr() { | ||||
16137 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
16138 | } | ||||
16139 | |||||
16140 | void Sema::ActOnStmtExprError() { | ||||
16141 | // Note that function is also called by TreeTransform when leaving a | ||||
16142 | // StmtExpr scope without rebuilding anything. | ||||
16143 | |||||
16144 | DiscardCleanupsInEvaluationContext(); | ||||
16145 | PopExpressionEvaluationContext(); | ||||
16146 | } | ||||
16147 | |||||
16148 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | ||||
16149 | SourceLocation RPLoc) { | ||||
16150 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | ||||
16151 | } | ||||
16152 | |||||
16153 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | ||||
16154 | SourceLocation RPLoc, unsigned TemplateDepth) { | ||||
16155 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast <bool> (SubStmt && isa<CompoundStmt >(SubStmt) && "Invalid action invocation!") ? void (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "clang/lib/Sema/SemaExpr.cpp", 16155, __extension__ __PRETTY_FUNCTION__ )); | ||||
16156 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | ||||
16157 | |||||
16158 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
16159 | DiscardCleanupsInEvaluationContext(); | ||||
16160 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 16161, __extension__ __PRETTY_FUNCTION__ )) | ||||
16161 | "cleanups within StmtExpr not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 16161, __extension__ __PRETTY_FUNCTION__ )); | ||||
16162 | PopExpressionEvaluationContext(); | ||||
16163 | |||||
16164 | // FIXME: there are a variety of strange constraints to enforce here, for | ||||
16165 | // example, it is not possible to goto into a stmt expression apparently. | ||||
16166 | // More semantic analysis is needed. | ||||
16167 | |||||
16168 | // If there are sub-stmts in the compound stmt, take the type of the last one | ||||
16169 | // as the type of the stmtexpr. | ||||
16170 | QualType Ty = Context.VoidTy; | ||||
16171 | bool StmtExprMayBindToTemp = false; | ||||
16172 | if (!Compound->body_empty()) { | ||||
16173 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | ||||
16174 | if (const auto *LastStmt = | ||||
16175 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | ||||
16176 | if (const Expr *Value = LastStmt->getExprStmt()) { | ||||
16177 | StmtExprMayBindToTemp = true; | ||||
16178 | Ty = Value->getType(); | ||||
16179 | } | ||||
16180 | } | ||||
16181 | } | ||||
16182 | |||||
16183 | // FIXME: Check that expression type is complete/non-abstract; statement | ||||
16184 | // expressions are not lvalues. | ||||
16185 | Expr *ResStmtExpr = | ||||
16186 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | ||||
16187 | if (StmtExprMayBindToTemp) | ||||
16188 | return MaybeBindToTemporary(ResStmtExpr); | ||||
16189 | return ResStmtExpr; | ||||
16190 | } | ||||
16191 | |||||
16192 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | ||||
16193 | if (ER.isInvalid()) | ||||
16194 | return ExprError(); | ||||
16195 | |||||
16196 | // Do function/array conversion on the last expression, but not | ||||
16197 | // lvalue-to-rvalue. However, initialize an unqualified type. | ||||
16198 | ER = DefaultFunctionArrayConversion(ER.get()); | ||||
16199 | if (ER.isInvalid()) | ||||
16200 | return ExprError(); | ||||
16201 | Expr *E = ER.get(); | ||||
16202 | |||||
16203 | if (E->isTypeDependent()) | ||||
16204 | return E; | ||||
16205 | |||||
16206 | // In ARC, if the final expression ends in a consume, splice | ||||
16207 | // the consume out and bind it later. In the alternate case | ||||
16208 | // (when dealing with a retainable type), the result | ||||
16209 | // initialization will create a produce. In both cases the | ||||
16210 | // result will be +1, and we'll need to balance that out with | ||||
16211 | // a bind. | ||||
16212 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | ||||
16213 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | ||||
16214 | return Cast->getSubExpr(); | ||||
16215 | |||||
16216 | // FIXME: Provide a better location for the initialization. | ||||
16217 | return PerformCopyInitialization( | ||||
16218 | InitializedEntity::InitializeStmtExprResult( | ||||
16219 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | ||||
16220 | SourceLocation(), E); | ||||
16221 | } | ||||
16222 | |||||
16223 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | ||||
16224 | TypeSourceInfo *TInfo, | ||||
16225 | ArrayRef<OffsetOfComponent> Components, | ||||
16226 | SourceLocation RParenLoc) { | ||||
16227 | QualType ArgTy = TInfo->getType(); | ||||
16228 | bool Dependent = ArgTy->isDependentType(); | ||||
16229 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | ||||
16230 | |||||
16231 | // We must have at least one component that refers to the type, and the first | ||||
16232 | // one is known to be a field designator. Verify that the ArgTy represents | ||||
16233 | // a struct/union/class. | ||||
16234 | if (!Dependent && !ArgTy->isRecordType()) | ||||
16235 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | ||||
16236 | << ArgTy << TypeRange); | ||||
16237 | |||||
16238 | // Type must be complete per C99 7.17p3 because a declaring a variable | ||||
16239 | // with an incomplete type would be ill-formed. | ||||
16240 | if (!Dependent | ||||
16241 | && RequireCompleteType(BuiltinLoc, ArgTy, | ||||
16242 | diag::err_offsetof_incomplete_type, TypeRange)) | ||||
16243 | return ExprError(); | ||||
16244 | |||||
16245 | bool DidWarnAboutNonPOD = false; | ||||
16246 | QualType CurrentType = ArgTy; | ||||
16247 | SmallVector<OffsetOfNode, 4> Comps; | ||||
16248 | SmallVector<Expr*, 4> Exprs; | ||||
16249 | for (const OffsetOfComponent &OC : Components) { | ||||
16250 | if (OC.isBrackets) { | ||||
16251 | // Offset of an array sub-field. TODO: Should we allow vector elements? | ||||
16252 | if (!CurrentType->isDependentType()) { | ||||
16253 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | ||||
16254 | if(!AT) | ||||
16255 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | ||||
16256 | << CurrentType); | ||||
16257 | CurrentType = AT->getElementType(); | ||||
16258 | } else | ||||
16259 | CurrentType = Context.DependentTy; | ||||
16260 | |||||
16261 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | ||||
16262 | if (IdxRval.isInvalid()) | ||||
16263 | return ExprError(); | ||||
16264 | Expr *Idx = IdxRval.get(); | ||||
16265 | |||||
16266 | // The expression must be an integral expression. | ||||
16267 | // FIXME: An integral constant expression? | ||||
16268 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | ||||
16269 | !Idx->getType()->isIntegerType()) | ||||
16270 | return ExprError( | ||||
16271 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | ||||
16272 | << Idx->getSourceRange()); | ||||
16273 | |||||
16274 | // Record this array index. | ||||
16275 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | ||||
16276 | Exprs.push_back(Idx); | ||||
16277 | continue; | ||||
16278 | } | ||||
16279 | |||||
16280 | // Offset of a field. | ||||
16281 | if (CurrentType->isDependentType()) { | ||||
16282 | // We have the offset of a field, but we can't look into the dependent | ||||
16283 | // type. Just record the identifier of the field. | ||||
16284 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | ||||
16285 | CurrentType = Context.DependentTy; | ||||
16286 | continue; | ||||
16287 | } | ||||
16288 | |||||
16289 | // We need to have a complete type to look into. | ||||
16290 | if (RequireCompleteType(OC.LocStart, CurrentType, | ||||
16291 | diag::err_offsetof_incomplete_type)) | ||||
16292 | return ExprError(); | ||||
16293 | |||||
16294 | // Look for the designated field. | ||||
16295 | const RecordType *RC = CurrentType->getAs<RecordType>(); | ||||
16296 | if (!RC) | ||||
16297 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | ||||
16298 | << CurrentType); | ||||
16299 | RecordDecl *RD = RC->getDecl(); | ||||
16300 | |||||
16301 | // C++ [lib.support.types]p5: | ||||
16302 | // The macro offsetof accepts a restricted set of type arguments in this | ||||
16303 | // International Standard. type shall be a POD structure or a POD union | ||||
16304 | // (clause 9). | ||||
16305 | // C++11 [support.types]p4: | ||||
16306 | // If type is not a standard-layout class (Clause 9), the results are | ||||
16307 | // undefined. | ||||
16308 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
16309 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | ||||
16310 | unsigned DiagID = | ||||
16311 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | ||||
16312 | : diag::ext_offsetof_non_pod_type; | ||||
16313 | |||||
16314 | if (!IsSafe && !DidWarnAboutNonPOD && | ||||
16315 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | ||||
16316 | PDiag(DiagID) | ||||
16317 | << SourceRange(Components[0].LocStart, OC.LocEnd) | ||||
16318 | << CurrentType)) | ||||
16319 | DidWarnAboutNonPOD = true; | ||||
16320 | } | ||||
16321 | |||||
16322 | // Look for the field. | ||||
16323 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | ||||
16324 | LookupQualifiedName(R, RD); | ||||
16325 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | ||||
16326 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | ||||
16327 | if (!MemberDecl) { | ||||
16328 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | ||||
16329 | MemberDecl = IndirectMemberDecl->getAnonField(); | ||||
16330 | } | ||||
16331 | |||||
16332 | if (!MemberDecl) | ||||
16333 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | ||||
16334 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | ||||
16335 | OC.LocEnd)); | ||||
16336 | |||||
16337 | // C99 7.17p3: | ||||
16338 | // (If the specified member is a bit-field, the behavior is undefined.) | ||||
16339 | // | ||||
16340 | // We diagnose this as an error. | ||||
16341 | if (MemberDecl->isBitField()) { | ||||
16342 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | ||||
16343 | << MemberDecl->getDeclName() | ||||
16344 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
16345 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | ||||
16346 | return ExprError(); | ||||
16347 | } | ||||
16348 | |||||
16349 | RecordDecl *Parent = MemberDecl->getParent(); | ||||
16350 | if (IndirectMemberDecl) | ||||
16351 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | ||||
16352 | |||||
16353 | // If the member was found in a base class, introduce OffsetOfNodes for | ||||
16354 | // the base class indirections. | ||||
16355 | CXXBasePaths Paths; | ||||
16356 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | ||||
16357 | Paths)) { | ||||
16358 | if (Paths.getDetectedVirtual()) { | ||||
16359 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | ||||
16360 | << MemberDecl->getDeclName() | ||||
16361 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
16362 | return ExprError(); | ||||
16363 | } | ||||
16364 | |||||
16365 | CXXBasePath &Path = Paths.front(); | ||||
16366 | for (const CXXBasePathElement &B : Path) | ||||
16367 | Comps.push_back(OffsetOfNode(B.Base)); | ||||
16368 | } | ||||
16369 | |||||
16370 | if (IndirectMemberDecl) { | ||||
16371 | for (auto *FI : IndirectMemberDecl->chain()) { | ||||
16372 | assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp" , 16372, __extension__ __PRETTY_FUNCTION__)); | ||||
16373 | Comps.push_back(OffsetOfNode(OC.LocStart, | ||||
16374 | cast<FieldDecl>(FI), OC.LocEnd)); | ||||
16375 | } | ||||
16376 | } else | ||||
16377 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | ||||
16378 | |||||
16379 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
16380 | } | ||||
16381 | |||||
16382 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | ||||
16383 | Comps, Exprs, RParenLoc); | ||||
16384 | } | ||||
16385 | |||||
16386 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | ||||
16387 | SourceLocation BuiltinLoc, | ||||
16388 | SourceLocation TypeLoc, | ||||
16389 | ParsedType ParsedArgTy, | ||||
16390 | ArrayRef<OffsetOfComponent> Components, | ||||
16391 | SourceLocation RParenLoc) { | ||||
16392 | |||||
16393 | TypeSourceInfo *ArgTInfo; | ||||
16394 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | ||||
16395 | if (ArgTy.isNull()) | ||||
16396 | return ExprError(); | ||||
16397 | |||||
16398 | if (!ArgTInfo) | ||||
16399 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | ||||
16400 | |||||
16401 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | ||||
16402 | } | ||||
16403 | |||||
16404 | |||||
16405 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | ||||
16406 | Expr *CondExpr, | ||||
16407 | Expr *LHSExpr, Expr *RHSExpr, | ||||
16408 | SourceLocation RPLoc) { | ||||
16409 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast <bool> ((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? void (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "clang/lib/Sema/SemaExpr.cpp", 16409, __extension__ __PRETTY_FUNCTION__ )); | ||||
16410 | |||||
16411 | ExprValueKind VK = VK_PRValue; | ||||
16412 | ExprObjectKind OK = OK_Ordinary; | ||||
16413 | QualType resType; | ||||
16414 | bool CondIsTrue = false; | ||||
16415 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | ||||
16416 | resType = Context.DependentTy; | ||||
16417 | } else { | ||||
16418 | // The conditional expression is required to be a constant expression. | ||||
16419 | llvm::APSInt condEval(32); | ||||
16420 | ExprResult CondICE = VerifyIntegerConstantExpression( | ||||
16421 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | ||||
16422 | if (CondICE.isInvalid()) | ||||
16423 | return ExprError(); | ||||
16424 | CondExpr = CondICE.get(); | ||||
16425 | CondIsTrue = condEval.getZExtValue(); | ||||
16426 | |||||
16427 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | ||||
16428 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | ||||
16429 | |||||
16430 | resType = ActiveExpr->getType(); | ||||
16431 | VK = ActiveExpr->getValueKind(); | ||||
16432 | OK = ActiveExpr->getObjectKind(); | ||||
16433 | } | ||||
16434 | |||||
16435 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | ||||
16436 | resType, VK, OK, RPLoc, CondIsTrue); | ||||
16437 | } | ||||
16438 | |||||
16439 | //===----------------------------------------------------------------------===// | ||||
16440 | // Clang Extensions. | ||||
16441 | //===----------------------------------------------------------------------===// | ||||
16442 | |||||
16443 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | ||||
16444 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | ||||
16445 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | ||||
16446 | |||||
16447 | if (LangOpts.CPlusPlus) { | ||||
16448 | MangleNumberingContext *MCtx; | ||||
16449 | Decl *ManglingContextDecl; | ||||
16450 | std::tie(MCtx, ManglingContextDecl) = | ||||
16451 | getCurrentMangleNumberContext(Block->getDeclContext()); | ||||
16452 | if (MCtx) { | ||||
16453 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | ||||
16454 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | ||||
16455 | } | ||||
16456 | } | ||||
16457 | |||||
16458 | PushBlockScope(CurScope, Block); | ||||
16459 | CurContext->addDecl(Block); | ||||
16460 | if (CurScope) | ||||
16461 | PushDeclContext(CurScope, Block); | ||||
16462 | else | ||||
16463 | CurContext = Block; | ||||
16464 | |||||
16465 | getCurBlock()->HasImplicitReturnType = true; | ||||
16466 | |||||
16467 | // Enter a new evaluation context to insulate the block from any | ||||
16468 | // cleanups from the enclosing full-expression. | ||||
16469 | PushExpressionEvaluationContext( | ||||
16470 | ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
16471 | } | ||||
16472 | |||||
16473 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | ||||
16474 | Scope *CurScope) { | ||||
16475 | assert(ParamInfo.getIdentifier() == nullptr &&(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "clang/lib/Sema/SemaExpr.cpp", 16476, __extension__ __PRETTY_FUNCTION__ )) | ||||
16476 | "block-id should have no identifier!")(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "clang/lib/Sema/SemaExpr.cpp", 16476, __extension__ __PRETTY_FUNCTION__ )); | ||||
16477 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext ::BlockLiteral) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "clang/lib/Sema/SemaExpr.cpp", 16477, __extension__ __PRETTY_FUNCTION__ )); | ||||
16478 | BlockScopeInfo *CurBlock = getCurBlock(); | ||||
16479 | |||||
16480 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | ||||
16481 | QualType T = Sig->getType(); | ||||
16482 | |||||
16483 | // FIXME: We should allow unexpanded parameter packs here, but that would, | ||||
16484 | // in turn, make the block expression contain unexpanded parameter packs. | ||||
16485 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | ||||
16486 | // Drop the parameters. | ||||
16487 | FunctionProtoType::ExtProtoInfo EPI; | ||||
16488 | EPI.HasTrailingReturn = false; | ||||
16489 | EPI.TypeQuals.addConst(); | ||||
16490 | T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI); | ||||
16491 | Sig = Context.getTrivialTypeSourceInfo(T); | ||||
16492 | } | ||||
16493 | |||||
16494 | // GetTypeForDeclarator always produces a function type for a block | ||||
16495 | // literal signature. Furthermore, it is always a FunctionProtoType | ||||
16496 | // unless the function was written with a typedef. | ||||
16497 | assert(T->isFunctionType() &&(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "clang/lib/Sema/SemaExpr.cpp", 16498, __extension__ __PRETTY_FUNCTION__ )) | ||||
16498 | "GetTypeForDeclarator made a non-function block signature")(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "clang/lib/Sema/SemaExpr.cpp", 16498, __extension__ __PRETTY_FUNCTION__ )); | ||||
16499 | |||||
16500 | // Look for an explicit signature in that function type. | ||||
16501 | FunctionProtoTypeLoc ExplicitSignature; | ||||
16502 | |||||
16503 | if ((ExplicitSignature = Sig->getTypeLoc() | ||||
16504 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | ||||
16505 | |||||
16506 | // Check whether that explicit signature was synthesized by | ||||
16507 | // GetTypeForDeclarator. If so, don't save that as part of the | ||||
16508 | // written signature. | ||||
16509 | if (ExplicitSignature.getLocalRangeBegin() == | ||||
16510 | ExplicitSignature.getLocalRangeEnd()) { | ||||
16511 | // This would be much cheaper if we stored TypeLocs instead of | ||||
16512 | // TypeSourceInfos. | ||||
16513 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | ||||
16514 | unsigned Size = Result.getFullDataSize(); | ||||
16515 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | ||||
16516 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | ||||
16517 | |||||
16518 | ExplicitSignature = FunctionProtoTypeLoc(); | ||||
16519 | } | ||||
16520 | } | ||||
16521 | |||||
16522 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | ||||
16523 | CurBlock->FunctionType = T; | ||||
16524 | |||||
16525 | const auto *Fn = T->castAs<FunctionType>(); | ||||
16526 | QualType RetTy = Fn->getReturnType(); | ||||
16527 | bool isVariadic = | ||||
16528 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | ||||
16529 | |||||
16530 | CurBlock->TheDecl->setIsVariadic(isVariadic); | ||||
16531 | |||||
16532 | // Context.DependentTy is used as a placeholder for a missing block | ||||
16533 | // return type. TODO: what should we do with declarators like: | ||||
16534 | // ^ * { ... } | ||||
16535 | // If the answer is "apply template argument deduction".... | ||||
16536 | if (RetTy != Context.DependentTy) { | ||||
16537 | CurBlock->ReturnType = RetTy; | ||||
16538 | CurBlock->TheDecl->setBlockMissingReturnType(false); | ||||
16539 | CurBlock->HasImplicitReturnType = false; | ||||
16540 | } | ||||
16541 | |||||
16542 | // Push block parameters from the declarator if we had them. | ||||
16543 | SmallVector<ParmVarDecl*, 8> Params; | ||||
16544 | if (ExplicitSignature) { | ||||
16545 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | ||||
16546 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | ||||
16547 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | ||||
16548 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | ||||
16549 | // Diagnose this as an extension in C17 and earlier. | ||||
16550 | if (!getLangOpts().C2x) | ||||
16551 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | ||||
16552 | } | ||||
16553 | Params.push_back(Param); | ||||
16554 | } | ||||
16555 | |||||
16556 | // Fake up parameter variables if we have a typedef, like | ||||
16557 | // ^ fntype { ... } | ||||
16558 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | ||||
16559 | for (const auto &I : Fn->param_types()) { | ||||
16560 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | ||||
16561 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | ||||
16562 | Params.push_back(Param); | ||||
16563 | } | ||||
16564 | } | ||||
16565 | |||||
16566 | // Set the parameters on the block decl. | ||||
16567 | if (!Params.empty()) { | ||||
16568 | CurBlock->TheDecl->setParams(Params); | ||||
16569 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | ||||
16570 | /*CheckParameterNames=*/false); | ||||
16571 | } | ||||
16572 | |||||
16573 | // Finally we can process decl attributes. | ||||
16574 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | ||||
16575 | |||||
16576 | // Put the parameter variables in scope. | ||||
16577 | for (auto *AI : CurBlock->TheDecl->parameters()) { | ||||
16578 | AI->setOwningFunction(CurBlock->TheDecl); | ||||
16579 | |||||
16580 | // If this has an identifier, add it to the scope stack. | ||||
16581 | if (AI->getIdentifier()) { | ||||
16582 | CheckShadow(CurBlock->TheScope, AI); | ||||
16583 | |||||
16584 | PushOnScopeChains(AI, CurBlock->TheScope); | ||||
16585 | } | ||||
16586 | } | ||||
16587 | } | ||||
16588 | |||||
16589 | /// ActOnBlockError - If there is an error parsing a block, this callback | ||||
16590 | /// is invoked to pop the information about the block from the action impl. | ||||
16591 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | ||||
16592 | // Leave the expression-evaluation context. | ||||
16593 | DiscardCleanupsInEvaluationContext(); | ||||
16594 | PopExpressionEvaluationContext(); | ||||
16595 | |||||
16596 | // Pop off CurBlock, handle nested blocks. | ||||
16597 | PopDeclContext(); | ||||
16598 | PopFunctionScopeInfo(); | ||||
16599 | } | ||||
16600 | |||||
16601 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | ||||
16602 | /// literal was successfully completed. ^(int x){...} | ||||
16603 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | ||||
16604 | Stmt *Body, Scope *CurScope) { | ||||
16605 | // If blocks are disabled, emit an error. | ||||
16606 | if (!LangOpts.Blocks) | ||||
16607 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||
16608 | |||||
16609 | // Leave the expression-evaluation context. | ||||
16610 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
16611 | DiscardCleanupsInEvaluationContext(); | ||||
16612 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 16613, __extension__ __PRETTY_FUNCTION__ )) | ||||
16613 | "cleanups within block not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 16613, __extension__ __PRETTY_FUNCTION__ )); | ||||
16614 | PopExpressionEvaluationContext(); | ||||
16615 | |||||
16616 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | ||||
16617 | BlockDecl *BD = BSI->TheDecl; | ||||
16618 | |||||
16619 | if (BSI->HasImplicitReturnType) | ||||
16620 | deduceClosureReturnType(*BSI); | ||||
16621 | |||||
16622 | QualType RetTy = Context.VoidTy; | ||||
16623 | if (!BSI->ReturnType.isNull()) | ||||
16624 | RetTy = BSI->ReturnType; | ||||
16625 | |||||
16626 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | ||||
16627 | QualType BlockTy; | ||||
16628 | |||||
16629 | // If the user wrote a function type in some form, try to use that. | ||||
16630 | if (!BSI->FunctionType.isNull()) { | ||||
16631 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | ||||
16632 | |||||
16633 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | ||||
16634 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | ||||
16635 | |||||
16636 | // Turn protoless block types into nullary block types. | ||||
16637 | if (isa<FunctionNoProtoType>(FTy)) { | ||||
16638 | FunctionProtoType::ExtProtoInfo EPI; | ||||
16639 | EPI.ExtInfo = Ext; | ||||
16640 | BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI); | ||||
16641 | |||||
16642 | // Otherwise, if we don't need to change anything about the function type, | ||||
16643 | // preserve its sugar structure. | ||||
16644 | } else if (FTy->getReturnType() == RetTy && | ||||
16645 | (!NoReturn || FTy->getNoReturnAttr())) { | ||||
16646 | BlockTy = BSI->FunctionType; | ||||
16647 | |||||
16648 | // Otherwise, make the minimal modifications to the function type. | ||||
16649 | } else { | ||||
16650 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | ||||
16651 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
16652 | EPI.TypeQuals = Qualifiers(); | ||||
16653 | EPI.ExtInfo = Ext; | ||||
16654 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | ||||
16655 | } | ||||
16656 | |||||
16657 | // If we don't have a function type, just build one from nothing. | ||||
16658 | } else { | ||||
16659 | FunctionProtoType::ExtProtoInfo EPI; | ||||
16660 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | ||||
16661 | BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI); | ||||
16662 | } | ||||
16663 | |||||
16664 | DiagnoseUnusedParameters(BD->parameters()); | ||||
16665 | BlockTy = Context.getBlockPointerType(BlockTy); | ||||
16666 | |||||
16667 | // If needed, diagnose invalid gotos and switches in the block. | ||||
16668 | if (getCurFunction()->NeedsScopeChecking() && | ||||
16669 | !PP.isCodeCompletionEnabled()) | ||||
16670 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | ||||
16671 | |||||
16672 | BD->setBody(cast<CompoundStmt>(Body)); | ||||
16673 | |||||
16674 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||
16675 | DiagnoseUnguardedAvailabilityViolations(BD); | ||||
16676 | |||||
16677 | // Try to apply the named return value optimization. We have to check again | ||||
16678 | // if we can do this, though, because blocks keep return statements around | ||||
16679 | // to deduce an implicit return type. | ||||
16680 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | ||||
16681 | !BD->isDependentContext()) | ||||
16682 | computeNRVO(Body, BSI); | ||||
16683 | |||||
16684 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | ||||
16685 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
16686 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | ||||
16687 | NTCUK_Destruct|NTCUK_Copy); | ||||
16688 | |||||
16689 | PopDeclContext(); | ||||
16690 | |||||
16691 | // Set the captured variables on the block. | ||||
16692 | SmallVector<BlockDecl::Capture, 4> Captures; | ||||
16693 | for (Capture &Cap : BSI->Captures) { | ||||
16694 | if (Cap.isInvalid() || Cap.isThisCapture()) | ||||
16695 | continue; | ||||
16696 | // Cap.getVariable() is always a VarDecl because | ||||
16697 | // blocks cannot capture structured bindings or other ValueDecl kinds. | ||||
16698 | auto *Var = cast<VarDecl>(Cap.getVariable()); | ||||
16699 | Expr *CopyExpr = nullptr; | ||||
16700 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | ||||
16701 | if (const RecordType *Record = | ||||
16702 | Cap.getCaptureType()->getAs<RecordType>()) { | ||||
16703 | // The capture logic needs the destructor, so make sure we mark it. | ||||
16704 | // Usually this is unnecessary because most local variables have | ||||
16705 | // their destructors marked at declaration time, but parameters are | ||||
16706 | // an exception because it's technically only the call site that | ||||
16707 | // actually requires the destructor. | ||||
16708 | if (isa<ParmVarDecl>(Var)) | ||||
16709 | FinalizeVarWithDestructor(Var, Record); | ||||
16710 | |||||
16711 | // Enter a separate potentially-evaluated context while building block | ||||
16712 | // initializers to isolate their cleanups from those of the block | ||||
16713 | // itself. | ||||
16714 | // FIXME: Is this appropriate even when the block itself occurs in an | ||||
16715 | // unevaluated operand? | ||||
16716 | EnterExpressionEvaluationContext EvalContext( | ||||
16717 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
16718 | |||||
16719 | SourceLocation Loc = Cap.getLocation(); | ||||
16720 | |||||
16721 | ExprResult Result = BuildDeclarationNameExpr( | ||||
16722 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | ||||
16723 | |||||
16724 | // According to the blocks spec, the capture of a variable from | ||||
16725 | // the stack requires a const copy constructor. This is not true | ||||
16726 | // of the copy/move done to move a __block variable to the heap. | ||||
16727 | if (!Result.isInvalid() && | ||||
16728 | !Result.get()->getType().isConstQualified()) { | ||||
16729 | Result = ImpCastExprToType(Result.get(), | ||||
16730 | Result.get()->getType().withConst(), | ||||
16731 | CK_NoOp, VK_LValue); | ||||
16732 | } | ||||
16733 | |||||
16734 | if (!Result.isInvalid()) { | ||||
16735 | Result = PerformCopyInitialization( | ||||
16736 | InitializedEntity::InitializeBlock(Var->getLocation(), | ||||
16737 | Cap.getCaptureType()), | ||||
16738 | Loc, Result.get()); | ||||
16739 | } | ||||
16740 | |||||
16741 | // Build a full-expression copy expression if initialization | ||||
16742 | // succeeded and used a non-trivial constructor. Recover from | ||||
16743 | // errors by pretending that the copy isn't necessary. | ||||
16744 | if (!Result.isInvalid() && | ||||
16745 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | ||||
16746 | ->isTrivial()) { | ||||
16747 | Result = MaybeCreateExprWithCleanups(Result); | ||||
16748 | CopyExpr = Result.get(); | ||||
16749 | } | ||||
16750 | } | ||||
16751 | } | ||||
16752 | |||||
16753 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | ||||
16754 | CopyExpr); | ||||
16755 | Captures.push_back(NewCap); | ||||
16756 | } | ||||
16757 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | ||||
16758 | |||||
16759 | // Pop the block scope now but keep it alive to the end of this function. | ||||
16760 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||
16761 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | ||||
16762 | |||||
16763 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | ||||
16764 | |||||
16765 | // If the block isn't obviously global, i.e. it captures anything at | ||||
16766 | // all, then we need to do a few things in the surrounding context: | ||||
16767 | if (Result->getBlockDecl()->hasCaptures()) { | ||||
16768 | // First, this expression has a new cleanup object. | ||||
16769 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | ||||
16770 | Cleanup.setExprNeedsCleanups(true); | ||||
16771 | |||||
16772 | // It also gets a branch-protected scope if any of the captured | ||||
16773 | // variables needs destruction. | ||||
16774 | for (const auto &CI : Result->getBlockDecl()->captures()) { | ||||
16775 | const VarDecl *var = CI.getVariable(); | ||||
16776 | if (var->getType().isDestructedType() != QualType::DK_none) { | ||||
16777 | setFunctionHasBranchProtectedScope(); | ||||
16778 | break; | ||||
16779 | } | ||||
16780 | } | ||||
16781 | } | ||||
16782 | |||||
16783 | if (getCurFunction()) | ||||
16784 | getCurFunction()->addBlock(BD); | ||||
16785 | |||||
16786 | return Result; | ||||
16787 | } | ||||
16788 | |||||
16789 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | ||||
16790 | SourceLocation RPLoc) { | ||||
16791 | TypeSourceInfo *TInfo; | ||||
16792 | GetTypeFromParser(Ty, &TInfo); | ||||
16793 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | ||||
16794 | } | ||||
16795 | |||||
16796 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | ||||
16797 | Expr *E, TypeSourceInfo *TInfo, | ||||
16798 | SourceLocation RPLoc) { | ||||
16799 | Expr *OrigExpr = E; | ||||
16800 | bool IsMS = false; | ||||
16801 | |||||
16802 | // CUDA device code does not support varargs. | ||||
16803 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | ||||
16804 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | ||||
16805 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | ||||
16806 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | ||||
16807 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | ||||
16808 | } | ||||
16809 | } | ||||
16810 | |||||
16811 | // NVPTX does not support va_arg expression. | ||||
16812 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | ||||
16813 | Context.getTargetInfo().getTriple().isNVPTX()) | ||||
16814 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | ||||
16815 | |||||
16816 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | ||||
16817 | // as Microsoft ABI on an actual Microsoft platform, where | ||||
16818 | // __builtin_ms_va_list and __builtin_va_list are the same.) | ||||
16819 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | ||||
16820 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | ||||
16821 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | ||||
16822 | if (Context.hasSameType(MSVaListType, E->getType())) { | ||||
16823 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
16824 | return ExprError(); | ||||
16825 | IsMS = true; | ||||
16826 | } | ||||
16827 | } | ||||
16828 | |||||
16829 | // Get the va_list type | ||||
16830 | QualType VaListType = Context.getBuiltinVaListType(); | ||||
16831 | if (!IsMS) { | ||||
16832 | if (VaListType->isArrayType()) { | ||||
16833 | // Deal with implicit array decay; for example, on x86-64, | ||||
16834 | // va_list is an array, but it's supposed to decay to | ||||
16835 | // a pointer for va_arg. | ||||
16836 | VaListType = Context.getArrayDecayedType(VaListType); | ||||
16837 | // Make sure the input expression also decays appropriately. | ||||
16838 | ExprResult Result = UsualUnaryConversions(E); | ||||
16839 | if (Result.isInvalid()) | ||||
16840 | return ExprError(); | ||||
16841 | E = Result.get(); | ||||
16842 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | ||||
16843 | // If va_list is a record type and we are compiling in C++ mode, | ||||
16844 | // check the argument using reference binding. | ||||
16845 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
16846 | Context, Context.getLValueReferenceType(VaListType), false); | ||||
16847 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | ||||
16848 | if (Init.isInvalid()) | ||||
16849 | return ExprError(); | ||||
16850 | E = Init.getAs<Expr>(); | ||||
16851 | } else { | ||||
16852 | // Otherwise, the va_list argument must be an l-value because | ||||
16853 | // it is modified by va_arg. | ||||
16854 | if (!E->isTypeDependent() && | ||||
16855 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
16856 | return ExprError(); | ||||
16857 | } | ||||
16858 | } | ||||
16859 | |||||
16860 | if (!IsMS && !E->isTypeDependent() && | ||||
16861 | !Context.hasSameType(VaListType, E->getType())) | ||||
16862 | return ExprError( | ||||
16863 | Diag(E->getBeginLoc(), | ||||
16864 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | ||||
16865 | << OrigExpr->getType() << E->getSourceRange()); | ||||
16866 | |||||
16867 | if (!TInfo->getType()->isDependentType()) { | ||||
16868 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | ||||
16869 | diag::err_second_parameter_to_va_arg_incomplete, | ||||
16870 | TInfo->getTypeLoc())) | ||||
16871 | return ExprError(); | ||||
16872 | |||||
16873 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | ||||
16874 | TInfo->getType(), | ||||
16875 | diag::err_second_parameter_to_va_arg_abstract, | ||||
16876 | TInfo->getTypeLoc())) | ||||
16877 | return ExprError(); | ||||
16878 | |||||
16879 | if (!TInfo->getType().isPODType(Context)) { | ||||
16880 | Diag(TInfo->getTypeLoc().getBeginLoc(), | ||||
16881 | TInfo->getType()->isObjCLifetimeType() | ||||
16882 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | ||||
16883 | : diag::warn_second_parameter_to_va_arg_not_pod) | ||||
16884 | << TInfo->getType() | ||||
16885 | << TInfo->getTypeLoc().getSourceRange(); | ||||
16886 | } | ||||
16887 | |||||
16888 | // Check for va_arg where arguments of the given type will be promoted | ||||
16889 | // (i.e. this va_arg is guaranteed to have undefined behavior). | ||||
16890 | QualType PromoteType; | ||||
16891 | if (Context.isPromotableIntegerType(TInfo->getType())) { | ||||
16892 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | ||||
16893 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, | ||||
16894 | // and C2x 7.16.1.1p2 says, in part: | ||||
16895 | // If type is not compatible with the type of the actual next argument | ||||
16896 | // (as promoted according to the default argument promotions), the | ||||
16897 | // behavior is undefined, except for the following cases: | ||||
16898 | // - both types are pointers to qualified or unqualified versions of | ||||
16899 | // compatible types; | ||||
16900 | // - one type is a signed integer type, the other type is the | ||||
16901 | // corresponding unsigned integer type, and the value is | ||||
16902 | // representable in both types; | ||||
16903 | // - one type is pointer to qualified or unqualified void and the | ||||
16904 | // other is a pointer to a qualified or unqualified character type. | ||||
16905 | // Given that type compatibility is the primary requirement (ignoring | ||||
16906 | // qualifications), you would think we could call typesAreCompatible() | ||||
16907 | // directly to test this. However, in C++, that checks for *same type*, | ||||
16908 | // which causes false positives when passing an enumeration type to | ||||
16909 | // va_arg. Instead, get the underlying type of the enumeration and pass | ||||
16910 | // that. | ||||
16911 | QualType UnderlyingType = TInfo->getType(); | ||||
16912 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) | ||||
16913 | UnderlyingType = ET->getDecl()->getIntegerType(); | ||||
16914 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | ||||
16915 | /*CompareUnqualified*/ true)) | ||||
16916 | PromoteType = QualType(); | ||||
16917 | |||||
16918 | // If the types are still not compatible, we need to test whether the | ||||
16919 | // promoted type and the underlying type are the same except for | ||||
16920 | // signedness. Ask the AST for the correctly corresponding type and see | ||||
16921 | // if that's compatible. | ||||
16922 | if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && | ||||
16923 | PromoteType->isUnsignedIntegerType() != | ||||
16924 | UnderlyingType->isUnsignedIntegerType()) { | ||||
16925 | UnderlyingType = | ||||
16926 | UnderlyingType->isUnsignedIntegerType() | ||||
16927 | ? Context.getCorrespondingSignedType(UnderlyingType) | ||||
16928 | : Context.getCorrespondingUnsignedType(UnderlyingType); | ||||
16929 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | ||||
16930 | /*CompareUnqualified*/ true)) | ||||
16931 | PromoteType = QualType(); | ||||
16932 | } | ||||
16933 | } | ||||
16934 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | ||||
16935 | PromoteType = Context.DoubleTy; | ||||
16936 | if (!PromoteType.isNull()) | ||||
16937 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | ||||
16938 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | ||||
16939 | << TInfo->getType() | ||||
16940 | << PromoteType | ||||
16941 | << TInfo->getTypeLoc().getSourceRange()); | ||||
16942 | } | ||||
16943 | |||||
16944 | QualType T = TInfo->getType().getNonLValueExprType(Context); | ||||
16945 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | ||||
16946 | } | ||||
16947 | |||||
16948 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | ||||
16949 | // The type of __null will be int or long, depending on the size of | ||||
16950 | // pointers on the target. | ||||
16951 | QualType Ty; | ||||
16952 | unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default); | ||||
16953 | if (pw == Context.getTargetInfo().getIntWidth()) | ||||
16954 | Ty = Context.IntTy; | ||||
16955 | else if (pw == Context.getTargetInfo().getLongWidth()) | ||||
16956 | Ty = Context.LongTy; | ||||
16957 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | ||||
16958 | Ty = Context.LongLongTy; | ||||
16959 | else { | ||||
16960 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "clang/lib/Sema/SemaExpr.cpp", 16960); | ||||
16961 | } | ||||
16962 | |||||
16963 | return new (Context) GNUNullExpr(Ty, TokenLoc); | ||||
16964 | } | ||||
16965 | |||||
16966 | static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { | ||||
16967 | CXXRecordDecl *ImplDecl = nullptr; | ||||
16968 | |||||
16969 | // Fetch the std::source_location::__impl decl. | ||||
16970 | if (NamespaceDecl *Std = S.getStdNamespace()) { | ||||
16971 | LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), | ||||
16972 | Loc, Sema::LookupOrdinaryName); | ||||
16973 | if (S.LookupQualifiedName(ResultSL, Std)) { | ||||
16974 | if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { | ||||
16975 | LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), | ||||
16976 | Loc, Sema::LookupOrdinaryName); | ||||
16977 | if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && | ||||
16978 | S.LookupQualifiedName(ResultImpl, SLDecl)) { | ||||
16979 | ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); | ||||
16980 | } | ||||
16981 | } | ||||
16982 | } | ||||
16983 | } | ||||
16984 | |||||
16985 | if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { | ||||
16986 | S.Diag(Loc, diag::err_std_source_location_impl_not_found); | ||||
16987 | return nullptr; | ||||
16988 | } | ||||
16989 | |||||
16990 | // Verify that __impl is a trivial struct type, with no base classes, and with | ||||
16991 | // only the four expected fields. | ||||
16992 | if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || | ||||
16993 | ImplDecl->getNumBases() != 0) { | ||||
16994 | S.Diag(Loc, diag::err_std_source_location_impl_malformed); | ||||
16995 | return nullptr; | ||||
16996 | } | ||||
16997 | |||||
16998 | unsigned Count = 0; | ||||
16999 | for (FieldDecl *F : ImplDecl->fields()) { | ||||
17000 | StringRef Name = F->getName(); | ||||
17001 | |||||
17002 | if (Name == "_M_file_name") { | ||||
17003 | if (F->getType() != | ||||
17004 | S.Context.getPointerType(S.Context.CharTy.withConst())) | ||||
17005 | break; | ||||
17006 | Count++; | ||||
17007 | } else if (Name == "_M_function_name") { | ||||
17008 | if (F->getType() != | ||||
17009 | S.Context.getPointerType(S.Context.CharTy.withConst())) | ||||
17010 | break; | ||||
17011 | Count++; | ||||
17012 | } else if (Name == "_M_line") { | ||||
17013 | if (!F->getType()->isIntegerType()) | ||||
17014 | break; | ||||
17015 | Count++; | ||||
17016 | } else if (Name == "_M_column") { | ||||
17017 | if (!F->getType()->isIntegerType()) | ||||
17018 | break; | ||||
17019 | Count++; | ||||
17020 | } else { | ||||
17021 | Count = 100; // invalid | ||||
17022 | break; | ||||
17023 | } | ||||
17024 | } | ||||
17025 | if (Count != 4) { | ||||
17026 | S.Diag(Loc, diag::err_std_source_location_impl_malformed); | ||||
17027 | return nullptr; | ||||
17028 | } | ||||
17029 | |||||
17030 | return ImplDecl; | ||||
17031 | } | ||||
17032 | |||||
17033 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
17034 | SourceLocation BuiltinLoc, | ||||
17035 | SourceLocation RPLoc) { | ||||
17036 | QualType ResultTy; | ||||
17037 | switch (Kind) { | ||||
17038 | case SourceLocExpr::File: | ||||
17039 | case SourceLocExpr::Function: { | ||||
17040 | QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); | ||||
17041 | ResultTy = | ||||
17042 | Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); | ||||
17043 | break; | ||||
17044 | } | ||||
17045 | case SourceLocExpr::Line: | ||||
17046 | case SourceLocExpr::Column: | ||||
17047 | ResultTy = Context.UnsignedIntTy; | ||||
17048 | break; | ||||
17049 | case SourceLocExpr::SourceLocStruct: | ||||
17050 | if (!StdSourceLocationImplDecl) { | ||||
17051 | StdSourceLocationImplDecl = | ||||
17052 | LookupStdSourceLocationImpl(*this, BuiltinLoc); | ||||
17053 | if (!StdSourceLocationImplDecl) | ||||
17054 | return ExprError(); | ||||
17055 | } | ||||
17056 | ResultTy = Context.getPointerType( | ||||
17057 | Context.getRecordType(StdSourceLocationImplDecl).withConst()); | ||||
17058 | break; | ||||
17059 | } | ||||
17060 | |||||
17061 | return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); | ||||
17062 | } | ||||
17063 | |||||
17064 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
17065 | QualType ResultTy, | ||||
17066 | SourceLocation BuiltinLoc, | ||||
17067 | SourceLocation RPLoc, | ||||
17068 | DeclContext *ParentContext) { | ||||
17069 | return new (Context) | ||||
17070 | SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); | ||||
17071 | } | ||||
17072 | |||||
17073 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | ||||
17074 | bool Diagnose) { | ||||
17075 | if (!getLangOpts().ObjC) | ||||
17076 | return false; | ||||
17077 | |||||
17078 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | ||||
17079 | if (!PT) | ||||
17080 | return false; | ||||
17081 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | ||||
17082 | |||||
17083 | // Ignore any parens, implicit casts (should only be | ||||
17084 | // array-to-pointer decays), and not-so-opaque values. The last is | ||||
17085 | // important for making this trigger for property assignments. | ||||
17086 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | ||||
17087 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | ||||
17088 | if (OV->getSourceExpr()) | ||||
17089 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | ||||
17090 | |||||
17091 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | ||||
17092 | if (!PT->isObjCIdType() && | ||||
17093 | !(ID && ID->getIdentifier()->isStr("NSString"))) | ||||
17094 | return false; | ||||
17095 | if (!SL->isOrdinary()) | ||||
17096 | return false; | ||||
17097 | |||||
17098 | if (Diagnose) { | ||||
17099 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
17100 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | ||||
17101 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | ||||
17102 | } | ||||
17103 | return true; | ||||
17104 | } | ||||
17105 | |||||
17106 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | ||||
17107 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | ||||
17108 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | ||||
17109 | !SrcExpr->isNullPointerConstant( | ||||
17110 | getASTContext(), Expr::NPC_NeverValueDependent)) { | ||||
17111 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | ||||
17112 | return false; | ||||
17113 | if (Diagnose) { | ||||
17114 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
17115 | << /*number*/1 | ||||
17116 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | ||||
17117 | Expr *NumLit = | ||||
17118 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | ||||
17119 | if (NumLit) | ||||
17120 | Exp = NumLit; | ||||
17121 | } | ||||
17122 | return true; | ||||
17123 | } | ||||
17124 | |||||
17125 | return false; | ||||
17126 | } | ||||
17127 | |||||
17128 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | ||||
17129 | const Expr *SrcExpr) { | ||||
17130 | if (!DstType->isFunctionPointerType() || | ||||
17131 | !SrcExpr->getType()->isFunctionType()) | ||||
17132 | return false; | ||||
17133 | |||||
17134 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | ||||
17135 | if (!DRE) | ||||
17136 | return false; | ||||
17137 | |||||
17138 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||
17139 | if (!FD) | ||||
17140 | return false; | ||||
17141 | |||||
17142 | return !S.checkAddressOfFunctionIsAvailable(FD, | ||||
17143 | /*Complain=*/true, | ||||
17144 | SrcExpr->getBeginLoc()); | ||||
17145 | } | ||||
17146 | |||||
17147 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | ||||
17148 | SourceLocation Loc, | ||||
17149 | QualType DstType, QualType SrcType, | ||||
17150 | Expr *SrcExpr, AssignmentAction Action, | ||||
17151 | bool *Complained) { | ||||
17152 | if (Complained) | ||||
17153 | *Complained = false; | ||||
17154 | |||||
17155 | // Decode the result (notice that AST's are still created for extensions). | ||||
17156 | bool CheckInferredResultType = false; | ||||
17157 | bool isInvalid = false; | ||||
17158 | unsigned DiagKind = 0; | ||||
17159 | ConversionFixItGenerator ConvHints; | ||||
17160 | bool MayHaveConvFixit = false; | ||||
17161 | bool MayHaveFunctionDiff = false; | ||||
17162 | const ObjCInterfaceDecl *IFace = nullptr; | ||||
17163 | const ObjCProtocolDecl *PDecl = nullptr; | ||||
17164 | |||||
17165 | switch (ConvTy) { | ||||
17166 | case Compatible: | ||||
17167 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | ||||
17168 | return false; | ||||
17169 | |||||
17170 | case PointerToInt: | ||||
17171 | if (getLangOpts().CPlusPlus) { | ||||
17172 | DiagKind = diag::err_typecheck_convert_pointer_int; | ||||
17173 | isInvalid = true; | ||||
17174 | } else { | ||||
17175 | DiagKind = diag::ext_typecheck_convert_pointer_int; | ||||
17176 | } | ||||
17177 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17178 | MayHaveConvFixit = true; | ||||
17179 | break; | ||||
17180 | case IntToPointer: | ||||
17181 | if (getLangOpts().CPlusPlus) { | ||||
17182 | DiagKind = diag::err_typecheck_convert_int_pointer; | ||||
17183 | isInvalid = true; | ||||
17184 | } else { | ||||
17185 | DiagKind = diag::ext_typecheck_convert_int_pointer; | ||||
17186 | } | ||||
17187 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17188 | MayHaveConvFixit = true; | ||||
17189 | break; | ||||
17190 | case IncompatibleFunctionPointerStrict: | ||||
17191 | DiagKind = | ||||
17192 | diag::warn_typecheck_convert_incompatible_function_pointer_strict; | ||||
17193 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17194 | MayHaveConvFixit = true; | ||||
17195 | break; | ||||
17196 | case IncompatibleFunctionPointer: | ||||
17197 | if (getLangOpts().CPlusPlus) { | ||||
17198 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | ||||
17199 | isInvalid = true; | ||||
17200 | } else { | ||||
17201 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | ||||
17202 | } | ||||
17203 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17204 | MayHaveConvFixit = true; | ||||
17205 | break; | ||||
17206 | case IncompatiblePointer: | ||||
17207 | if (Action == AA_Passing_CFAudited) { | ||||
17208 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | ||||
17209 | } else if (getLangOpts().CPlusPlus) { | ||||
17210 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | ||||
17211 | isInvalid = true; | ||||
17212 | } else { | ||||
17213 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | ||||
17214 | } | ||||
17215 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | ||||
17216 | SrcType->isObjCObjectPointerType(); | ||||
17217 | if (!CheckInferredResultType) { | ||||
17218 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17219 | } else if (CheckInferredResultType) { | ||||
17220 | SrcType = SrcType.getUnqualifiedType(); | ||||
17221 | DstType = DstType.getUnqualifiedType(); | ||||
17222 | } | ||||
17223 | MayHaveConvFixit = true; | ||||
17224 | break; | ||||
17225 | case IncompatiblePointerSign: | ||||
17226 | if (getLangOpts().CPlusPlus) { | ||||
17227 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | ||||
17228 | isInvalid = true; | ||||
17229 | } else { | ||||
17230 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | ||||
17231 | } | ||||
17232 | break; | ||||
17233 | case FunctionVoidPointer: | ||||
17234 | if (getLangOpts().CPlusPlus) { | ||||
17235 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | ||||
17236 | isInvalid = true; | ||||
17237 | } else { | ||||
17238 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | ||||
17239 | } | ||||
17240 | break; | ||||
17241 | case IncompatiblePointerDiscardsQualifiers: { | ||||
17242 | // Perform array-to-pointer decay if necessary. | ||||
17243 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | ||||
17244 | |||||
17245 | isInvalid = true; | ||||
17246 | |||||
17247 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | ||||
17248 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | ||||
17249 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | ||||
17250 | DiagKind = diag::err_typecheck_incompatible_address_space; | ||||
17251 | break; | ||||
17252 | |||||
17253 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | ||||
17254 | DiagKind = diag::err_typecheck_incompatible_ownership; | ||||
17255 | break; | ||||
17256 | } | ||||
17257 | |||||
17258 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "clang/lib/Sema/SemaExpr.cpp", 17258); | ||||
17259 | // fallthrough | ||||
17260 | } | ||||
17261 | case CompatiblePointerDiscardsQualifiers: | ||||
17262 | // If the qualifiers lost were because we were applying the | ||||
17263 | // (deprecated) C++ conversion from a string literal to a char* | ||||
17264 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | ||||
17265 | // Ideally, this check would be performed in | ||||
17266 | // checkPointerTypesForAssignment. However, that would require a | ||||
17267 | // bit of refactoring (so that the second argument is an | ||||
17268 | // expression, rather than a type), which should be done as part | ||||
17269 | // of a larger effort to fix checkPointerTypesForAssignment for | ||||
17270 | // C++ semantics. | ||||
17271 | if (getLangOpts().CPlusPlus && | ||||
17272 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | ||||
17273 | return false; | ||||
17274 | if (getLangOpts().CPlusPlus) { | ||||
17275 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | ||||
17276 | isInvalid = true; | ||||
17277 | } else { | ||||
17278 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | ||||
17279 | } | ||||
17280 | |||||
17281 | break; | ||||
17282 | case IncompatibleNestedPointerQualifiers: | ||||
17283 | if (getLangOpts().CPlusPlus) { | ||||
17284 | isInvalid = true; | ||||
17285 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | ||||
17286 | } else { | ||||
17287 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | ||||
17288 | } | ||||
17289 | break; | ||||
17290 | case IncompatibleNestedPointerAddressSpaceMismatch: | ||||
17291 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | ||||
17292 | isInvalid = true; | ||||
17293 | break; | ||||
17294 | case IntToBlockPointer: | ||||
17295 | DiagKind = diag::err_int_to_block_pointer; | ||||
17296 | isInvalid = true; | ||||
17297 | break; | ||||
17298 | case IncompatibleBlockPointer: | ||||
17299 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | ||||
17300 | isInvalid = true; | ||||
17301 | break; | ||||
17302 | case IncompatibleObjCQualifiedId: { | ||||
17303 | if (SrcType->isObjCQualifiedIdType()) { | ||||
17304 | const ObjCObjectPointerType *srcOPT = | ||||
17305 | SrcType->castAs<ObjCObjectPointerType>(); | ||||
17306 | for (auto *srcProto : srcOPT->quals()) { | ||||
17307 | PDecl = srcProto; | ||||
17308 | break; | ||||
17309 | } | ||||
17310 | if (const ObjCInterfaceType *IFaceT = | ||||
17311 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
17312 | IFace = IFaceT->getDecl(); | ||||
17313 | } | ||||
17314 | else if (DstType->isObjCQualifiedIdType()) { | ||||
17315 | const ObjCObjectPointerType *dstOPT = | ||||
17316 | DstType->castAs<ObjCObjectPointerType>(); | ||||
17317 | for (auto *dstProto : dstOPT->quals()) { | ||||
17318 | PDecl = dstProto; | ||||
17319 | break; | ||||
17320 | } | ||||
17321 | if (const ObjCInterfaceType *IFaceT = | ||||
17322 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
17323 | IFace = IFaceT->getDecl(); | ||||
17324 | } | ||||
17325 | if (getLangOpts().CPlusPlus) { | ||||
17326 | DiagKind = diag::err_incompatible_qualified_id; | ||||
17327 | isInvalid = true; | ||||
17328 | } else { | ||||
17329 | DiagKind = diag::warn_incompatible_qualified_id; | ||||
17330 | } | ||||
17331 | break; | ||||
17332 | } | ||||
17333 | case IncompatibleVectors: | ||||
17334 | if (getLangOpts().CPlusPlus) { | ||||
17335 | DiagKind = diag::err_incompatible_vectors; | ||||
17336 | isInvalid = true; | ||||
17337 | } else { | ||||
17338 | DiagKind = diag::warn_incompatible_vectors; | ||||
17339 | } | ||||
17340 | break; | ||||
17341 | case IncompatibleObjCWeakRef: | ||||
17342 | DiagKind = diag::err_arc_weak_unavailable_assign; | ||||
17343 | isInvalid = true; | ||||
17344 | break; | ||||
17345 | case Incompatible: | ||||
17346 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | ||||
17347 | if (Complained) | ||||
17348 | *Complained = true; | ||||
17349 | return true; | ||||
17350 | } | ||||
17351 | |||||
17352 | DiagKind = diag::err_typecheck_convert_incompatible; | ||||
17353 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17354 | MayHaveConvFixit = true; | ||||
17355 | isInvalid = true; | ||||
17356 | MayHaveFunctionDiff = true; | ||||
17357 | break; | ||||
17358 | } | ||||
17359 | |||||
17360 | QualType FirstType, SecondType; | ||||
17361 | switch (Action) { | ||||
17362 | case AA_Assigning: | ||||
17363 | case AA_Initializing: | ||||
17364 | // The destination type comes first. | ||||
17365 | FirstType = DstType; | ||||
17366 | SecondType = SrcType; | ||||
17367 | break; | ||||
17368 | |||||
17369 | case AA_Returning: | ||||
17370 | case AA_Passing: | ||||
17371 | case AA_Passing_CFAudited: | ||||
17372 | case AA_Converting: | ||||
17373 | case AA_Sending: | ||||
17374 | case AA_Casting: | ||||
17375 | // The source type comes first. | ||||
17376 | FirstType = SrcType; | ||||
17377 | SecondType = DstType; | ||||
17378 | break; | ||||
17379 | } | ||||
17380 | |||||
17381 | PartialDiagnostic FDiag = PDiag(DiagKind); | ||||
17382 | AssignmentAction ActionForDiag = Action; | ||||
17383 | if (Action == AA_Passing_CFAudited) | ||||
17384 | ActionForDiag = AA_Passing; | ||||
17385 | |||||
17386 | FDiag << FirstType << SecondType << ActionForDiag | ||||
17387 | << SrcExpr->getSourceRange(); | ||||
17388 | |||||
17389 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || | ||||
17390 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { | ||||
17391 | auto isPlainChar = [](const clang::Type *Type) { | ||||
17392 | return Type->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
17393 | Type->isSpecificBuiltinType(BuiltinType::Char_U); | ||||
17394 | }; | ||||
17395 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || | ||||
17396 | isPlainChar(SecondType->getPointeeOrArrayElementType())); | ||||
17397 | } | ||||
17398 | |||||
17399 | // If we can fix the conversion, suggest the FixIts. | ||||
17400 | if (!ConvHints.isNull()) { | ||||
17401 | for (FixItHint &H : ConvHints.Hints) | ||||
17402 | FDiag << H; | ||||
17403 | } | ||||
17404 | |||||
17405 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | ||||
17406 | |||||
17407 | if (MayHaveFunctionDiff) | ||||
17408 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | ||||
17409 | |||||
17410 | Diag(Loc, FDiag); | ||||
17411 | if ((DiagKind == diag::warn_incompatible_qualified_id || | ||||
17412 | DiagKind == diag::err_incompatible_qualified_id) && | ||||
17413 | PDecl && IFace && !IFace->hasDefinition()) | ||||
17414 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | ||||
17415 | << IFace << PDecl; | ||||
17416 | |||||
17417 | if (SecondType == Context.OverloadTy) | ||||
17418 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | ||||
17419 | FirstType, /*TakingAddress=*/true); | ||||
17420 | |||||
17421 | if (CheckInferredResultType) | ||||
17422 | EmitRelatedResultTypeNote(SrcExpr); | ||||
17423 | |||||
17424 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | ||||
17425 | EmitRelatedResultTypeNoteForReturn(DstType); | ||||
17426 | |||||
17427 | if (Complained) | ||||
17428 | *Complained = true; | ||||
17429 | return isInvalid; | ||||
17430 | } | ||||
17431 | |||||
17432 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
17433 | llvm::APSInt *Result, | ||||
17434 | AllowFoldKind CanFold) { | ||||
17435 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | ||||
17436 | public: | ||||
17437 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
17438 | QualType T) override { | ||||
17439 | return S.Diag(Loc, diag::err_ice_not_integral) | ||||
17440 | << T << S.LangOpts.CPlusPlus; | ||||
17441 | } | ||||
17442 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
17443 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
17444 | } | ||||
17445 | } Diagnoser; | ||||
17446 | |||||
17447 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
17448 | } | ||||
17449 | |||||
17450 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
17451 | llvm::APSInt *Result, | ||||
17452 | unsigned DiagID, | ||||
17453 | AllowFoldKind CanFold) { | ||||
17454 | class IDDiagnoser : public VerifyICEDiagnoser { | ||||
17455 | unsigned DiagID; | ||||
17456 | |||||
17457 | public: | ||||
17458 | IDDiagnoser(unsigned DiagID) | ||||
17459 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | ||||
17460 | |||||
17461 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
17462 | return S.Diag(Loc, DiagID); | ||||
17463 | } | ||||
17464 | } Diagnoser(DiagID); | ||||
17465 | |||||
17466 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
17467 | } | ||||
17468 | |||||
17469 | Sema::SemaDiagnosticBuilder | ||||
17470 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
17471 | QualType T) { | ||||
17472 | return diagnoseNotICE(S, Loc); | ||||
17473 | } | ||||
17474 | |||||
17475 | Sema::SemaDiagnosticBuilder | ||||
17476 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | ||||
17477 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
17478 | } | ||||
17479 | |||||
17480 | ExprResult | ||||
17481 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | ||||
17482 | VerifyICEDiagnoser &Diagnoser, | ||||
17483 | AllowFoldKind CanFold) { | ||||
17484 | SourceLocation DiagLoc = E->getBeginLoc(); | ||||
17485 | |||||
17486 | if (getLangOpts().CPlusPlus11) { | ||||
17487 | // C++11 [expr.const]p5: | ||||
17488 | // If an expression of literal class type is used in a context where an | ||||
17489 | // integral constant expression is required, then that class type shall | ||||
17490 | // have a single non-explicit conversion function to an integral or | ||||
17491 | // unscoped enumeration type | ||||
17492 | ExprResult Converted; | ||||
17493 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | ||||
17494 | VerifyICEDiagnoser &BaseDiagnoser; | ||||
17495 | public: | ||||
17496 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | ||||
17497 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | ||||
17498 | BaseDiagnoser.Suppress, true), | ||||
17499 | BaseDiagnoser(BaseDiagnoser) {} | ||||
17500 | |||||
17501 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | ||||
17502 | QualType T) override { | ||||
17503 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | ||||
17504 | } | ||||
17505 | |||||
17506 | SemaDiagnosticBuilder diagnoseIncomplete( | ||||
17507 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
17508 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | ||||
17509 | } | ||||
17510 | |||||
17511 | SemaDiagnosticBuilder diagnoseExplicitConv( | ||||
17512 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
17513 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | ||||
17514 | } | ||||
17515 | |||||
17516 | SemaDiagnosticBuilder noteExplicitConv( | ||||
17517 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
17518 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
17519 | << ConvTy->isEnumeralType() << ConvTy; | ||||
17520 | } | ||||
17521 | |||||
17522 | SemaDiagnosticBuilder diagnoseAmbiguous( | ||||
17523 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
17524 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | ||||
17525 | } | ||||
17526 | |||||
17527 | SemaDiagnosticBuilder noteAmbiguous( | ||||
17528 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
17529 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
17530 | << ConvTy->isEnumeralType() << ConvTy; | ||||
17531 | } | ||||
17532 | |||||
17533 | SemaDiagnosticBuilder diagnoseConversion( | ||||
17534 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
17535 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "clang/lib/Sema/SemaExpr.cpp", 17535); | ||||
17536 | } | ||||
17537 | } ConvertDiagnoser(Diagnoser); | ||||
17538 | |||||
17539 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | ||||
17540 | ConvertDiagnoser); | ||||
17541 | if (Converted.isInvalid()) | ||||
17542 | return Converted; | ||||
17543 | E = Converted.get(); | ||||
17544 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | ||||
17545 | return ExprError(); | ||||
17546 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
17547 | // An ICE must be of integral or unscoped enumeration type. | ||||
17548 | if (!Diagnoser.Suppress) | ||||
17549 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | ||||
17550 | << E->getSourceRange(); | ||||
17551 | return ExprError(); | ||||
17552 | } | ||||
17553 | |||||
17554 | ExprResult RValueExpr = DefaultLvalueConversion(E); | ||||
17555 | if (RValueExpr.isInvalid()) | ||||
17556 | return ExprError(); | ||||
17557 | |||||
17558 | E = RValueExpr.get(); | ||||
17559 | |||||
17560 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | ||||
17561 | // in the non-ICE case. | ||||
17562 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | ||||
17563 | if (Result) | ||||
17564 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | ||||
17565 | if (!isa<ConstantExpr>(E)) | ||||
17566 | E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) | ||||
17567 | : ConstantExpr::Create(Context, E); | ||||
17568 | return E; | ||||
17569 | } | ||||
17570 | |||||
17571 | Expr::EvalResult EvalResult; | ||||
17572 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
17573 | EvalResult.Diag = &Notes; | ||||
17574 | |||||
17575 | // Try to evaluate the expression, and produce diagnostics explaining why it's | ||||
17576 | // not a constant expression as a side-effect. | ||||
17577 | bool Folded = | ||||
17578 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | ||||
17579 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | ||||
17580 | |||||
17581 | if (!isa<ConstantExpr>(E)) | ||||
17582 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | ||||
17583 | |||||
17584 | // In C++11, we can rely on diagnostics being produced for any expression | ||||
17585 | // which is not a constant expression. If no diagnostics were produced, then | ||||
17586 | // this is a constant expression. | ||||
17587 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | ||||
17588 | if (Result) | ||||
17589 | *Result = EvalResult.Val.getInt(); | ||||
17590 | return E; | ||||
17591 | } | ||||
17592 | |||||
17593 | // If our only note is the usual "invalid subexpression" note, just point | ||||
17594 | // the caret at its location rather than producing an essentially | ||||
17595 | // redundant note. | ||||
17596 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||
17597 | diag::note_invalid_subexpr_in_const_expr) { | ||||
17598 | DiagLoc = Notes[0].first; | ||||
17599 | Notes.clear(); | ||||
17600 | } | ||||
17601 | |||||
17602 | if (!Folded || !CanFold) { | ||||
17603 | if (!Diagnoser.Suppress) { | ||||
17604 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | ||||
17605 | for (const PartialDiagnosticAt &Note : Notes) | ||||
17606 | Diag(Note.first, Note.second); | ||||
17607 | } | ||||
17608 | |||||
17609 | return ExprError(); | ||||
17610 | } | ||||
17611 | |||||
17612 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | ||||
17613 | for (const PartialDiagnosticAt &Note : Notes) | ||||
17614 | Diag(Note.first, Note.second); | ||||
17615 | |||||
17616 | if (Result) | ||||
17617 | *Result = EvalResult.Val.getInt(); | ||||
17618 | return E; | ||||
17619 | } | ||||
17620 | |||||
17621 | namespace { | ||||
17622 | // Handle the case where we conclude a expression which we speculatively | ||||
17623 | // considered to be unevaluated is actually evaluated. | ||||
17624 | class TransformToPE : public TreeTransform<TransformToPE> { | ||||
17625 | typedef TreeTransform<TransformToPE> BaseTransform; | ||||
17626 | |||||
17627 | public: | ||||
17628 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | ||||
17629 | |||||
17630 | // Make sure we redo semantic analysis | ||||
17631 | bool AlwaysRebuild() { return true; } | ||||
17632 | bool ReplacingOriginal() { return true; } | ||||
17633 | |||||
17634 | // We need to special-case DeclRefExprs referring to FieldDecls which | ||||
17635 | // are not part of a member pointer formation; normal TreeTransforming | ||||
17636 | // doesn't catch this case because of the way we represent them in the AST. | ||||
17637 | // FIXME: This is a bit ugly; is it really the best way to handle this | ||||
17638 | // case? | ||||
17639 | // | ||||
17640 | // Error on DeclRefExprs referring to FieldDecls. | ||||
17641 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
17642 | if (isa<FieldDecl>(E->getDecl()) && | ||||
17643 | !SemaRef.isUnevaluatedContext()) | ||||
17644 | return SemaRef.Diag(E->getLocation(), | ||||
17645 | diag::err_invalid_non_static_member_use) | ||||
17646 | << E->getDecl() << E->getSourceRange(); | ||||
17647 | |||||
17648 | return BaseTransform::TransformDeclRefExpr(E); | ||||
17649 | } | ||||
17650 | |||||
17651 | // Exception: filter out member pointer formation | ||||
17652 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | ||||
17653 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | ||||
17654 | return E; | ||||
17655 | |||||
17656 | return BaseTransform::TransformUnaryOperator(E); | ||||
17657 | } | ||||
17658 | |||||
17659 | // The body of a lambda-expression is in a separate expression evaluation | ||||
17660 | // context so never needs to be transformed. | ||||
17661 | // FIXME: Ideally we wouldn't transform the closure type either, and would | ||||
17662 | // just recreate the capture expressions and lambda expression. | ||||
17663 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | ||||
17664 | return SkipLambdaBody(E, Body); | ||||
17665 | } | ||||
17666 | }; | ||||
17667 | } | ||||
17668 | |||||
17669 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | ||||
17670 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17671, __extension__ __PRETTY_FUNCTION__ )) | ||||
17671 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17671, __extension__ __PRETTY_FUNCTION__ )); | ||||
17672 | ExprEvalContexts.back().Context = | ||||
17673 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | ||||
17674 | if (isUnevaluatedContext()) | ||||
17675 | return E; | ||||
17676 | return TransformToPE(*this).TransformExpr(E); | ||||
17677 | } | ||||
17678 | |||||
17679 | TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { | ||||
17680 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17681, __extension__ __PRETTY_FUNCTION__ )) | ||||
17681 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17681, __extension__ __PRETTY_FUNCTION__ )); | ||||
17682 | ExprEvalContexts.back().Context = | ||||
17683 | ExprEvalContexts[ExprEvalContexts.size() - 2].Context; | ||||
17684 | if (isUnevaluatedContext()) | ||||
17685 | return TInfo; | ||||
17686 | return TransformToPE(*this).TransformType(TInfo); | ||||
17687 | } | ||||
17688 | |||||
17689 | void | ||||
17690 | Sema::PushExpressionEvaluationContext( | ||||
17691 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | ||||
17692 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
17693 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | ||||
17694 | LambdaContextDecl, ExprContext); | ||||
17695 | |||||
17696 | // Discarded statements and immediate contexts nested in other | ||||
17697 | // discarded statements or immediate context are themselves | ||||
17698 | // a discarded statement or an immediate context, respectively. | ||||
17699 | ExprEvalContexts.back().InDiscardedStatement = | ||||
17700 | ExprEvalContexts[ExprEvalContexts.size() - 2] | ||||
17701 | .isDiscardedStatementContext(); | ||||
17702 | ExprEvalContexts.back().InImmediateFunctionContext = | ||||
17703 | ExprEvalContexts[ExprEvalContexts.size() - 2] | ||||
17704 | .isImmediateFunctionContext(); | ||||
17705 | |||||
17706 | Cleanup.reset(); | ||||
17707 | if (!MaybeODRUseExprs.empty()) | ||||
17708 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | ||||
17709 | } | ||||
17710 | |||||
17711 | void | ||||
17712 | Sema::PushExpressionEvaluationContext( | ||||
17713 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | ||||
17714 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
17715 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | ||||
17716 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | ||||
17717 | } | ||||
17718 | |||||
17719 | namespace { | ||||
17720 | |||||
17721 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | ||||
17722 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | ||||
17723 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | ||||
17724 | if (E->getOpcode() == UO_Deref) | ||||
17725 | return CheckPossibleDeref(S, E->getSubExpr()); | ||||
17726 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | ||||
17727 | return CheckPossibleDeref(S, E->getBase()); | ||||
17728 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | ||||
17729 | return CheckPossibleDeref(S, E->getBase()); | ||||
17730 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | ||||
17731 | QualType Inner; | ||||
17732 | QualType Ty = E->getType(); | ||||
17733 | if (const auto *Ptr = Ty->getAs<PointerType>()) | ||||
17734 | Inner = Ptr->getPointeeType(); | ||||
17735 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | ||||
17736 | Inner = Arr->getElementType(); | ||||
17737 | else | ||||
17738 | return nullptr; | ||||
17739 | |||||
17740 | if (Inner->hasAttr(attr::NoDeref)) | ||||
17741 | return E; | ||||
17742 | } | ||||
17743 | return nullptr; | ||||
17744 | } | ||||
17745 | |||||
17746 | } // namespace | ||||
17747 | |||||
17748 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | ||||
17749 | for (const Expr *E : Rec.PossibleDerefs) { | ||||
17750 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | ||||
17751 | if (DeclRef) { | ||||
17752 | const ValueDecl *Decl = DeclRef->getDecl(); | ||||
17753 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | ||||
17754 | << Decl->getName() << E->getSourceRange(); | ||||
17755 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | ||||
17756 | } else { | ||||
17757 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | ||||
17758 | << E->getSourceRange(); | ||||
17759 | } | ||||
17760 | } | ||||
17761 | Rec.PossibleDerefs.clear(); | ||||
17762 | } | ||||
17763 | |||||
17764 | /// Check whether E, which is either a discarded-value expression or an | ||||
17765 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | ||||
17766 | /// and if so, remove it from the list of volatile-qualified assignments that | ||||
17767 | /// we are going to warn are deprecated. | ||||
17768 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | ||||
17769 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | ||||
17770 | return; | ||||
17771 | |||||
17772 | // Note: ignoring parens here is not justified by the standard rules, but | ||||
17773 | // ignoring parentheses seems like a more reasonable approach, and this only | ||||
17774 | // drives a deprecation warning so doesn't affect conformance. | ||||
17775 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | ||||
17776 | if (BO->getOpcode() == BO_Assign) { | ||||
17777 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | ||||
17778 | llvm::erase_value(LHSs, BO->getLHS()); | ||||
17779 | } | ||||
17780 | } | ||||
17781 | } | ||||
17782 | |||||
17783 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | ||||
17784 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || | ||||
17785 | !Decl->isConsteval() || isConstantEvaluated() || | ||||
17786 | isCheckingDefaultArgumentOrInitializer() || | ||||
17787 | RebuildingImmediateInvocation || isImmediateFunctionContext()) | ||||
17788 | return E; | ||||
17789 | |||||
17790 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | ||||
17791 | /// It's OK if this fails; we'll also remove this in | ||||
17792 | /// HandleImmediateInvocations, but catching it here allows us to avoid | ||||
17793 | /// walking the AST looking for it in simple cases. | ||||
17794 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | ||||
17795 | if (auto *DeclRef = | ||||
17796 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | ||||
17797 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | ||||
17798 | |||||
17799 | E = MaybeCreateExprWithCleanups(E); | ||||
17800 | |||||
17801 | ConstantExpr *Res = ConstantExpr::Create( | ||||
17802 | getASTContext(), E.get(), | ||||
17803 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | ||||
17804 | getASTContext()), | ||||
17805 | /*IsImmediateInvocation*/ true); | ||||
17806 | /// Value-dependent constant expressions should not be immediately | ||||
17807 | /// evaluated until they are instantiated. | ||||
17808 | if (!Res->isValueDependent()) | ||||
17809 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | ||||
17810 | return Res; | ||||
17811 | } | ||||
17812 | |||||
17813 | static void EvaluateAndDiagnoseImmediateInvocation( | ||||
17814 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | ||||
17815 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
17816 | Expr::EvalResult Eval; | ||||
17817 | Eval.Diag = &Notes; | ||||
17818 | ConstantExpr *CE = Candidate.getPointer(); | ||||
17819 | bool Result = CE->EvaluateAsConstantExpr( | ||||
17820 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | ||||
17821 | if (!Result || !Notes.empty()) { | ||||
17822 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | ||||
17823 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | ||||
17824 | InnerExpr = FunctionalCast->getSubExpr(); | ||||
17825 | FunctionDecl *FD = nullptr; | ||||
17826 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | ||||
17827 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | ||||
17828 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | ||||
17829 | FD = Call->getConstructor(); | ||||
17830 | else | ||||
17831 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp" , 17831); | ||||
17832 | assert(FD && FD->isConsteval())(static_cast <bool> (FD && FD->isConsteval() ) ? void (0) : __assert_fail ("FD && FD->isConsteval()" , "clang/lib/Sema/SemaExpr.cpp", 17832, __extension__ __PRETTY_FUNCTION__ )); | ||||
17833 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | ||||
17834 | if (auto Context = | ||||
17835 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { | ||||
17836 | SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer) | ||||
17837 | << Context->Decl; | ||||
17838 | SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at); | ||||
17839 | } | ||||
17840 | for (auto &Note : Notes) | ||||
17841 | SemaRef.Diag(Note.first, Note.second); | ||||
17842 | return; | ||||
17843 | } | ||||
17844 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | ||||
17845 | } | ||||
17846 | |||||
17847 | static void RemoveNestedImmediateInvocation( | ||||
17848 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | ||||
17849 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | ||||
17850 | struct ComplexRemove : TreeTransform<ComplexRemove> { | ||||
17851 | using Base = TreeTransform<ComplexRemove>; | ||||
17852 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
17853 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | ||||
17854 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | ||||
17855 | CurrentII; | ||||
17856 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | ||||
17857 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | ||||
17858 | SmallVector<Sema::ImmediateInvocationCandidate, | ||||
17859 | 4>::reverse_iterator Current) | ||||
17860 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | ||||
17861 | void RemoveImmediateInvocation(ConstantExpr* E) { | ||||
17862 | auto It = std::find_if(CurrentII, IISet.rend(), | ||||
17863 | [E](Sema::ImmediateInvocationCandidate Elem) { | ||||
17864 | return Elem.getPointer() == E; | ||||
17865 | }); | ||||
17866 | assert(It != IISet.rend() &&(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 17868, __extension__ __PRETTY_FUNCTION__ )) | ||||
17867 | "ConstantExpr marked IsImmediateInvocation should "(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 17868, __extension__ __PRETTY_FUNCTION__ )) | ||||
17868 | "be present")(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 17868, __extension__ __PRETTY_FUNCTION__ )); | ||||
17869 | It->setInt(1); // Mark as deleted | ||||
17870 | } | ||||
17871 | ExprResult TransformConstantExpr(ConstantExpr *E) { | ||||
17872 | if (!E->isImmediateInvocation()) | ||||
17873 | return Base::TransformConstantExpr(E); | ||||
17874 | RemoveImmediateInvocation(E); | ||||
17875 | return Base::TransformExpr(E->getSubExpr()); | ||||
17876 | } | ||||
17877 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | ||||
17878 | /// we need to remove its DeclRefExpr from the DRSet. | ||||
17879 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
17880 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | ||||
17881 | return Base::TransformCXXOperatorCallExpr(E); | ||||
17882 | } | ||||
17883 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | ||||
17884 | /// here. | ||||
17885 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | ||||
17886 | if (!Init) | ||||
17887 | return Init; | ||||
17888 | /// ConstantExpr are the first layer of implicit node to be removed so if | ||||
17889 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | ||||
17890 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||
17891 | if (CE->isImmediateInvocation()) | ||||
17892 | RemoveImmediateInvocation(CE); | ||||
17893 | return Base::TransformInitializer(Init, NotCopyInit); | ||||
17894 | } | ||||
17895 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
17896 | DRSet.erase(E); | ||||
17897 | return E; | ||||
17898 | } | ||||
17899 | ExprResult TransformLambdaExpr(LambdaExpr *E) { | ||||
17900 | // Do not rebuild lambdas to avoid creating a new type. | ||||
17901 | // Lambdas have already been processed inside their eval context. | ||||
17902 | return E; | ||||
17903 | } | ||||
17904 | bool AlwaysRebuild() { return false; } | ||||
17905 | bool ReplacingOriginal() { return true; } | ||||
17906 | bool AllowSkippingCXXConstructExpr() { | ||||
17907 | bool Res = AllowSkippingFirstCXXConstructExpr; | ||||
17908 | AllowSkippingFirstCXXConstructExpr = true; | ||||
17909 | return Res; | ||||
17910 | } | ||||
17911 | bool AllowSkippingFirstCXXConstructExpr = true; | ||||
17912 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | ||||
17913 | Rec.ImmediateInvocationCandidates, It); | ||||
17914 | |||||
17915 | /// CXXConstructExpr with a single argument are getting skipped by | ||||
17916 | /// TreeTransform in some situtation because they could be implicit. This | ||||
17917 | /// can only occur for the top-level CXXConstructExpr because it is used | ||||
17918 | /// nowhere in the expression being transformed therefore will not be rebuilt. | ||||
17919 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | ||||
17920 | /// skipping the first CXXConstructExpr. | ||||
17921 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | ||||
17922 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | ||||
17923 | |||||
17924 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | ||||
17925 | // The result may not be usable in case of previous compilation errors. | ||||
17926 | // In this case evaluation of the expression may result in crash so just | ||||
17927 | // don't do anything further with the result. | ||||
17928 | if (Res.isUsable()) { | ||||
17929 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | ||||
17930 | It->getPointer()->setSubExpr(Res.get()); | ||||
17931 | } | ||||
17932 | } | ||||
17933 | |||||
17934 | static void | ||||
17935 | HandleImmediateInvocations(Sema &SemaRef, | ||||
17936 | Sema::ExpressionEvaluationContextRecord &Rec) { | ||||
17937 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | ||||
17938 | Rec.ReferenceToConsteval.size() == 0) || | ||||
17939 | SemaRef.RebuildingImmediateInvocation) | ||||
17940 | return; | ||||
17941 | |||||
17942 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | ||||
17943 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | ||||
17944 | /// need to remove ReferenceToConsteval in the immediate invocation. | ||||
17945 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | ||||
17946 | |||||
17947 | /// Prevent sema calls during the tree transform from adding pointers that | ||||
17948 | /// are already in the sets. | ||||
17949 | llvm::SaveAndRestore DisableIITracking( | ||||
17950 | SemaRef.RebuildingImmediateInvocation, true); | ||||
17951 | |||||
17952 | /// Prevent diagnostic during tree transfrom as they are duplicates | ||||
17953 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | ||||
17954 | |||||
17955 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | ||||
17956 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | ||||
17957 | if (!It->getInt()) | ||||
17958 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | ||||
17959 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | ||||
17960 | Rec.ReferenceToConsteval.size()) { | ||||
17961 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | ||||
17962 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
17963 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | ||||
17964 | bool VisitDeclRefExpr(DeclRefExpr *E) { | ||||
17965 | DRSet.erase(E); | ||||
17966 | return DRSet.size(); | ||||
17967 | } | ||||
17968 | } Visitor(Rec.ReferenceToConsteval); | ||||
17969 | Visitor.TraverseStmt( | ||||
17970 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | ||||
17971 | } | ||||
17972 | for (auto CE : Rec.ImmediateInvocationCandidates) | ||||
17973 | if (!CE.getInt()) | ||||
17974 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | ||||
17975 | for (auto *DR : Rec.ReferenceToConsteval) { | ||||
17976 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | ||||
17977 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | ||||
17978 | << FD; | ||||
17979 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | ||||
17980 | } | ||||
17981 | } | ||||
17982 | |||||
17983 | void Sema::PopExpressionEvaluationContext() { | ||||
17984 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | ||||
17985 | unsigned NumTypos = Rec.NumTypos; | ||||
17986 | |||||
17987 | if (!Rec.Lambdas.empty()) { | ||||
17988 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | ||||
17989 | if (!getLangOpts().CPlusPlus20 && | ||||
17990 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || | ||||
17991 | Rec.isUnevaluated() || | ||||
17992 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { | ||||
17993 | unsigned D; | ||||
17994 | if (Rec.isUnevaluated()) { | ||||
17995 | // C++11 [expr.prim.lambda]p2: | ||||
17996 | // A lambda-expression shall not appear in an unevaluated operand | ||||
17997 | // (Clause 5). | ||||
17998 | D = diag::err_lambda_unevaluated_operand; | ||||
17999 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | ||||
18000 | // C++1y [expr.const]p2: | ||||
18001 | // A conditional-expression e is a core constant expression unless the | ||||
18002 | // evaluation of e, following the rules of the abstract machine, would | ||||
18003 | // evaluate [...] a lambda-expression. | ||||
18004 | D = diag::err_lambda_in_constant_expression; | ||||
18005 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | ||||
18006 | // C++17 [expr.prim.lamda]p2: | ||||
18007 | // A lambda-expression shall not appear [...] in a template-argument. | ||||
18008 | D = diag::err_lambda_in_invalid_context; | ||||
18009 | } else | ||||
18010 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "clang/lib/Sema/SemaExpr.cpp", 18010); | ||||
18011 | |||||
18012 | for (const auto *L : Rec.Lambdas) | ||||
18013 | Diag(L->getBeginLoc(), D); | ||||
18014 | } | ||||
18015 | } | ||||
18016 | |||||
18017 | WarnOnPendingNoDerefs(Rec); | ||||
18018 | HandleImmediateInvocations(*this, Rec); | ||||
18019 | |||||
18020 | // Warn on any volatile-qualified simple-assignments that are not discarded- | ||||
18021 | // value expressions nor unevaluated operands (those cases get removed from | ||||
18022 | // this list by CheckUnusedVolatileAssignment). | ||||
18023 | for (auto *BO : Rec.VolatileAssignmentLHSs) | ||||
18024 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | ||||
18025 | << BO->getType(); | ||||
18026 | |||||
18027 | // When are coming out of an unevaluated context, clear out any | ||||
18028 | // temporaries that we may have created as part of the evaluation of | ||||
18029 | // the expression in that context: they aren't relevant because they | ||||
18030 | // will never be constructed. | ||||
18031 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | ||||
18032 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | ||||
18033 | ExprCleanupObjects.end()); | ||||
18034 | Cleanup = Rec.ParentCleanup; | ||||
18035 | CleanupVarDeclMarking(); | ||||
18036 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | ||||
18037 | // Otherwise, merge the contexts together. | ||||
18038 | } else { | ||||
18039 | Cleanup.mergeFrom(Rec.ParentCleanup); | ||||
18040 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | ||||
18041 | Rec.SavedMaybeODRUseExprs.end()); | ||||
18042 | } | ||||
18043 | |||||
18044 | // Pop the current expression evaluation context off the stack. | ||||
18045 | ExprEvalContexts.pop_back(); | ||||
18046 | |||||
18047 | // The global expression evaluation context record is never popped. | ||||
18048 | ExprEvalContexts.back().NumTypos += NumTypos; | ||||
18049 | } | ||||
18050 | |||||
18051 | void Sema::DiscardCleanupsInEvaluationContext() { | ||||
18052 | ExprCleanupObjects.erase( | ||||
18053 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | ||||
18054 | ExprCleanupObjects.end()); | ||||
18055 | Cleanup.reset(); | ||||
18056 | MaybeODRUseExprs.clear(); | ||||
18057 | } | ||||
18058 | |||||
18059 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | ||||
18060 | ExprResult Result = CheckPlaceholderExpr(E); | ||||
18061 | if (Result.isInvalid()) | ||||
18062 | return ExprError(); | ||||
18063 | E = Result.get(); | ||||
18064 | if (!E->getType()->isVariablyModifiedType()) | ||||
18065 | return E; | ||||
18066 | return TransformToPotentiallyEvaluated(E); | ||||
18067 | } | ||||
18068 | |||||
18069 | /// Are we in a context that is potentially constant evaluated per C++20 | ||||
18070 | /// [expr.const]p12? | ||||
18071 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | ||||
18072 | /// C++2a [expr.const]p12: | ||||
18073 | // An expression or conversion is potentially constant evaluated if it is | ||||
18074 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
18075 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
18076 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: | ||||
18077 | |||||
18078 | // -- a manifestly constant-evaluated expression, | ||||
18079 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
18080 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
18081 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
18082 | // -- a potentially-evaluated expression, | ||||
18083 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
18084 | // -- an immediate subexpression of a braced-init-list, | ||||
18085 | |||||
18086 | // -- [FIXME] an expression of the form & cast-expression that occurs | ||||
18087 | // within a templated entity | ||||
18088 | // -- a subexpression of one of the above that is not a subexpression of | ||||
18089 | // a nested unevaluated operand. | ||||
18090 | return true; | ||||
18091 | |||||
18092 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
18093 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
18094 | // Expressions in this context are never evaluated. | ||||
18095 | return false; | ||||
18096 | } | ||||
18097 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp" , 18097); | ||||
18098 | } | ||||
18099 | |||||
18100 | /// Return true if this function has a calling convention that requires mangling | ||||
18101 | /// in the size of the parameter pack. | ||||
18102 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | ||||
18103 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | ||||
18104 | // we don't need parameter type sizes. | ||||
18105 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | ||||
18106 | if (!TT.isOSWindows() || !TT.isX86()) | ||||
18107 | return false; | ||||
18108 | |||||
18109 | // If this is C++ and this isn't an extern "C" function, parameters do not | ||||
18110 | // need to be complete. In this case, C++ mangling will apply, which doesn't | ||||
18111 | // use the size of the parameters. | ||||
18112 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | ||||
18113 | return false; | ||||
18114 | |||||
18115 | // Stdcall, fastcall, and vectorcall need this special treatment. | ||||
18116 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
18117 | switch (CC) { | ||||
18118 | case CC_X86StdCall: | ||||
18119 | case CC_X86FastCall: | ||||
18120 | case CC_X86VectorCall: | ||||
18121 | return true; | ||||
18122 | default: | ||||
18123 | break; | ||||
18124 | } | ||||
18125 | return false; | ||||
18126 | } | ||||
18127 | |||||
18128 | /// Require that all of the parameter types of function be complete. Normally, | ||||
18129 | /// parameter types are only required to be complete when a function is called | ||||
18130 | /// or defined, but to mangle functions with certain calling conventions, the | ||||
18131 | /// mangler needs to know the size of the parameter list. In this situation, | ||||
18132 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | ||||
18133 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | ||||
18134 | /// result in a linker error. Clang doesn't implement this behavior, and instead | ||||
18135 | /// attempts to error at compile time. | ||||
18136 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | ||||
18137 | SourceLocation Loc) { | ||||
18138 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | ||||
18139 | FunctionDecl *FD; | ||||
18140 | ParmVarDecl *Param; | ||||
18141 | |||||
18142 | public: | ||||
18143 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | ||||
18144 | : FD(FD), Param(Param) {} | ||||
18145 | |||||
18146 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
18147 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
18148 | StringRef CCName; | ||||
18149 | switch (CC) { | ||||
18150 | case CC_X86StdCall: | ||||
18151 | CCName = "stdcall"; | ||||
18152 | break; | ||||
18153 | case CC_X86FastCall: | ||||
18154 | CCName = "fastcall"; | ||||
18155 | break; | ||||
18156 | case CC_X86VectorCall: | ||||
18157 | CCName = "vectorcall"; | ||||
18158 | break; | ||||
18159 | default: | ||||
18160 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "clang/lib/Sema/SemaExpr.cpp", 18160); | ||||
18161 | } | ||||
18162 | |||||
18163 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | ||||
18164 | << Param->getDeclName() << FD->getDeclName() << CCName; | ||||
18165 | } | ||||
18166 | }; | ||||
18167 | |||||
18168 | for (ParmVarDecl *Param : FD->parameters()) { | ||||
18169 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | ||||
18170 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | ||||
18171 | } | ||||
18172 | } | ||||
18173 | |||||
18174 | namespace { | ||||
18175 | enum class OdrUseContext { | ||||
18176 | /// Declarations in this context are not odr-used. | ||||
18177 | None, | ||||
18178 | /// Declarations in this context are formally odr-used, but this is a | ||||
18179 | /// dependent context. | ||||
18180 | Dependent, | ||||
18181 | /// Declarations in this context are odr-used but not actually used (yet). | ||||
18182 | FormallyOdrUsed, | ||||
18183 | /// Declarations in this context are used. | ||||
18184 | Used | ||||
18185 | }; | ||||
18186 | } | ||||
18187 | |||||
18188 | /// Are we within a context in which references to resolved functions or to | ||||
18189 | /// variables result in odr-use? | ||||
18190 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | ||||
18191 | OdrUseContext Result; | ||||
18192 | |||||
18193 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
18194 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
18195 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
18196 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
18197 | return OdrUseContext::None; | ||||
18198 | |||||
18199 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
18200 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: | ||||
18201 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
18202 | Result = OdrUseContext::Used; | ||||
18203 | break; | ||||
18204 | |||||
18205 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
18206 | Result = OdrUseContext::FormallyOdrUsed; | ||||
18207 | break; | ||||
18208 | |||||
18209 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
18210 | // A default argument formally results in odr-use, but doesn't actually | ||||
18211 | // result in a use in any real sense until it itself is used. | ||||
18212 | Result = OdrUseContext::FormallyOdrUsed; | ||||
18213 | break; | ||||
18214 | } | ||||
18215 | |||||
18216 | if (SemaRef.CurContext->isDependentContext()) | ||||
18217 | return OdrUseContext::Dependent; | ||||
18218 | |||||
18219 | return Result; | ||||
18220 | } | ||||
18221 | |||||
18222 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | ||||
18223 | if (!Func->isConstexpr()) | ||||
18224 | return false; | ||||
18225 | |||||
18226 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | ||||
18227 | return true; | ||||
18228 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | ||||
18229 | return CCD && CCD->getInheritedConstructor(); | ||||
18230 | } | ||||
18231 | |||||
18232 | /// Mark a function referenced, and check whether it is odr-used | ||||
18233 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | ||||
18234 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | ||||
18235 | bool MightBeOdrUse) { | ||||
18236 | assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void (0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp" , 18236, __extension__ __PRETTY_FUNCTION__)); | ||||
18237 | |||||
18238 | Func->setReferenced(); | ||||
18239 | |||||
18240 | // Recursive functions aren't really used until they're used from some other | ||||
18241 | // context. | ||||
18242 | bool IsRecursiveCall = CurContext == Func; | ||||
18243 | |||||
18244 | // C++11 [basic.def.odr]p3: | ||||
18245 | // A function whose name appears as a potentially-evaluated expression is | ||||
18246 | // odr-used if it is the unique lookup result or the selected member of a | ||||
18247 | // set of overloaded functions [...]. | ||||
18248 | // | ||||
18249 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | ||||
18250 | // can just check that here. | ||||
18251 | OdrUseContext OdrUse = | ||||
18252 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | ||||
18253 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | ||||
18254 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
18255 | |||||
18256 | // Trivial default constructors and destructors are never actually used. | ||||
18257 | // FIXME: What about other special members? | ||||
18258 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | ||||
18259 | OdrUse == OdrUseContext::Used) { | ||||
18260 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | ||||
18261 | if (Constructor->isDefaultConstructor()) | ||||
18262 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
18263 | if (isa<CXXDestructorDecl>(Func)) | ||||
18264 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
18265 | } | ||||
18266 | |||||
18267 | // C++20 [expr.const]p12: | ||||
18268 | // A function [...] is needed for constant evaluation if it is [...] a | ||||
18269 | // constexpr function that is named by an expression that is potentially | ||||
18270 | // constant evaluated | ||||
18271 | bool NeededForConstantEvaluation = | ||||
18272 | isPotentiallyConstantEvaluatedContext(*this) && | ||||
18273 | isImplicitlyDefinableConstexprFunction(Func); | ||||
18274 | |||||
18275 | // Determine whether we require a function definition to exist, per | ||||
18276 | // C++11 [temp.inst]p3: | ||||
18277 | // Unless a function template specialization has been explicitly | ||||
18278 | // instantiated or explicitly specialized, the function template | ||||
18279 | // specialization is implicitly instantiated when the specialization is | ||||
18280 | // referenced in a context that requires a function definition to exist. | ||||
18281 | // C++20 [temp.inst]p7: | ||||
18282 | // The existence of a definition of a [...] function is considered to | ||||
18283 | // affect the semantics of the program if the [...] function is needed for | ||||
18284 | // constant evaluation by an expression | ||||
18285 | // C++20 [basic.def.odr]p10: | ||||
18286 | // Every program shall contain exactly one definition of every non-inline | ||||
18287 | // function or variable that is odr-used in that program outside of a | ||||
18288 | // discarded statement | ||||
18289 | // C++20 [special]p1: | ||||
18290 | // The implementation will implicitly define [defaulted special members] | ||||
18291 | // if they are odr-used or needed for constant evaluation. | ||||
18292 | // | ||||
18293 | // Note that we skip the implicit instantiation of templates that are only | ||||
18294 | // used in unused default arguments or by recursive calls to themselves. | ||||
18295 | // This is formally non-conforming, but seems reasonable in practice. | ||||
18296 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | ||||
18297 | NeededForConstantEvaluation); | ||||
18298 | |||||
18299 | // C++14 [temp.expl.spec]p6: | ||||
18300 | // If a template [...] is explicitly specialized then that specialization | ||||
18301 | // shall be declared before the first use of that specialization that would | ||||
18302 | // cause an implicit instantiation to take place, in every translation unit | ||||
18303 | // in which such a use occurs | ||||
18304 | if (NeedDefinition && | ||||
18305 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | ||||
18306 | Func->getMemberSpecializationInfo())) | ||||
18307 | checkSpecializationReachability(Loc, Func); | ||||
18308 | |||||
18309 | if (getLangOpts().CUDA) | ||||
18310 | CheckCUDACall(Loc, Func); | ||||
18311 | |||||
18312 | if (getLangOpts().SYCLIsDevice) | ||||
18313 | checkSYCLDeviceFunction(Loc, Func); | ||||
18314 | |||||
18315 | // If we need a definition, try to create one. | ||||
18316 | if (NeedDefinition && !Func->getBody()) { | ||||
18317 | runWithSufficientStackSpace(Loc, [&] { | ||||
18318 | if (CXXConstructorDecl *Constructor = | ||||
18319 | dyn_cast<CXXConstructorDecl>(Func)) { | ||||
18320 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | ||||
18321 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | ||||
18322 | if (Constructor->isDefaultConstructor()) { | ||||
18323 | if (Constructor->isTrivial() && | ||||
18324 | !Constructor->hasAttr<DLLExportAttr>()) | ||||
18325 | return; | ||||
18326 | DefineImplicitDefaultConstructor(Loc, Constructor); | ||||
18327 | } else if (Constructor->isCopyConstructor()) { | ||||
18328 | DefineImplicitCopyConstructor(Loc, Constructor); | ||||
18329 | } else if (Constructor->isMoveConstructor()) { | ||||
18330 | DefineImplicitMoveConstructor(Loc, Constructor); | ||||
18331 | } | ||||
18332 | } else if (Constructor->getInheritedConstructor()) { | ||||
18333 | DefineInheritingConstructor(Loc, Constructor); | ||||
18334 | } | ||||
18335 | } else if (CXXDestructorDecl *Destructor = | ||||
18336 | dyn_cast<CXXDestructorDecl>(Func)) { | ||||
18337 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | ||||
18338 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | ||||
18339 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | ||||
18340 | return; | ||||
18341 | DefineImplicitDestructor(Loc, Destructor); | ||||
18342 | } | ||||
18343 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | ||||
18344 | MarkVTableUsed(Loc, Destructor->getParent()); | ||||
18345 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | ||||
18346 | if (MethodDecl->isOverloadedOperator() && | ||||
18347 | MethodDecl->getOverloadedOperator() == OO_Equal) { | ||||
18348 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | ||||
18349 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | ||||
18350 | if (MethodDecl->isCopyAssignmentOperator()) | ||||
18351 | DefineImplicitCopyAssignment(Loc, MethodDecl); | ||||
18352 | else if (MethodDecl->isMoveAssignmentOperator()) | ||||
18353 | DefineImplicitMoveAssignment(Loc, MethodDecl); | ||||
18354 | } | ||||
18355 | } else if (isa<CXXConversionDecl>(MethodDecl) && | ||||
18356 | MethodDecl->getParent()->isLambda()) { | ||||
18357 | CXXConversionDecl *Conversion = | ||||
18358 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | ||||
18359 | if (Conversion->isLambdaToBlockPointerConversion()) | ||||
18360 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | ||||
18361 | else | ||||
18362 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | ||||
18363 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | ||||
18364 | MarkVTableUsed(Loc, MethodDecl->getParent()); | ||||
18365 | } | ||||
18366 | |||||
18367 | if (Func->isDefaulted() && !Func->isDeleted()) { | ||||
18368 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | ||||
18369 | if (DCK != DefaultedComparisonKind::None) | ||||
18370 | DefineDefaultedComparison(Loc, Func, DCK); | ||||
18371 | } | ||||
18372 | |||||
18373 | // Implicit instantiation of function templates and member functions of | ||||
18374 | // class templates. | ||||
18375 | if (Func->isImplicitlyInstantiable()) { | ||||
18376 | TemplateSpecializationKind TSK = | ||||
18377 | Func->getTemplateSpecializationKindForInstantiation(); | ||||
18378 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | ||||
18379 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
18380 | if (FirstInstantiation) { | ||||
18381 | PointOfInstantiation = Loc; | ||||
18382 | if (auto *MSI = Func->getMemberSpecializationInfo()) | ||||
18383 | MSI->setPointOfInstantiation(Loc); | ||||
18384 | // FIXME: Notify listener. | ||||
18385 | else | ||||
18386 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
18387 | } else if (TSK != TSK_ImplicitInstantiation) { | ||||
18388 | // Use the point of use as the point of instantiation, instead of the | ||||
18389 | // point of explicit instantiation (which we track as the actual point | ||||
18390 | // of instantiation). This gives better backtraces in diagnostics. | ||||
18391 | PointOfInstantiation = Loc; | ||||
18392 | } | ||||
18393 | |||||
18394 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | ||||
18395 | Func->isConstexpr()) { | ||||
18396 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | ||||
18397 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | ||||
18398 | CodeSynthesisContexts.size()) | ||||
18399 | PendingLocalImplicitInstantiations.push_back( | ||||
18400 | std::make_pair(Func, PointOfInstantiation)); | ||||
18401 | else if (Func->isConstexpr()) | ||||
18402 | // Do not defer instantiations of constexpr functions, to avoid the | ||||
18403 | // expression evaluator needing to call back into Sema if it sees a | ||||
18404 | // call to such a function. | ||||
18405 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | ||||
18406 | else { | ||||
18407 | Func->setInstantiationIsPending(true); | ||||
18408 | PendingInstantiations.push_back( | ||||
18409 | std::make_pair(Func, PointOfInstantiation)); | ||||
18410 | // Notify the consumer that a function was implicitly instantiated. | ||||
18411 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | ||||
18412 | } | ||||
18413 | } | ||||
18414 | } else { | ||||
18415 | // Walk redefinitions, as some of them may be instantiable. | ||||
18416 | for (auto *i : Func->redecls()) { | ||||
18417 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | ||||
18418 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | ||||
18419 | } | ||||
18420 | } | ||||
18421 | }); | ||||
18422 | } | ||||
18423 | |||||
18424 | // If a constructor was defined in the context of a default parameter | ||||
18425 | // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed | ||||
18426 | // context), its initializers may not be referenced yet. | ||||
18427 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { | ||||
18428 | for (CXXCtorInitializer *Init : Constructor->inits()) { | ||||
18429 | if (Init->isInClassMemberInitializer()) | ||||
18430 | MarkDeclarationsReferencedInExpr(Init->getInit()); | ||||
18431 | } | ||||
18432 | } | ||||
18433 | |||||
18434 | // C++14 [except.spec]p17: | ||||
18435 | // An exception-specification is considered to be needed when: | ||||
18436 | // - the function is odr-used or, if it appears in an unevaluated operand, | ||||
18437 | // would be odr-used if the expression were potentially-evaluated; | ||||
18438 | // | ||||
18439 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | ||||
18440 | // function is a pure virtual function we're calling, and in that case the | ||||
18441 | // function was selected by overload resolution and we need to resolve its | ||||
18442 | // exception specification for a different reason. | ||||
18443 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | ||||
18444 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | ||||
18445 | ResolveExceptionSpec(Loc, FPT); | ||||
18446 | |||||
18447 | // If this is the first "real" use, act on that. | ||||
18448 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | ||||
18449 | // Keep track of used but undefined functions. | ||||
18450 | if (!Func->isDefined()) { | ||||
18451 | if (mightHaveNonExternalLinkage(Func)) | ||||
18452 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
18453 | else if (Func->getMostRecentDecl()->isInlined() && | ||||
18454 | !LangOpts.GNUInline && | ||||
18455 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | ||||
18456 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
18457 | else if (isExternalWithNoLinkageType(Func)) | ||||
18458 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
18459 | } | ||||
18460 | |||||
18461 | // Some x86 Windows calling conventions mangle the size of the parameter | ||||
18462 | // pack into the name. Computing the size of the parameters requires the | ||||
18463 | // parameter types to be complete. Check that now. | ||||
18464 | if (funcHasParameterSizeMangling(*this, Func)) | ||||
18465 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | ||||
18466 | |||||
18467 | // In the MS C++ ABI, the compiler emits destructor variants where they are | ||||
18468 | // used. If the destructor is used here but defined elsewhere, mark the | ||||
18469 | // virtual base destructors referenced. If those virtual base destructors | ||||
18470 | // are inline, this will ensure they are defined when emitting the complete | ||||
18471 | // destructor variant. This checking may be redundant if the destructor is | ||||
18472 | // provided later in this TU. | ||||
18473 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
18474 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | ||||
18475 | CXXRecordDecl *Parent = Dtor->getParent(); | ||||
18476 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | ||||
18477 | CheckCompleteDestructorVariant(Loc, Dtor); | ||||
18478 | } | ||||
18479 | } | ||||
18480 | |||||
18481 | Func->markUsed(Context); | ||||
18482 | } | ||||
18483 | } | ||||
18484 | |||||
18485 | /// Directly mark a variable odr-used. Given a choice, prefer to use | ||||
18486 | /// MarkVariableReferenced since it does additional checks and then | ||||
18487 | /// calls MarkVarDeclODRUsed. | ||||
18488 | /// If the variable must be captured: | ||||
18489 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | ||||
18490 | /// - else capture it in the DeclContext that maps to the | ||||
18491 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | ||||
18492 | static void | ||||
18493 | MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, | ||||
18494 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | ||||
18495 | // Keep track of used but undefined variables. | ||||
18496 | // FIXME: We shouldn't suppress this warning for static data members. | ||||
18497 | VarDecl *Var = V->getPotentiallyDecomposedVarDecl(); | ||||
18498 | assert(Var && "expected a capturable variable")(static_cast <bool> (Var && "expected a capturable variable" ) ? void (0) : __assert_fail ("Var && \"expected a capturable variable\"" , "clang/lib/Sema/SemaExpr.cpp", 18498, __extension__ __PRETTY_FUNCTION__ )); | ||||
18499 | |||||
18500 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | ||||
18501 | (!Var->isExternallyVisible() || Var->isInline() || | ||||
18502 | SemaRef.isExternalWithNoLinkageType(Var)) && | ||||
18503 | !(Var->isStaticDataMember() && Var->hasInit())) { | ||||
18504 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | ||||
18505 | if (old.isInvalid()) | ||||
18506 | old = Loc; | ||||
18507 | } | ||||
18508 | QualType CaptureType, DeclRefType; | ||||
18509 | if (SemaRef.LangOpts.OpenMP) | ||||
18510 | SemaRef.tryCaptureOpenMPLambdas(V); | ||||
18511 | SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit, | ||||
18512 | /*EllipsisLoc*/ SourceLocation(), | ||||
18513 | /*BuildAndDiagnose*/ true, CaptureType, | ||||
18514 | DeclRefType, FunctionScopeIndexToStopAt); | ||||
18515 | |||||
18516 | if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { | ||||
18517 | auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); | ||||
18518 | auto VarTarget = SemaRef.IdentifyCUDATarget(Var); | ||||
18519 | auto UserTarget = SemaRef.IdentifyCUDATarget(FD); | ||||
18520 | if (VarTarget == Sema::CVT_Host && | ||||
18521 | (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || | ||||
18522 | UserTarget == Sema::CFT_Global)) { | ||||
18523 | // Diagnose ODR-use of host global variables in device functions. | ||||
18524 | // Reference of device global variables in host functions is allowed | ||||
18525 | // through shadow variables therefore it is not diagnosed. | ||||
18526 | if (SemaRef.LangOpts.CUDAIsDevice) { | ||||
18527 | SemaRef.targetDiag(Loc, diag::err_ref_bad_target) | ||||
18528 | << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; | ||||
18529 | SemaRef.targetDiag(Var->getLocation(), | ||||
18530 | Var->getType().isConstQualified() | ||||
18531 | ? diag::note_cuda_const_var_unpromoted | ||||
18532 | : diag::note_cuda_host_var); | ||||
18533 | } | ||||
18534 | } else if (VarTarget == Sema::CVT_Device && | ||||
18535 | (UserTarget == Sema::CFT_Host || | ||||
18536 | UserTarget == Sema::CFT_HostDevice)) { | ||||
18537 | // Record a CUDA/HIP device side variable if it is ODR-used | ||||
18538 | // by host code. This is done conservatively, when the variable is | ||||
18539 | // referenced in any of the following contexts: | ||||
18540 | // - a non-function context | ||||
18541 | // - a host function | ||||
18542 | // - a host device function | ||||
18543 | // This makes the ODR-use of the device side variable by host code to | ||||
18544 | // be visible in the device compilation for the compiler to be able to | ||||
18545 | // emit template variables instantiated by host code only and to | ||||
18546 | // externalize the static device side variable ODR-used by host code. | ||||
18547 | if (!Var->hasExternalStorage()) | ||||
18548 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); | ||||
18549 | else if (SemaRef.LangOpts.GPURelocatableDeviceCode) | ||||
18550 | SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); | ||||
18551 | } | ||||
18552 | } | ||||
18553 | |||||
18554 | V->markUsed(SemaRef.Context); | ||||
18555 | } | ||||
18556 | |||||
18557 | void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, | ||||
18558 | SourceLocation Loc, | ||||
18559 | unsigned CapturingScopeIndex) { | ||||
18560 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | ||||
18561 | } | ||||
18562 | |||||
18563 | void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, | ||||
18564 | ValueDecl *var) { | ||||
18565 | DeclContext *VarDC = var->getDeclContext(); | ||||
18566 | |||||
18567 | // If the parameter still belongs to the translation unit, then | ||||
18568 | // we're actually just using one parameter in the declaration of | ||||
18569 | // the next. | ||||
18570 | if (isa<ParmVarDecl>(var) && | ||||
18571 | isa<TranslationUnitDecl>(VarDC)) | ||||
18572 | return; | ||||
18573 | |||||
18574 | // For C code, don't diagnose about capture if we're not actually in code | ||||
18575 | // right now; it's impossible to write a non-constant expression outside of | ||||
18576 | // function context, so we'll get other (more useful) diagnostics later. | ||||
18577 | // | ||||
18578 | // For C++, things get a bit more nasty... it would be nice to suppress this | ||||
18579 | // diagnostic for certain cases like using a local variable in an array bound | ||||
18580 | // for a member of a local class, but the correct predicate is not obvious. | ||||
18581 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | ||||
18582 | return; | ||||
18583 | |||||
18584 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | ||||
18585 | unsigned ContextKind = 3; // unknown | ||||
18586 | if (isa<CXXMethodDecl>(VarDC) && | ||||
18587 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | ||||
18588 | ContextKind = 2; | ||||
18589 | } else if (isa<FunctionDecl>(VarDC)) { | ||||
18590 | ContextKind = 0; | ||||
18591 | } else if (isa<BlockDecl>(VarDC)) { | ||||
18592 | ContextKind = 1; | ||||
18593 | } | ||||
18594 | |||||
18595 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | ||||
18596 | << var << ValueKind << ContextKind << VarDC; | ||||
18597 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | ||||
18598 | << var; | ||||
18599 | |||||
18600 | // FIXME: Add additional diagnostic info about class etc. which prevents | ||||
18601 | // capture. | ||||
18602 | } | ||||
18603 | |||||
18604 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, | ||||
18605 | ValueDecl *Var, | ||||
18606 | bool &SubCapturesAreNested, | ||||
18607 | QualType &CaptureType, | ||||
18608 | QualType &DeclRefType) { | ||||
18609 | // Check whether we've already captured it. | ||||
18610 | if (CSI->CaptureMap.count(Var)) { | ||||
18611 | // If we found a capture, any subcaptures are nested. | ||||
18612 | SubCapturesAreNested = true; | ||||
18613 | |||||
18614 | // Retrieve the capture type for this variable. | ||||
18615 | CaptureType = CSI->getCapture(Var).getCaptureType(); | ||||
18616 | |||||
18617 | // Compute the type of an expression that refers to this variable. | ||||
18618 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18619 | |||||
18620 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | ||||
18621 | // are mutable in the sense that user can change their value - they are | ||||
18622 | // private instances of the captured declarations. | ||||
18623 | const Capture &Cap = CSI->getCapture(Var); | ||||
18624 | if (Cap.isCopyCapture() && | ||||
18625 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | ||||
18626 | !(isa<CapturedRegionScopeInfo>(CSI) && | ||||
18627 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | ||||
18628 | DeclRefType.addConst(); | ||||
18629 | return true; | ||||
18630 | } | ||||
18631 | return false; | ||||
18632 | } | ||||
18633 | |||||
18634 | // Only block literals, captured statements, and lambda expressions can | ||||
18635 | // capture; other scopes don't work. | ||||
18636 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, | ||||
18637 | ValueDecl *Var, | ||||
18638 | SourceLocation Loc, | ||||
18639 | const bool Diagnose, | ||||
18640 | Sema &S) { | ||||
18641 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | ||||
18642 | return getLambdaAwareParentOfDeclContext(DC); | ||||
18643 | |||||
18644 | VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); | ||||
18645 | if (Underlying) { | ||||
18646 | if (Underlying->hasLocalStorage() && Diagnose) | ||||
18647 | diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); | ||||
18648 | } | ||||
18649 | return nullptr; | ||||
18650 | } | ||||
18651 | |||||
18652 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
18653 | // certain types of variables (unnamed, variably modified types etc.) | ||||
18654 | // so check for eligibility. | ||||
18655 | static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, | ||||
18656 | SourceLocation Loc, const bool Diagnose, | ||||
18657 | Sema &S) { | ||||
18658 | |||||
18659 | assert((isa<VarDecl, BindingDecl>(Var)) &&(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var )) && "Only variables and structured bindings can be captured" ) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\"" , "clang/lib/Sema/SemaExpr.cpp", 18660, __extension__ __PRETTY_FUNCTION__ )) | ||||
18660 | "Only variables and structured bindings can be captured")(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var )) && "Only variables and structured bindings can be captured" ) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\"" , "clang/lib/Sema/SemaExpr.cpp", 18660, __extension__ __PRETTY_FUNCTION__ )); | ||||
18661 | |||||
18662 | bool IsBlock = isa<BlockScopeInfo>(CSI); | ||||
18663 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | ||||
18664 | |||||
18665 | // Lambdas are not allowed to capture unnamed variables | ||||
18666 | // (e.g. anonymous unions). | ||||
18667 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | ||||
18668 | // assuming that's the intent. | ||||
18669 | if (IsLambda && !Var->getDeclName()) { | ||||
18670 | if (Diagnose) { | ||||
18671 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | ||||
18672 | S.Diag(Var->getLocation(), diag::note_declared_at); | ||||
18673 | } | ||||
18674 | return false; | ||||
18675 | } | ||||
18676 | |||||
18677 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | ||||
18678 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | ||||
18679 | if (Diagnose) { | ||||
18680 | S.Diag(Loc, diag::err_ref_vm_type); | ||||
18681 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18682 | } | ||||
18683 | return false; | ||||
18684 | } | ||||
18685 | // Prohibit structs with flexible array members too. | ||||
18686 | // We cannot capture what is in the tail end of the struct. | ||||
18687 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | ||||
18688 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | ||||
18689 | if (Diagnose) { | ||||
18690 | if (IsBlock) | ||||
18691 | S.Diag(Loc, diag::err_ref_flexarray_type); | ||||
18692 | else | ||||
18693 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | ||||
18694 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18695 | } | ||||
18696 | return false; | ||||
18697 | } | ||||
18698 | } | ||||
18699 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
18700 | // Lambdas and captured statements are not allowed to capture __block | ||||
18701 | // variables; they don't support the expected semantics. | ||||
18702 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | ||||
18703 | if (Diagnose) { | ||||
18704 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | ||||
18705 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18706 | } | ||||
18707 | return false; | ||||
18708 | } | ||||
18709 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | ||||
18710 | if (S.getLangOpts().OpenCL && IsBlock && | ||||
18711 | Var->getType()->isBlockPointerType()) { | ||||
18712 | if (Diagnose) | ||||
18713 | S.Diag(Loc, diag::err_opencl_block_ref_block); | ||||
18714 | return false; | ||||
18715 | } | ||||
18716 | |||||
18717 | if (isa<BindingDecl>(Var)) { | ||||
18718 | if (!IsLambda || !S.getLangOpts().CPlusPlus) { | ||||
18719 | if (Diagnose) | ||||
18720 | diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); | ||||
18721 | return false; | ||||
18722 | } else if (Diagnose && S.getLangOpts().CPlusPlus) { | ||||
18723 | S.Diag(Loc, S.LangOpts.CPlusPlus20 | ||||
18724 | ? diag::warn_cxx17_compat_capture_binding | ||||
18725 | : diag::ext_capture_binding) | ||||
18726 | << Var; | ||||
18727 | S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; | ||||
18728 | } | ||||
18729 | } | ||||
18730 | |||||
18731 | return true; | ||||
18732 | } | ||||
18733 | |||||
18734 | // Returns true if the capture by block was successful. | ||||
18735 | static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, | ||||
18736 | SourceLocation Loc, const bool BuildAndDiagnose, | ||||
18737 | QualType &CaptureType, QualType &DeclRefType, | ||||
18738 | const bool Nested, Sema &S, bool Invalid) { | ||||
18739 | bool ByRef = false; | ||||
18740 | |||||
18741 | // Blocks are not allowed to capture arrays, excepting OpenCL. | ||||
18742 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | ||||
18743 | // (decayed to pointers). | ||||
18744 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | ||||
18745 | if (BuildAndDiagnose) { | ||||
18746 | S.Diag(Loc, diag::err_ref_array_type); | ||||
18747 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18748 | Invalid = true; | ||||
18749 | } else { | ||||
18750 | return false; | ||||
18751 | } | ||||
18752 | } | ||||
18753 | |||||
18754 | // Forbid the block-capture of autoreleasing variables. | ||||
18755 | if (!Invalid && | ||||
18756 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
18757 | if (BuildAndDiagnose) { | ||||
18758 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | ||||
18759 | << /*block*/ 0; | ||||
18760 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18761 | Invalid = true; | ||||
18762 | } else { | ||||
18763 | return false; | ||||
18764 | } | ||||
18765 | } | ||||
18766 | |||||
18767 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | ||||
18768 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | ||||
18769 | QualType PointeeTy = PT->getPointeeType(); | ||||
18770 | |||||
18771 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | ||||
18772 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | ||||
18773 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | ||||
18774 | if (BuildAndDiagnose) { | ||||
18775 | SourceLocation VarLoc = Var->getLocation(); | ||||
18776 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | ||||
18777 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | ||||
18778 | } | ||||
18779 | } | ||||
18780 | } | ||||
18781 | |||||
18782 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
18783 | if (HasBlocksAttr || CaptureType->isReferenceType() || | ||||
18784 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | ||||
18785 | // Block capture by reference does not change the capture or | ||||
18786 | // declaration reference types. | ||||
18787 | ByRef = true; | ||||
18788 | } else { | ||||
18789 | // Block capture by copy introduces 'const'. | ||||
18790 | CaptureType = CaptureType.getNonReferenceType().withConst(); | ||||
18791 | DeclRefType = CaptureType; | ||||
18792 | } | ||||
18793 | |||||
18794 | // Actually capture the variable. | ||||
18795 | if (BuildAndDiagnose) | ||||
18796 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | ||||
18797 | CaptureType, Invalid); | ||||
18798 | |||||
18799 | return !Invalid; | ||||
18800 | } | ||||
18801 | |||||
18802 | /// Capture the given variable in the captured region. | ||||
18803 | static bool captureInCapturedRegion( | ||||
18804 | CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, | ||||
18805 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, | ||||
18806 | const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, | ||||
18807 | bool IsTopScope, Sema &S, bool Invalid) { | ||||
18808 | // By default, capture variables by reference. | ||||
18809 | bool ByRef = true; | ||||
18810 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
18811 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
18812 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | ||||
18813 | // Using an LValue reference type is consistent with Lambdas (see below). | ||||
18814 | if (S.isOpenMPCapturedDecl(Var)) { | ||||
18815 | bool HasConst = DeclRefType.isConstQualified(); | ||||
18816 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
18817 | // Don't lose diagnostics about assignments to const. | ||||
18818 | if (HasConst) | ||||
18819 | DeclRefType.addConst(); | ||||
18820 | } | ||||
18821 | // Do not capture firstprivates in tasks. | ||||
18822 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | ||||
18823 | OMPC_unknown) | ||||
18824 | return true; | ||||
18825 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | ||||
18826 | RSI->OpenMPCaptureLevel); | ||||
18827 | } | ||||
18828 | |||||
18829 | if (ByRef) | ||||
18830 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
18831 | else | ||||
18832 | CaptureType = DeclRefType; | ||||
18833 | |||||
18834 | // Actually capture the variable. | ||||
18835 | if (BuildAndDiagnose) | ||||
18836 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | ||||
18837 | Loc, SourceLocation(), CaptureType, Invalid); | ||||
18838 | |||||
18839 | return !Invalid; | ||||
18840 | } | ||||
18841 | |||||
18842 | /// Capture the given variable in the lambda. | ||||
18843 | static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, | ||||
18844 | SourceLocation Loc, const bool BuildAndDiagnose, | ||||
18845 | QualType &CaptureType, QualType &DeclRefType, | ||||
18846 | const bool RefersToCapturedVariable, | ||||
18847 | const Sema::TryCaptureKind Kind, | ||||
18848 | SourceLocation EllipsisLoc, const bool IsTopScope, | ||||
18849 | Sema &S, bool Invalid) { | ||||
18850 | // Determine whether we are capturing by reference or by value. | ||||
18851 | bool ByRef = false; | ||||
18852 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
18853 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
18854 | } else { | ||||
18855 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | ||||
18856 | } | ||||
18857 | |||||
18858 | BindingDecl *BD = dyn_cast<BindingDecl>(Var); | ||||
18859 | // FIXME: We should support capturing structured bindings in OpenMP. | ||||
18860 | if (!Invalid && BD && S.LangOpts.OpenMP) { | ||||
18861 | if (BuildAndDiagnose) { | ||||
18862 | S.Diag(Loc, diag::err_capture_binding_openmp) << Var; | ||||
18863 | S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; | ||||
18864 | } | ||||
18865 | Invalid = true; | ||||
18866 | } | ||||
18867 | |||||
18868 | if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() && | ||||
18869 | CaptureType.getNonReferenceType()->isWebAssemblyReferenceType()) { | ||||
18870 | S.Diag(Loc, diag::err_wasm_ca_reference) << 0; | ||||
18871 | Invalid = true; | ||||
18872 | } | ||||
18873 | |||||
18874 | // Compute the type of the field that will capture this variable. | ||||
18875 | if (ByRef) { | ||||
18876 | // C++11 [expr.prim.lambda]p15: | ||||
18877 | // An entity is captured by reference if it is implicitly or | ||||
18878 | // explicitly captured but not captured by copy. It is | ||||
18879 | // unspecified whether additional unnamed non-static data | ||||
18880 | // members are declared in the closure type for entities | ||||
18881 | // captured by reference. | ||||
18882 | // | ||||
18883 | // FIXME: It is not clear whether we want to build an lvalue reference | ||||
18884 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | ||||
18885 | // to do the former, while EDG does the latter. Core issue 1249 will | ||||
18886 | // clarify, but for now we follow GCC because it's a more permissive and | ||||
18887 | // easily defensible position. | ||||
18888 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
18889 | } else { | ||||
18890 | // C++11 [expr.prim.lambda]p14: | ||||
18891 | // For each entity captured by copy, an unnamed non-static | ||||
18892 | // data member is declared in the closure type. The | ||||
18893 | // declaration order of these members is unspecified. The type | ||||
18894 | // of such a data member is the type of the corresponding | ||||
18895 | // captured entity if the entity is not a reference to an | ||||
18896 | // object, or the referenced type otherwise. [Note: If the | ||||
18897 | // captured entity is a reference to a function, the | ||||
18898 | // corresponding data member is also a reference to a | ||||
18899 | // function. - end note ] | ||||
18900 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | ||||
18901 | if (!RefType->getPointeeType()->isFunctionType()) | ||||
18902 | CaptureType = RefType->getPointeeType(); | ||||
18903 | } | ||||
18904 | |||||
18905 | // Forbid the lambda copy-capture of autoreleasing variables. | ||||
18906 | if (!Invalid && | ||||
18907 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
18908 | if (BuildAndDiagnose) { | ||||
18909 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | ||||
18910 | S.Diag(Var->getLocation(), diag::note_previous_decl) | ||||
18911 | << Var->getDeclName(); | ||||
18912 | Invalid = true; | ||||
18913 | } else { | ||||
18914 | return false; | ||||
18915 | } | ||||
18916 | } | ||||
18917 | |||||
18918 | // Make sure that by-copy captures are of a complete and non-abstract type. | ||||
18919 | if (!Invalid && BuildAndDiagnose) { | ||||
18920 | if (!CaptureType->isDependentType() && | ||||
18921 | S.RequireCompleteSizedType( | ||||
18922 | Loc, CaptureType, | ||||
18923 | diag::err_capture_of_incomplete_or_sizeless_type, | ||||
18924 | Var->getDeclName())) | ||||
18925 | Invalid = true; | ||||
18926 | else if (S.RequireNonAbstractType(Loc, CaptureType, | ||||
18927 | diag::err_capture_of_abstract_type)) | ||||
18928 | Invalid = true; | ||||
18929 | } | ||||
18930 | } | ||||
18931 | |||||
18932 | // Compute the type of a reference to this captured variable. | ||||
18933 | if (ByRef) | ||||
18934 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18935 | else { | ||||
18936 | // C++ [expr.prim.lambda]p5: | ||||
18937 | // The closure type for a lambda-expression has a public inline | ||||
18938 | // function call operator [...]. This function call operator is | ||||
18939 | // declared const (9.3.1) if and only if the lambda-expression's | ||||
18940 | // parameter-declaration-clause is not followed by mutable. | ||||
18941 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18942 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | ||||
18943 | DeclRefType.addConst(); | ||||
18944 | } | ||||
18945 | |||||
18946 | // Add the capture. | ||||
18947 | if (BuildAndDiagnose) | ||||
18948 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | ||||
18949 | Loc, EllipsisLoc, CaptureType, Invalid); | ||||
18950 | |||||
18951 | return !Invalid; | ||||
18952 | } | ||||
18953 | |||||
18954 | static bool canCaptureVariableByCopy(ValueDecl *Var, | ||||
18955 | const ASTContext &Context) { | ||||
18956 | // Offer a Copy fix even if the type is dependent. | ||||
18957 | if (Var->getType()->isDependentType()) | ||||
18958 | return true; | ||||
18959 | QualType T = Var->getType().getNonReferenceType(); | ||||
18960 | if (T.isTriviallyCopyableType(Context)) | ||||
18961 | return true; | ||||
18962 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | ||||
18963 | |||||
18964 | if (!(RD = RD->getDefinition())) | ||||
18965 | return false; | ||||
18966 | if (RD->hasSimpleCopyConstructor()) | ||||
18967 | return true; | ||||
18968 | if (RD->hasUserDeclaredCopyConstructor()) | ||||
18969 | for (CXXConstructorDecl *Ctor : RD->ctors()) | ||||
18970 | if (Ctor->isCopyConstructor()) | ||||
18971 | return !Ctor->isDeleted(); | ||||
18972 | } | ||||
18973 | return false; | ||||
18974 | } | ||||
18975 | |||||
18976 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or | ||||
18977 | /// default capture. Fixes may be omitted if they aren't allowed by the | ||||
18978 | /// standard, for example we can't emit a default copy capture fix-it if we | ||||
18979 | /// already explicitly copy capture capture another variable. | ||||
18980 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, | ||||
18981 | ValueDecl *Var) { | ||||
18982 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast <bool> (LSI->ImpCaptureStyle == CapturingScopeInfo ::ImpCap_None) ? void (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None" , "clang/lib/Sema/SemaExpr.cpp", 18982, __extension__ __PRETTY_FUNCTION__ )); | ||||
18983 | // Don't offer Capture by copy of default capture by copy fixes if Var is | ||||
18984 | // known not to be copy constructible. | ||||
18985 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); | ||||
18986 | |||||
18987 | SmallString<32> FixBuffer; | ||||
18988 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; | ||||
18989 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { | ||||
18990 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); | ||||
18991 | if (ShouldOfferCopyFix) { | ||||
18992 | // Offer fixes to insert an explicit capture for the variable. | ||||
18993 | // [] -> [VarName] | ||||
18994 | // [OtherCapture] -> [OtherCapture, VarName] | ||||
18995 | FixBuffer.assign({Separator, Var->getName()}); | ||||
18996 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
18997 | << Var << /*value*/ 0 | ||||
18998 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
18999 | } | ||||
19000 | // As above but capture by reference. | ||||
19001 | FixBuffer.assign({Separator, "&", Var->getName()}); | ||||
19002 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
19003 | << Var << /*reference*/ 1 | ||||
19004 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
19005 | } | ||||
19006 | |||||
19007 | // Only try to offer default capture if there are no captures excluding this | ||||
19008 | // and init captures. | ||||
19009 | // [this]: OK. | ||||
19010 | // [X = Y]: OK. | ||||
19011 | // [&A, &B]: Don't offer. | ||||
19012 | // [A, B]: Don't offer. | ||||
19013 | if (llvm::any_of(LSI->Captures, [](Capture &C) { | ||||
19014 | return !C.isThisCapture() && !C.isInitCapture(); | ||||
19015 | })) | ||||
19016 | return; | ||||
19017 | |||||
19018 | // The default capture specifiers, '=' or '&', must appear first in the | ||||
19019 | // capture body. | ||||
19020 | SourceLocation DefaultInsertLoc = | ||||
19021 | LSI->IntroducerRange.getBegin().getLocWithOffset(1); | ||||
19022 | |||||
19023 | if (ShouldOfferCopyFix) { | ||||
19024 | bool CanDefaultCopyCapture = true; | ||||
19025 | // [=, *this] OK since c++17 | ||||
19026 | // [=, this] OK since c++20 | ||||
19027 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) | ||||
19028 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 | ||||
19029 | ? LSI->getCXXThisCapture().isCopyCapture() | ||||
19030 | : false; | ||||
19031 | // We can't use default capture by copy if any captures already specified | ||||
19032 | // capture by copy. | ||||
19033 | if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
19034 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); | ||||
19035 | })) { | ||||
19036 | FixBuffer.assign({"=", Separator}); | ||||
19037 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
19038 | << /*value*/ 0 | ||||
19039 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
19040 | } | ||||
19041 | } | ||||
19042 | |||||
19043 | // We can't use default capture by reference if any captures already specified | ||||
19044 | // capture by reference. | ||||
19045 | if (llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
19046 | return !C.isInitCapture() && C.isReferenceCapture() && | ||||
19047 | !C.isThisCapture(); | ||||
19048 | })) { | ||||
19049 | FixBuffer.assign({"&", Separator}); | ||||
19050 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
19051 | << /*reference*/ 1 | ||||
19052 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
19053 | } | ||||
19054 | } | ||||
19055 | |||||
19056 | bool Sema::tryCaptureVariable( | ||||
19057 | ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | ||||
19058 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | ||||
19059 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | ||||
19060 | // An init-capture is notionally from the context surrounding its | ||||
19061 | // declaration, but its parent DC is the lambda class. | ||||
19062 | DeclContext *VarDC = Var->getDeclContext(); | ||||
19063 | const auto *VD = dyn_cast<VarDecl>(Var); | ||||
19064 | if (VD) { | ||||
19065 | if (VD->isInitCapture()) | ||||
19066 | VarDC = VarDC->getParent(); | ||||
19067 | } else { | ||||
19068 | VD = Var->getPotentiallyDecomposedVarDecl(); | ||||
19069 | } | ||||
19070 | assert(VD && "Cannot capture a null variable")(static_cast <bool> (VD && "Cannot capture a null variable" ) ? void (0) : __assert_fail ("VD && \"Cannot capture a null variable\"" , "clang/lib/Sema/SemaExpr.cpp", 19070, __extension__ __PRETTY_FUNCTION__ )); | ||||
19071 | |||||
19072 | DeclContext *DC = CurContext; | ||||
19073 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | ||||
19074 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | ||||
19075 | // We need to sync up the Declaration Context with the | ||||
19076 | // FunctionScopeIndexToStopAt | ||||
19077 | if (FunctionScopeIndexToStopAt) { | ||||
19078 | unsigned FSIndex = FunctionScopes.size() - 1; | ||||
19079 | while (FSIndex != MaxFunctionScopesIndex) { | ||||
19080 | DC = getLambdaAwareParentOfDeclContext(DC); | ||||
19081 | --FSIndex; | ||||
19082 | } | ||||
19083 | } | ||||
19084 | |||||
19085 | |||||
19086 | // If the variable is declared in the current context, there is no need to | ||||
19087 | // capture it. | ||||
19088 | if (VarDC == DC) return true; | ||||
19089 | |||||
19090 | // Capture global variables if it is required to use private copy of this | ||||
19091 | // variable. | ||||
19092 | bool IsGlobal = !VD->hasLocalStorage(); | ||||
19093 | if (IsGlobal && | ||||
19094 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | ||||
19095 | MaxFunctionScopesIndex))) | ||||
19096 | return true; | ||||
19097 | |||||
19098 | if (isa<VarDecl>(Var)) | ||||
19099 | Var = cast<VarDecl>(Var->getCanonicalDecl()); | ||||
19100 | |||||
19101 | // Walk up the stack to determine whether we can capture the variable, | ||||
19102 | // performing the "simple" checks that don't depend on type. We stop when | ||||
19103 | // we've either hit the declared scope of the variable or find an existing | ||||
19104 | // capture of that variable. We start from the innermost capturing-entity | ||||
19105 | // (the DC) and ensure that all intervening capturing-entities | ||||
19106 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | ||||
19107 | // declcontext can either capture the variable or have already captured | ||||
19108 | // the variable. | ||||
19109 | CaptureType = Var->getType(); | ||||
19110 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
19111 | bool Nested = false; | ||||
19112 | bool Explicit = (Kind != TryCapture_Implicit); | ||||
19113 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | ||||
19114 | do { | ||||
19115 | // Only block literals, captured statements, and lambda expressions can | ||||
19116 | // capture; other scopes don't work. | ||||
19117 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | ||||
19118 | ExprLoc, | ||||
19119 | BuildAndDiagnose, | ||||
19120 | *this); | ||||
19121 | // We need to check for the parent *first* because, if we *have* | ||||
19122 | // private-captured a global variable, we need to recursively capture it in | ||||
19123 | // intermediate blocks, lambdas, etc. | ||||
19124 | if (!ParentDC) { | ||||
19125 | if (IsGlobal) { | ||||
19126 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | ||||
19127 | break; | ||||
19128 | } | ||||
19129 | return true; | ||||
19130 | } | ||||
19131 | |||||
19132 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | ||||
19133 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | ||||
19134 | |||||
19135 | |||||
19136 | // Check whether we've already captured it. | ||||
19137 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | ||||
19138 | DeclRefType)) { | ||||
19139 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | ||||
19140 | break; | ||||
19141 | } | ||||
19142 | // If we are instantiating a generic lambda call operator body, | ||||
19143 | // we do not want to capture new variables. What was captured | ||||
19144 | // during either a lambdas transformation or initial parsing | ||||
19145 | // should be used. | ||||
19146 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | ||||
19147 | if (BuildAndDiagnose) { | ||||
19148 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
19149 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | ||||
19150 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
19151 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
19152 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
19153 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
19154 | } else | ||||
19155 | diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var); | ||||
19156 | } | ||||
19157 | return true; | ||||
19158 | } | ||||
19159 | |||||
19160 | // Try to capture variable-length arrays types. | ||||
19161 | if (Var->getType()->isVariablyModifiedType()) { | ||||
19162 | // We're going to walk down into the type and look for VLA | ||||
19163 | // expressions. | ||||
19164 | QualType QTy = Var->getType(); | ||||
19165 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
19166 | QTy = PVD->getOriginalType(); | ||||
19167 | captureVariablyModifiedType(Context, QTy, CSI); | ||||
19168 | } | ||||
19169 | |||||
19170 | if (getLangOpts().OpenMP) { | ||||
19171 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
19172 | // OpenMP private variables should not be captured in outer scope, so | ||||
19173 | // just break here. Similarly, global variables that are captured in a | ||||
19174 | // target region should not be captured outside the scope of the region. | ||||
19175 | if (RSI->CapRegionKind == CR_OpenMP) { | ||||
19176 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | ||||
19177 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | ||||
19178 | // If the variable is private (i.e. not captured) and has variably | ||||
19179 | // modified type, we still need to capture the type for correct | ||||
19180 | // codegen in all regions, associated with the construct. Currently, | ||||
19181 | // it is captured in the innermost captured region only. | ||||
19182 | if (IsOpenMPPrivateDecl != OMPC_unknown && | ||||
19183 | Var->getType()->isVariablyModifiedType()) { | ||||
19184 | QualType QTy = Var->getType(); | ||||
19185 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
19186 | QTy = PVD->getOriginalType(); | ||||
19187 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | ||||
19188 | I < E; ++I) { | ||||
19189 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | ||||
19190 | FunctionScopes[FunctionScopesIndex - I]); | ||||
19191 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 19193, __extension__ __PRETTY_FUNCTION__ )) | ||||
19192 | "Wrong number of captured regions associated with the "(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 19193, __extension__ __PRETTY_FUNCTION__ )) | ||||
19193 | "OpenMP construct.")(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 19193, __extension__ __PRETTY_FUNCTION__ )); | ||||
19194 | captureVariablyModifiedType(Context, QTy, OuterRSI); | ||||
19195 | } | ||||
19196 | } | ||||
19197 | bool IsTargetCap = | ||||
19198 | IsOpenMPPrivateDecl != OMPC_private && | ||||
19199 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | ||||
19200 | RSI->OpenMPCaptureLevel); | ||||
19201 | // Do not capture global if it is not privatized in outer regions. | ||||
19202 | bool IsGlobalCap = | ||||
19203 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | ||||
19204 | RSI->OpenMPCaptureLevel); | ||||
19205 | |||||
19206 | // When we detect target captures we are looking from inside the | ||||
19207 | // target region, therefore we need to propagate the capture from the | ||||
19208 | // enclosing region. Therefore, the capture is not initially nested. | ||||
19209 | if (IsTargetCap) | ||||
19210 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | ||||
19211 | |||||
19212 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | ||||
19213 | (IsGlobal && !IsGlobalCap)) { | ||||
19214 | Nested = !IsTargetCap; | ||||
19215 | bool HasConst = DeclRefType.isConstQualified(); | ||||
19216 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
19217 | // Don't lose diagnostics about assignments to const. | ||||
19218 | if (HasConst) | ||||
19219 | DeclRefType.addConst(); | ||||
19220 | CaptureType = Context.getLValueReferenceType(DeclRefType); | ||||
19221 | break; | ||||
19222 | } | ||||
19223 | } | ||||
19224 | } | ||||
19225 | } | ||||
19226 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | ||||
19227 | // No capture-default, and this is not an explicit capture | ||||
19228 | // so cannot capture this variable. | ||||
19229 | if (BuildAndDiagnose) { | ||||
19230 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
19231 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
19232 | auto *LSI = cast<LambdaScopeInfo>(CSI); | ||||
19233 | if (LSI->Lambda) { | ||||
19234 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
19235 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
19236 | } | ||||
19237 | // FIXME: If we error out because an outer lambda can not implicitly | ||||
19238 | // capture a variable that an inner lambda explicitly captures, we | ||||
19239 | // should have the inner lambda do the explicit capture - because | ||||
19240 | // it makes for cleaner diagnostics later. This would purely be done | ||||
19241 | // so that the diagnostic does not misleadingly claim that a variable | ||||
19242 | // can not be captured by a lambda implicitly even though it is captured | ||||
19243 | // explicitly. Suggestion: | ||||
19244 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | ||||
19245 | // at the function head | ||||
19246 | // - cache the StartingDeclContext - this must be a lambda | ||||
19247 | // - captureInLambda in the innermost lambda the variable. | ||||
19248 | } | ||||
19249 | return true; | ||||
19250 | } | ||||
19251 | |||||
19252 | FunctionScopesIndex--; | ||||
19253 | DC = ParentDC; | ||||
19254 | Explicit = false; | ||||
19255 | } while (!VarDC->Equals(DC)); | ||||
19256 | |||||
19257 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | ||||
19258 | // computing the type of the capture at each step, checking type-specific | ||||
19259 | // requirements, and adding captures if requested. | ||||
19260 | // If the variable had already been captured previously, we start capturing | ||||
19261 | // at the lambda nested within that one. | ||||
19262 | bool Invalid = false; | ||||
19263 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | ||||
19264 | ++I) { | ||||
19265 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | ||||
19266 | |||||
19267 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
19268 | // certain types of variables (unnamed, variably modified types etc.) | ||||
19269 | // so check for eligibility. | ||||
19270 | if (!Invalid) | ||||
19271 | Invalid = | ||||
19272 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | ||||
19273 | |||||
19274 | // After encountering an error, if we're actually supposed to capture, keep | ||||
19275 | // capturing in nested contexts to suppress any follow-on diagnostics. | ||||
19276 | if (Invalid && !BuildAndDiagnose) | ||||
19277 | return true; | ||||
19278 | |||||
19279 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | ||||
19280 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
19281 | DeclRefType, Nested, *this, Invalid); | ||||
19282 | Nested = true; | ||||
19283 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
19284 | Invalid = !captureInCapturedRegion( | ||||
19285 | RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, | ||||
19286 | Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
19287 | Nested = true; | ||||
19288 | } else { | ||||
19289 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
19290 | Invalid = | ||||
19291 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
19292 | DeclRefType, Nested, Kind, EllipsisLoc, | ||||
19293 | /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
19294 | Nested = true; | ||||
19295 | } | ||||
19296 | |||||
19297 | if (Invalid && !BuildAndDiagnose) | ||||
19298 | return true; | ||||
19299 | } | ||||
19300 | return Invalid; | ||||
19301 | } | ||||
19302 | |||||
19303 | bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, | ||||
19304 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | ||||
19305 | QualType CaptureType; | ||||
19306 | QualType DeclRefType; | ||||
19307 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | ||||
19308 | /*BuildAndDiagnose=*/true, CaptureType, | ||||
19309 | DeclRefType, nullptr); | ||||
19310 | } | ||||
19311 | |||||
19312 | bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { | ||||
19313 | QualType CaptureType; | ||||
19314 | QualType DeclRefType; | ||||
19315 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
19316 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
19317 | DeclRefType, nullptr); | ||||
19318 | } | ||||
19319 | |||||
19320 | QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { | ||||
19321 | QualType CaptureType; | ||||
19322 | QualType DeclRefType; | ||||
19323 | |||||
19324 | // Determine whether we can capture this variable. | ||||
19325 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
19326 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
19327 | DeclRefType, nullptr)) | ||||
19328 | return QualType(); | ||||
19329 | |||||
19330 | return DeclRefType; | ||||
19331 | } | ||||
19332 | |||||
19333 | namespace { | ||||
19334 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | ||||
19335 | // The produced TemplateArgumentListInfo* points to data stored within this | ||||
19336 | // object, so should only be used in contexts where the pointer will not be | ||||
19337 | // used after the CopiedTemplateArgs object is destroyed. | ||||
19338 | class CopiedTemplateArgs { | ||||
19339 | bool HasArgs; | ||||
19340 | TemplateArgumentListInfo TemplateArgStorage; | ||||
19341 | public: | ||||
19342 | template<typename RefExpr> | ||||
19343 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | ||||
19344 | if (HasArgs) | ||||
19345 | E->copyTemplateArgumentsInto(TemplateArgStorage); | ||||
19346 | } | ||||
19347 | operator TemplateArgumentListInfo*() | ||||
19348 | #ifdef __has_cpp_attribute | ||||
19349 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | ||||
19350 | [[clang::lifetimebound]] | ||||
19351 | #endif | ||||
19352 | #endif | ||||
19353 | { | ||||
19354 | return HasArgs ? &TemplateArgStorage : nullptr; | ||||
19355 | } | ||||
19356 | }; | ||||
19357 | } | ||||
19358 | |||||
19359 | /// Walk the set of potential results of an expression and mark them all as | ||||
19360 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | ||||
19361 | /// | ||||
19362 | /// \return A new expression if we found any potential results, ExprEmpty() if | ||||
19363 | /// not, and ExprError() if we diagnosed an error. | ||||
19364 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | ||||
19365 | NonOdrUseReason NOUR) { | ||||
19366 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | ||||
19367 | // an object that satisfies the requirements for appearing in a | ||||
19368 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | ||||
19369 | // is immediately applied." This function handles the lvalue-to-rvalue | ||||
19370 | // conversion part. | ||||
19371 | // | ||||
19372 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | ||||
19373 | // transform it into the relevant kind of non-odr-use node and rebuild the | ||||
19374 | // tree of nodes leading to it. | ||||
19375 | // | ||||
19376 | // This is a mini-TreeTransform that only transforms a restricted subset of | ||||
19377 | // nodes (and only certain operands of them). | ||||
19378 | |||||
19379 | // Rebuild a subexpression. | ||||
19380 | auto Rebuild = [&](Expr *Sub) { | ||||
19381 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | ||||
19382 | }; | ||||
19383 | |||||
19384 | // Check whether a potential result satisfies the requirements of NOUR. | ||||
19385 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | ||||
19386 | // Any entity other than a VarDecl is always odr-used whenever it's named | ||||
19387 | // in a potentially-evaluated expression. | ||||
19388 | auto *VD = dyn_cast<VarDecl>(D); | ||||
19389 | if (!VD) | ||||
19390 | return true; | ||||
19391 | |||||
19392 | // C++2a [basic.def.odr]p4: | ||||
19393 | // A variable x whose name appears as a potentially-evalauted expression | ||||
19394 | // e is odr-used by e unless | ||||
19395 | // -- x is a reference that is usable in constant expressions, or | ||||
19396 | // -- x is a variable of non-reference type that is usable in constant | ||||
19397 | // expressions and has no mutable subobjects, and e is an element of | ||||
19398 | // the set of potential results of an expression of | ||||
19399 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
19400 | // conversion is applied, or | ||||
19401 | // -- x is a variable of non-reference type, and e is an element of the | ||||
19402 | // set of potential results of a discarded-value expression to which | ||||
19403 | // the lvalue-to-rvalue conversion is not applied | ||||
19404 | // | ||||
19405 | // We check the first bullet and the "potentially-evaluated" condition in | ||||
19406 | // BuildDeclRefExpr. We check the type requirements in the second bullet | ||||
19407 | // in CheckLValueToRValueConversionOperand below. | ||||
19408 | switch (NOUR) { | ||||
19409 | case NOUR_None: | ||||
19410 | case NOUR_Unevaluated: | ||||
19411 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "clang/lib/Sema/SemaExpr.cpp", 19411); | ||||
19412 | |||||
19413 | case NOUR_Constant: | ||||
19414 | // Constant references were handled when they were built. | ||||
19415 | if (VD->getType()->isReferenceType()) | ||||
19416 | return true; | ||||
19417 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | ||||
19418 | if (RD->hasMutableFields()) | ||||
19419 | return true; | ||||
19420 | if (!VD->isUsableInConstantExpressions(S.Context)) | ||||
19421 | return true; | ||||
19422 | break; | ||||
19423 | |||||
19424 | case NOUR_Discarded: | ||||
19425 | if (VD->getType()->isReferenceType()) | ||||
19426 | return true; | ||||
19427 | break; | ||||
19428 | } | ||||
19429 | return false; | ||||
19430 | }; | ||||
19431 | |||||
19432 | // Mark that this expression does not constitute an odr-use. | ||||
19433 | auto MarkNotOdrUsed = [&] { | ||||
19434 | S.MaybeODRUseExprs.remove(E); | ||||
19435 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | ||||
19436 | LSI->markVariableExprAsNonODRUsed(E); | ||||
19437 | }; | ||||
19438 | |||||
19439 | // C++2a [basic.def.odr]p2: | ||||
19440 | // The set of potential results of an expression e is defined as follows: | ||||
19441 | switch (E->getStmtClass()) { | ||||
19442 | // -- If e is an id-expression, ... | ||||
19443 | case Expr::DeclRefExprClass: { | ||||
19444 | auto *DRE = cast<DeclRefExpr>(E); | ||||
19445 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | ||||
19446 | break; | ||||
19447 | |||||
19448 | // Rebuild as a non-odr-use DeclRefExpr. | ||||
19449 | MarkNotOdrUsed(); | ||||
19450 | return DeclRefExpr::Create( | ||||
19451 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | ||||
19452 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | ||||
19453 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | ||||
19454 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | ||||
19455 | } | ||||
19456 | |||||
19457 | case Expr::FunctionParmPackExprClass: { | ||||
19458 | auto *FPPE = cast<FunctionParmPackExpr>(E); | ||||
19459 | // If any of the declarations in the pack is odr-used, then the expression | ||||
19460 | // as a whole constitutes an odr-use. | ||||
19461 | for (VarDecl *D : *FPPE) | ||||
19462 | if (IsPotentialResultOdrUsed(D)) | ||||
19463 | return ExprEmpty(); | ||||
19464 | |||||
19465 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | ||||
19466 | // nothing cares about whether we marked this as an odr-use, but it might | ||||
19467 | // be useful for non-compiler tools. | ||||
19468 | MarkNotOdrUsed(); | ||||
19469 | break; | ||||
19470 | } | ||||
19471 | |||||
19472 | // -- If e is a subscripting operation with an array operand... | ||||
19473 | case Expr::ArraySubscriptExprClass: { | ||||
19474 | auto *ASE = cast<ArraySubscriptExpr>(E); | ||||
19475 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | ||||
19476 | if (!OldBase->getType()->isArrayType()) | ||||
19477 | break; | ||||
19478 | ExprResult Base = Rebuild(OldBase); | ||||
19479 | if (!Base.isUsable()) | ||||
19480 | return Base; | ||||
19481 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | ||||
19482 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | ||||
19483 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | ||||
19484 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | ||||
19485 | ASE->getRBracketLoc()); | ||||
19486 | } | ||||
19487 | |||||
19488 | case Expr::MemberExprClass: { | ||||
19489 | auto *ME = cast<MemberExpr>(E); | ||||
19490 | // -- If e is a class member access expression [...] naming a non-static | ||||
19491 | // data member... | ||||
19492 | if (isa<FieldDecl>(ME->getMemberDecl())) { | ||||
19493 | ExprResult Base = Rebuild(ME->getBase()); | ||||
19494 | if (!Base.isUsable()) | ||||
19495 | return Base; | ||||
19496 | return MemberExpr::Create( | ||||
19497 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | ||||
19498 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | ||||
19499 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | ||||
19500 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | ||||
19501 | ME->getObjectKind(), ME->isNonOdrUse()); | ||||
19502 | } | ||||
19503 | |||||
19504 | if (ME->getMemberDecl()->isCXXInstanceMember()) | ||||
19505 | break; | ||||
19506 | |||||
19507 | // -- If e is a class member access expression naming a static data member, | ||||
19508 | // ... | ||||
19509 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | ||||
19510 | break; | ||||
19511 | |||||
19512 | // Rebuild as a non-odr-use MemberExpr. | ||||
19513 | MarkNotOdrUsed(); | ||||
19514 | return MemberExpr::Create( | ||||
19515 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | ||||
19516 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | ||||
19517 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | ||||
19518 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | ||||
19519 | } | ||||
19520 | |||||
19521 | case Expr::BinaryOperatorClass: { | ||||
19522 | auto *BO = cast<BinaryOperator>(E); | ||||
19523 | Expr *LHS = BO->getLHS(); | ||||
19524 | Expr *RHS = BO->getRHS(); | ||||
19525 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | ||||
19526 | if (BO->getOpcode() == BO_PtrMemD) { | ||||
19527 | ExprResult Sub = Rebuild(LHS); | ||||
19528 | if (!Sub.isUsable()) | ||||
19529 | return Sub; | ||||
19530 | LHS = Sub.get(); | ||||
19531 | // -- If e is a comma expression, ... | ||||
19532 | } else if (BO->getOpcode() == BO_Comma) { | ||||
19533 | ExprResult Sub = Rebuild(RHS); | ||||
19534 | if (!Sub.isUsable()) | ||||
19535 | return Sub; | ||||
19536 | RHS = Sub.get(); | ||||
19537 | } else { | ||||
19538 | break; | ||||
19539 | } | ||||
19540 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | ||||
19541 | LHS, RHS); | ||||
19542 | } | ||||
19543 | |||||
19544 | // -- If e has the form (e1)... | ||||
19545 | case Expr::ParenExprClass: { | ||||
19546 | auto *PE = cast<ParenExpr>(E); | ||||
19547 | ExprResult Sub = Rebuild(PE->getSubExpr()); | ||||
19548 | if (!Sub.isUsable()) | ||||
19549 | return Sub; | ||||
19550 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | ||||
19551 | } | ||||
19552 | |||||
19553 | // -- If e is a glvalue conditional expression, ... | ||||
19554 | // We don't apply this to a binary conditional operator. FIXME: Should we? | ||||
19555 | case Expr::ConditionalOperatorClass: { | ||||
19556 | auto *CO = cast<ConditionalOperator>(E); | ||||
19557 | ExprResult LHS = Rebuild(CO->getLHS()); | ||||
19558 | if (LHS.isInvalid()) | ||||
19559 | return ExprError(); | ||||
19560 | ExprResult RHS = Rebuild(CO->getRHS()); | ||||
19561 | if (RHS.isInvalid()) | ||||
19562 | return ExprError(); | ||||
19563 | if (!LHS.isUsable() && !RHS.isUsable()) | ||||
19564 | return ExprEmpty(); | ||||
19565 | if (!LHS.isUsable()) | ||||
19566 | LHS = CO->getLHS(); | ||||
19567 | if (!RHS.isUsable()) | ||||
19568 | RHS = CO->getRHS(); | ||||
19569 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | ||||
19570 | CO->getCond(), LHS.get(), RHS.get()); | ||||
19571 | } | ||||
19572 | |||||
19573 | // [Clang extension] | ||||
19574 | // -- If e has the form __extension__ e1... | ||||
19575 | case Expr::UnaryOperatorClass: { | ||||
19576 | auto *UO = cast<UnaryOperator>(E); | ||||
19577 | if (UO->getOpcode() != UO_Extension) | ||||
19578 | break; | ||||
19579 | ExprResult Sub = Rebuild(UO->getSubExpr()); | ||||
19580 | if (!Sub.isUsable()) | ||||
19581 | return Sub; | ||||
19582 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | ||||
19583 | Sub.get()); | ||||
19584 | } | ||||
19585 | |||||
19586 | // [Clang extension] | ||||
19587 | // -- If e has the form _Generic(...), the set of potential results is the | ||||
19588 | // union of the sets of potential results of the associated expressions. | ||||
19589 | case Expr::GenericSelectionExprClass: { | ||||
19590 | auto *GSE = cast<GenericSelectionExpr>(E); | ||||
19591 | |||||
19592 | SmallVector<Expr *, 4> AssocExprs; | ||||
19593 | bool AnyChanged = false; | ||||
19594 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | ||||
19595 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | ||||
19596 | if (AssocExpr.isInvalid()) | ||||
19597 | return ExprError(); | ||||
19598 | if (AssocExpr.isUsable()) { | ||||
19599 | AssocExprs.push_back(AssocExpr.get()); | ||||
19600 | AnyChanged = true; | ||||
19601 | } else { | ||||
19602 | AssocExprs.push_back(OrigAssocExpr); | ||||
19603 | } | ||||
19604 | } | ||||
19605 | |||||
19606 | return AnyChanged ? S.CreateGenericSelectionExpr( | ||||
19607 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | ||||
19608 | GSE->getRParenLoc(), GSE->getControllingExpr(), | ||||
19609 | GSE->getAssocTypeSourceInfos(), AssocExprs) | ||||
19610 | : ExprEmpty(); | ||||
19611 | } | ||||
19612 | |||||
19613 | // [Clang extension] | ||||
19614 | // -- If e has the form __builtin_choose_expr(...), the set of potential | ||||
19615 | // results is the union of the sets of potential results of the | ||||
19616 | // second and third subexpressions. | ||||
19617 | case Expr::ChooseExprClass: { | ||||
19618 | auto *CE = cast<ChooseExpr>(E); | ||||
19619 | |||||
19620 | ExprResult LHS = Rebuild(CE->getLHS()); | ||||
19621 | if (LHS.isInvalid()) | ||||
19622 | return ExprError(); | ||||
19623 | |||||
19624 | ExprResult RHS = Rebuild(CE->getLHS()); | ||||
19625 | if (RHS.isInvalid()) | ||||
19626 | return ExprError(); | ||||
19627 | |||||
19628 | if (!LHS.get() && !RHS.get()) | ||||
19629 | return ExprEmpty(); | ||||
19630 | if (!LHS.isUsable()) | ||||
19631 | LHS = CE->getLHS(); | ||||
19632 | if (!RHS.isUsable()) | ||||
19633 | RHS = CE->getRHS(); | ||||
19634 | |||||
19635 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | ||||
19636 | RHS.get(), CE->getRParenLoc()); | ||||
19637 | } | ||||
19638 | |||||
19639 | // Step through non-syntactic nodes. | ||||
19640 | case Expr::ConstantExprClass: { | ||||
19641 | auto *CE = cast<ConstantExpr>(E); | ||||
19642 | ExprResult Sub = Rebuild(CE->getSubExpr()); | ||||
19643 | if (!Sub.isUsable()) | ||||
19644 | return Sub; | ||||
19645 | return ConstantExpr::Create(S.Context, Sub.get()); | ||||
19646 | } | ||||
19647 | |||||
19648 | // We could mostly rely on the recursive rebuilding to rebuild implicit | ||||
19649 | // casts, but not at the top level, so rebuild them here. | ||||
19650 | case Expr::ImplicitCastExprClass: { | ||||
19651 | auto *ICE = cast<ImplicitCastExpr>(E); | ||||
19652 | // Only step through the narrow set of cast kinds we expect to encounter. | ||||
19653 | // Anything else suggests we've left the region in which potential results | ||||
19654 | // can be found. | ||||
19655 | switch (ICE->getCastKind()) { | ||||
19656 | case CK_NoOp: | ||||
19657 | case CK_DerivedToBase: | ||||
19658 | case CK_UncheckedDerivedToBase: { | ||||
19659 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | ||||
19660 | if (!Sub.isUsable()) | ||||
19661 | return Sub; | ||||
19662 | CXXCastPath Path(ICE->path()); | ||||
19663 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | ||||
19664 | ICE->getValueKind(), &Path); | ||||
19665 | } | ||||
19666 | |||||
19667 | default: | ||||
19668 | break; | ||||
19669 | } | ||||
19670 | break; | ||||
19671 | } | ||||
19672 | |||||
19673 | default: | ||||
19674 | break; | ||||
19675 | } | ||||
19676 | |||||
19677 | // Can't traverse through this node. Nothing to do. | ||||
19678 | return ExprEmpty(); | ||||
19679 | } | ||||
19680 | |||||
19681 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | ||||
19682 | // Check whether the operand is or contains an object of non-trivial C union | ||||
19683 | // type. | ||||
19684 | if (E->getType().isVolatileQualified() && | ||||
19685 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
19686 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | ||||
19687 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
19688 | Sema::NTCUC_LValueToRValueVolatile, | ||||
19689 | NTCUK_Destruct|NTCUK_Copy); | ||||
19690 | |||||
19691 | // C++2a [basic.def.odr]p4: | ||||
19692 | // [...] an expression of non-volatile-qualified non-class type to which | ||||
19693 | // the lvalue-to-rvalue conversion is applied [...] | ||||
19694 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | ||||
19695 | return E; | ||||
19696 | |||||
19697 | ExprResult Result = | ||||
19698 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | ||||
19699 | if (Result.isInvalid()) | ||||
19700 | return ExprError(); | ||||
19701 | return Result.get() ? Result : E; | ||||
19702 | } | ||||
19703 | |||||
19704 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | ||||
19705 | Res = CorrectDelayedTyposInExpr(Res); | ||||
19706 | |||||
19707 | if (!Res.isUsable()) | ||||
19708 | return Res; | ||||
19709 | |||||
19710 | // If a constant-expression is a reference to a variable where we delay | ||||
19711 | // deciding whether it is an odr-use, just assume we will apply the | ||||
19712 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | ||||
19713 | // (a non-type template argument), we have special handling anyway. | ||||
19714 | return CheckLValueToRValueConversionOperand(Res.get()); | ||||
19715 | } | ||||
19716 | |||||
19717 | void Sema::CleanupVarDeclMarking() { | ||||
19718 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | ||||
19719 | // call. | ||||
19720 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | ||||
19721 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | ||||
19722 | |||||
19723 | for (Expr *E : LocalMaybeODRUseExprs) { | ||||
19724 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
19725 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | ||||
19726 | DRE->getLocation(), *this); | ||||
19727 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
19728 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | ||||
19729 | *this); | ||||
19730 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | ||||
19731 | for (VarDecl *VD : *FP) | ||||
19732 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | ||||
19733 | } else { | ||||
19734 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp" , 19734); | ||||
19735 | } | ||||
19736 | } | ||||
19737 | |||||
19738 | assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "clang/lib/Sema/SemaExpr.cpp", 19739, __extension__ __PRETTY_FUNCTION__ )) | ||||
19739 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "clang/lib/Sema/SemaExpr.cpp", 19739, __extension__ __PRETTY_FUNCTION__ )); | ||||
19740 | } | ||||
19741 | |||||
19742 | static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, | ||||
19743 | ValueDecl *Var, Expr *E) { | ||||
19744 | VarDecl *VD = Var->getPotentiallyDecomposedVarDecl(); | ||||
19745 | if (!VD) | ||||
19746 | return; | ||||
19747 | |||||
19748 | const bool RefersToEnclosingScope = | ||||
19749 | (SemaRef.CurContext != VD->getDeclContext() && | ||||
19750 | VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage()); | ||||
19751 | if (RefersToEnclosingScope) { | ||||
19752 | LambdaScopeInfo *const LSI = | ||||
19753 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | ||||
19754 | if (LSI && (!LSI->CallOperator || | ||||
19755 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | ||||
19756 | // If a variable could potentially be odr-used, defer marking it so | ||||
19757 | // until we finish analyzing the full expression for any | ||||
19758 | // lvalue-to-rvalue | ||||
19759 | // or discarded value conversions that would obviate odr-use. | ||||
19760 | // Add it to the list of potential captures that will be analyzed | ||||
19761 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | ||||
19762 | // unless the variable is a reference that was initialized by a constant | ||||
19763 | // expression (this will never need to be captured or odr-used). | ||||
19764 | // | ||||
19765 | // FIXME: We can simplify this a lot after implementing P0588R1. | ||||
19766 | assert(E && "Capture variable should be used in an expression.")(static_cast <bool> (E && "Capture variable should be used in an expression." ) ? void (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "clang/lib/Sema/SemaExpr.cpp", 19766, __extension__ __PRETTY_FUNCTION__ )); | ||||
19767 | if (!Var->getType()->isReferenceType() || | ||||
19768 | !VD->isUsableInConstantExpressions(SemaRef.Context)) | ||||
19769 | LSI->addPotentialCapture(E->IgnoreParens()); | ||||
19770 | } | ||||
19771 | } | ||||
19772 | } | ||||
19773 | |||||
19774 | static void DoMarkVarDeclReferenced( | ||||
19775 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, | ||||
19776 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | ||||
19777 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 19779, __extension__ __PRETTY_FUNCTION__ )) | ||||
19778 | isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 19779, __extension__ __PRETTY_FUNCTION__ )) | ||||
19779 | "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 19779, __extension__ __PRETTY_FUNCTION__ )); | ||||
19780 | Var->setReferenced(); | ||||
19781 | |||||
19782 | if (Var->isInvalidDecl()) | ||||
19783 | return; | ||||
19784 | |||||
19785 | auto *MSI = Var->getMemberSpecializationInfo(); | ||||
19786 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | ||||
19787 | : Var->getTemplateSpecializationKind(); | ||||
19788 | |||||
19789 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
19790 | bool UsableInConstantExpr = | ||||
19791 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | ||||
19792 | |||||
19793 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { | ||||
19794 | RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; | ||||
19795 | } | ||||
19796 | |||||
19797 | // C++20 [expr.const]p12: | ||||
19798 | // A variable [...] is needed for constant evaluation if it is [...] a | ||||
19799 | // variable whose name appears as a potentially constant evaluated | ||||
19800 | // expression that is either a contexpr variable or is of non-volatile | ||||
19801 | // const-qualified integral type or of reference type | ||||
19802 | bool NeededForConstantEvaluation = | ||||
19803 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | ||||
19804 | |||||
19805 | bool NeedDefinition = | ||||
19806 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | ||||
19807 | |||||
19808 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "clang/lib/Sema/SemaExpr.cpp", 19809, __extension__ __PRETTY_FUNCTION__ )) | ||||
19809 | "Can't instantiate a partial template specialization.")(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "clang/lib/Sema/SemaExpr.cpp", 19809, __extension__ __PRETTY_FUNCTION__ )); | ||||
19810 | |||||
19811 | // If this might be a member specialization of a static data member, check | ||||
19812 | // the specialization is visible. We already did the checks for variable | ||||
19813 | // template specializations when we created them. | ||||
19814 | if (NeedDefinition && TSK != TSK_Undeclared && | ||||
19815 | !isa<VarTemplateSpecializationDecl>(Var)) | ||||
19816 | SemaRef.checkSpecializationVisibility(Loc, Var); | ||||
19817 | |||||
19818 | // Perform implicit instantiation of static data members, static data member | ||||
19819 | // templates of class templates, and variable template specializations. Delay | ||||
19820 | // instantiations of variable templates, except for those that could be used | ||||
19821 | // in a constant expression. | ||||
19822 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | ||||
19823 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | ||||
19824 | // instantiation declaration if a variable is usable in a constant | ||||
19825 | // expression (among other cases). | ||||
19826 | bool TryInstantiating = | ||||
19827 | TSK == TSK_ImplicitInstantiation || | ||||
19828 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | ||||
19829 | |||||
19830 | if (TryInstantiating) { | ||||
19831 | SourceLocation PointOfInstantiation = | ||||
19832 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | ||||
19833 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
19834 | if (FirstInstantiation) { | ||||
19835 | PointOfInstantiation = Loc; | ||||
19836 | if (MSI) | ||||
19837 | MSI->setPointOfInstantiation(PointOfInstantiation); | ||||
19838 | // FIXME: Notify listener. | ||||
19839 | else | ||||
19840 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
19841 | } | ||||
19842 | |||||
19843 | if (UsableInConstantExpr) { | ||||
19844 | // Do not defer instantiations of variables that could be used in a | ||||
19845 | // constant expression. | ||||
19846 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||
19847 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||
19848 | }); | ||||
19849 | |||||
19850 | // Re-set the member to trigger a recomputation of the dependence bits | ||||
19851 | // for the expression. | ||||
19852 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
19853 | DRE->setDecl(DRE->getDecl()); | ||||
19854 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
19855 | ME->setMemberDecl(ME->getMemberDecl()); | ||||
19856 | } else if (FirstInstantiation || | ||||
19857 | isa<VarTemplateSpecializationDecl>(Var)) { | ||||
19858 | // FIXME: For a specialization of a variable template, we don't | ||||
19859 | // distinguish between "declaration and type implicitly instantiated" | ||||
19860 | // and "implicit instantiation of definition requested", so we have | ||||
19861 | // no direct way to avoid enqueueing the pending instantiation | ||||
19862 | // multiple times. | ||||
19863 | SemaRef.PendingInstantiations | ||||
19864 | .push_back(std::make_pair(Var, PointOfInstantiation)); | ||||
19865 | } | ||||
19866 | } | ||||
19867 | } | ||||
19868 | |||||
19869 | // C++2a [basic.def.odr]p4: | ||||
19870 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
19871 | // is odr-used by e unless | ||||
19872 | // -- x is a reference that is usable in constant expressions | ||||
19873 | // -- x is a variable of non-reference type that is usable in constant | ||||
19874 | // expressions and has no mutable subobjects [FIXME], and e is an | ||||
19875 | // element of the set of potential results of an expression of | ||||
19876 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
19877 | // conversion is applied | ||||
19878 | // -- x is a variable of non-reference type, and e is an element of the set | ||||
19879 | // of potential results of a discarded-value expression to which the | ||||
19880 | // lvalue-to-rvalue conversion is not applied [FIXME] | ||||
19881 | // | ||||
19882 | // We check the first part of the second bullet here, and | ||||
19883 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | ||||
19884 | // FIXME: To get the third bullet right, we need to delay this even for | ||||
19885 | // variables that are not usable in constant expressions. | ||||
19886 | |||||
19887 | // If we already know this isn't an odr-use, there's nothing more to do. | ||||
19888 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
19889 | if (DRE->isNonOdrUse()) | ||||
19890 | return; | ||||
19891 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
19892 | if (ME->isNonOdrUse()) | ||||
19893 | return; | ||||
19894 | |||||
19895 | switch (OdrUse) { | ||||
19896 | case OdrUseContext::None: | ||||
19897 | // In some cases, a variable may not have been marked unevaluated, if it | ||||
19898 | // appears in a defaukt initializer. | ||||
19899 | assert((!E || isa<FunctionParmPackExpr>(E) ||(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 19901, __extension__ __PRETTY_FUNCTION__ )) | ||||
19900 | SemaRef.isUnevaluatedContext()) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 19901, __extension__ __PRETTY_FUNCTION__ )) | ||||
19901 | "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 19901, __extension__ __PRETTY_FUNCTION__ )); | ||||
19902 | break; | ||||
19903 | |||||
19904 | case OdrUseContext::FormallyOdrUsed: | ||||
19905 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | ||||
19906 | // behavior. | ||||
19907 | break; | ||||
19908 | |||||
19909 | case OdrUseContext::Used: | ||||
19910 | // If we might later find that this expression isn't actually an odr-use, | ||||
19911 | // delay the marking. | ||||
19912 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
19913 | SemaRef.MaybeODRUseExprs.insert(E); | ||||
19914 | else | ||||
19915 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | ||||
19916 | break; | ||||
19917 | |||||
19918 | case OdrUseContext::Dependent: | ||||
19919 | // If this is a dependent context, we don't need to mark variables as | ||||
19920 | // odr-used, but we may still need to track them for lambda capture. | ||||
19921 | // FIXME: Do we also need to do this inside dependent typeid expressions | ||||
19922 | // (which are modeled as unevaluated at this point)? | ||||
19923 | DoMarkPotentialCapture(SemaRef, Loc, Var, E); | ||||
19924 | break; | ||||
19925 | } | ||||
19926 | } | ||||
19927 | |||||
19928 | static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, | ||||
19929 | BindingDecl *BD, Expr *E) { | ||||
19930 | BD->setReferenced(); | ||||
19931 | |||||
19932 | if (BD->isInvalidDecl()) | ||||
19933 | return; | ||||
19934 | |||||
19935 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
19936 | if (OdrUse == OdrUseContext::Used) { | ||||
19937 | QualType CaptureType, DeclRefType; | ||||
19938 | SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit, | ||||
19939 | /*EllipsisLoc*/ SourceLocation(), | ||||
19940 | /*BuildAndDiagnose*/ true, CaptureType, | ||||
19941 | DeclRefType, | ||||
19942 | /*FunctionScopeIndexToStopAt*/ nullptr); | ||||
19943 | } else if (OdrUse == OdrUseContext::Dependent) { | ||||
19944 | DoMarkPotentialCapture(SemaRef, Loc, BD, E); | ||||
19945 | } | ||||
19946 | } | ||||
19947 | |||||
19948 | /// Mark a variable referenced, and check whether it is odr-used | ||||
19949 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | ||||
19950 | /// used directly for normal expressions referring to VarDecl. | ||||
19951 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | ||||
19952 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); | ||||
19953 | } | ||||
19954 | |||||
19955 | static void | ||||
19956 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, | ||||
19957 | bool MightBeOdrUse, | ||||
19958 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | ||||
19959 | if (SemaRef.isInOpenMPDeclareTargetContext()) | ||||
19960 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | ||||
19961 | |||||
19962 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | ||||
19963 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); | ||||
19964 | return; | ||||
19965 | } | ||||
19966 | |||||
19967 | if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) { | ||||
19968 | DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E); | ||||
19969 | return; | ||||
19970 | } | ||||
19971 | |||||
19972 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | ||||
19973 | |||||
19974 | // If this is a call to a method via a cast, also mark the method in the | ||||
19975 | // derived class used in case codegen can devirtualize the call. | ||||
19976 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
19977 | if (!ME) | ||||
19978 | return; | ||||
19979 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
19980 | if (!MD) | ||||
19981 | return; | ||||
19982 | // Only attempt to devirtualize if this is truly a virtual call. | ||||
19983 | bool IsVirtualCall = MD->isVirtual() && | ||||
19984 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | ||||
19985 | if (!IsVirtualCall) | ||||
19986 | return; | ||||
19987 | |||||
19988 | // If it's possible to devirtualize the call, mark the called function | ||||
19989 | // referenced. | ||||
19990 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | ||||
19991 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | ||||
19992 | if (DM) | ||||
19993 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | ||||
19994 | } | ||||
19995 | |||||
19996 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | ||||
19997 | /// | ||||
19998 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to be | ||||
19999 | /// handled with care if the DeclRefExpr is not newly-created. | ||||
20000 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | ||||
20001 | // TODO: update this with DR# once a defect report is filed. | ||||
20002 | // C++11 defect. The address of a pure member should not be an ODR use, even | ||||
20003 | // if it's a qualified reference. | ||||
20004 | bool OdrUse = true; | ||||
20005 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | ||||
20006 | if (Method->isVirtual() && | ||||
20007 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | ||||
20008 | OdrUse = false; | ||||
20009 | |||||
20010 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||
20011 | if (!isUnevaluatedContext() && !isConstantEvaluated() && | ||||
20012 | !isImmediateFunctionContext() && | ||||
20013 | !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() && | ||||
20014 | !RebuildingImmediateInvocation && !FD->isDependentContext()) | ||||
20015 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | ||||
20016 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, | ||||
20017 | RefsMinusAssignments); | ||||
20018 | } | ||||
20019 | |||||
20020 | /// Perform reference-marking and odr-use handling for a MemberExpr. | ||||
20021 | void Sema::MarkMemberReferenced(MemberExpr *E) { | ||||
20022 | // C++11 [basic.def.odr]p2: | ||||
20023 | // A non-overloaded function whose name appears as a potentially-evaluated | ||||
20024 | // expression or a member of a set of candidate functions, if selected by | ||||
20025 | // overload resolution when referred to from a potentially-evaluated | ||||
20026 | // expression, is odr-used, unless it is a pure virtual function and its | ||||
20027 | // name is not explicitly qualified. | ||||
20028 | bool MightBeOdrUse = true; | ||||
20029 | if (E->performsVirtualDispatch(getLangOpts())) { | ||||
20030 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | ||||
20031 | if (Method->isPure()) | ||||
20032 | MightBeOdrUse = false; | ||||
20033 | } | ||||
20034 | SourceLocation Loc = | ||||
20035 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | ||||
20036 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, | ||||
20037 | RefsMinusAssignments); | ||||
20038 | } | ||||
20039 | |||||
20040 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | ||||
20041 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | ||||
20042 | for (VarDecl *VD : *E) | ||||
20043 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, | ||||
20044 | RefsMinusAssignments); | ||||
20045 | } | ||||
20046 | |||||
20047 | /// Perform marking for a reference to an arbitrary declaration. It | ||||
20048 | /// marks the declaration referenced, and performs odr-use checking for | ||||
20049 | /// functions and variables. This method should not be used when building a | ||||
20050 | /// normal expression which refers to a variable. | ||||
20051 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | ||||
20052 | bool MightBeOdrUse) { | ||||
20053 | if (MightBeOdrUse) { | ||||
20054 | if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||
20055 | MarkVariableReferenced(Loc, VD); | ||||
20056 | return; | ||||
20057 | } | ||||
20058 | } | ||||
20059 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||
20060 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | ||||
20061 | return; | ||||
20062 | } | ||||
20063 | D->setReferenced(); | ||||
20064 | } | ||||
20065 | |||||
20066 | namespace { | ||||
20067 | // Mark all of the declarations used by a type as referenced. | ||||
20068 | // FIXME: Not fully implemented yet! We need to have a better understanding | ||||
20069 | // of when we're entering a context we should not recurse into. | ||||
20070 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | ||||
20071 | // TreeTransforms rebuilding the type in a new context. Rather than | ||||
20072 | // duplicating the TreeTransform logic, we should consider reusing it here. | ||||
20073 | // Currently that causes problems when rebuilding LambdaExprs. | ||||
20074 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | ||||
20075 | Sema &S; | ||||
20076 | SourceLocation Loc; | ||||
20077 | |||||
20078 | public: | ||||
20079 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | ||||
20080 | |||||
20081 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | ||||
20082 | |||||
20083 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | ||||
20084 | }; | ||||
20085 | } | ||||
20086 | |||||
20087 | bool MarkReferencedDecls::TraverseTemplateArgument( | ||||
20088 | const TemplateArgument &Arg) { | ||||
20089 | { | ||||
20090 | // A non-type template argument is a constant-evaluated context. | ||||
20091 | EnterExpressionEvaluationContext Evaluated( | ||||
20092 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
20093 | if (Arg.getKind() == TemplateArgument::Declaration) { | ||||
20094 | if (Decl *D = Arg.getAsDecl()) | ||||
20095 | S.MarkAnyDeclReferenced(Loc, D, true); | ||||
20096 | } else if (Arg.getKind() == TemplateArgument::Expression) { | ||||
20097 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | ||||
20098 | } | ||||
20099 | } | ||||
20100 | |||||
20101 | return Inherited::TraverseTemplateArgument(Arg); | ||||
20102 | } | ||||
20103 | |||||
20104 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | ||||
20105 | MarkReferencedDecls Marker(*this, Loc); | ||||
20106 | Marker.TraverseType(T); | ||||
20107 | } | ||||
20108 | |||||
20109 | namespace { | ||||
20110 | /// Helper class that marks all of the declarations referenced by | ||||
20111 | /// potentially-evaluated subexpressions as "referenced". | ||||
20112 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | ||||
20113 | public: | ||||
20114 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | ||||
20115 | bool SkipLocalVariables; | ||||
20116 | ArrayRef<const Expr *> StopAt; | ||||
20117 | |||||
20118 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, | ||||
20119 | ArrayRef<const Expr *> StopAt) | ||||
20120 | : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} | ||||
20121 | |||||
20122 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | ||||
20123 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | ||||
20124 | } | ||||
20125 | |||||
20126 | void Visit(Expr *E) { | ||||
20127 | if (llvm::is_contained(StopAt, E)) | ||||
20128 | return; | ||||
20129 | Inherited::Visit(E); | ||||
20130 | } | ||||
20131 | |||||
20132 | void VisitConstantExpr(ConstantExpr *E) { | ||||
20133 | // Don't mark declarations within a ConstantExpression, as this expression | ||||
20134 | // will be evaluated and folded to a value. | ||||
20135 | } | ||||
20136 | |||||
20137 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||
20138 | // If we were asked not to visit local variables, don't. | ||||
20139 | if (SkipLocalVariables) { | ||||
20140 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||
20141 | if (VD->hasLocalStorage()) | ||||
20142 | return; | ||||
20143 | } | ||||
20144 | |||||
20145 | // FIXME: This can trigger the instantiation of the initializer of a | ||||
20146 | // variable, which can cause the expression to become value-dependent | ||||
20147 | // or error-dependent. Do we need to propagate the new dependence bits? | ||||
20148 | S.MarkDeclRefReferenced(E); | ||||
20149 | } | ||||
20150 | |||||
20151 | void VisitMemberExpr(MemberExpr *E) { | ||||
20152 | S.MarkMemberReferenced(E); | ||||
20153 | Visit(E->getBase()); | ||||
20154 | } | ||||
20155 | }; | ||||
20156 | } // namespace | ||||
20157 | |||||
20158 | /// Mark any declarations that appear within this expression or any | ||||
20159 | /// potentially-evaluated subexpressions as "referenced". | ||||
20160 | /// | ||||
20161 | /// \param SkipLocalVariables If true, don't mark local variables as | ||||
20162 | /// 'referenced'. | ||||
20163 | /// \param StopAt Subexpressions that we shouldn't recurse into. | ||||
20164 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | ||||
20165 | bool SkipLocalVariables, | ||||
20166 | ArrayRef<const Expr*> StopAt) { | ||||
20167 | EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); | ||||
20168 | } | ||||
20169 | |||||
20170 | /// Emit a diagnostic when statements are reachable. | ||||
20171 | /// FIXME: check for reachability even in expressions for which we don't build a | ||||
20172 | /// CFG (eg, in the initializer of a global or in a constant expression). | ||||
20173 | /// For example, | ||||
20174 | /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } | ||||
20175 | bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, | ||||
20176 | const PartialDiagnostic &PD) { | ||||
20177 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | ||||
20178 | if (!FunctionScopes.empty()) | ||||
20179 | FunctionScopes.back()->PossiblyUnreachableDiags.push_back( | ||||
20180 | sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | ||||
20181 | return true; | ||||
20182 | } | ||||
20183 | |||||
20184 | // The initializer of a constexpr variable or of the first declaration of a | ||||
20185 | // static data member is not syntactically a constant evaluated constant, | ||||
20186 | // but nonetheless is always required to be a constant expression, so we | ||||
20187 | // can skip diagnosing. | ||||
20188 | // FIXME: Using the mangling context here is a hack. | ||||
20189 | if (auto *VD = dyn_cast_or_null<VarDecl>( | ||||
20190 | ExprEvalContexts.back().ManglingContextDecl)) { | ||||
20191 | if (VD->isConstexpr() || | ||||
20192 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | ||||
20193 | return false; | ||||
20194 | // FIXME: For any other kind of variable, we should build a CFG for its | ||||
20195 | // initializer and check whether the context in question is reachable. | ||||
20196 | } | ||||
20197 | |||||
20198 | Diag(Loc, PD); | ||||
20199 | return true; | ||||
20200 | } | ||||
20201 | |||||
20202 | /// Emit a diagnostic that describes an effect on the run-time behavior | ||||
20203 | /// of the program being compiled. | ||||
20204 | /// | ||||
20205 | /// This routine emits the given diagnostic when the code currently being | ||||
20206 | /// type-checked is "potentially evaluated", meaning that there is a | ||||
20207 | /// possibility that the code will actually be executable. Code in sizeof() | ||||
20208 | /// expressions, code used only during overload resolution, etc., are not | ||||
20209 | /// potentially evaluated. This routine will suppress such diagnostics or, | ||||
20210 | /// in the absolutely nutty case of potentially potentially evaluated | ||||
20211 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | ||||
20212 | /// later. | ||||
20213 | /// | ||||
20214 | /// This routine should be used for all diagnostics that describe the run-time | ||||
20215 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | ||||
20216 | /// Failure to do so will likely result in spurious diagnostics or failures | ||||
20217 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | ||||
20218 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | ||||
20219 | const PartialDiagnostic &PD) { | ||||
20220 | |||||
20221 | if (ExprEvalContexts.back().isDiscardedStatementContext()) | ||||
20222 | return false; | ||||
20223 | |||||
20224 | switch (ExprEvalContexts.back().Context) { | ||||
20225 | case ExpressionEvaluationContext::Unevaluated: | ||||
20226 | case ExpressionEvaluationContext::UnevaluatedList: | ||||
20227 | case ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
20228 | case ExpressionEvaluationContext::DiscardedStatement: | ||||
20229 | // The argument will never be evaluated, so don't complain. | ||||
20230 | break; | ||||
20231 | |||||
20232 | case ExpressionEvaluationContext::ConstantEvaluated: | ||||
20233 | case ExpressionEvaluationContext::ImmediateFunctionContext: | ||||
20234 | // Relevant diagnostics should be produced by constant evaluation. | ||||
20235 | break; | ||||
20236 | |||||
20237 | case ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
20238 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
20239 | return DiagIfReachable(Loc, Stmts, PD); | ||||
20240 | } | ||||
20241 | |||||
20242 | return false; | ||||
20243 | } | ||||
20244 | |||||
20245 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | ||||
20246 | const PartialDiagnostic &PD) { | ||||
20247 | return DiagRuntimeBehavior( | ||||
20248 | Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD); | ||||
20249 | } | ||||
20250 | |||||
20251 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | ||||
20252 | CallExpr *CE, FunctionDecl *FD) { | ||||
20253 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | ||||
20254 | return false; | ||||
20255 | |||||
20256 | // If we're inside a decltype's expression, don't check for a valid return | ||||
20257 | // type or construct temporaries until we know whether this is the last call. | ||||
20258 | if (ExprEvalContexts.back().ExprContext == | ||||
20259 | ExpressionEvaluationContextRecord::EK_Decltype) { | ||||
20260 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | ||||
20261 | return false; | ||||
20262 | } | ||||
20263 | |||||
20264 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | ||||
20265 | FunctionDecl *FD; | ||||
20266 | CallExpr *CE; | ||||
20267 | |||||
20268 | public: | ||||
20269 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | ||||
20270 | : FD(FD), CE(CE) { } | ||||
20271 | |||||
20272 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
20273 | if (!FD) { | ||||
20274 | S.Diag(Loc, diag::err_call_incomplete_return) | ||||
20275 | << T << CE->getSourceRange(); | ||||
20276 | return; | ||||
20277 | } | ||||
20278 | |||||
20279 | S.Diag(Loc, diag::err_call_function_incomplete_return) | ||||
20280 | << CE->getSourceRange() << FD << T; | ||||
20281 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | ||||
20282 | << FD->getDeclName(); | ||||
20283 | } | ||||
20284 | } Diagnoser(FD, CE); | ||||
20285 | |||||
20286 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | ||||
20287 | return true; | ||||
20288 | |||||
20289 | return false; | ||||
20290 | } | ||||
20291 | |||||
20292 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | ||||
20293 | // will prevent this condition from triggering, which is what we want. | ||||
20294 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | ||||
20295 | SourceLocation Loc; | ||||
20296 | |||||
20297 | unsigned diagnostic = diag::warn_condition_is_assignment; | ||||
20298 | bool IsOrAssign = false; | ||||
20299 | |||||
20300 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | ||||
20301 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | ||||
20302 | return; | ||||
20303 | |||||
20304 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | ||||
20305 | |||||
20306 | // Greylist some idioms by putting them into a warning subcategory. | ||||
20307 | if (ObjCMessageExpr *ME | ||||
20308 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | ||||
20309 | Selector Sel = ME->getSelector(); | ||||
20310 | |||||
20311 | // self = [<foo> init...] | ||||
20312 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | ||||
20313 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
20314 | |||||
20315 | // <foo> = [<bar> nextObject] | ||||
20316 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | ||||
20317 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
20318 | } | ||||
20319 | |||||
20320 | Loc = Op->getOperatorLoc(); | ||||
20321 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
20322 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | ||||
20323 | return; | ||||
20324 | |||||
20325 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | ||||
20326 | Loc = Op->getOperatorLoc(); | ||||
20327 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | ||||
20328 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | ||||
20329 | else { | ||||
20330 | // Not an assignment. | ||||
20331 | return; | ||||
20332 | } | ||||
20333 | |||||
20334 | Diag(Loc, diagnostic) << E->getSourceRange(); | ||||
20335 | |||||
20336 | SourceLocation Open = E->getBeginLoc(); | ||||
20337 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | ||||
20338 | Diag(Loc, diag::note_condition_assign_silence) | ||||
20339 | << FixItHint::CreateInsertion(Open, "(") | ||||
20340 | << FixItHint::CreateInsertion(Close, ")"); | ||||
20341 | |||||
20342 | if (IsOrAssign) | ||||
20343 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | ||||
20344 | << FixItHint::CreateReplacement(Loc, "!="); | ||||
20345 | else | ||||
20346 | Diag(Loc, diag::note_condition_assign_to_comparison) | ||||
20347 | << FixItHint::CreateReplacement(Loc, "=="); | ||||
20348 | } | ||||
20349 | |||||
20350 | /// Redundant parentheses over an equality comparison can indicate | ||||
20351 | /// that the user intended an assignment used as condition. | ||||
20352 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | ||||
20353 | // Don't warn if the parens came from a macro. | ||||
20354 | SourceLocation parenLoc = ParenE->getBeginLoc(); | ||||
20355 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | ||||
20356 | return; | ||||
20357 | // Don't warn for dependent expressions. | ||||
20358 | if (ParenE->isTypeDependent()) | ||||
20359 | return; | ||||
20360 | |||||
20361 | Expr *E = ParenE->IgnoreParens(); | ||||
20362 | |||||
20363 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | ||||
20364 | if (opE->getOpcode() == BO_EQ && | ||||
20365 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | ||||
20366 | == Expr::MLV_Valid) { | ||||
20367 | SourceLocation Loc = opE->getOperatorLoc(); | ||||
20368 | |||||
20369 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | ||||
20370 | SourceRange ParenERange = ParenE->getSourceRange(); | ||||
20371 | Diag(Loc, diag::note_equality_comparison_silence) | ||||
20372 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | ||||
20373 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | ||||
20374 | Diag(Loc, diag::note_equality_comparison_to_assign) | ||||
20375 | << FixItHint::CreateReplacement(Loc, "="); | ||||
20376 | } | ||||
20377 | } | ||||
20378 | |||||
20379 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | ||||
20380 | bool IsConstexpr) { | ||||
20381 | DiagnoseAssignmentAsCondition(E); | ||||
20382 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | ||||
20383 | DiagnoseEqualityWithExtraParens(parenE); | ||||
20384 | |||||
20385 | ExprResult result = CheckPlaceholderExpr(E); | ||||
20386 | if (result.isInvalid()) return ExprError(); | ||||
20387 | E = result.get(); | ||||
20388 | |||||
20389 | if (!E->isTypeDependent()) { | ||||
20390 | if (getLangOpts().CPlusPlus) | ||||
20391 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | ||||
20392 | |||||
20393 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | ||||
20394 | if (ERes.isInvalid()) | ||||
20395 | return ExprError(); | ||||
20396 | E = ERes.get(); | ||||
20397 | |||||
20398 | QualType T = E->getType(); | ||||
20399 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | ||||
20400 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | ||||
20401 | << T << E->getSourceRange(); | ||||
20402 | return ExprError(); | ||||
20403 | } | ||||
20404 | CheckBoolLikeConversion(E, Loc); | ||||
20405 | } | ||||
20406 | |||||
20407 | return E; | ||||
20408 | } | ||||
20409 | |||||
20410 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | ||||
20411 | Expr *SubExpr, ConditionKind CK, | ||||
20412 | bool MissingOK) { | ||||
20413 | // MissingOK indicates whether having no condition expression is valid | ||||
20414 | // (for loop) or invalid (e.g. while loop). | ||||
20415 | if (!SubExpr) | ||||
20416 | return MissingOK ? ConditionResult() : ConditionError(); | ||||
20417 | |||||
20418 | ExprResult Cond; | ||||
20419 | switch (CK) { | ||||
20420 | case ConditionKind::Boolean: | ||||
20421 | Cond = CheckBooleanCondition(Loc, SubExpr); | ||||
20422 | break; | ||||
20423 | |||||
20424 | case ConditionKind::ConstexprIf: | ||||
20425 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | ||||
20426 | break; | ||||
20427 | |||||
20428 | case ConditionKind::Switch: | ||||
20429 | Cond = CheckSwitchCondition(Loc, SubExpr); | ||||
20430 | break; | ||||
20431 | } | ||||
20432 | if (Cond.isInvalid()) { | ||||
20433 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | ||||
20434 | {SubExpr}, PreferredConditionType(CK)); | ||||
20435 | if (!Cond.get()) | ||||
20436 | return ConditionError(); | ||||
20437 | } | ||||
20438 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | ||||
20439 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | ||||
20440 | if (!FullExpr.get()) | ||||
20441 | return ConditionError(); | ||||
20442 | |||||
20443 | return ConditionResult(*this, nullptr, FullExpr, | ||||
20444 | CK == ConditionKind::ConstexprIf); | ||||
20445 | } | ||||
20446 | |||||
20447 | namespace { | ||||
20448 | /// A visitor for rebuilding a call to an __unknown_any expression | ||||
20449 | /// to have an appropriate type. | ||||
20450 | struct RebuildUnknownAnyFunction | ||||
20451 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | ||||
20452 | |||||
20453 | Sema &S; | ||||
20454 | |||||
20455 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | ||||
20456 | |||||
20457 | ExprResult VisitStmt(Stmt *S) { | ||||
20458 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp" , 20458); | ||||
20459 | } | ||||
20460 | |||||
20461 | ExprResult VisitExpr(Expr *E) { | ||||
20462 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | ||||
20463 | << E->getSourceRange(); | ||||
20464 | return ExprError(); | ||||
20465 | } | ||||
20466 | |||||
20467 | /// Rebuild an expression which simply semantically wraps another | ||||
20468 | /// expression which it shares the type and value kind of. | ||||
20469 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
20470 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20471 | if (SubResult.isInvalid()) return ExprError(); | ||||
20472 | |||||
20473 | Expr *SubExpr = SubResult.get(); | ||||
20474 | E->setSubExpr(SubExpr); | ||||
20475 | E->setType(SubExpr->getType()); | ||||
20476 | E->setValueKind(SubExpr->getValueKind()); | ||||
20477 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20477, __extension__ __PRETTY_FUNCTION__ )); | ||||
20478 | return E; | ||||
20479 | } | ||||
20480 | |||||
20481 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
20482 | return rebuildSugarExpr(E); | ||||
20483 | } | ||||
20484 | |||||
20485 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
20486 | return rebuildSugarExpr(E); | ||||
20487 | } | ||||
20488 | |||||
20489 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
20490 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20491 | if (SubResult.isInvalid()) return ExprError(); | ||||
20492 | |||||
20493 | Expr *SubExpr = SubResult.get(); | ||||
20494 | E->setSubExpr(SubExpr); | ||||
20495 | E->setType(S.Context.getPointerType(SubExpr->getType())); | ||||
20496 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20496, __extension__ __PRETTY_FUNCTION__)); | ||||
20497 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20497, __extension__ __PRETTY_FUNCTION__ )); | ||||
20498 | return E; | ||||
20499 | } | ||||
20500 | |||||
20501 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | ||||
20502 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | ||||
20503 | |||||
20504 | E->setType(VD->getType()); | ||||
20505 | |||||
20506 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20506, __extension__ __PRETTY_FUNCTION__)); | ||||
20507 | if (S.getLangOpts().CPlusPlus && | ||||
20508 | !(isa<CXXMethodDecl>(VD) && | ||||
20509 | cast<CXXMethodDecl>(VD)->isInstance())) | ||||
20510 | E->setValueKind(VK_LValue); | ||||
20511 | |||||
20512 | return E; | ||||
20513 | } | ||||
20514 | |||||
20515 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
20516 | return resolveDecl(E, E->getMemberDecl()); | ||||
20517 | } | ||||
20518 | |||||
20519 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
20520 | return resolveDecl(E, E->getDecl()); | ||||
20521 | } | ||||
20522 | }; | ||||
20523 | } | ||||
20524 | |||||
20525 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
20526 | /// to have a function type. | ||||
20527 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | ||||
20528 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | ||||
20529 | if (Result.isInvalid()) return ExprError(); | ||||
20530 | return S.DefaultFunctionArrayConversion(Result.get()); | ||||
20531 | } | ||||
20532 | |||||
20533 | namespace { | ||||
20534 | /// A visitor for rebuilding an expression of type __unknown_anytype | ||||
20535 | /// into one which resolves the type directly on the referring | ||||
20536 | /// expression. Strict preservation of the original source | ||||
20537 | /// structure is not a goal. | ||||
20538 | struct RebuildUnknownAnyExpr | ||||
20539 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | ||||
20540 | |||||
20541 | Sema &S; | ||||
20542 | |||||
20543 | /// The current destination type. | ||||
20544 | QualType DestType; | ||||
20545 | |||||
20546 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | ||||
20547 | : S(S), DestType(CastType) {} | ||||
20548 | |||||
20549 | ExprResult VisitStmt(Stmt *S) { | ||||
20550 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp" , 20550); | ||||
20551 | } | ||||
20552 | |||||
20553 | ExprResult VisitExpr(Expr *E) { | ||||
20554 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
20555 | << E->getSourceRange(); | ||||
20556 | return ExprError(); | ||||
20557 | } | ||||
20558 | |||||
20559 | ExprResult VisitCallExpr(CallExpr *E); | ||||
20560 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | ||||
20561 | |||||
20562 | /// Rebuild an expression which simply semantically wraps another | ||||
20563 | /// expression which it shares the type and value kind of. | ||||
20564 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
20565 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20566 | if (SubResult.isInvalid()) return ExprError(); | ||||
20567 | Expr *SubExpr = SubResult.get(); | ||||
20568 | E->setSubExpr(SubExpr); | ||||
20569 | E->setType(SubExpr->getType()); | ||||
20570 | E->setValueKind(SubExpr->getValueKind()); | ||||
20571 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20571, __extension__ __PRETTY_FUNCTION__ )); | ||||
20572 | return E; | ||||
20573 | } | ||||
20574 | |||||
20575 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
20576 | return rebuildSugarExpr(E); | ||||
20577 | } | ||||
20578 | |||||
20579 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
20580 | return rebuildSugarExpr(E); | ||||
20581 | } | ||||
20582 | |||||
20583 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
20584 | const PointerType *Ptr = DestType->getAs<PointerType>(); | ||||
20585 | if (!Ptr) { | ||||
20586 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | ||||
20587 | << E->getSourceRange(); | ||||
20588 | return ExprError(); | ||||
20589 | } | ||||
20590 | |||||
20591 | if (isa<CallExpr>(E->getSubExpr())) { | ||||
20592 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | ||||
20593 | << E->getSourceRange(); | ||||
20594 | return ExprError(); | ||||
20595 | } | ||||
20596 | |||||
20597 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20597, __extension__ __PRETTY_FUNCTION__)); | ||||
20598 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20598, __extension__ __PRETTY_FUNCTION__ )); | ||||
20599 | E->setType(DestType); | ||||
20600 | |||||
20601 | // Build the sub-expression as if it were an object of the pointee type. | ||||
20602 | DestType = Ptr->getPointeeType(); | ||||
20603 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20604 | if (SubResult.isInvalid()) return ExprError(); | ||||
20605 | E->setSubExpr(SubResult.get()); | ||||
20606 | return E; | ||||
20607 | } | ||||
20608 | |||||
20609 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | ||||
20610 | |||||
20611 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | ||||
20612 | |||||
20613 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
20614 | return resolveDecl(E, E->getMemberDecl()); | ||||
20615 | } | ||||
20616 | |||||
20617 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
20618 | return resolveDecl(E, E->getDecl()); | ||||
20619 | } | ||||
20620 | }; | ||||
20621 | } | ||||
20622 | |||||
20623 | /// Rebuilds a call expression which yielded __unknown_anytype. | ||||
20624 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | ||||
20625 | Expr *CalleeExpr = E->getCallee(); | ||||
20626 | |||||
20627 | enum FnKind { | ||||
20628 | FK_MemberFunction, | ||||
20629 | FK_FunctionPointer, | ||||
20630 | FK_BlockPointer | ||||
20631 | }; | ||||
20632 | |||||
20633 | FnKind Kind; | ||||
20634 | QualType CalleeType = CalleeExpr->getType(); | ||||
20635 | if (CalleeType == S.Context.BoundMemberTy) { | ||||
20636 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast <bool> (isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)) ? void (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "clang/lib/Sema/SemaExpr.cpp", 20636, __extension__ __PRETTY_FUNCTION__ )); | ||||
20637 | Kind = FK_MemberFunction; | ||||
20638 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | ||||
20639 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | ||||
20640 | CalleeType = Ptr->getPointeeType(); | ||||
20641 | Kind = FK_FunctionPointer; | ||||
20642 | } else { | ||||
20643 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | ||||
20644 | Kind = FK_BlockPointer; | ||||
20645 | } | ||||
20646 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | ||||
20647 | |||||
20648 | // Verify that this is a legal result type of a function. | ||||
20649 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
20650 | unsigned diagID = diag::err_func_returning_array_function; | ||||
20651 | if (Kind == FK_BlockPointer) | ||||
20652 | diagID = diag::err_block_returning_array_function; | ||||
20653 | |||||
20654 | S.Diag(E->getExprLoc(), diagID) | ||||
20655 | << DestType->isFunctionType() << DestType; | ||||
20656 | return ExprError(); | ||||
20657 | } | ||||
20658 | |||||
20659 | // Otherwise, go ahead and set DestType as the call's result. | ||||
20660 | E->setType(DestType.getNonLValueExprType(S.Context)); | ||||
20661 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
20662 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20662, __extension__ __PRETTY_FUNCTION__ )); | ||||
20663 | |||||
20664 | // Rebuild the function type, replacing the result type with DestType. | ||||
20665 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | ||||
20666 | if (Proto) { | ||||
20667 | // __unknown_anytype(...) is a special case used by the debugger when | ||||
20668 | // it has no idea what a function's signature is. | ||||
20669 | // | ||||
20670 | // We want to build this call essentially under the K&R | ||||
20671 | // unprototyped rules, but making a FunctionNoProtoType in C++ | ||||
20672 | // would foul up all sorts of assumptions. However, we cannot | ||||
20673 | // simply pass all arguments as variadic arguments, nor can we | ||||
20674 | // portably just call the function under a non-variadic type; see | ||||
20675 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | ||||
20676 | // However, it turns out that in practice it is generally safe to | ||||
20677 | // call a function declared as "A foo(B,C,D);" under the prototype | ||||
20678 | // "A foo(B,C,D,...);". The only known exception is with the | ||||
20679 | // Windows ABI, where any variadic function is implicitly cdecl | ||||
20680 | // regardless of its normal CC. Therefore we change the parameter | ||||
20681 | // types to match the types of the arguments. | ||||
20682 | // | ||||
20683 | // This is a hack, but it is far superior to moving the | ||||
20684 | // corresponding target-specific code from IR-gen to Sema/AST. | ||||
20685 | |||||
20686 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | ||||
20687 | SmallVector<QualType, 8> ArgTypes; | ||||
20688 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | ||||
20689 | ArgTypes.reserve(E->getNumArgs()); | ||||
20690 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | ||||
20691 | ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); | ||||
20692 | } | ||||
20693 | ParamTypes = ArgTypes; | ||||
20694 | } | ||||
20695 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | ||||
20696 | Proto->getExtProtoInfo()); | ||||
20697 | } else { | ||||
20698 | DestType = S.Context.getFunctionNoProtoType(DestType, | ||||
20699 | FnType->getExtInfo()); | ||||
20700 | } | ||||
20701 | |||||
20702 | // Rebuild the appropriate pointer-to-function type. | ||||
20703 | switch (Kind) { | ||||
20704 | case FK_MemberFunction: | ||||
20705 | // Nothing to do. | ||||
20706 | break; | ||||
20707 | |||||
20708 | case FK_FunctionPointer: | ||||
20709 | DestType = S.Context.getPointerType(DestType); | ||||
20710 | break; | ||||
20711 | |||||
20712 | case FK_BlockPointer: | ||||
20713 | DestType = S.Context.getBlockPointerType(DestType); | ||||
20714 | break; | ||||
20715 | } | ||||
20716 | |||||
20717 | // Finally, we can recurse. | ||||
20718 | ExprResult CalleeResult = Visit(CalleeExpr); | ||||
20719 | if (!CalleeResult.isUsable()) return ExprError(); | ||||
20720 | E->setCallee(CalleeResult.get()); | ||||
20721 | |||||
20722 | // Bind a temporary if necessary. | ||||
20723 | return S.MaybeBindToTemporary(E); | ||||
20724 | } | ||||
20725 | |||||
20726 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | ||||
20727 | // Verify that this is a legal result type of a call. | ||||
20728 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
20729 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | ||||
20730 | << DestType->isFunctionType() << DestType; | ||||
20731 | return ExprError(); | ||||
20732 | } | ||||
20733 | |||||
20734 | // Rewrite the method result type if available. | ||||
20735 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | ||||
20736 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context .UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "clang/lib/Sema/SemaExpr.cpp", 20736, __extension__ __PRETTY_FUNCTION__ )); | ||||
20737 | Method->setReturnType(DestType); | ||||
20738 | } | ||||
20739 | |||||
20740 | // Change the type of the message. | ||||
20741 | E->setType(DestType.getNonReferenceType()); | ||||
20742 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
20743 | |||||
20744 | return S.MaybeBindToTemporary(E); | ||||
20745 | } | ||||
20746 | |||||
20747 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
20748 | // The only case we should ever see here is a function-to-pointer decay. | ||||
20749 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | ||||
20750 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20750, __extension__ __PRETTY_FUNCTION__)); | ||||
20751 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20751, __extension__ __PRETTY_FUNCTION__ )); | ||||
20752 | |||||
20753 | E->setType(DestType); | ||||
20754 | |||||
20755 | // Rebuild the sub-expression as the pointee (function) type. | ||||
20756 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | ||||
20757 | |||||
20758 | ExprResult Result = Visit(E->getSubExpr()); | ||||
20759 | if (!Result.isUsable()) return ExprError(); | ||||
20760 | |||||
20761 | E->setSubExpr(Result.get()); | ||||
20762 | return E; | ||||
20763 | } else if (E->getCastKind() == CK_LValueToRValue) { | ||||
20764 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20764, __extension__ __PRETTY_FUNCTION__)); | ||||
20765 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20765, __extension__ __PRETTY_FUNCTION__ )); | ||||
20766 | |||||
20767 | assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E-> getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "clang/lib/Sema/SemaExpr.cpp", 20767, __extension__ __PRETTY_FUNCTION__ )); | ||||
20768 | |||||
20769 | E->setType(DestType); | ||||
20770 | |||||
20771 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | ||||
20772 | DestType = S.Context.getLValueReferenceType(DestType); | ||||
20773 | |||||
20774 | ExprResult Result = Visit(E->getSubExpr()); | ||||
20775 | if (!Result.isUsable()) return ExprError(); | ||||
20776 | |||||
20777 | E->setSubExpr(Result.get()); | ||||
20778 | return E; | ||||
20779 | } else { | ||||
20780 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp" , 20780); | ||||
20781 | } | ||||
20782 | } | ||||
20783 | |||||
20784 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | ||||
20785 | ExprValueKind ValueKind = VK_LValue; | ||||
20786 | QualType Type = DestType; | ||||
20787 | |||||
20788 | // We know how to make this work for certain kinds of decls: | ||||
20789 | |||||
20790 | // - functions | ||||
20791 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | ||||
20792 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | ||||
20793 | DestType = Ptr->getPointeeType(); | ||||
20794 | ExprResult Result = resolveDecl(E, VD); | ||||
20795 | if (Result.isInvalid()) return ExprError(); | ||||
20796 | return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, | ||||
20797 | VK_PRValue); | ||||
20798 | } | ||||
20799 | |||||
20800 | if (!Type->isFunctionType()) { | ||||
20801 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | ||||
20802 | << VD << E->getSourceRange(); | ||||
20803 | return ExprError(); | ||||
20804 | } | ||||
20805 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | ||||
20806 | // We must match the FunctionDecl's type to the hack introduced in | ||||
20807 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | ||||
20808 | // type. See the lengthy commentary in that routine. | ||||
20809 | QualType FDT = FD->getType(); | ||||
20810 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | ||||
20811 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | ||||
20812 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
20813 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | ||||
20814 | SourceLocation Loc = FD->getLocation(); | ||||
20815 | FunctionDecl *NewFD = FunctionDecl::Create( | ||||
20816 | S.Context, FD->getDeclContext(), Loc, Loc, | ||||
20817 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | ||||
20818 | SC_None, S.getCurFPFeatures().isFPConstrained(), | ||||
20819 | false /*isInlineSpecified*/, FD->hasPrototype(), | ||||
20820 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | ||||
20821 | |||||
20822 | if (FD->getQualifier()) | ||||
20823 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | ||||
20824 | |||||
20825 | SmallVector<ParmVarDecl*, 16> Params; | ||||
20826 | for (const auto &AI : FT->param_types()) { | ||||
20827 | ParmVarDecl *Param = | ||||
20828 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | ||||
20829 | Param->setScopeInfo(0, Params.size()); | ||||
20830 | Params.push_back(Param); | ||||
20831 | } | ||||
20832 | NewFD->setParams(Params); | ||||
20833 | DRE->setDecl(NewFD); | ||||
20834 | VD = DRE->getDecl(); | ||||
20835 | } | ||||
20836 | } | ||||
20837 | |||||
20838 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | ||||
20839 | if (MD->isInstance()) { | ||||
20840 | ValueKind = VK_PRValue; | ||||
20841 | Type = S.Context.BoundMemberTy; | ||||
20842 | } | ||||
20843 | |||||
20844 | // Function references aren't l-values in C. | ||||
20845 | if (!S.getLangOpts().CPlusPlus) | ||||
20846 | ValueKind = VK_PRValue; | ||||
20847 | |||||
20848 | // - variables | ||||
20849 | } else if (isa<VarDecl>(VD)) { | ||||
20850 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | ||||
20851 | Type = RefTy->getPointeeType(); | ||||
20852 | } else if (Type->isFunctionType()) { | ||||
20853 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | ||||
20854 | << VD << E->getSourceRange(); | ||||
20855 | return ExprError(); | ||||
20856 | } | ||||
20857 | |||||
20858 | // - nothing else | ||||
20859 | } else { | ||||
20860 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | ||||
20861 | << VD << E->getSourceRange(); | ||||
20862 | return ExprError(); | ||||
20863 | } | ||||
20864 | |||||
20865 | // Modifying the declaration like this is friendly to IR-gen but | ||||
20866 | // also really dangerous. | ||||
20867 | VD->setType(DestType); | ||||
20868 | E->setType(Type); | ||||
20869 | E->setValueKind(ValueKind); | ||||
20870 | return E; | ||||
20871 | } | ||||
20872 | |||||
20873 | /// Check a cast of an unknown-any type. We intentionally only | ||||
20874 | /// trigger this for C-style casts. | ||||
20875 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | ||||
20876 | Expr *CastExpr, CastKind &CastKind, | ||||
20877 | ExprValueKind &VK, CXXCastPath &Path) { | ||||
20878 | // The type we're casting to must be either void or complete. | ||||
20879 | if (!CastType->isVoidType() && | ||||
20880 | RequireCompleteType(TypeRange.getBegin(), CastType, | ||||
20881 | diag::err_typecheck_cast_to_incomplete)) | ||||
20882 | return ExprError(); | ||||
20883 | |||||
20884 | // Rewrite the casted expression from scratch. | ||||
20885 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | ||||
20886 | if (!result.isUsable()) return ExprError(); | ||||
20887 | |||||
20888 | CastExpr = result.get(); | ||||
20889 | VK = CastExpr->getValueKind(); | ||||
20890 | CastKind = CK_NoOp; | ||||
20891 | |||||
20892 | return CastExpr; | ||||
20893 | } | ||||
20894 | |||||
20895 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | ||||
20896 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | ||||
20897 | } | ||||
20898 | |||||
20899 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | ||||
20900 | Expr *arg, QualType ¶mType) { | ||||
20901 | // If the syntactic form of the argument is not an explicit cast of | ||||
20902 | // any sort, just do default argument promotion. | ||||
20903 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | ||||
20904 | if (!castArg) { | ||||
20905 | ExprResult result = DefaultArgumentPromotion(arg); | ||||
20906 | if (result.isInvalid()) return ExprError(); | ||||
20907 | paramType = result.get()->getType(); | ||||
20908 | return result; | ||||
20909 | } | ||||
20910 | |||||
20911 | // Otherwise, use the type that was written in the explicit cast. | ||||
20912 | assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void (0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp" , 20912, __extension__ __PRETTY_FUNCTION__)); | ||||
20913 | paramType = castArg->getTypeAsWritten(); | ||||
20914 | |||||
20915 | // Copy-initialize a parameter of that type. | ||||
20916 | InitializedEntity entity = | ||||
20917 | InitializedEntity::InitializeParameter(Context, paramType, | ||||
20918 | /*consumed*/ false); | ||||
20919 | return PerformCopyInitialization(entity, callLoc, arg); | ||||
20920 | } | ||||
20921 | |||||
20922 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | ||||
20923 | Expr *orig = E; | ||||
20924 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | ||||
20925 | while (true) { | ||||
20926 | E = E->IgnoreParenImpCasts(); | ||||
20927 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | ||||
20928 | E = call->getCallee(); | ||||
20929 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
20930 | } else { | ||||
20931 | break; | ||||
20932 | } | ||||
20933 | } | ||||
20934 | |||||
20935 | SourceLocation loc; | ||||
20936 | NamedDecl *d; | ||||
20937 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | ||||
20938 | loc = ref->getLocation(); | ||||
20939 | d = ref->getDecl(); | ||||
20940 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | ||||
20941 | loc = mem->getMemberLoc(); | ||||
20942 | d = mem->getMemberDecl(); | ||||
20943 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | ||||
20944 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
20945 | loc = msg->getSelectorStartLoc(); | ||||
20946 | d = msg->getMethodDecl(); | ||||
20947 | if (!d) { | ||||
20948 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | ||||
20949 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | ||||
20950 | << orig->getSourceRange(); | ||||
20951 | return ExprError(); | ||||
20952 | } | ||||
20953 | } else { | ||||
20954 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
20955 | << E->getSourceRange(); | ||||
20956 | return ExprError(); | ||||
20957 | } | ||||
20958 | |||||
20959 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | ||||
20960 | |||||
20961 | // Never recoverable. | ||||
20962 | return ExprError(); | ||||
20963 | } | ||||
20964 | |||||
20965 | /// Check for operands with placeholder types and complain if found. | ||||
20966 | /// Returns ExprError() if there was an error and no recovery was possible. | ||||
20967 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | ||||
20968 | if (!Context.isDependenceAllowed()) { | ||||
20969 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
20970 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
20971 | // been dealt with before checking the operands. | ||||
20972 | ExprResult Result = CorrectDelayedTyposInExpr(E); | ||||
20973 | if (!Result.isUsable()) return ExprError(); | ||||
20974 | E = Result.get(); | ||||
20975 | } | ||||
20976 | |||||
20977 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | ||||
20978 | if (!placeholderType) return E; | ||||
20979 | |||||
20980 | switch (placeholderType->getKind()) { | ||||
20981 | |||||
20982 | // Overloaded expressions. | ||||
20983 | case BuiltinType::Overload: { | ||||
20984 | // Try to resolve a single function template specialization. | ||||
20985 | // This is obligatory. | ||||
20986 | ExprResult Result = E; | ||||
20987 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | ||||
20988 | return Result; | ||||
20989 | |||||
20990 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||
20991 | // leaves Result unchanged on failure. | ||||
20992 | Result = E; | ||||
20993 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | ||||
20994 | return Result; | ||||
20995 | |||||
20996 | // If that failed, try to recover with a call. | ||||
20997 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | ||||
20998 | /*complain*/ true); | ||||
20999 | return Result; | ||||
21000 | } | ||||
21001 | |||||
21002 | // Bound member functions. | ||||
21003 | case BuiltinType::BoundMember: { | ||||
21004 | ExprResult result = E; | ||||
21005 | const Expr *BME = E->IgnoreParens(); | ||||
21006 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | ||||
21007 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | ||||
21008 | if (isa<CXXPseudoDestructorExpr>(BME)) { | ||||
21009 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | ||||
21010 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | ||||
21011 | if (ME->getMemberNameInfo().getName().getNameKind() == | ||||
21012 | DeclarationName::CXXDestructorName) | ||||
21013 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | ||||
21014 | } | ||||
21015 | tryToRecoverWithCall(result, PD, | ||||
21016 | /*complain*/ true); | ||||
21017 | return result; | ||||
21018 | } | ||||
21019 | |||||
21020 | // ARC unbridged casts. | ||||
21021 | case BuiltinType::ARCUnbridgedCast: { | ||||
21022 | Expr *realCast = stripARCUnbridgedCast(E); | ||||
21023 | diagnoseARCUnbridgedCast(realCast); | ||||
21024 | return realCast; | ||||
21025 | } | ||||
21026 | |||||
21027 | // Expressions of unknown type. | ||||
21028 | case BuiltinType::UnknownAny: | ||||
21029 | return diagnoseUnknownAnyExpr(*this, E); | ||||
21030 | |||||
21031 | // Pseudo-objects. | ||||
21032 | case BuiltinType::PseudoObject: | ||||
21033 | return checkPseudoObjectRValue(E); | ||||
21034 | |||||
21035 | case BuiltinType::BuiltinFn: { | ||||
21036 | // Accept __noop without parens by implicitly converting it to a call expr. | ||||
21037 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | ||||
21038 | if (DRE) { | ||||
21039 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | ||||
21040 | unsigned BuiltinID = FD->getBuiltinID(); | ||||
21041 | if (BuiltinID == Builtin::BI__noop) { | ||||
21042 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | ||||
21043 | CK_BuiltinFnToFnPtr) | ||||
21044 | .get(); | ||||
21045 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | ||||
21046 | VK_PRValue, SourceLocation(), | ||||
21047 | FPOptionsOverride()); | ||||
21048 | } | ||||
21049 | |||||
21050 | if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { | ||||
21051 | // Any use of these other than a direct call is ill-formed as of C++20, | ||||
21052 | // because they are not addressable functions. In earlier language | ||||
21053 | // modes, warn and force an instantiation of the real body. | ||||
21054 | Diag(E->getBeginLoc(), | ||||
21055 | getLangOpts().CPlusPlus20 | ||||
21056 | ? diag::err_use_of_unaddressable_function | ||||
21057 | : diag::warn_cxx20_compat_use_of_unaddressable_function); | ||||
21058 | if (FD->isImplicitlyInstantiable()) { | ||||
21059 | // Require a definition here because a normal attempt at | ||||
21060 | // instantiation for a builtin will be ignored, and we won't try | ||||
21061 | // again later. We assume that the definition of the template | ||||
21062 | // precedes this use. | ||||
21063 | InstantiateFunctionDefinition(E->getBeginLoc(), FD, | ||||
21064 | /*Recursive=*/false, | ||||
21065 | /*DefinitionRequired=*/true, | ||||
21066 | /*AtEndOfTU=*/false); | ||||
21067 | } | ||||
21068 | // Produce a properly-typed reference to the function. | ||||
21069 | CXXScopeSpec SS; | ||||
21070 | SS.Adopt(DRE->getQualifierLoc()); | ||||
21071 | TemplateArgumentListInfo TemplateArgs; | ||||
21072 | DRE->copyTemplateArgumentsInto(TemplateArgs); | ||||
21073 | return BuildDeclRefExpr( | ||||
21074 | FD, FD->getType(), VK_LValue, DRE->getNameInfo(), | ||||
21075 | DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), | ||||
21076 | DRE->getTemplateKeywordLoc(), | ||||
21077 | DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); | ||||
21078 | } | ||||
21079 | } | ||||
21080 | |||||
21081 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | ||||
21082 | return ExprError(); | ||||
21083 | } | ||||
21084 | |||||
21085 | case BuiltinType::IncompleteMatrixIdx: | ||||
21086 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | ||||
21087 | ->getRowIdx() | ||||
21088 | ->getBeginLoc(), | ||||
21089 | diag::err_matrix_incomplete_index); | ||||
21090 | return ExprError(); | ||||
21091 | |||||
21092 | // Expressions of unknown type. | ||||
21093 | case BuiltinType::OMPArraySection: | ||||
21094 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | ||||
21095 | return ExprError(); | ||||
21096 | |||||
21097 | // Expressions of unknown type. | ||||
21098 | case BuiltinType::OMPArrayShaping: | ||||
21099 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | ||||
21100 | |||||
21101 | case BuiltinType::OMPIterator: | ||||
21102 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | ||||
21103 | |||||
21104 | // Everything else should be impossible. | ||||
21105 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
21106 | case BuiltinType::Id: | ||||
21107 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
21108 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
21109 | case BuiltinType::Id: | ||||
21110 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
21111 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
21112 | case BuiltinType::Id: | ||||
21113 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
21114 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
21115 | case BuiltinType::Id: | ||||
21116 | #include "clang/Basic/PPCTypes.def" | ||||
21117 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
21118 | #include "clang/Basic/RISCVVTypes.def" | ||||
21119 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
21120 | #include "clang/Basic/WebAssemblyReferenceTypes.def" | ||||
21121 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | ||||
21122 | #define PLACEHOLDER_TYPE(Id, SingletonId) | ||||
21123 | #include "clang/AST/BuiltinTypes.def" | ||||
21124 | break; | ||||
21125 | } | ||||
21126 | |||||
21127 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "clang/lib/Sema/SemaExpr.cpp", 21127); | ||||
21128 | } | ||||
21129 | |||||
21130 | bool Sema::CheckCaseExpression(Expr *E) { | ||||
21131 | if (E->isTypeDependent()) | ||||
21132 | return true; | ||||
21133 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | ||||
21134 | return E->getType()->isIntegralOrEnumerationType(); | ||||
21135 | return false; | ||||
21136 | } | ||||
21137 | |||||
21138 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | ||||
21139 | ExprResult | ||||
21140 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | ||||
21141 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "clang/lib/Sema/SemaExpr.cpp", 21142, __extension__ __PRETTY_FUNCTION__ )) | ||||
21142 | "Unknown Objective-C Boolean value!")(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "clang/lib/Sema/SemaExpr.cpp", 21142, __extension__ __PRETTY_FUNCTION__ )); | ||||
21143 | QualType BoolT = Context.ObjCBuiltinBoolTy; | ||||
21144 | if (!Context.getBOOLDecl()) { | ||||
21145 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | ||||
21146 | Sema::LookupOrdinaryName); | ||||
21147 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | ||||
21148 | NamedDecl *ND = Result.getFoundDecl(); | ||||
21149 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | ||||
21150 | Context.setBOOLDecl(TD); | ||||
21151 | } | ||||
21152 | } | ||||
21153 | if (Context.getBOOLDecl()) | ||||
21154 | BoolT = Context.getBOOLType(); | ||||
21155 | return new (Context) | ||||
21156 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | ||||
21157 | } | ||||
21158 | |||||
21159 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | ||||
21160 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | ||||
21161 | SourceLocation RParen) { | ||||
21162 | auto FindSpecVersion = | ||||
21163 | [&](StringRef Platform) -> std::optional<VersionTuple> { | ||||
21164 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
21165 | return Spec.getPlatform() == Platform; | ||||
21166 | }); | ||||
21167 | // Transcribe the "ios" availability check to "maccatalyst" when compiling | ||||
21168 | // for "maccatalyst" if "maccatalyst" is not specified. | ||||
21169 | if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { | ||||
21170 | Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
21171 | return Spec.getPlatform() == "ios"; | ||||
21172 | }); | ||||
21173 | } | ||||
21174 | if (Spec == AvailSpecs.end()) | ||||
21175 | return std::nullopt; | ||||
21176 | return Spec->getVersion(); | ||||
21177 | }; | ||||
21178 | |||||
21179 | VersionTuple Version; | ||||
21180 | if (auto MaybeVersion = | ||||
21181 | FindSpecVersion(Context.getTargetInfo().getPlatformName())) | ||||
21182 | Version = *MaybeVersion; | ||||
21183 | |||||
21184 | // The use of `@available` in the enclosing context should be analyzed to | ||||
21185 | // warn when it's used inappropriately (i.e. not if(@available)). | ||||
21186 | if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) | ||||
21187 | Context->HasPotentialAvailabilityViolations = true; | ||||
21188 | |||||
21189 | return new (Context) | ||||
21190 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | ||||
21191 | } | ||||
21192 | |||||
21193 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | ||||
21194 | ArrayRef<Expr *> SubExprs, QualType T) { | ||||
21195 | if (!Context.getLangOpts().RecoveryAST) | ||||
21196 | return ExprError(); | ||||
21197 | |||||
21198 | if (isSFINAEContext()) | ||||
21199 | return ExprError(); | ||||
21200 | |||||
21201 | if (T.isNull() || T->isUndeducedType() || | ||||
21202 | !Context.getLangOpts().RecoveryASTType) | ||||
21203 | // We don't know the concrete type, fallback to dependent type. | ||||
21204 | T = Context.DependentTy; | ||||
21205 | |||||
21206 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | ||||
21207 | } |
1 | //===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), |
10 | // cast_if_present<X>(), and dyn_cast_if_present<X>() templates. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_SUPPORT_CASTING_H |
15 | #define LLVM_SUPPORT_CASTING_H |
16 | |
17 | #include "llvm/Support/Compiler.h" |
18 | #include "llvm/Support/type_traits.h" |
19 | #include <cassert> |
20 | #include <memory> |
21 | #include <optional> |
22 | #include <type_traits> |
23 | |
24 | namespace llvm { |
25 | |
26 | //===----------------------------------------------------------------------===// |
27 | // simplify_type |
28 | //===----------------------------------------------------------------------===// |
29 | |
30 | /// Define a template that can be specialized by smart pointers to reflect the |
31 | /// fact that they are automatically dereferenced, and are not involved with the |
32 | /// template selection process... the default implementation is a noop. |
33 | // TODO: rename this and/or replace it with other cast traits. |
34 | template <typename From> struct simplify_type { |
35 | using SimpleType = From; // The real type this represents... |
36 | |
37 | // An accessor to get the real value... |
38 | static SimpleType &getSimplifiedValue(From &Val) { return Val; } |
39 | }; |
40 | |
41 | template <typename From> struct simplify_type<const From> { |
42 | using NonConstSimpleType = typename simplify_type<From>::SimpleType; |
43 | using SimpleType = typename add_const_past_pointer<NonConstSimpleType>::type; |
44 | using RetType = |
45 | typename add_lvalue_reference_if_not_pointer<SimpleType>::type; |
46 | |
47 | static RetType getSimplifiedValue(const From &Val) { |
48 | return simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val)); |
49 | } |
50 | }; |
51 | |
52 | // TODO: add this namespace once everyone is switched to using the new |
53 | // interface. |
54 | // namespace detail { |
55 | |
56 | //===----------------------------------------------------------------------===// |
57 | // isa_impl |
58 | //===----------------------------------------------------------------------===// |
59 | |
60 | // The core of the implementation of isa<X> is here; To and From should be |
61 | // the names of classes. This template can be specialized to customize the |
62 | // implementation of isa<> without rewriting it from scratch. |
63 | template <typename To, typename From, typename Enabler = void> struct isa_impl { |
64 | static inline bool doit(const From &Val) { return To::classof(&Val); } |
65 | }; |
66 | |
67 | // Always allow upcasts, and perform no dynamic check for them. |
68 | template <typename To, typename From> |
69 | struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> { |
70 | static inline bool doit(const From &) { return true; } |
71 | }; |
72 | |
73 | template <typename To, typename From> struct isa_impl_cl { |
74 | static inline bool doit(const From &Val) { |
75 | return isa_impl<To, From>::doit(Val); |
76 | } |
77 | }; |
78 | |
79 | template <typename To, typename From> struct isa_impl_cl<To, const From> { |
80 | static inline bool doit(const From &Val) { |
81 | return isa_impl<To, From>::doit(Val); |
82 | } |
83 | }; |
84 | |
85 | template <typename To, typename From> |
86 | struct isa_impl_cl<To, const std::unique_ptr<From>> { |
87 | static inline bool doit(const std::unique_ptr<From> &Val) { |
88 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 88, __extension__ __PRETTY_FUNCTION__ )); |
89 | return isa_impl_cl<To, From>::doit(*Val); |
90 | } |
91 | }; |
92 | |
93 | template <typename To, typename From> struct isa_impl_cl<To, From *> { |
94 | static inline bool doit(const From *Val) { |
95 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 95, __extension__ __PRETTY_FUNCTION__ )); |
96 | return isa_impl<To, From>::doit(*Val); |
97 | } |
98 | }; |
99 | |
100 | template <typename To, typename From> struct isa_impl_cl<To, From *const> { |
101 | static inline bool doit(const From *Val) { |
102 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 102, __extension__ __PRETTY_FUNCTION__ )); |
103 | return isa_impl<To, From>::doit(*Val); |
104 | } |
105 | }; |
106 | |
107 | template <typename To, typename From> struct isa_impl_cl<To, const From *> { |
108 | static inline bool doit(const From *Val) { |
109 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 109, __extension__ __PRETTY_FUNCTION__ )); |
110 | return isa_impl<To, From>::doit(*Val); |
111 | } |
112 | }; |
113 | |
114 | template <typename To, typename From> |
115 | struct isa_impl_cl<To, const From *const> { |
116 | static inline bool doit(const From *Val) { |
117 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 117, __extension__ __PRETTY_FUNCTION__ )); |
118 | return isa_impl<To, From>::doit(*Val); |
119 | } |
120 | }; |
121 | |
122 | template <typename To, typename From, typename SimpleFrom> |
123 | struct isa_impl_wrap { |
124 | // When From != SimplifiedType, we can simplify the type some more by using |
125 | // the simplify_type template. |
126 | static bool doit(const From &Val) { |
127 | return isa_impl_wrap<To, SimpleFrom, |
128 | typename simplify_type<SimpleFrom>::SimpleType>:: |
129 | doit(simplify_type<const From>::getSimplifiedValue(Val)); |
130 | } |
131 | }; |
132 | |
133 | template <typename To, typename FromTy> |
134 | struct isa_impl_wrap<To, FromTy, FromTy> { |
135 | // When From == SimpleType, we are as simple as we are going to get. |
136 | static bool doit(const FromTy &Val) { |
137 | return isa_impl_cl<To, FromTy>::doit(Val); |
138 | } |
139 | }; |
140 | |
141 | //===----------------------------------------------------------------------===// |
142 | // cast_retty + cast_retty_impl |
143 | //===----------------------------------------------------------------------===// |
144 | |
145 | template <class To, class From> struct cast_retty; |
146 | |
147 | // Calculate what type the 'cast' function should return, based on a requested |
148 | // type of To and a source type of From. |
149 | template <class To, class From> struct cast_retty_impl { |
150 | using ret_type = To &; // Normal case, return Ty& |
151 | }; |
152 | template <class To, class From> struct cast_retty_impl<To, const From> { |
153 | using ret_type = const To &; // Normal case, return Ty& |
154 | }; |
155 | |
156 | template <class To, class From> struct cast_retty_impl<To, From *> { |
157 | using ret_type = To *; // Pointer arg case, return Ty* |
158 | }; |
159 | |
160 | template <class To, class From> struct cast_retty_impl<To, const From *> { |
161 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
162 | }; |
163 | |
164 | template <class To, class From> struct cast_retty_impl<To, const From *const> { |
165 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
166 | }; |
167 | |
168 | template <class To, class From> |
169 | struct cast_retty_impl<To, std::unique_ptr<From>> { |
170 | private: |
171 | using PointerType = typename cast_retty_impl<To, From *>::ret_type; |
172 | using ResultType = std::remove_pointer_t<PointerType>; |
173 | |
174 | public: |
175 | using ret_type = std::unique_ptr<ResultType>; |
176 | }; |
177 | |
178 | template <class To, class From, class SimpleFrom> struct cast_retty_wrap { |
179 | // When the simplified type and the from type are not the same, use the type |
180 | // simplifier to reduce the type, then reuse cast_retty_impl to get the |
181 | // resultant type. |
182 | using ret_type = typename cast_retty<To, SimpleFrom>::ret_type; |
183 | }; |
184 | |
185 | template <class To, class FromTy> struct cast_retty_wrap<To, FromTy, FromTy> { |
186 | // When the simplified type is equal to the from type, use it directly. |
187 | using ret_type = typename cast_retty_impl<To, FromTy>::ret_type; |
188 | }; |
189 | |
190 | template <class To, class From> struct cast_retty { |
191 | using ret_type = typename cast_retty_wrap< |
192 | To, From, typename simplify_type<From>::SimpleType>::ret_type; |
193 | }; |
194 | |
195 | //===----------------------------------------------------------------------===// |
196 | // cast_convert_val |
197 | //===----------------------------------------------------------------------===// |
198 | |
199 | // Ensure the non-simple values are converted using the simplify_type template |
200 | // that may be specialized by smart pointers... |
201 | // |
202 | template <class To, class From, class SimpleFrom> struct cast_convert_val { |
203 | // This is not a simple type, use the template to simplify it... |
204 | static typename cast_retty<To, From>::ret_type doit(const From &Val) { |
205 | return cast_convert_val<To, SimpleFrom, |
206 | typename simplify_type<SimpleFrom>::SimpleType>:: |
207 | doit(simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val))); |
208 | } |
209 | }; |
210 | |
211 | template <class To, class FromTy> struct cast_convert_val<To, FromTy, FromTy> { |
212 | // If it's a reference, switch to a pointer to do the cast and then deref it. |
213 | static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) { |
214 | return *(std::remove_reference_t<typename cast_retty<To, FromTy>::ret_type> |
215 | *)&const_cast<FromTy &>(Val); |
216 | } |
217 | }; |
218 | |
219 | template <class To, class FromTy> |
220 | struct cast_convert_val<To, FromTy *, FromTy *> { |
221 | // If it's a pointer, we can use c-style casting directly. |
222 | static typename cast_retty<To, FromTy *>::ret_type doit(const FromTy *Val) { |
223 | return (typename cast_retty<To, FromTy *>::ret_type) const_cast<FromTy *>( |
224 | Val); |
225 | } |
226 | }; |
227 | |
228 | //===----------------------------------------------------------------------===// |
229 | // is_simple_type |
230 | //===----------------------------------------------------------------------===// |
231 | |
232 | template <class X> struct is_simple_type { |
233 | static const bool value = |
234 | std::is_same<X, typename simplify_type<X>::SimpleType>::value; |
235 | }; |
236 | |
237 | // } // namespace detail |
238 | |
239 | //===----------------------------------------------------------------------===// |
240 | // CastIsPossible |
241 | //===----------------------------------------------------------------------===// |
242 | |
243 | /// This struct provides a way to check if a given cast is possible. It provides |
244 | /// a static function called isPossible that is used to check if a cast can be |
245 | /// performed. It should be overridden like this: |
246 | /// |
247 | /// template<> struct CastIsPossible<foo, bar> { |
248 | /// static inline bool isPossible(const bar &b) { |
249 | /// return bar.isFoo(); |
250 | /// } |
251 | /// }; |
252 | template <typename To, typename From, typename Enable = void> |
253 | struct CastIsPossible { |
254 | static inline bool isPossible(const From &f) { |
255 | return isa_impl_wrap< |
256 | To, const From, |
257 | typename simplify_type<const From>::SimpleType>::doit(f); |
258 | } |
259 | }; |
260 | |
261 | // Needed for optional unwrapping. This could be implemented with isa_impl, but |
262 | // we want to implement things in the new method and move old implementations |
263 | // over. In fact, some of the isa_impl templates should be moved over to |
264 | // CastIsPossible. |
265 | template <typename To, typename From> |
266 | struct CastIsPossible<To, std::optional<From>> { |
267 | static inline bool isPossible(const std::optional<From> &f) { |
268 | assert(f && "CastIsPossible::isPossible called on a nullopt!")(static_cast <bool> (f && "CastIsPossible::isPossible called on a nullopt!" ) ? void (0) : __assert_fail ("f && \"CastIsPossible::isPossible called on a nullopt!\"" , "llvm/include/llvm/Support/Casting.h", 268, __extension__ __PRETTY_FUNCTION__ )); |
269 | return isa_impl_wrap< |
270 | To, const From, |
271 | typename simplify_type<const From>::SimpleType>::doit(*f); |
272 | } |
273 | }; |
274 | |
275 | /// Upcasting (from derived to base) and casting from a type to itself should |
276 | /// always be possible. |
277 | template <typename To, typename From> |
278 | struct CastIsPossible<To, From, |
279 | std::enable_if_t<std::is_base_of<To, From>::value>> { |
280 | static inline bool isPossible(const From &f) { return true; } |
281 | }; |
282 | |
283 | //===----------------------------------------------------------------------===// |
284 | // Cast traits |
285 | //===----------------------------------------------------------------------===// |
286 | |
287 | /// All of these cast traits are meant to be implementations for useful casts |
288 | /// that users may want to use that are outside the standard behavior. An |
289 | /// example of how to use a special cast called `CastTrait` is: |
290 | /// |
291 | /// template<> struct CastInfo<foo, bar> : public CastTrait<foo, bar> {}; |
292 | /// |
293 | /// Essentially, if your use case falls directly into one of the use cases |
294 | /// supported by a given cast trait, simply inherit your special CastInfo |
295 | /// directly from one of these to avoid having to reimplement the boilerplate |
296 | /// `isPossible/castFailed/doCast/doCastIfPossible`. A cast trait can also |
297 | /// provide a subset of those functions. |
298 | |
299 | /// This cast trait just provides castFailed for the specified `To` type to make |
300 | /// CastInfo specializations more declarative. In order to use this, the target |
301 | /// result type must be `To` and `To` must be constructible from `nullptr`. |
302 | template <typename To> struct NullableValueCastFailed { |
303 | static To castFailed() { return To(nullptr); } |
304 | }; |
305 | |
306 | /// This cast trait just provides the default implementation of doCastIfPossible |
307 | /// to make CastInfo specializations more declarative. The `Derived` template |
308 | /// parameter *must* be provided for forwarding castFailed and doCast. |
309 | template <typename To, typename From, typename Derived> |
310 | struct DefaultDoCastIfPossible { |
311 | static To doCastIfPossible(From f) { |
312 | if (!Derived::isPossible(f)) |
313 | return Derived::castFailed(); |
314 | return Derived::doCast(f); |
315 | } |
316 | }; |
317 | |
318 | namespace detail { |
319 | /// A helper to derive the type to use with `Self` for cast traits, when the |
320 | /// provided CRTP derived type is allowed to be void. |
321 | template <typename OptionalDerived, typename Default> |
322 | using SelfType = std::conditional_t<std::is_same<OptionalDerived, void>::value, |
323 | Default, OptionalDerived>; |
324 | } // namespace detail |
325 | |
326 | /// This cast trait provides casting for the specific case of casting to a |
327 | /// value-typed object from a pointer-typed object. Note that `To` must be |
328 | /// nullable/constructible from a pointer to `From` to use this cast. |
329 | template <typename To, typename From, typename Derived = void> |
330 | struct ValueFromPointerCast |
331 | : public CastIsPossible<To, From *>, |
332 | public NullableValueCastFailed<To>, |
333 | public DefaultDoCastIfPossible< |
334 | To, From *, |
335 | detail::SelfType<Derived, ValueFromPointerCast<To, From>>> { |
336 | static inline To doCast(From *f) { return To(f); } |
337 | }; |
338 | |
339 | /// This cast trait provides std::unique_ptr casting. It has the semantics of |
340 | /// moving the contents of the input unique_ptr into the output unique_ptr |
341 | /// during the cast. It's also a good example of how to implement a move-only |
342 | /// cast. |
343 | template <typename To, typename From, typename Derived = void> |
344 | struct UniquePtrCast : public CastIsPossible<To, From *> { |
345 | using Self = detail::SelfType<Derived, UniquePtrCast<To, From>>; |
346 | using CastResultType = std::unique_ptr< |
347 | std::remove_reference_t<typename cast_retty<To, From>::ret_type>>; |
348 | |
349 | static inline CastResultType doCast(std::unique_ptr<From> &&f) { |
350 | return CastResultType((typename CastResultType::element_type *)f.release()); |
351 | } |
352 | |
353 | static inline CastResultType castFailed() { return CastResultType(nullptr); } |
354 | |
355 | static inline CastResultType doCastIfPossible(std::unique_ptr<From> &&f) { |
356 | if (!Self::isPossible(f)) |
357 | return castFailed(); |
358 | return doCast(f); |
359 | } |
360 | }; |
361 | |
362 | /// This cast trait provides std::optional<T> casting. This means that if you |
363 | /// have a value type, you can cast it to another value type and have dyn_cast |
364 | /// return an std::optional<T>. |
365 | template <typename To, typename From, typename Derived = void> |
366 | struct OptionalValueCast |
367 | : public CastIsPossible<To, From>, |
368 | public DefaultDoCastIfPossible< |
369 | std::optional<To>, From, |
370 | detail::SelfType<Derived, OptionalValueCast<To, From>>> { |
371 | static inline std::optional<To> castFailed() { return std::optional<To>{}; } |
372 | |
373 | static inline std::optional<To> doCast(const From &f) { return To(f); } |
374 | }; |
375 | |
376 | /// Provides a cast trait that strips `const` from types to make it easier to |
377 | /// implement a const-version of a non-const cast. It just removes boilerplate |
378 | /// and reduces the amount of code you as the user need to implement. You can |
379 | /// use it like this: |
380 | /// |
381 | /// template<> struct CastInfo<foo, bar> { |
382 | /// ...verbose implementation... |
383 | /// }; |
384 | /// |
385 | /// template<> struct CastInfo<foo, const bar> : public |
386 | /// ConstStrippingForwardingCast<foo, const bar, CastInfo<foo, bar>> {}; |
387 | /// |
388 | template <typename To, typename From, typename ForwardTo> |
389 | struct ConstStrippingForwardingCast { |
390 | // Remove the pointer if it exists, then we can get rid of consts/volatiles. |
391 | using DecayedFrom = std::remove_cv_t<std::remove_pointer_t<From>>; |
392 | // Now if it's a pointer, add it back. Otherwise, we want a ref. |
393 | using NonConstFrom = std::conditional_t<std::is_pointer<From>::value, |
394 | DecayedFrom *, DecayedFrom &>; |
395 | |
396 | static inline bool isPossible(const From &f) { |
397 | return ForwardTo::isPossible(const_cast<NonConstFrom>(f)); |
398 | } |
399 | |
400 | static inline decltype(auto) castFailed() { return ForwardTo::castFailed(); } |
401 | |
402 | static inline decltype(auto) doCast(const From &f) { |
403 | return ForwardTo::doCast(const_cast<NonConstFrom>(f)); |
404 | } |
405 | |
406 | static inline decltype(auto) doCastIfPossible(const From &f) { |
407 | return ForwardTo::doCastIfPossible(const_cast<NonConstFrom>(f)); |
408 | } |
409 | }; |
410 | |
411 | /// Provides a cast trait that uses a defined pointer to pointer cast as a base |
412 | /// for reference-to-reference casts. Note that it does not provide castFailed |
413 | /// and doCastIfPossible because a pointer-to-pointer cast would likely just |
414 | /// return `nullptr` which could cause nullptr dereference. You can use it like |
415 | /// this: |
416 | /// |
417 | /// template <> struct CastInfo<foo, bar *> { ... verbose implementation... }; |
418 | /// |
419 | /// template <> |
420 | /// struct CastInfo<foo, bar> |
421 | /// : public ForwardToPointerCast<foo, bar, CastInfo<foo, bar *>> {}; |
422 | /// |
423 | template <typename To, typename From, typename ForwardTo> |
424 | struct ForwardToPointerCast { |
425 | static inline bool isPossible(const From &f) { |
426 | return ForwardTo::isPossible(&f); |
427 | } |
428 | |
429 | static inline decltype(auto) doCast(const From &f) { |
430 | return *ForwardTo::doCast(&f); |
431 | } |
432 | }; |
433 | |
434 | //===----------------------------------------------------------------------===// |
435 | // CastInfo |
436 | //===----------------------------------------------------------------------===// |
437 | |
438 | /// This struct provides a method for customizing the way a cast is performed. |
439 | /// It inherits from CastIsPossible, to support the case of declaring many |
440 | /// CastIsPossible specializations without having to specialize the full |
441 | /// CastInfo. |
442 | /// |
443 | /// In order to specialize different behaviors, specify different functions in |
444 | /// your CastInfo specialization. |
445 | /// For isa<> customization, provide: |
446 | /// |
447 | /// `static bool isPossible(const From &f)` |
448 | /// |
449 | /// For cast<> customization, provide: |
450 | /// |
451 | /// `static To doCast(const From &f)` |
452 | /// |
453 | /// For dyn_cast<> and the *_if_present<> variants' customization, provide: |
454 | /// |
455 | /// `static To castFailed()` and `static To doCastIfPossible(const From &f)` |
456 | /// |
457 | /// Your specialization might look something like this: |
458 | /// |
459 | /// template<> struct CastInfo<foo, bar> : public CastIsPossible<foo, bar> { |
460 | /// static inline foo doCast(const bar &b) { |
461 | /// return foo(const_cast<bar &>(b)); |
462 | /// } |
463 | /// static inline foo castFailed() { return foo(); } |
464 | /// static inline foo doCastIfPossible(const bar &b) { |
465 | /// if (!CastInfo<foo, bar>::isPossible(b)) |
466 | /// return castFailed(); |
467 | /// return doCast(b); |
468 | /// } |
469 | /// }; |
470 | |
471 | // The default implementations of CastInfo don't use cast traits for now because |
472 | // we need to specify types all over the place due to the current expected |
473 | // casting behavior and the way cast_retty works. New use cases can and should |
474 | // take advantage of the cast traits whenever possible! |
475 | |
476 | template <typename To, typename From, typename Enable = void> |
477 | struct CastInfo : public CastIsPossible<To, From> { |
478 | using Self = CastInfo<To, From, Enable>; |
479 | |
480 | using CastReturnType = typename cast_retty<To, From>::ret_type; |
481 | |
482 | static inline CastReturnType doCast(const From &f) { |
483 | return cast_convert_val< |
484 | To, From, |
485 | typename simplify_type<From>::SimpleType>::doit(const_cast<From &>(f)); |
486 | } |
487 | |
488 | // This assumes that you can construct the cast return type from `nullptr`. |
489 | // This is largely to support legacy use cases - if you don't want this |
490 | // behavior you should specialize CastInfo for your use case. |
491 | static inline CastReturnType castFailed() { return CastReturnType(nullptr); } |
492 | |
493 | static inline CastReturnType doCastIfPossible(const From &f) { |
494 | if (!Self::isPossible(f)) |
495 | return castFailed(); |
496 | return doCast(f); |
497 | } |
498 | }; |
499 | |
500 | /// This struct provides an overload for CastInfo where From has simplify_type |
501 | /// defined. This simply forwards to the appropriate CastInfo with the |
502 | /// simplified type/value, so you don't have to implement both. |
503 | template <typename To, typename From> |
504 | struct CastInfo<To, From, std::enable_if_t<!is_simple_type<From>::value>> { |
505 | using Self = CastInfo<To, From>; |
506 | using SimpleFrom = typename simplify_type<From>::SimpleType; |
507 | using SimplifiedSelf = CastInfo<To, SimpleFrom>; |
508 | |
509 | static inline bool isPossible(From &f) { |
510 | return SimplifiedSelf::isPossible( |
511 | simplify_type<From>::getSimplifiedValue(f)); |
512 | } |
513 | |
514 | static inline decltype(auto) doCast(From &f) { |
515 | return SimplifiedSelf::doCast(simplify_type<From>::getSimplifiedValue(f)); |
516 | } |
517 | |
518 | static inline decltype(auto) castFailed() { |
519 | return SimplifiedSelf::castFailed(); |
520 | } |
521 | |
522 | static inline decltype(auto) doCastIfPossible(From &f) { |
523 | return SimplifiedSelf::doCastIfPossible( |
524 | simplify_type<From>::getSimplifiedValue(f)); |
525 | } |
526 | }; |
527 | |
528 | //===----------------------------------------------------------------------===// |
529 | // Pre-specialized CastInfo |
530 | //===----------------------------------------------------------------------===// |
531 | |
532 | /// Provide a CastInfo specialized for std::unique_ptr. |
533 | template <typename To, typename From> |
534 | struct CastInfo<To, std::unique_ptr<From>> : public UniquePtrCast<To, From> {}; |
535 | |
536 | /// Provide a CastInfo specialized for std::optional<From>. It's assumed that if |
537 | /// the input is std::optional<From> that the output can be std::optional<To>. |
538 | /// If that's not the case, specialize CastInfo for your use case. |
539 | template <typename To, typename From> |
540 | struct CastInfo<To, std::optional<From>> : public OptionalValueCast<To, From> { |
541 | }; |
542 | |
543 | /// isa<X> - Return true if the parameter to the template is an instance of one |
544 | /// of the template type arguments. Used like this: |
545 | /// |
546 | /// if (isa<Type>(myVal)) { ... } |
547 | /// if (isa<Type0, Type1, Type2>(myVal)) { ... } |
548 | template <typename To, typename From> |
549 | [[nodiscard]] inline bool isa(const From &Val) { |
550 | return CastInfo<To, const From>::isPossible(Val); |
551 | } |
552 | |
553 | template <typename First, typename Second, typename... Rest, typename From> |
554 | [[nodiscard]] inline bool isa(const From &Val) { |
555 | return isa<First>(Val) || isa<Second, Rest...>(Val); |
556 | } |
557 | |
558 | /// cast<X> - Return the argument parameter cast to the specified type. This |
559 | /// casting operator asserts that the type is correct, so it does not return |
560 | /// null on failure. It does not allow a null argument (use cast_if_present for |
561 | /// that). It is typically used like this: |
562 | /// |
563 | /// cast<Instruction>(myVal)->getParent() |
564 | |
565 | template <typename To, typename From> |
566 | [[nodiscard]] inline decltype(auto) cast(const From &Val) { |
567 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 567, __extension__ __PRETTY_FUNCTION__ )); |
568 | return CastInfo<To, const From>::doCast(Val); |
569 | } |
570 | |
571 | template <typename To, typename From> |
572 | [[nodiscard]] inline decltype(auto) cast(From &Val) { |
573 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 573, __extension__ __PRETTY_FUNCTION__ )); |
574 | return CastInfo<To, From>::doCast(Val); |
575 | } |
576 | |
577 | template <typename To, typename From> |
578 | [[nodiscard]] inline decltype(auto) cast(From *Val) { |
579 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 579, __extension__ __PRETTY_FUNCTION__ )); |
580 | return CastInfo<To, From *>::doCast(Val); |
581 | } |
582 | |
583 | template <typename To, typename From> |
584 | [[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) { |
585 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 585, __extension__ __PRETTY_FUNCTION__ )); |
586 | return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val)); |
587 | } |
588 | |
589 | //===----------------------------------------------------------------------===// |
590 | // ValueIsPresent |
591 | //===----------------------------------------------------------------------===// |
592 | |
593 | template <typename T> |
594 | constexpr bool IsNullable = |
595 | std::is_pointer_v<T> || std::is_constructible_v<T, std::nullptr_t>; |
596 | |
597 | /// ValueIsPresent provides a way to check if a value is, well, present. For |
598 | /// pointers, this is the equivalent of checking against nullptr, for Optionals |
599 | /// this is the equivalent of checking hasValue(). It also provides a method for |
600 | /// unwrapping a value (think calling .value() on an optional). |
601 | |
602 | // Generic values can't *not* be present. |
603 | template <typename T, typename Enable = void> struct ValueIsPresent { |
604 | using UnwrappedType = T; |
605 | static inline bool isPresent(const T &t) { return true; } |
606 | static inline decltype(auto) unwrapValue(T &t) { return t; } |
607 | }; |
608 | |
609 | // Optional provides its own way to check if something is present. |
610 | template <typename T> struct ValueIsPresent<std::optional<T>> { |
611 | using UnwrappedType = T; |
612 | static inline bool isPresent(const std::optional<T> &t) { |
613 | return t.has_value(); |
614 | } |
615 | static inline decltype(auto) unwrapValue(std::optional<T> &t) { return *t; } |
616 | }; |
617 | |
618 | // If something is "nullable" then we just compare it to nullptr to see if it |
619 | // exists. |
620 | template <typename T> |
621 | struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> { |
622 | using UnwrappedType = T; |
623 | static inline bool isPresent(const T &t) { return t != T(nullptr); } |
624 | static inline decltype(auto) unwrapValue(T &t) { return t; } |
625 | }; |
626 | |
627 | namespace detail { |
628 | // Convenience function we can use to check if a value is present. Because of |
629 | // simplify_type, we have to call it on the simplified type for now. |
630 | template <typename T> inline bool isPresent(const T &t) { |
631 | return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent( |
632 | simplify_type<T>::getSimplifiedValue(const_cast<T &>(t))); |
633 | } |
634 | |
635 | // Convenience function we can use to unwrap a value. |
636 | template <typename T> inline decltype(auto) unwrapValue(T &t) { |
637 | return ValueIsPresent<T>::unwrapValue(t); |
638 | } |
639 | } // namespace detail |
640 | |
641 | /// dyn_cast<X> - Return the argument parameter cast to the specified type. This |
642 | /// casting operator returns null if the argument is of the wrong type, so it |
643 | /// can be used to test for a type as well as cast if successful. The value |
644 | /// passed in must be present, if not, use dyn_cast_if_present. This should be |
645 | /// used in the context of an if statement like this: |
646 | /// |
647 | /// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... } |
648 | |
649 | template <typename To, typename From> |
650 | [[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) { |
651 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 651, __extension__ __PRETTY_FUNCTION__ )); |
652 | return CastInfo<To, const From>::doCastIfPossible(Val); |
653 | } |
654 | |
655 | template <typename To, typename From> |
656 | [[nodiscard]] inline decltype(auto) dyn_cast(From &Val) { |
657 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 657, __extension__ __PRETTY_FUNCTION__ )); |
658 | return CastInfo<To, From>::doCastIfPossible(Val); |
659 | } |
660 | |
661 | template <typename To, typename From> |
662 | [[nodiscard]] inline decltype(auto) dyn_cast(From *Val) { |
663 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 663, __extension__ __PRETTY_FUNCTION__ )); |
664 | return CastInfo<To, From *>::doCastIfPossible(Val); |
665 | } |
666 | |
667 | template <typename To, typename From> |
668 | [[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &&Val) { |
669 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 669, __extension__ __PRETTY_FUNCTION__ )); |
670 | return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible( |
671 | std::forward<std::unique_ptr<From> &&>(Val)); |
672 | } |
673 | |
674 | /// isa_and_present<X> - Functionally identical to isa, except that a null value |
675 | /// is accepted. |
676 | template <typename... X, class Y> |
677 | [[nodiscard]] inline bool isa_and_present(const Y &Val) { |
678 | if (!detail::isPresent(Val)) |
679 | return false; |
680 | return isa<X...>(Val); |
681 | } |
682 | |
683 | template <typename... X, class Y> |
684 | [[nodiscard]] inline bool isa_and_nonnull(const Y &Val) { |
685 | return isa_and_present<X...>(Val); |
686 | } |
687 | |
688 | /// cast_if_present<X> - Functionally identical to cast, except that a null |
689 | /// value is accepted. |
690 | template <class X, class Y> |
691 | [[nodiscard]] inline auto cast_if_present(const Y &Val) { |
692 | if (!detail::isPresent(Val)) |
693 | return CastInfo<X, const Y>::castFailed(); |
694 | assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 694, __extension__ __PRETTY_FUNCTION__ )); |
695 | return cast<X>(detail::unwrapValue(Val)); |
696 | } |
697 | |
698 | template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) { |
699 | if (!detail::isPresent(Val)) |
700 | return CastInfo<X, Y>::castFailed(); |
701 | assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 701, __extension__ __PRETTY_FUNCTION__ )); |
702 | return cast<X>(detail::unwrapValue(Val)); |
703 | } |
704 | |
705 | template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) { |
706 | if (!detail::isPresent(Val)) |
707 | return CastInfo<X, Y *>::castFailed(); |
708 | assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 708, __extension__ __PRETTY_FUNCTION__ )); |
709 | return cast<X>(detail::unwrapValue(Val)); |
710 | } |
711 | |
712 | template <class X, class Y> |
713 | [[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) { |
714 | if (!detail::isPresent(Val)) |
715 | return UniquePtrCast<X, Y>::castFailed(); |
716 | return UniquePtrCast<X, Y>::doCast(std::move(Val)); |
717 | } |
718 | |
719 | // Provide a forwarding from cast_or_null to cast_if_present for current |
720 | // users. This is deprecated and will be removed in a future patch, use |
721 | // cast_if_present instead. |
722 | template <class X, class Y> auto cast_or_null(const Y &Val) { |
723 | return cast_if_present<X>(Val); |
724 | } |
725 | |
726 | template <class X, class Y> auto cast_or_null(Y &Val) { |
727 | return cast_if_present<X>(Val); |
728 | } |
729 | |
730 | template <class X, class Y> auto cast_or_null(Y *Val) { |
731 | return cast_if_present<X>(Val); |
732 | } |
733 | |
734 | template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) { |
735 | return cast_if_present<X>(std::move(Val)); |
736 | } |
737 | |
738 | /// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a |
739 | /// null (or none in the case of optionals) value is accepted. |
740 | template <class X, class Y> auto dyn_cast_if_present(const Y &Val) { |
741 | if (!detail::isPresent(Val)) |
742 | return CastInfo<X, const Y>::castFailed(); |
743 | return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val)); |
744 | } |
745 | |
746 | template <class X, class Y> auto dyn_cast_if_present(Y &Val) { |
747 | if (!detail::isPresent(Val)) |
748 | return CastInfo<X, Y>::castFailed(); |
749 | return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val)); |
750 | } |
751 | |
752 | template <class X, class Y> auto dyn_cast_if_present(Y *Val) { |
753 | if (!detail::isPresent(Val)) |
754 | return CastInfo<X, Y *>::castFailed(); |
755 | return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val)); |
756 | } |
757 | |
758 | // Forwards to dyn_cast_if_present to avoid breaking current users. This is |
759 | // deprecated and will be removed in a future patch, use |
760 | // cast_if_present instead. |
761 | template <class X, class Y> auto dyn_cast_or_null(const Y &Val) { |
762 | return dyn_cast_if_present<X>(Val); |
763 | } |
764 | |
765 | template <class X, class Y> auto dyn_cast_or_null(Y &Val) { |
766 | return dyn_cast_if_present<X>(Val); |
767 | } |
768 | |
769 | template <class X, class Y> auto dyn_cast_or_null(Y *Val) { |
770 | return dyn_cast_if_present<X>(Val); |
771 | } |
772 | |
773 | /// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>, |
774 | /// taking ownership of the input pointer iff isa<X>(Val) is true. If the |
775 | /// cast is successful, From refers to nullptr on exit and the casted value |
776 | /// is returned. If the cast is unsuccessful, the function returns nullptr |
777 | /// and From is unchanged. |
778 | template <class X, class Y> |
779 | [[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType |
780 | unique_dyn_cast(std::unique_ptr<Y> &Val) { |
781 | if (!isa<X>(Val)) |
782 | return nullptr; |
783 | return cast<X>(std::move(Val)); |
784 | } |
785 | |
786 | template <class X, class Y> |
787 | [[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) { |
788 | return unique_dyn_cast<X, Y>(Val); |
789 | } |
790 | |
791 | // unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, |
792 | // except that a null value is accepted. |
793 | template <class X, class Y> |
794 | [[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType |
795 | unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) { |
796 | if (!Val) |
797 | return nullptr; |
798 | return unique_dyn_cast<X, Y>(Val); |
799 | } |
800 | |
801 | template <class X, class Y> |
802 | [[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) { |
803 | return unique_dyn_cast_or_null<X, Y>(Val); |
804 | } |
805 | |
806 | } // end namespace llvm |
807 | |
808 | #endif // LLVM_SUPPORT_CASTING_H |